Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE

Problem: Count how many query words are subsequences of a long log string, using per-letter position lists and binary search (instead of rescanning the string for each word).

Problem: Count how many query words are subsequences of a long log string, using per-letter position lists and binary search (instead of rescanning the string for each word).
from bisect import bisect_right
from collections import defaultdict
def count_subseq(s, words):
    pos = defaultdict(list)
    for i, c in enumerate(s): pos[c].append(i)
    def ok(w):
        cur = -1
        for c in w:
            lst = pos[c]; j = bisect_right(lst, cur)
            if j == len(lst): return False
            cur = lst[j]
        return True
    return sum(ok(w) for w in words)
print(count_subseq("bananapie", ["ban", "nap", "pin", "bane", "aaa", "nnp"]))
What is printed?
  1. A. 5
  2. B. 4
  3. C. 6
  4. D. 3

Correct answer: A. 5

For each letter of a word, jump to its first occurrence after the current index (bisect_right on that letter's sorted positions). "bananapie": ban, nap (n2 a3 p6), bane (… e8), aaa (1, 3, 5) and nnp (2, 4, 6) all match; "pin" fails because no 'n' follows the 'i' at index 7. Cost O(|s| + Σ|w| log |s|) versus O(|s| · #words) for naive rescans.

More Coding Interview Problems questions

Exams that ask this topic