#720

Longest Word in Dictionary

Medium
ArrayHash TableStringTrieSortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

This approach uses a set to store the words for quick lookup. By sorting the words first, we ensure that we can build longer words in lexicographical order efficiently.

⚙️

Algorithm

5 steps
  1. 1Step 1: Sort the words array lexicographically.
  2. 2Step 2: Initialize a set to store the words and a variable for the longest word.
  3. 3Step 3: Iterate through the sorted words and check if the current word can be formed by its prefixes in the set.
  4. 4Step 4: If valid, update the longest word.
  5. 5Step 5: Add the current word to the set.
solution.py9 lines
1def longestWord(words):
2    words.sort()
3    word_set = set()
4    longest = ''
5    for word in words:
6        if len(word) == 1 or word[:-1] in word_set:
7            longest = word if len(word) > len(longest) else longest
8            word_set.add(word)
9    return longest

Complexity note: The time complexity is O(n log n) due to the sorting step, while the space complexity is O(n) for storing the words in a set.

  • 1Sorting the words helps in checking prefixes in lexicographical order.
  • 2Using a set allows for O(1) average time complexity for lookups.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.