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?
- A. O(n) – every word must be visited
- B. O(log n) – a trie is a balanced BST
- C. O(m log n) – each level is binary searched among n words
- 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
- Problem: Insert words into a trie and count how many stored words start with a given prefix. python def make(words): root = {} for w in…
- Problem: Count islands (groups of '1' cells connected up, down, left or right) on a satellite grid. python def islands(g): R, C = len(g)…
- Problem: In a grid of fresh (1) and rotten (2) oranges, every minute rot spreads to 4-neighbours. Return the minutes until no fresh orange…
- Problem: Courses with prerequisites [a, b] (b before a). Return one valid order using Kahn's algorithm with a min-heap for ties, or [] if…
- Problem: Detect a cycle in a directed dependency graph with three-colour DFS. python def hascycle(n, edges): adj = [[] for in range(n)]…
- Problem: Find the shortest travel time from node 0 to every node in a road network with non-negative weights. python import heapq def…