#3768
Minimum Inversion Count in Subarrays of Fixed Length
HardArraySegment TreeSliding WindowFenwick TreeSliding Window
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
Using a Fenwick Tree (BIT) allows us to efficiently count inversions as we slide the window across the array, maintaining counts dynamically.
⚙️
Algorithm
3 steps- 1Step 1: Compress the values in nums to a range of 1 to n.
- 2Step 2: Initialize a Fenwick Tree to count occurrences of elements in the current window.
- 3Step 3: For each new element added to the window, update the tree and count inversions, then slide the window by removing the oldest element.
solution.py30 lines
1class FenwickTree:
2 def __init__(self, size):
3 self.size = size
4 self.tree = [0] * (size + 1)
5 def update(self, index, delta):
6 while index <= self.size:
7 self.tree[index] += delta
8 index += index & -index
9 def query(self, index):
10 sum = 0
11 while index > 0:
12 sum += self.tree[index]
13 index -= index & -index
14 return sum
15
16def min_inversion_count(nums, k):
17 compressed = {v: i + 1 for i, v in enumerate(sorted(set(nums))) }
18 ft = FenwickTree(len(compressed))
19 inversions = 0
20 for i in range(k):
21 inversions += i - ft.query(compressed[nums[i]] - 1)
22 ft.update(compressed[nums[i]], 1)
23 min_inversions = inversions
24 for i in range(k, len(nums)):
25 inversions += k - ft.query(compressed[nums[i]])
26 inversions -= ft.query(compressed[nums[i - k]])
27 ft.update(compressed[nums[i]], 1)
28 ft.update(compressed[nums[i - k]], -1)
29 min_inversions = min(min_inversions, inversions)
30 return min_inversionsℹ
Complexity note: The Fenwick Tree operations are O(log n), and we perform them for each of the n elements.
- 1Inversions count can be efficiently tracked using data structures like Fenwick Tree.
- 2Sliding window technique helps in maintaining the current state without recalculating from scratch.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.