Maximum Length of Repeated Subarray solution explained

Maximum Length of Repeated Subarray asks for the length of the longest block of consecutive values that appears in both of two arrays. The standard answer is a dynamic programming table where each cell holds the length of the common run ending at a pair of positions: one more than the diagonal cell on a match, zero on a mismatch. That is O(n × m) time and, with a single row updated right to left, O(min(n, m)) memory.

By Published 10 min read

The problem, in plain terms

Two sensors log a sequence of readings each. You want to know the longest stretch of back-to-back readings that both logs contain somewhere, in exactly the same order and with nothing in between. Positions do not have to line up: the stretch can start at index 1 in the first log and index 0 in the second. Return how long that stretch is, or 0 if the logs have no value in common.

Case A
  a = [4, 7, 1, 2, 9, 3]
  b = [7, 1, 2, 9, 5, 4, 7]
  shared blocks: [4, 7] (length 2), [7, 1, 2, 9] (length 4)
  answer: 4

Case B
  a = [5, 5]
  b = [6]
  answer: 0
Two cases, made up for this page

Questions to settle before coding: are the values small integers or anything hashable? Can either array be empty? Do you need the block itself or only its length? The base task wants the length, and returning the block is a one-line follow-up once you track where the best cell was.

Why interviewers like it

It checks whether you can define a DP state precisely. Many candidates write the longest common subsequence recurrence from memory, which takes the max of the left and upper neighbors on a mismatch, and get an answer that is too large. Saying out loud that the state is the run ending exactly at i and j, and therefore must break on a mismatch, is the whole insight. The space optimization then tests whether you understand which cells a row still needs.

Brute force: extend from every pair of starts

Try every start position i in a and j in b, and walk forward while the values agree. Keep the longest walk. With n and m elements this is O(n × m × min(n, m)) in the worst case, for example two arrays of the same repeated value. It is still the right first answer to say, and it is the reference the faster versions were tested against.

def longest_common_run_brute(a, b):
    best = 0
    for i in range(len(a)):
        for j in range(len(b)):
            k = 0
            while i + k < len(a) and j + k < len(b) and a[i + k] == b[j + k]:
                k += 1
            best = max(best, k)
    return best
Python: every pair of starts, extended while equal

The waste is easy to point at. If a block starting at (i, j) has length 5, then the block starting at (i + 1, j + 1) has length 4, and the brute force recounts it from scratch. Dynamic programming stores the run that ends at each pair so each one is computed once.

Dynamic programming: the run ending at (i, j)

Let run[i][j] be the length of the common block that ends exactly at a[i - 1] and b[j - 1], using one-based table indexes so row 0 and column 0 are zero padding. If the two values differ, no common block can end there, so the cell is 0. If they match, the block ending one step earlier on both sides can be extended by one, so the cell is run[i - 1][j - 1] + 1. Every common block ends somewhere, so the answer is the largest cell anywhere in the table.

           7  1  2  9  5  4  7
      4    .  .  .  .  .  1  .
      7    1  .  .  .  .  .  2
      1    .  2  .  .  .  .  .
      2    .  .  3  .  .  .  .
      9    .  .  .  4  .  .  .
      3    .  .  .  .  .  .  .
  largest cell: 4, on the diagonal that starts at (7, 7)
Table for Case A (rows: a, columns: b, only non-zero cells shown)

Each cell reads only its upper-left neighbor. That means a single row can hold the table if you update it from right to left: when you write position j, position j - 1 still holds the value from the previous row, which is exactly the diagonal you need. Sweeping left to right would overwrite it first and silently produce wrong answers.

def longest_common_run(a, b):
    if len(b) > len(a):
        a, b = b, a  # keep the row as short as possible
    row = [0] * (len(b) + 1)
    best = 0
    for x in a:
        for j in range(len(b), 0, -1):
            if x == b[j - 1]:
                row[j] = row[j - 1] + 1
                if row[j] > best:
                    best = row[j]
            else:
                row[j] = 0  # a mismatch breaks the run
    return best
Python: one row, swept right to left. O(n × m) time, O(min(n, m)) memory.

The else branch is not optional. In the full table every cell is written fresh, but in one reused row a stale value from the previous row would survive a mismatch and leak into the next diagonal. The JavaScript version uses a typed array, which starts filled with zeros and keeps the inner loop tight.

function longestCommonRun(a, b) {
  if (b.length > a.length) [a, b] = [b, a];
  const row = new Int32Array(b.length + 1);
  let best = 0;
  for (const x of a) {
    for (let j = b.length; j >= 1; j--) {
      if (x === b[j - 1]) {
        row[j] = row[j - 1] + 1;
        if (row[j] > best) best = row[j];
      } else {
        row[j] = 0;
      }
    }
  }
  return best;
}
JavaScript: the same single-row sweep

Faster follow-up: binary search on the length

If a common block of length L exists, a common block of every shorter length exists too, because you can trim it. That monotonic yes-then-no shape allows a binary search on L. For a given L, hash every window of length L in one array with a rolling hash, then slide over the other array and look each window up. A hash match is only a candidate, so compare the actual values before saying yes; skipping that check is how collisions turn into wrong answers. Each check is O(n + m) on average, so the whole search is O((n + m) log min(n, m)).

def has_common_run(a, b, length):
    if length == 0:
        return True
    mod = (1 << 61) - 1
    base = 1_000_003
    top = pow(base, length - 1, mod)

    def windows(arr):
        h = 0
        for i, x in enumerate(arr):
            if i >= length:
                h = (h - arr[i - length] * top) % mod
            h = (h * base + x) % mod
            if i >= length - 1:
                yield h, i - length + 1

    seen = {}
    for h, start in windows(a):
        seen.setdefault(h, []).append(start)
    for h, start in windows(b):
        for s in seen.get(h, ()):
            if a[s:s + length] == b[start:start + length]:
                return True
    return False


def longest_common_run_search(a, b):
    lo, hi = 0, min(len(a), len(b))
    while lo < hi:
        mid = (lo + hi + 1) // 2
        if has_common_run(a, b, mid):
            lo = mid
        else:
            hi = mid - 1
    return lo
Python: binary search on L with a verified rolling hash

The verification step can cost more than linear time on adversarial inputs full of repeats, so present this as the average-case improvement it is. A suffix automaton or suffix array gives a guaranteed linear or near-linear bound, which is worth naming but rarely expected in a 45-minute round. Python integers do not overflow, which keeps the hash simple; in JavaScript you would need BigInt or a smaller modulus to keep products exact.

Complexity summary

n and m are the two array lengths
ApproachTimeExtra memoryNote
Every pair of startsO(n × m × min(n, m))O(1)Reference only
Full DP tableO(n × m)O(n × m)Easiest to explain and debug
One row, right to leftO(n × m)O(min(n, m))Expected answer
Binary search plus rolling hashO((n + m) log min(n, m)) on averageO(n + m)Follow-up; verify every hash hit
n and m are the two array lengths. Scroll sideways on a small screen.

Edge cases to try

  • Either array empty: the answer is 0, and the loops must not index past the end.
  • No value in common: every cell stays 0.
  • One array contained whole in the other: the answer is the shorter length.
  • Both arrays made of one repeated value: the brute force hits its worst case, the DP does not care.
  • Two shared blocks of different lengths, like Case A: checks that you take the maximum over all cells, not the last cell.
  • A two-value alphabet such as 0s and 1s: many short partial matches, which is where a missing reset shows up.

Mistakes to avoid

  • Using the longest common subsequence rule on a mismatch (max of left and up). That answers a different question and overcounts.
  • Returning the bottom-right cell. The best block can end anywhere.
  • Sweeping the single row left to right, which overwrites the diagonal value before it is read.
  • Forgetting to write 0 on a mismatch in the rolling version, so last row's value leaks forward.
  • Trusting a rolling hash match without comparing the values.

Follow-ups

  • Return the block, not just its length. Remember the i where the best cell was set; the block is a[i - best : i].
  • The inputs are strings. This is the longest common substring problem, and the same table works character by character.
  • Allow gaps. Then it becomes longest common subsequence: on a mismatch take the larger of the left and upper cells instead of 0.
  • Many queries against one long array. Build a suffix structure once over the long array, then answer each query faster than a fresh table.

How to explain it out loud

Fictional example

Naming the state before the recurrence
Candidate
The brute force tries every pair of start positions and walks forward. It recounts the same overlap many times, so I want a table.
Candidate
My state is the length of the shared block that ends exactly at a[i] and b[j]. Because it has to end there, a mismatch means zero, and a match means the diagonal plus one.
Interviewer
What is the answer, then?
Candidate
The largest value anywhere in the table, since the block could end at any pair. That is O(n times m).
Candidate
Each cell only needs its upper-left neighbor, so I can keep one row and update it from right to left. Memory drops to the shorter length.

Count Square Submatrices with All Ones uses the same idea of a cell that measures a shape ending at that cell, in two dimensions. Longest Arithmetic Subsequence is another pairwise table, this time keyed by a difference. Maximum Subarray is the one-array version of a run that resets when it stops paying off. Longest common subsequence is the gap-allowing sibling to mention when the interviewer changes the rules.

Practicing it with Natively

The hard part of this problem is saying the state definition clearly enough that the reset on a mismatch sounds obvious. Natively runs on Mac and Windows; in a practice session it can read the problem from a screenshot and sketch the table approach, and it keeps a transcript of your spoken answer so you can check whether you explained why the row is swept backward. See the AI coding interview helper for how that works.

Questions people ask

How do you solve Maximum Length of Repeated Subarray?

Build a table where cell (i, j) is the length of the common block ending at a[i] and b[j]: the upper-left cell plus one when the values match, and 0 when they do not. The answer is the largest cell in the table.

What is the time complexity of Maximum Length of Repeated Subarray?

The dynamic programming solution is O(n × m) time. Keeping a single row and updating it from right to left cuts memory to O(min(n, m)). Binary search on the length with a rolling hash is faster on average.

How is it different from longest common subsequence?

A subarray must be contiguous, so a mismatch resets the cell to 0. Longest common subsequence allows gaps, so on a mismatch it takes the larger of the left and upper cells instead.

Why update the single row from right to left?

Each cell needs the upper-left value from the previous row. Going right to left means position j - 1 has not been overwritten yet when position j reads it.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP