Python 0493.py
class Solution:
def reversePairs(self, nums: List[int]) -> int:
result = 0
ordered = []
for n in nums:
pos = bisect_right(ordered, 2 * n)
big = len(ordered) - pos
result += big
insort(ordered, n)
return result
Difficulty
and has an acceptance rate of about 35% (1+ million submissions).
Typical patterns to solve this problem:
- Array
- Binary Indexed Tree
- Binary Search
- Divide And Conquer
- Merge Sort
- Ordered Set
- Segment Tree
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a single method reversePairs. The method receives a list of integers and returns the count of “reverse pairs” - pairs of indices (i, j) such that i < j and nums[i] > 2 * nums[j]. The algorithm processes the input from left to right, maintaining a dynamically sorted collection of the elements that have already been visited. For each new element it determines how many of the previously seen values are larger than twice the current value, adds that number to the running total, and then inserts the current value into the sorted collection. The use of binary-search based helpers from the bisect module enables each query and insertion to be performed in logarithmic time with respect to the size of the collection.
Key Steps
Initialization
result = 0
ordered = []
Two variables are created at the start of the method. result accumulates the total number of reverse pairs, while ordered will hold the elements that have already been processed in sorted order.
Iterating Over the Input
for n in nums:
...
The method iterates through the original list nums exactly once, handling each element n in the order it appears. This single pass guarantees that only elements with a smaller index than the current one are considered when counting pairs.
Counting Larger Elements
pos = bisect_right(ordered, 2 * n)
big = len(ordered) - pos
result += big
For the current element n, the code computes 2 * n and uses bisect_right to locate the insertion point that would keep ordered sorted if 2 * n were inserted. The returned index pos points to the first element in ordered that is greater than 2 * n. Subtracting pos from the length of ordered yields big, the number of previously seen elements that are strictly larger than 2 * n. This value is added to result, thereby counting all reverse pairs that end at the current index.
Maintaining the Sorted Collection
insort(ordered, n)
After the count for the current element is recorded, the element itself is inserted into ordered using insort. This function places n at the correct position to keep the list sorted, preserving the invariant required for subsequent binary searches.
Returning the Result
return result
When the loop finishes, result holds the total number of reverse pairs across the entire array, and it is returned to the caller.
Edge Cases Handled
The algorithm gracefully handles an empty input list. In that situation the for loop never executes, result remains zero, and the method returns 0, which is the correct count for an empty sequence.
When the input contains a single element, the loop runs once. The binary search on an empty ordered list yields a position of 0, big becomes 0, and after inserting the sole element the method still returns 0. This matches the expectation that no pair can be formed with only one element.
The code also works correctly when the list contains duplicate values. Because bisect_right returns the index after the last occurrence of 2 * n, any equal values are not counted as “larger than” and therefore are excluded from the pair count, adhering to the strict inequality required by the definition of a reverse pair.
Large integer values are safely processed because Python’s integer type automatically expands to arbitrary precision. Multiplying an element by 2 never overflows, and the comparison performed by bisect_right remains accurate regardless of magnitude.
Performance Optimizations
The central optimization is the use of a sorted list together with binary-search operations provided by the bisect module. By keeping the previously seen elements in order, the algorithm can determine the number of elements exceeding a threshold (2 * n) in logarithmic time rather than scanning the entire collection. The insort function also inserts while preserving order in logarithmic time, avoiding the need for a full re-sort after each insertion.
Because the algorithm processes each element exactly once and each step involves only O(log k) work where k is the number of elements already processed, the overall running time scales efficiently with the size of the input. The choice of a plain Python list for ordered leverages the highly optimized C implementation of the bisect functions, providing fast low-level operations without additional overhead.
Memory usage is limited to the ordered list, which stores a copy of the input elements in sorted form. No auxiliary structures such as hash tables or auxiliary arrays are allocated, keeping the footprint modest and proportional to the input size.
ELI5 - Simplified Explanation
Imagine a long line of numbered cards lying on a table. The goal here is to find pairs of cards where the first one is more than twice as big as the second one. To do this, the computer walks through the cards one by one from left to right.
As it looks at each card, it keeps a separate sorted stack of all the cards it has already seen. It uses the sorted stack to quickly figure out how many cards are already in there that are smaller than half of the current card. It knows that any card in that stack which is smaller than the current card divided by two must be part of a pair, so it counts those up. After counting, it carefully places the current card into the sorted stack so it stays perfectly organized for the next step. By keeping the stack sorted, the computer can find the right spot for each new number very fast without having to check every single card again. It keeps doing this for every card until the entire line has been checked.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | ||||||||
| leetcode.ca | C++ | Java | Python | Go | |||||
| LeetcodeHelp | C++ | Java | Python | ||||||
| Progiez | C++ | Java | Python | ||||||
| github | BigEggStudy | C# | |||||||
| black-shadows | C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| FelixFan1122 | Java | ||||||||
| fsq | C++ | ||||||||
| gouthampradhan | Java | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| linouk23 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| ruoru | Rust | ||||||||
| shreymehul | C# | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++ | ||||||||
| leetcode.ca | C++, Go, Java, Python | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| FelixFan1122 | Java | ||||||||
| fsq | C++ | ||||||||
| gouthampradhan | Java | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| linouk23 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| ruoru | Rust | ||||||||
| shreymehul | C# | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 315: Count of Smaller Numbers After Self
- problem 327: Count of Range Sum
- problem 2659: Make Array Empty
Solved On The Same Day
- problem 2558: Take Gifts From the Richest Pile
- problem 395: Longest Substring with At Least K Repeating Characters
- problem 932: Beautiful Array
- problem 1382: Balance a Binary Search Tree
- problem 1424: Diagonal Traverse II
- problem 2406: Divide Intervals Into Minimum Number of Groups
- problem 2593: Find Score of an Array After Marking All Elements
- problem 2611: Mice and Cheese
- problem 2679: Sum in a Matrix
- problem 2551: Put Marbles in Bags
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality