Longest common prefix
Standard · Write code · about 10 min
Return the longest prefix shared by every word in words. Return the empty string when there is none, or when words is empty.
Insert all words into a trie. The common prefix is the path from the root where each node has exactly one child and no word ends.
Example 1
Input:
[["flower","flow","flight"]]
Output:
fl
The path f, l is shared. Then the trie branches into o and i.
Example 2
Input:
[["dog","racecar","car"]]
Output:
The root already has more than one child.
Constraints
- 0 ≤ words.length ≤ 2,000
- Each word has 0 to 20 lowercase letters
Learn the idea first: Tries: insert, search, prefix, a visual lesson.
More Tries: insert, search, prefix problems
- Node count Warm-up
- Starts-with Warm-up
- Implement a trie Standard
- Trace a search Standard
- Word dictionary with wildcard Challenge