Maximum Length of Repeated Subarray
Real-world version: Longest Shared Run of Road SegmentsThe statement here is our own: the same inputs, outputs and technique.
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 starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def longest_shared_run(route_a: list[int], route_b: list[int]) -> int:public int longestSharedRun(int[] routeA, int[] routeB)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 11 test cases: 11 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Longest Duplicate SubstringReal-world version: Longest Repeated Stretch on a Log LineHard
- Max Consecutive Ones IIIReal-world version: Longest Verified Backup StreakMedium
- Longest Increasing SubsequenceReal-world version: Longest Rising Anomaly PickMedium
- Subarray Product Less Than KReal-world version: Safe Stretches of the Filter CascadeMedium