Data Structures & AlgorithmsVery hardProduct company OA
Problem: Is c formed by interleaving a and b (keeping each string's internal order)? dp[i][j] = first i chars of a and j chars of b can form c[:i+j].
Problem: Is c formed by interleaving a and b (keeping each string's internal order)? dp[i][j] = first i chars of a and j chars of b can form c[:i+j].
def interleave(a, b, c):
if len(a) + len(b) != len(c): return False
dp = [[False] * (len(b) + 1) for _ in range(len(a) + 1)]
dp[0][0] = True
for i in range(len(a) + 1):
for j in range(len(b) + 1):
if i and a[i - 1] == c[i + j - 1] and dp[i - 1][j]: dp[i][j] = True
if j and b[j - 1] == c[i + j - 1] and dp[i][j - 1]: dp[i][j] = True
return dp[-1][-1]
print(interleave("abc", "abd", "aabdbc"), interleave("abc", "abd", "abadcb"), interleave("ab", "ab", "abab"))What is printed?- A. False False True
- B. True True True
- C. True False True
- D. True False False
Correct answer: C. True False True
Greedy matching fails when both strings offer the same next letter, so the DP tries both. "aabdbc" = a(a) a(b) b(b) d(b) b(a) c(a) → True. "abadcb": 'c' would have to come before a's 'b', breaking a's order → False. "abab" works several ways. O(|a|·|b|).
More Coding Interview Problems questions
- Problem: Wildcard matching over the whole string: '?' matches any one character, '' matches any sequence (including empty). python def…
- Problem: Return (length of the longest strictly increasing subsequence, number of such longest subsequences). python def numlis(a): n =…
- Problem: With k identical eggs and an n-floor building, find the minimum number of drops that guarantees finding the critical floor. DP on…
- Problem: Two players alternately take a pile from either END of a row; both play optimally. Compute (first player's total − second…
- Problem: Maximum sum of a non-empty contiguous subarray where you may delete at most one element (the result must stay non-empty). Track…
- Problem: Assign 4 workers to 4 jobs (one each) minimising total cost with a bitmask DP over the set of jobs already taken; compare with…