Skip to main content

Phrase Prefix Retrieval

easy
TrieStringDepth First SearchTrie AutocompleteDfs Recursive
Asked atGoogleAmazonMicrosoftUber

Problem Description

Given a list of words and a query prefix, return all words from the list that start with the given prefix, in lexicographic order.

You should build a trie from the word list for efficient prefix lookups.

**Example 1:**
```
Input: wordList = ["tornado", "torch", "tortoise", "table", "tank"], queryPrefix = "tor"
Output: ["torch", "tortoise", "tornado"]
```

**Example 2:**
```
Input: wordList = ["bicycle", "bike", "biplane", "bird", "bite"], queryPrefix = "bi"
Output: ["bicycle", "bike", "biplane", "bird", "bite"]
```

**Example 3:**
```
Input: wordList = ["cat", "car", "card"], queryPrefix = "xyz"
Output: []
```

Constraints

  • 1 <= wordList.length <= 500
  • 1 <= wordList[i].length <= 30
  • 1 <= queryPrefix.length <= 30
  • All strings consist of lowercase English letters
  • All words in wordList are distinct

Follow-up

Return only the top-3 lexicographically smallest matching words, avoiding the cost of collecting all matches.

Hints

Try the problem first. If you get stuck, you can reveal hints one at a time.

Solution

Leaderboard

No entries yet for python.

Be the first — submit an accepted solution.