Longest Shared Run Between Two Integer Lists
Dynamic ProgrammingAuto-graded · 22 test casesLast updated
Find the longest block of consecutive values common to two integer lists, and report its length and the smallest pair of start positions, using dynamic programming over suffix matches.
You are given two integer lists, first and second. A run is a block of consecutive elements of a list. Find the longest run that occurs in both lists, and report where it begins in each list.
Return a list of three integers [length, start_first, start_second], where:
lengthis the largestLfor which some run ofLconsecutive elements offirstis identical (same values, same order) to some run ofLconsecutive elements ofsecond.start_firstandstart_secondare the 0-based positions at which such a run begins infirstandsecond, so thatfirst[start_first : start_first + length] == second[start_second : start_second + length].
Tie-breaking. Several pairs of start positions may achieve the maximum length. Among them, return the pair that is smallest in lexicographic order: the smallest start_first, and, if that is still tied, the smallest start_second.
Empty result. If either list is empty, or the lists have no element in common, return [0, 0, 0].
Note that the run must be contiguous in both lists. Skipping elements is not allowed.
Constraints
0 <= len(first), len(second)and both lengths are small enough for anO(len(first) * len(second))approach.- Elements are integers and may be negative or repeated.
- The output must be exactly
[length, start_first, start_second]following the tie-break rule above.
Examples
Example 1
Input: longest_shared_run([1, 2, 3, 2, 1], [3, 2, 1, 4, 7])
Output: [3, 2, 0]
Example 2
Input: longest_shared_run([0, 0, 0], [0, 0])
Output: [2, 0, 0]
Example 3
Input: longest_shared_run([1, 2, 3], [4, 5, 6])
Output: [0, 0, 0]
Example 4
Input: longest_shared_run([1, 2, 3, 2, 1], [1, 2, 3, 2, 1])
Output: [5, 0, 0]
Hints
Hint 1
Think about a table where cell (i, j) stores how many elements match in a row when you start comparing at first[i] and second[j].
Hint 2
If first[i] equals second[j], the match length at (i, j) is one more than at (i+1, j+1); otherwise it is 0, since a contiguous match cannot skip a mismatch.
Hint 3
Fill the table from the ends of the lists backwards, track the maximum, and when a cell ties the current best, keep it only if its (i, j) is lexicographically smaller.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Let match[i][j] be the number of consecutive equal elements when you line up first starting at index i with second starting at index j. In other words, it is the longest common prefix of first[i:] and second[j:].
- If
first[i] == second[j], thenmatch[i][j] = 1 + match[i+1][j+1]. - Otherwise
match[i][j] = 0, because a contiguous match cannot step over a mismatch.
The table has one extra row and column of zeros, which represent "past the end" and serve as the base case. Cells are filled with i and j both decreasing, since each cell depends on its down-right neighbour.
The answer is the largest value in the table. The cell holding it is directly the pair of start positions, because match is indexed by where the run begins.
Why it is correct
Every common run has a unique pair of start positions (i, j). The longest common run beginning at that pair extends while elements agree and stops at the first mismatch or at the end of either list, which is exactly what the recurrence computes. Taking the maximum over all pairs therefore considers every candidate.
For ties, the loops visit cells in decreasing (i, j) order, so a newly visited cell is lexicographically smaller than any visited before it. We update the best cell when the length is strictly larger, or when it equals the best length and the pair is lexicographically smaller. The final recorded cell is thus the smallest pair among all maximum-length matches. If no elements match, the best length stays 0 and the default (0, 0) is returned, giving [0, 0, 0].
Complexity
- Time:
O(n * m), constant work per cell. - Space:
O(n * m)for the table. Since rowionly reads rowi+1, two rows suffice, reducing space toO(m)without changing the visiting order or tie-breaking.
Reference solution
from typing import List
def longest_shared_run(first: List[int], second: List[int]) -> List[int]:
"""Return [length, start_first, start_second] for the longest run of
consecutive elements present in both lists. Ties are broken by the
lexicographically smallest (start_first, start_second). If there is no
common element (or a list is empty), return [0, 0, 0].
"""
n, m = len(first), len(second)
if n == 0 or m == 0:
return [0, 0, 0]
# match[i][j] = number of consecutive equal elements starting at
# first[i] and second[j]. Row n and column m are zero padding.
match = [[0] * (m + 1) for _ in range(n + 1)]
best_len = 0
best_i = 0
best_j = 0
for i in range(n - 1, -1, -1):
for j in range(m - 1, -1, -1):
if first[i] == second[j]:
cur = 1 + match[i + 1][j + 1]
match[i][j] = cur
if cur > best_len:
best_len = cur
best_i = i
best_j = j
elif cur == best_len and (i, j) < (best_i, best_j):
best_i = i
best_j = j
return [best_len, best_i, best_j]