← Questions
Longest common contiguous subarray
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Amazon's coding round, last asked Sep 2025. It tests dynamic programming and sliding window.
Given two integer arrays, return the length of the longest run of values that appears contiguously in both, and a pair of starting indices where it occurs.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
longest_common_subarray(a: list[int], b: list[int]) -> tuple[int, int, int]—(length, start_in_a, start_in_b); any one pair of starts if several runs tie;(0, 0, 0)if the arrays share no value.
Example
longest_common_subarray([1, 2, 3, 2, 1], [3, 2, 1, 4, 7]) -> (3, 2, 0) # [3, 2, 1]
longest_common_subarray([0, 0, 0, 0, 0], [0, 0, 0, 0, 0]) -> (5, 0, 0)
longest_common_subarray([1, 2], [3, 4]) -> (0, 0, 0)
Constraints
-
1 <= len(a), len(b) <= 1000for the dynamic program; discuss what changes at 10^5. - Values are integers.
Clarifying questions
- Contiguous in both arrays? (Yes, unlike the longest common subsequence.)
- If several runs tie, which starting indices?
- How large can the arrays be?
What a strong answer covers
- Dynamic programming:
dp[i][j]is the length of the common run ending ata[i-1]andb[j-1], equal todp[i-1][j-1] + 1when the values match and 0 otherwise; track the maximum and where it ends. O(n · m) time. - Memory cut to O(min(n, m)) with one row, filled right to left (or two rows).
- For long arrays: binary search on the length
L, checking with rolling hashes whether some run of lengthLappears in both, O((n + m) log min(n, m)) expected; verifying hash matches to rule out collisions. A suffix automaton or suffix array as the linear-time option. - Edge cases: no common value, identical arrays, the run at the very end.
Follow-ups
- Return the run itself, or every run of the maximum length.
- Find the longest run common to
karrays. - Allow at most one mismatch inside the run.
Where it's asked
- Amazon · Coding · Last asked Sep 202555 min · Usually two rounds; one is often an object-oriented design built in steps · No AI
What it tests
dynamic programming · sliding window
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
