Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Count how many distinct index sequences of s spell t as a subsequence.
Problem: Count how many distinct index sequences of s spell t as a subsequence.
def distinct(s, t):
dp = [1] + [0] * len(t)
for c in s:
for j in range(len(t), 0, -1):
if t[j-1] == c: dp[j] += dp[j-1]
return dp[-1]
print(distinct("aabbcc", "abc"), distinct("abab", "ab"))What is printed?- A. 8 4
- B. 6 3
- C. 2 3
- D. 8 3
Correct answer: D. 8 3
For 'aabbcc' choose one of 2 a's, 2 b's and 2 c's in order: 2 × 2 × 2 = 8. For 'abab', the pairs (a, b) with a before b are (0,1), (0,3), (2,3): 3. Looping j backwards stops a character from being used twice in one update.
More Coding Interview Problems questions
- Problem: Maximum profit from at most 2 buy-sell transactions (sell before buying again). python def two(p): b1 = b2 = float('-inf'); s1 =…
- Problem: A courier starts at depot 0, must visit every city exactly once and return to 0. Solve it with bitmask DP (Held–Karp). python INF…
- Problem: Sum a[i] XOR a[j] over all pairs i < j in O(n · bits) by counting, for each bit, how many numbers have it set. python def…
- Edge case: nCr mod p is computed with factorials and Fermat inverses. Here n ≥ p. python p = 7 fact = [1] 11 for i in range(1, 11)…
- Problem: Extended Euclid returns g = gcd(a, b) and integers x, y with a·x + b·y = g. python def eg(a, b): if b == 0: return a, 1, 0 g, x…
- Problem: A segment tree with lazy propagation supports 'add v to a[l..r]' and 'sum of a[l..r]' on an array of 8 zeros. python N = 8 t, lz…