Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: A trie stores n words of average length L over a 26-letter alphabet. Autocomplete must list whether any word starts with a prefix p of length m. What is the cost of the prefix check, and why is a trie preferred to a hash set of words?

  1. A. O(n) – every word must be visited
  2. B. O(log n) – a trie is a balanced BST
  3. C. O(m log n) – each level is binary searched among n words
  4. D. O(m) by walking m edges; a hash set of whole words cannot answer prefix queries without scanning all words

Correct answer: D. O(m) by walking m edges; a hash set of whole words cannot answer prefix queries without scanning all words

Each character moves one level down the trie, independent of n. A hash set answers exact membership in O(L) but prefix existence needs either all prefixes stored (O(nL) extra) or a full scan.

More Coding Interview Problems questions

Exams that ask this topic