How Many Numbers Are Smaller Than the Current Number

You are given an array nums, and you need to find out, for each element, how many numbers in the array are smaller than it. Return the answer in an array.

Approach

We’ll use the following approach to solve this problem:

  1. Create a result list to store the count of smaller numbers for each number in nums.
  2. For each number in nums, count how many numbers are smaller than it, and store the count in the result list.
  3. Return the result list.

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
    def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
        result = []
        for i in nums:
            count = 0
            for j in nums:
                if j < i:
                    count += 1
            result.append(count)
        return result

Example

Let’s take nums = [8,1,2,2,3] as an example:

  • For 8, there are 4 smaller numbers (1, 2, 2, 3).
  • For 1, there are 0 smaller numbers.
  • For 2, there is 1 smaller number (1).
  • For the other 2, there is 1 smaller number (1).
  • For 3, there are 3 smaller numbers (1, 2, 2).

So the output will be [4,0,1,1,3].

This solution works but is not highly efficient. It has a time complexity of (O(n^2)) where (n) is the length of the array nums. For larger inputs, a more optimized solution can be implemented, but this code is simple and clear for beginners and will work well within the given constraints.