Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Count the number of distinct subsequences of s that equal t.
Problem: Count the number of distinct subsequences of s that equal t.
def distinct(s, t):
dp = [1] + [0] * len(t)
for ch in s:
for j in range(len(t), 0, -1):
if t[j - 1] == ch: dp[j] += dp[j - 1]
return dp[-1]
print(distinct("rabbbit", "rabbit"), distinct("babgbag", "bag"))What is printed?- A. 3 4
- B. 2 5
- C. 6 5
- D. 3 5
Correct answer: D. 3 5
dp[j] = ways to form t[:j] from the processed prefix of s. Iterating j downwards ensures each character of s is used at most once per subsequence (like the 0/1 knapsack). "rabbbit" drops one of three b's → 3; "babgbag" → 5. O(|s|·|t|).
More Coding Interview Problems questions
- Problem: Find the longest increasing path in a matrix (moving up/down/left/right to strictly larger values). python from functools import…
- Problem: Find the cheapest way to cut a stick of length n at given positions; each cut costs the current piece's length. python from…
- Problem: Burst balloons; bursting balloon i earns left × a[i] × right with its current neighbours (1 beyond the ends). Maximise coins…
- Problem: Find the minimum number of intervals to remove so that the rest are non-overlapping – implemented with sort by START and keeping…
- Problem: Find the length of the longest valid (well-formed) parentheses substring. python def longestvalid(s): st, best = [-1], 0 for i…
- Problem: Return the number of provinces (connected components) from an adjacency matrix using DFS. java static int provinces(int[][] m) {…