Reverse Pairs
Master this topic with zero to advance depth.
Reverse Pairs
Given an integer array nums, return the number of reverse pairs in the array. A reverse pair is a pair such that and .
Examples
Level I: Brute Force (Nested Loops)
Intuition
Check every possible pair where . If the condition is met, increment the counter.
Thought Process
- Use a nested loop .
- Check if .
- Return count.
Pattern: All-Pairs Comparison
Level II: Merge Sort based Counting
Intuition
Similar to counting inversions, we can use merge sort to count reverse pairs. During the merge step, for each element in the left half, we find how many elements in the right half satisfy .
Level III: Optimal (Binary Indexed Tree / Fenwick Tree)
Intuition
As we iterate through the array, we want to count how many numbers seen so far are greater than . A Binary Indexed Tree (BIT) can efficiently handle point updates and prefix sums. Since values can be large, we use coordinate compression on all and .
Thought Process
- Collect all and and sort them to create distinct ranks (Coordinate Compression).
- Iterate through
numsfrom right to left (or left to right with adjustments):- Query BIT for how many elements are strictly less than .
- Update BIT with .
- This leverages the bitwise structure of indices in the BIT.
Pattern: BIT with Coordinate Compression
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.