Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Problem: Length of the longest common CONTIGUOUS subarray of two arrays (DP on suffix matches).
Problem: Length of the longest common CONTIGUOUS subarray of two arrays (DP on suffix matches).
def common(a, b):
dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]; best = 0
for i in range(len(a) - 1, -1, -1):
for j in range(len(b) - 1, -1, -1):
if a[i] == b[j]:
dp[i][j] = dp[i+1][j+1] + 1; best = max(best, dp[i][j])
return best
print(common([5, 1, 2, 3, 2, 1, 4], [3, 2, 1, 4, 7, 1, 2]))What is printed?- A. 3
- B. 4
- C. 5
- D. 2
Correct answer: B. 4
[3, 2, 1, 4] appears contiguously in both (a[3..6] and b[0..3]), length 4. A longest common SUBSEQUENCE would be allowed to skip elements and can be longer; here the contiguous answer is 4.
More Coding Interview Problems questions
- Problem: A knight makes k uniformly random moves (8 directions) on an n × n board; once it leaves the board it stays off. What is the…
- Problem: Choose the largest number of binary strings using at most m zeros and n ones in total (2-D 0/1 knapsack). python def most(strs…
- Problem: Delete characters from two strings so they become equal, minimising the sum of ASCII codes deleted. python def cost(a, b): m, n =…
- Problem: Two players alternately take a pile from either END of a row; both play optimally. Report (first player's total) − (second…
- Problem: Count the combinations (multisets) of candidates that sum to the target; each candidate may be used any number of times. python…
- Problem: AND of every integer in the range [lo, hi]. python def rangeand(lo, hi): shift = 0 while lo != hi: lo >>= 1; hi >>= 1; shift += 1…