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?- A. 5
- B. 4
- C. 6
- 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
- Problem: A candy-crush style cleaner repeatedly deletes any k equal adjacent letters (cascading) until none remain. A stack of (letter…
- Problem: Score a balanced bracket string: "()" = 1, AB = A + B, (A) = 2·A. Each innermost "()" at depth d contributes 2^d. python def…
- Problem: Delivery vans drive towards a depot at 20 km; a faster van that catches a slower one ahead must slow down and they arrive as one…
- Problem: Evaluate an expression of non-negative integers with + − / (no brackets, / truncates toward zero) in one pass with a stack…
- Problem: A magician reveals cards like this: show the top card, then move the next top card to the bottom; repeat. Arrange the deck so the…
- Problem: From a sorted linked list delete EVERY value that occurs more than once (keep only values that appear exactly once). python class…