Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

Longest common block

Medium · Target 15 minutes · Dynamic programming · Type asked atAmazon

Given two lists of integers nums1 and nums2, return the length of the longest contiguous block of values that appears in both. (For strings this is the longest common substring.)

Examples

InputOutputWhy
nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]3The block 3, 2, 1.
nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]5The whole list.
nums1 = [1,2], nums2 = [3,4]0No common value.

Constraints

  • 1 ≤ nums1.length, nums2.length ≤ 1000
  • 0 ≤ nums[i] ≤ 100

Hints

Hint 1

Unlike a subsequence, a block that is interrupted cannot continue. Fix where the block ends.

Hint 2

E[i][j] = length of the longest common block ending exactly at nums1[i − 1] and nums2[j − 1].

Hint 3

E[i][j] = E[i − 1][j − 1] + 1 on a match, else 0. The answer is the largest E anywhere.

Where people lose marks

  • Using the subsequence recurrence (max of above and left on a mismatch), which allows gaps.
  • Reading the answer from the bottom-right corner instead of taking the maximum entry.
  • Updating a single row left to right in place, which overwrites the diagonal value still needed (go right to left, or keep two rows).
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.