Dsa
Trie
Easy
Autocomplete System
You are building an autocomplete system for a text editor. Implement a Trie that supports adding words and retrieving autocompleted words based on a given prefix. Implement the following methods: 1. `add_word(word: str)` - adds a new word to the trie. 2. `autocomplete(prefix: str) -> List[str]` - returns a list of all words that start with the given prefix in lexicographical order.
Input format:
- The first line contains an integer, N (1 ≤ N ≤ 1000), the number of operations.
- The following N lines contain operations in the format:
- `add <word>` (where <word> contains lowercase letters only),
- `autocomplete <prefix>` (where <prefix> contains lowercase letters only).
Output format:
- For each `autocomplete` operation, print the list of matched words on a new line, separated by spaces, or '[]' if no matches found.
Example:
Input:
4
add apple
add application
add apply
autocomplete app
autocomplete a
Output:
apple application apply
a
Key concepts
trieautocompletesuggestions
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now