How Many Numbers Are Smaller Than the Current Number - Problem

Given an array nums, for each nums[i] find out how many numbers in the array are smaller than it.

That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i].

Return the answer in an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [8,2,6,7,1,3]
Output: [4,1,3,4,0,2]
💡 Note: For 8: numbers 2,6,7,1,3 are smaller → count=4. For 2: only 1 is smaller → count=1. For 6: numbers 2,1,3 are smaller → count=3. For 7: numbers 2,6,1,3 are smaller → count=4. For 1: no numbers are smaller → count=0. For 3: numbers 2,1 are smaller → count=2.
Example 2 — Duplicate Values
$ Input: nums = [6,5,4,8]
Output: [2,1,0,3]
💡 Note: For 6: numbers 5,4 are smaller → count=2. For 5: only 4 is smaller → count=1. For 4: no numbers are smaller → count=0. For 8: numbers 6,5,4 are smaller → count=3.
Example 3 — All Same Values
$ Input: nums = [7,7,7,7]
Output: [0,0,0,0]
💡 Note: All elements are equal, so no element is smaller than any other element. Each count is 0.

Constraints

  • 2 ≤ nums.length ≤ 500
  • 0 ≤ nums[i] ≤ 100

Visualization

Tap to expand
Count Smaller Numbers INPUT nums = [8, 2, 6, 7, 1, 3] 8 i=0 2 i=1 6 i=2 7 i=3 1 i=4 3 i=5 For each element, count how many elements in the array are smaller than it. Example: nums[0] = 8 Smaller: 2,6,7,1,3 = 5 nums But 6,7 not smaller than 8 Only: 2,1,3 are smaller Wait: 6,7 are smaller! Count = 4 (2,6,7,1,3 except 8) Result[0] = 4 ALGORITHM STEPS 1 Sort with Index Create pairs (value, index) Sort by value Sorted: [(1,4),(2,1),(3,5), (6,2),(7,3),(8,0)] 2 Track Position Position in sorted array = count of smaller elements 3 Handle Duplicates Same values get same count Track last different value 4 Map Back Use original indices to place counts in result Time: O(n log n) Space: O(n) FINAL RESULT Processing each position: pos 0: val=1 --> count=0 pos 1: val=2 --> count=1 pos 2: val=3 --> count=2 pos 3: val=6 --> count=3 pos 4: val=7 --> count=3 pos 5: val=8 --> count=4 Map to original indices: idx 4 (val 1) --> result[4]=0 idx 1 (val 2) --> result[1]=1 idx 5 (val 3) --> result[5]=2 idx 2 (val 6) --> result[2]=3 idx 3 (val 7) --> result[3]=3 idx 0 (val 8) --> result[0]=4 Output: [4, 1, 3, 3, 0, 2] OK - All counts verified! Key Insight: Sorting transforms the problem: the position of each element in the sorted array directly tells us how many elements are smaller than it. By storing original indices, we can map these counts back to their correct positions in O(n log n) time. TutorialsPoint - How Many Numbers Are Smaller Than the Current Number | Optimal Solution
Asked in
Amazon 15 Microsoft 12 Apple 8
125.0K Views
Medium Frequency
~15 min Avg. Time
2.8K 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