Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Insert words into a trie and count how many stored words start with a given prefix.
Problem: Insert words into a trie and count how many stored words start with a given prefix.
def make(words):
root = {}
for w in words:
node = root
for ch in w:
node = node.setdefault(ch, {'#': 0})
node['#'] += 1
return root
def count(root, p):
node = root
for ch in p:
if ch not in node: return 0
node = node[ch]
return node['#']
t = make(["car", "card", "care", "cat", "dog", "do"])
print(count(t, "car"), count(t, "ca"), count(t, "do"), count(t, "cow"))What is printed?- A. 3 4 2 0
- B. 1 4 2 0
- C. 3 4 1 0
- D. 3 3 2 0
Correct answer: A. 3 4 2 0
Each node stores how many words pass through it. 'car' is a prefix of car, card, care; 'ca' adds cat; 'do' covers do and dog. Storing only an end-of-word flag would need a subtree walk to count. Insert and query are O(length).
More Coding Interview Problems questions
- 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…
- Problem: A network has V = 10⁵ routers and E = 2 × 10⁵ links with latencies that can be negative (but no negative cycle). Which…