Ctrl K

Crown the Last Pair

Medium
You are given two arrays of the same length n: top and bottom. Elements with the same index form a pair, and in one operation you may pick an index i and swap top[i] with bottom[i]. You want the last element of each array to be its maximum: top[n - 1] is at least every element of top, and bottom[n - 1] is at least every element of bottom. Return the minimum number of swaps that satisfies both conditions, or -1 if that is impossible.
Example 1
top=[2, 8, 3], bottom=[6, 1, 9] → 1

Swap the pair at index 1: top = [2, 1, 3], bottom = [6, 8, 9]. Now 3 is the maximum of top and 9 is the maximum of bottom.

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

A single swap is enough: either the first pair or the last one.

Example 3
top=[5, 2], bottom=[6, 3] → -1

The pair (5, 6) beats both numbers of the last pair whichever way it is placed, so the condition cannot be met.

Constraints
  • 1 ≤ n ≤ 1000
  • len(top) == len(bottom) == n
  • 1 ≤ top[i], bottom[i] ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPrimes Below a Bound MediumLongest Ridge on the Route MediumLatest Clock From Digits MediumStrongest Signal Spot MediumFlanking Move on the Board Medium
loading Python…
Input
top=[2, 8, 3], bottom=[6, 1, 9]
Expected
1

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