How Many Numbers Are Smaller Than the Current Number Problem
Description
LeetCode Problem 1365.
Given the 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.
Example 1:
Input: nums = [8,1,2,2,3]
Output: [4,0,1,1,3]
Explanation:
For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3).
For nums[1]=1 does not exist any smaller number than it.
For nums[2]=2 there exist one smaller number than it (1).
For nums[3]=2 there exist one smaller number than it (1).
For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).
Example 2:
Input: nums = [6,5,4,8]
Output: [2,1,0,3]
Example 3:
Input: nums = [7,7,7,7]
Output: [0,0,0,0]
Constraints:
2 <= nums.length <= 5000 <= nums[i] <= 100
Solution
Approach: Counting with Prefix Sums
Comparing every pair works for 500 numbers, but the small value range (0 to 100) allows a linear solution.
Count how often each value occurs. The number of elements smaller than x is then the total count of all values 0, 1, ..., x - 1, a prefix sum over the counts. Build an array smaller where smaller[v] is the number of elements less than v:
- For each
x, add 1 tosmaller[x + 1](an elementxis smaller than every value fromx + 1up). - Take running sums:
smaller[v] += smaller[v - 1]. - The answer for
nums[i]issmaller[nums[i]].
Equal values do not count, because the comparison is strict: in [7,7,7,7] every answer is 0, and in Example 1 both 2s get 1 (only the 1 is smaller). Shifting the count to x + 1 is what keeps a value from counting itself and its duplicates.
(Without the small range, sort a copy and use binary search: the number of elements smaller than x is the index of the first x in the sorted copy, for O(n log n) time.)
Complexity: O(n + m) time and O(m) extra space, where m = 101 is the size of the value range.
class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
# smaller[v] = how many numbers are < v; values are between 0 and 100.
smaller = [0] * 102
for x in nums:
smaller[x + 1] += 1
for v in range(1, 102):
smaller[v] += smaller[v - 1]
return [smaller[x] for x in nums]