Minimum Threshold for Inversion Pairs Count - Problem

You are given an array of integers nums and an integer k. An inversion pair with a threshold x is defined as a pair of indices (i, j) such that:

  • i < j
  • nums[i] > nums[j]
  • The difference between the two numbers is at most x (i.e. nums[i] - nums[j] <= x)

Your task is to determine the minimum integer min_threshold such that there are at least k inversion pairs with threshold min_threshold. If no such integer exists, return -1.

Input & Output

Example 1 — Basic Case
$ Input: nums = [4,3,6,2], k = 2
Output: 1
💡 Note: Inversion pairs: (0,1) with diff=1, (0,3) with diff=2, (1,3) with diff=1, (2,3) with diff=4. With threshold=1, we have pairs (0,1) and (1,3), which gives us 2 pairs ≥ k=2.
Example 2 — Need Higher Threshold
$ Input: nums = [5,4,3,2], k = 3
Output: 2
💡 Note: Inversion pairs: (0,1)→1, (0,2)→2, (0,3)→3, (1,2)→1, (1,3)→2, (2,3)→1. Sorted differences: [1,1,1,2,2,3]. The 3rd smallest is 1, but we need threshold=2 to get exactly 3 pairs with diff ≤ 2.
Example 3 — No Solution
$ Input: nums = [1,2,3], k = 1
Output: -1
💡 Note: Array is already sorted, so no inversion pairs exist. Cannot find k=1 pairs, return -1.

Constraints

  • 2 ≤ nums.length ≤ 500
  • 1 ≤ nums[i] ≤ 106
  • 0 ≤ k ≤ n(n-1)/2

Visualization

Tap to expand
Minimum Threshold for k=2 Inversion PairsInput: nums = [4,3,6,2], k = 24362i=0i=1i=2i=3Inversion Pairs (i < j, nums[i] > nums[j]):• (0,1): 4 > 3, diff = 4-3 = 1• (0,3): 4 > 2, diff = 4-2 = 2• (1,3): 3 > 2, diff = 3-2 = 1• (2,3): 6 > 2, diff = 6-2 = 4Sorted differences: [1, 1, 2, 4]Threshold Analysis:• threshold=0: 0 pairs ≤ 0 → count=0 < k=2• threshold=1: pairs ≤ 1 → count=2 ≥ k=2 ✓ (minimum!)Output: 1
Understanding the Visualization
1
Input
Array [4,3,6,2] and k=2 (need 2+ pairs)
2
Find Pairs
Identify inversion pairs and their differences
3
Minimum Threshold
Find smallest threshold giving ≥k pairs
Key Takeaway
🎯 Key Insight: The minimum threshold is the k-th smallest difference among all inversion pairs
Asked in
Google 15 Amazon 12 Microsoft 8
8.9K Views
Medium Frequency
~25 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen