All problems
0657MediumArrayBinary SearchDynamic ProgrammingSliding WindowRolling HashHash Function

Longest Shared Run of Road Segments

Tracked in this browser only
Write code

Trains the technique from

LeetCode 718Maximum Length of Repeated Subarray

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

Two delivery vans spent the day on the road, and each one's tracker wrote down the id of every road segment it drove, in order. route_a is the first van's list of legs and route_b is the second van's.

A dispatcher wants the longest piece of road the two vans covered identically: a run of consecutive legs taken from route_a that appears, in the same order and with no gaps, as a run of consecutive legs of route_b.

Return how many legs that longest run holds, or 0 when the vans never drove even a single segment in common.

Examples

Example 1

Input
route_a = [3, 6, 9, 12, 15, 18], route_b = [9, 12, 15, 18, 21]
Output
4

Legs 9, 12, 15, 18 sit consecutively in both lists, which is a shared run of four. Segment 21 is not in the first list and segments 3, 6 are not in the second, so the run cannot be stretched at either end.

Example 2

Input
route_a = [8, 4], route_b = [4, 4, 4]
Output
1

The only segment on both lists is 4, and the first van drove it once, so the shared run holds a single leg.

Example 3

Input
route_a = [11, 12, 13], route_b = [21, 22]
Output
0

No segment id appears on both lists, so the answer is 0.

Constraints

  • 1 <= route_a.length, route_b.length <= 1000
  • 0 <= route_a[i], route_b[i] <= 100

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def longest_shared_run(route_a: list[int], route_b: list[int]) -> int:
Java
public int longestSharedRun(int[] routeA, int[] routeB)
September 7
Apply