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 Inversion Pairs Count INPUT Array nums: 4 i=0 3 i=1 6 i=2 2 i=3 Parameters: nums = [4, 3, 6, 2] k = 2 (need 2 pairs) Possible Inversions: (0,1): 4 > 3, diff=1 (0,3): 4 > 2, diff=2 (1,3): 3 > 2, diff=1 (2,3): 6 > 2, diff=4 ALGORITHM STEPS 1 Binary Search Setup Search range: [0, max_diff] 2 Count Inversions For threshold x, count pairs 3 Check Count >= k Adjust search bounds 4 Find Minimum Return min threshold Threshold Analysis: x Pairs Count 0 none 0 1 (0,1)(1,3) 2 2 +(0,3) 3 4 +(2,3) 4 FINAL RESULT Minimum Threshold Found: 1 min_threshold = 1 Valid Pairs (x=1): Pair 1: (0,1) Pair 2: (1,3) OK - Count = 2 Meets k = 2 requirement Key Insight: Binary search on threshold value combined with efficient inversion counting. For each candidate threshold x, count inversions where nums[i] - nums[j] <= x. The minimum x where count >= k is our answer. Time: O(n log n log(max_diff)) TutorialsPoint - Minimum Threshold for Inversion Pairs Count | Sort and Count Efficiently Approach
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