811. Longest Shared Stretch

Two sensors log integer readings: a from the first sensor and b from the second. A stretch is a run of consecutive readings. You want to find a stretch that appears, with exactly the same values in the same order, somewhere inside both logs.

Return the length of the longest such shared stretch. If the logs have no reading in common, return 0.

Unlike a subsequence, the readings in a stretch must be neighbours in each log. Aim for time O(n*m) and extra space O(m), where n and m are the lengths of the logs.

Example 1

Input:
a = [4,8,2,6,6,1], b = [9,2,6,6,1,3]
Output:
4
Explanation:

The block 2, 6, 6, 1 appears in both arrays and no longer shared block exists.

Example 2

Input:
a = [5,5,7,5,5,5], b = [5,5,5,2]
Output:
3
Explanation:

The block 5, 5, 5 closes the first array and opens the second, so the longest shared stretch is 3.

Constraints

1 ≤ a.length, b.length ≤ 500

0 ≤ a[i], b[j] ≤ 100

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 600 msC++ 150 msJava 300 msJavaScript 300 msTypeScript 300 ms

Expected complexity

Time
O(n*m)
Space
O(m)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…