Minimum Inversion Count in Subarrays of Fixed Length Problem
Description
LeetCode Problem 3768.
You are given an integer array nums of length n and an integer k.
An inversion is a pair of indices (i, j) from nums such that i < j and nums[i] > nums[j].
The inversion count of a subarray is the number of inversions within it.
Return the minimum inversion count among all subarrays of nums with length k.
Example 1:
Input: nums = [3,1,2,5,4], k = 3
Output: 0
Explanation:
We consider all subarrays of length k = 3 (indices below are relative to each subarray):
- [3, 1, 2] has 2 inversions: (0, 1) and (0, 2).
- [1, 2, 5] has 0 inversions.
- [2, 5, 4] has 1 inversion: (1, 2).
The minimum inversion count among all subarrays of length 3 is 0, achieved by subarray [1, 2, 5].
Example 2:
Input: nums = [5,3,2,1], k = 4
Output: 6
Explanation:
There is only one subarray of length k = 4: [5, 3, 2, 1].
Within this subarray, the inversions are: (0, 1), (0, 2), (0, 3), (1, 2), (1, 3), and (2, 3).
Total inversions is 6, so the minimum inversion count is 6.
Example 3:
Input: nums = [2,1], k = 1
Output: 0
Explanation:
All subarrays of length k = 1 contain only one element, so no inversions are possible.
The minimum inversion count is therefore 0.
Constraints:
1 <= n == nums.length <= 10^51 <= nums[i] <= 10^91 <= k <= n
Solution
Approach: Sliding Window + Fenwick Tree
Sliding the window one step to the right removes the leftmost element and adds a new element on the right, so the inversion count can be updated instead of recomputed.
Compress the values to ranks and keep a Fenwick tree (binary indexed tree) with the ranks of the elements currently in the window. When the leftmost element x leaves, it was the first element of every inversion it took part in, so we subtract the number of window elements smaller than x. When a new element y arrives, it is the last element of each of its inversions, so we add the number of window elements larger than y. After each step that has a full window, we update the minimum.
Complexity: time O(n log n), space O(n), where n is the length of the array.
class Solution:
def minInversionCount(self, nums: List[int], k: int) -> int:
n = len(nums)
ranks = {v: i + 1 for i, v in enumerate(sorted(set(nums)))}
m = len(ranks)
tree = [0] * (m + 1)
def update(i: int, delta: int) -> None:
while i <= m:
tree[i] += delta
i += i & -i
def query(i: int) -> int:
s = 0
while i > 0:
s += tree[i]
i -= i & -i
return s
cur = 0
ans = 0
for i in range(n):
if i >= k:
# drop the leftmost element: it formed an inversion with every smaller one after it
left = ranks[nums[i - k]]
update(left, -1)
cur -= query(left - 1)
# add nums[i]: it forms an inversion with every larger element already in the window
r = ranks[nums[i]]
cur += min(i, k - 1) - query(r)
update(r, 1)
if i >= k - 1:
ans = cur if i == k - 1 else min(ans, cur)
return ans