Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard
Problem: Length of the longest common subsequence of THREE strings (3-D DP).
Problem: Length of the longest common subsequence of THREE strings (3-D DP).
def lcs3(a, b, c):
dp = [[[0] * (len(c) + 1) for _ in range(len(b) + 1)] for _ in range(len(a) + 1)]
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
for k in range(1, len(c) + 1):
if a[i-1] == b[j-1] == c[k-1]: dp[i][j][k] = dp[i-1][j-1][k-1] + 1
else: dp[i][j][k] = max(dp[i-1][j][k], dp[i][j-1][k], dp[i][j][k-1])
return dp[-1][-1][-1]
print(lcs3("algorithm", "logarithm", "rhythm"))What is printed?- A. 4
- B. 5
- C. 6
- D. 3
Correct answer: A. 4
Pairwise LCS values do not combine: LCS(algorithm, logarithm) is long, but the third string 'rhythm' limits what all three share. Common to all three in order is 'rthm' (r, t, h, m) → 4. The 3-D table costs O(|a|·|b|·|c|).
More Coding Interview Problems questions
- Problem: Length of the longest strictly increasing path in a matrix (moves in 4 directions), with memoised DFS. python from functools…
- Problem: Smash stones pairwise (x ≤ y leaves y − x) until at most one remains; minimise the final weight. Equivalent to splitting into two…
- Problem: You may swap a[i] with b[i] at any indices. Find the minimum swaps making BOTH arrays strictly increasing (DP with 'swapped at i'…
- Problem: Remove every interval that is covered by another interval ([a, b] is covered by [c, d] if c ≤ a and b ≤ d); count those that…
- Problem: Delete the fewest characters from a string of a's and b's so that no 'b' comes before an 'a'. python def mindel(s): bseen = dels…
- Problem: Add two 32-bit integers without + or −, using XOR for the sum and AND-shift for the carry; Python needs explicit masking to…