You are given two lists of whole numbers, nums1 and nums2.
Find the longest stretch of consecutive values that appears, in the same order and without gaps, in both lists. Return its length, or 0 if the lists share no value at all.
Example 1
Input: nums1 = [4, 6, 2, 9, 6], nums2 = [6, 2, 9, 1] Output: 3 Why: [6, 2, 9] sits in both lists
2 more examples and the constraints
Example 2
Input: nums1 = [3, 3, 3], nums2 = [3, 3] Output: 2 Why: all of nums2 appears inside nums1
Example 3
Input: nums1 = [1, 2], nums2 = [3, 4] Output: 0 Why: no value is shared
Constraints
- 1 ≤ length of nums1, length of nums2 ≤ 1,000
- 0 ≤ nums1[i], nums2[i] ≤ 100
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Every pair of startsO(m·n·L)
- DP table on run endsO(m·n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for two lists of 1,000 zeros | Verdict |
|---|---|---|---|
| Every pair of starts | O(m·n·L) | Slow when runs are long | |
| DP table on run ends | O(m·n) | Best; one pass over the table |
m and n = list lengths, L = the shorter length.
Edge cases to test
- Nothing shared. [1, 2] and [3, 4] give 0.
- All values equal. [3, 3, 3] and [3, 3] give 2: the shorter list is the limit.
- A list of length 1. [5] and [7, 5, 7] give 1.
- Same values, wrong order. [1, 2, 3] and [3, 2, 1] share only single values: 1.
Common mistakes
- Solving longest common subsequence, which allows gaps, instead of a contiguous run.
- Returning
dp[m][n]instead of the largest cell: the best run can end anywhere. - Carrying the run across a mismatch instead of resetting it to 0.
How to talk through it
- 1Clarify. Does the shared piece have to be contiguous in both lists? Can the answer be 0?
- 2Give the brute force. Every pair of starts, walk while equal: O(m·n·L).
- 3Define the state. dp[i][j] is the run ending at both positions; it grows along a diagonal.
- 4Code the table. On equal values extend the diagonal, otherwise leave 0; track the maximum.
- 5Test out loud. Run no overlap, all equal values and a reversed list before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?