LeetCode 315, Hard. Topics: Array, Binary Search, Divide and Conquer, Binary Indexed Tree, Segment Tree, Merge Sort, Ordered Set, Treap. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 22 parametrized pytest cases, and a playground notebook:
Problem
Given an integer array nums, return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i].
Examples
Explanation:
To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.
Constraints
- 1 <= nums.length <= 10^5
- -10^4 <= nums[i] <= 10^4
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
Last modified on September 7, 2026