← Questions

Longest common contiguous subarray

0
AmazonCodingLast asked Sep 2025

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) <= 1000 for 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 at a[i-1] and b[j-1], equal to dp[i-1][j-1] + 1 when 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 length L appears 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 k arrays.
  • 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

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