Count of Smaller Numbers After Self - 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].
For each element at index i, count how many elements with indices j > i satisfy nums[j] < nums[i].
Example:
Input: nums = [5,2,6,1]
Output: [2,1,1,0]
Explanation:
- To the right of 5 there are 2 smaller elements (2 and 1)
- To the right of 2 there is 1 smaller element (1)
- To the right of 6 there is 1 smaller element (1)
- To the right of 1 there are 0 smaller elements
Input & Output
Example 1 — Basic Case
$
Input:
nums = [5,2,6,1]
›
Output:
[2,1,1,0]
💡 Note:
To the right of 5 there are 2 smaller elements (2 and 1). To the right of 2 there is 1 smaller element (1). To the right of 6 there is 1 smaller element (1). To the right of 1 there are 0 smaller elements.
Example 2 — Single Element
$
Input:
nums = [1]
›
Output:
[0]
💡 Note:
There are no elements to the right of the single element, so count is 0.
Example 3 — Sorted Array
$
Input:
nums = [1,2,3,4]
›
Output:
[0,0,0,0]
💡 Note:
Array is sorted in ascending order, so no element has smaller elements to its right.
Constraints
- 1 ≤ nums.length ≤ 105
- -104 ≤ nums[i] ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Array [5,2,6,1] with indices
2
Count Process
For each element, count smaller elements to the right
3
Result Array
Output [2,1,1,0] with counts
Key Takeaway
🎯 Key Insight: We need to efficiently count inversions - use merge sort or advanced data structures to achieve O(n log n) time complexity
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code