How Many Numbers Are Smaller Than the Current Number

easy hash map counting sort

Problem

You are given an array nums whose values all lie between 0 and 100. For each element nums[i], report how many elements of the array (at any other index) are strictly smaller than it. Return these counts as an array aligned with the input.

The small value range is the whole trick: instead of comparing every pair, count how often each value 0..100 appears, then a prefix sum over the buckets tells you, for every value v, exactly how many numbers are below it.

Inputnums = [8, 1, 2, 2, 3]
Output[4, 0, 1, 1, 3]
Four values (1, 2, 2, 3) are smaller than 8; nothing is smaller than 1; only the 1 is smaller than each 2; three values (1, 2, 2) are smaller than 3.

def smaller_numbers_than_current(nums):
    count = [0] * 101
    for x in nums:
        count[x] += 1
    smaller = [0] * 101
    running = 0
    for v in range(101):
        smaller[v] = running
        running += count[v]
    return [smaller[x] for x in nums]
function smallerNumbersThanCurrent(nums) {
  const count = new Array(101).fill(0);
  for (const x of nums) count[x]++;
  const smaller = new Array(101).fill(0);
  let running = 0;
  for (let v = 0; v <= 100; v++) {
    smaller[v] = running;
    running += count[v];
  }
  return nums.map(x => smaller[x]);
}
int[] smallerNumbersThanCurrent(int[] nums) {
    int[] count = new int[101];
    for (int x : nums) count[x]++;
    int[] smaller = new int[101];
    int running = 0;
    for (int v = 0; v <= 100; v++) {
        smaller[v] = running;
        running += count[v];
    }
    int[] ans = new int[nums.length];
    for (int i = 0; i < nums.length; i++) ans[i] = smaller[nums[i]];
    return ans;
}
vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
    int count[101] = {0};
    for (int x : nums) count[x]++;
    int smaller[101] = {0};
    int running = 0;
    for (int v = 0; v <= 100; v++) {
        smaller[v] = running;
        running += count[v];
    }
    vector<int> ans;
    for (int x : nums) ans.push_back(smaller[x]);
    return ans;
}
Time: O(n + k), k = 101 Space: O(k)