Ctrl K

Farthest Fitting Pair

Medium
You are given two non-increasing arrays lower and upper: each element is no larger than the one before it. A pair of indices (i, j) fits when i ≤ j and lower[i] ≤ upper[j]; its length is j - i. Return the greatest length of a fitting pair. If no pair fits, return 0.
Example 1
lower=[9, 7, 4, 4, 1], upper=[12, 8, 6, 5, 2] → 1

The pair (2, 3) works since lower[2] = 4 is at most upper[3] = 5, giving distance 1. Pairs like (0, 1) fail because 9 > 8, and no pair at distance 2 fits, so the answer is 1.

Example 2
lower=[3, 3], upper=[10, 9, 9, 3] → 3

lower[0] = 3 fits under upper[3] = 3 at distance 3, the largest possible.

Example 3
lower=[50, 40], upper=[20, 10] → 0

No pair fits, so the answer is 0.

Constraints
  • 1 ≤ lower.length, upper.length ≤ 10⁵
  • 1 ≤ lower[i], upper[j] ≤ 10⁵
  • both arrays are non-increasing
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPair in a Sorted List MediumTriples Under a Limit MediumSpot the Extra Copy MediumWarm Every Cabin MediumPairs With a Fixed Gap Medium
loading Python…
Input
lower=[9, 7, 4, 4, 1], upper=[12, 8, 6, 5, 2]
Expected
1

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