Dsa
Trie
Medium
Trie-Based Auto-Completion System
You are tasked with implementing a basic auto-completion system using a trie. The system should support inserting words and fetching possible completions for a given prefix.
Your program should first read an integer N, the number of words to insert into the trie. Then read N words, each on a new line. After that, read an integer Q, the number of prefix queries. For each of the next Q lines, read a prefix string. For each prefix, output a list of all words in the trie that start with that prefix, in lexicographical order. If there are no matching words, output "[]".
Input Format:
- The first line contains an integer N (1 ≤ N ≤ 1000)
- The next N lines contain strings representing the words (1 ≤ length ≤ 100)
- The next line contains an integer Q (1 ≤ Q ≤ 100)
- The next Q lines contain strings representing the prefixes (1 ≤ length ≤ 100)
Output Format:
- For each prefix query, output the corresponding list of words (or "[]" if none) in a new line.
Example:
Input:
5
apple
appetite
banana
bandana
band
3
ap
ban
cat
Output:
[apple, appetite]
[banana, bandana, band]
[]
Key concepts
triestringsautocomplete
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