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?
  1. A. 3
  2. B. 4
  3. C. 5
  4. 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

Exams that ask this topic