Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Count how many words are subsequences of s, by bucketing words by the next character they are waiting for.
Problem: Count how many words are subsequences of s, by bucketing words by the next character they are waiting for.
from collections import defaultdict
def count(s, words):
wait = defaultdict(list)
for w in words: wait[w[0]].append(iter(w[1:]))
done = 0
for c in s:
its = wait.pop(c, [])
for it in its:
nxt = next(it, None)
if nxt is None: done += 1
else: wait[nxt].append(it)
return done
print(count("abcdeab", ["a", "bb", "acd", "ace", "eab", "dca", "aab"]))What is printed?- A. 7
- B. 2
- C. 11
- D. 6
Correct answer: D. 6
Each word is advanced only when its awaited character appears, so s is scanned once. Subsequences of 'abcdeab': a, bb, acd, ace, eab, aab; 'dca' fails because the letters appear in the wrong order → 6. Ignoring order (only checking letters exist) gives 7, testing for substrings gives 2, and reading a bucket without popping it lets an iterator advance twice on one character (11).
More Coding Interview Problems questions
- Problem: Roads are one-way (a → b). Reorient the fewest roads so every city can reach city 0 (the roads form a tree). python def…
- Problem: A grid has exactly two islands (1s). Find the minimum number of 0s to flip to connect them (BFS outward from the first island)…
- Problem: Return the city that can reach the FEWEST other cities within a distance threshold (largest index on ties), using Floyd–Warshall…
- Problem: Count all paths from node 0 to node n − 1 in a DAG (memoised DFS). python from functools import lrucache g = {0: [1, 2, 3], 1…
- Problem: Rebuild a binary tree from its inorder and postorder traversals (distinct values) and print its preorder. python def prefrom(ino…
- Problem: Lowest common ancestor in a general binary tree (not a BST), with the recursive 'return whichever side found something' method…