Auto-Complete System - Problem

Design and implement an auto-complete system that suggests words based on a given prefix from a dictionary of words.

You need to implement a class AutoComplete with the following methods:

  • AutoComplete(dictionary) - Initialize the system with a list of words
  • search(prefix) - Return all words that start with the given prefix, sorted alphabetically

The system should efficiently handle multiple search queries and return results in lexicographical order.

Input & Output

Example 1 — Basic Auto-Complete
$ Input: dictionary = ["apple", "app", "application", "apply", "car", "card", "care"], prefix = "app"
Output: ["app", "apple", "application", "apply"]
💡 Note: All words starting with 'app' are: app, apple, application, apply. They are returned in alphabetical order.
Example 2 — Single Character Prefix
$ Input: dictionary = ["cat", "car", "card", "dog", "door"], prefix = "c"
Output: ["car", "card", "cat"]
💡 Note: Words starting with 'c' are: car, card, cat (sorted alphabetically).
Example 3 — No Matches
$ Input: dictionary = ["hello", "world", "test"], prefix = "xyz"
Output: []
💡 Note: No words in the dictionary start with 'xyz', so return empty array.

Constraints

  • 1 ≤ dictionary.length ≤ 1000
  • 1 ≤ dictionary[i].length ≤ 100
  • 1 ≤ prefix.length ≤ 100
  • dictionary[i] and prefix consist only of lowercase English letters

Visualization

Tap to expand
INPUT DICTIONARYTRIE BUILDINGSEARCH RESULTSWords Array"apple""app""application""apply""car""card"Prefix: "app"rootacppENDlTrie Structure Built1Navigate to prefix2Collect all words3Return sorted resultsOutput Array"app""apple""application"Key Insight:A Trie data structure allows O(prefix_length + results) time complexity byorganizing words in a tree where each path represents a prefix, eliminating the needto check every word in the dictionary for each search query.TutorialsPoint - Auto-Complete System | Trie Data Structure
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
52.0K Views
High Frequency
~25 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen