KatInterview

Longest Shared Run Between Two Integer Lists

Dynamic ProgrammingAuto-graded · 22 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingarrayssubarray

Last 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:

  • length is the largest L for which some run of L consecutive elements of first is identical (same values, same order) to some run of L consecutive elements of second.
  • start_first and start_second are the 0-based positions at which such a run begins in first and second, so that first[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 an O(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.