Uncrossed Lines

MediumDynamic Programming2d dp

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Two integer arrays nums1 and nums2 are written on two parallel horizontal lines, in order. You may draw a straight segment joining nums1[i] and nums2[j] only when nums1[i] == nums2[j]. Segments may not cross each other and may not share an endpoint, so each element is used by at most one segment. Return the maximum number of segments you can draw. An O(m * n) solution is expected.

Examples

Input: nums1 = [1,4,2], nums2 = [1,2,4]
Output: 2
Connect the 1s and either the 4s or the 2s; connecting both would cross.
Input: nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5,2]
Output: 3
For example 5-5, 1-1, 5-5 (or 2-2, 1-1, 2-2).
Input: nums1 = [1,3,7,1,7,5], nums2 = [1,9,2,5,1]
Output: 2
For example 1-1 and 5-5.

Constraints

  • 1 <= nums1.length, nums2.length <= 500
  • 1 <= nums1[i], nums2[j] <= 2000

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More 2d dp problems