Ctrl K

Strings Between Cards

Medium
Two rows of numbered cards lie on a table: the top row top and the bottom row bottom, each in the given order. A top card can be tied to a bottom card with a string if both show the same number. Strings are pulled straight and must not cross. Each card can hold at most one string, so even sharing an end counts as crossing. Return the largest number of strings you can stretch.
Example 1
top=[7, 3, 9, 3], bottom=[3, 7, 3, 9] → 3

Strings 7–7, 3–3 (the second top card to the third bottom card) and 9–9 do not cross. A fourth one is impossible: the last top 3 sits right of the 9, while the free bottom 3 sits left of it.

Example 2
top=[4, 4, 4], bottom=[4, 4] → 2

Only two pairs of 4s can be tied: there are just two cards at the bottom, and each card holds at most one string.

Example 3
top=[1, 2], bottom=[3, 4] → 0
Constraints
  • 1 ≤ len(top), len(bottom) ≤ 500
  • 1 ≤ top[i], bottom[j] ≤ 2000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFewest Jumps to the End MediumMost Profitable Streak MediumReach the Last Cell MediumWarehouse Cart Routes MediumCheapest Corner-to-Corner Route Medium
loading Python…
Input
top=[7, 3, 9, 3], bottom=[3, 7, 3, 9]
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 109 tests on the server, hidden ones included.