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
Count of Smaller Numbers After SelfInput Array:5261i=0i=1i=2i=3For each element, count smaller elements to the right:• nums[0]=5: elements 2,1 are smaller → count=2• nums[1]=2: element 1 is smaller → count=1• nums[2]=6: element 1 is smaller → count=1• nums[3]=1: no elements to the right → count=0Result Array:2110
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
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
98.3K Views
Medium Frequency
~35 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen