#1365
How Many Numbers Are Smaller Than the Current Number
EasyApproaches
💡
Intuition
Time O(n²)Space O(1)
The brute force approach involves checking each number in the array against every other number to count how many are smaller. This is straightforward but inefficient for larger arrays.
⚙️
Algorithm
5 steps- 1Step 1: Initialize an empty result array of the same length as nums.
- 2Step 2: For each element nums[i], initialize a count to 0.
- 3Step 3: Loop through the array again and for each nums[j], if nums[j] < nums[i], increment the count.
- 4Step 4: Store the count in the result array at the index corresponding to nums[i].
- 5Step 5: Return the result array.
solution.py14 lines
1# Full working Python code
2
3def smallerNumbersThanCurrent(nums):
4 result = []
5 for i in range(len(nums)):
6 count = 0
7 for j in range(len(nums)):
8 if nums[j] < nums[i]:
9 count += 1
10 result.append(count)
11 return result
12
13# Example usage
14print(smallerNumbersThanCurrent([8,1,2,2,3]))ℹ
Complexity note: This complexity arises because we use two nested loops to compare each element with every other element in the array.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.