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?
  1. A. 7
  2. B. 2
  3. C. 11
  4. 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

Exams that ask this topic