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,3,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=3. 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: [8,2,6,7,1,3]Input Array8267132,6,7,1,312,1,32,6,1,3none2,1Result Array413302Each result[i] = count of elements smaller than nums[i]
Understanding the Visualization
1
Input Array
Given array with elements to analyze
2
Count Smaller
For each element, count how many are smaller
3
Result Array
Array of counts corresponding to input positions
Key Takeaway
🎯 Key Insight: For each element, count how many other elements in the array are smaller than it
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