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 Self INPUT nums = [5, 2, 6, 1] 5 i=0 2 i=1 6 i=2 1 i=3 For each element, count smaller elements to its right: nums[0]=5: [2,6,1] has 2,1 < 5 nums[1]=2: [6,1] has 1 < 2 nums[2]=6: [1] has 1 < 6 nums[3]=1: [] none smaller Counts: [2, 1, 1, 0] ALGORITHM STEPS 1 Merge Sort Approach Use modified merge sort to count inversions efficiently 2 Track Original Indices Pair each num with its index to update correct position 3 Merge and Count During merge, count elements from right that moved left 4 Accumulate Results Add counts at each merge to result array Merge Sort Tree [5,2,6,1] [5,2] [6,1] [5] [2] [6] [1] FINAL RESULT Output counts array: 2 1 1 0 i=0 i=1 i=2 i=3 Breakdown: 5 --> 2 smaller (2,1) 2 --> 1 smaller (1) 6 --> 1 smaller (1) 1 --> 0 smaller Complexity: Time: O(n log n) Space: O(n) OK - Optimal! Key Insight: Modified Merge Sort counts inversions while sorting. When merging two sorted halves, if an element from the right half is placed before elements from the left half, those left elements have smaller numbers after them. This reduces O(n^2) brute force to O(n log n) using divide-and-conquer. TutorialsPoint - Count of Smaller Numbers After Self | Merge Sort Approach
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
98.4K 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