Skip to content

1365. How Many Numbers Are Smaller Than the Current Number 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
    constexpr int kMax = 100;
    vector<int> ans;
    vector<int> count(kMax + 1);

    for (const int num : nums)
      ++count[num];

    for (int i = 1; i <= kMax; ++i)
      count[i] += count[i - 1];

    for (const int num : nums)
      ans.push_back(num == 0 ? 0 : count[num - 1]);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int[] smallerNumbersThanCurrent(int[] nums) {
    final int kMax = 100;
    int[] ans = new int[nums.length];
    int[] count = new int[kMax + 1];

    for (final int num : nums)
      ++count[num];

    for (int i = 1; i <= kMax; ++i)
      count[i] += count[i - 1];

    for (int i = 0; i < nums.length; ++i)
      ans[i] = nums[i] == 0 ? 0 : count[nums[i] - 1];

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def smallerNumbersThanCurrent(self, nums: list[int]) -> list[int]:
    kMax = 100
    count = collections.Counter(nums)

    for i in range(1, kMax + 1):
      count[i] += count[i - 1]

    return [0 if num == 0 else count[num - 1]
            for num in nums]