Reverse Pairs
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Bit Manipulation.
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
Input: nums = [1,3,2,3,1]
Output: 2
Input: nums = [2,4,3,5,1]
Output: 3
Approach 1
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
⏱ O(N^2) - Quadratic complexity.💾 O(1) - No extra space.
Approach 2
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 .
⏱ $O(N \log N)$💾 $O(N)$
Approach 3
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
⏱ O(N \log N) - Sorting takes $O(N \log N)$, and $N$ BIT operations take $O(N \log N)$.💾 O(N) - To store the BIT and rank map.
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.