LeetCode #1365 “How Many Numbers Are Smaller Than the Current Number”

Opening

This is listed as an easy problem. This is their description:

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).
Input: nums = [6,5,4,8]
Output: [2,1,0,3]
Input: nums = [7,7,7,7]
Output: [0,0,0,0]
  • 0 <= nums[i] <= 100

Solution

First, you want to find out what you are being asked to do and what you are given. I don’t think the constraint helps too much.

for each number n
for each number in the list smaller than n, increment a counter
put the counter in a new list after all numbers have been compared with
return the list
from typing import Listclass Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
result = []
for num in nums:
count = 0
for comp in nums:
if num > comp:
count += 1
result.append(count)
return result
# Input
nums = [6,5,4,8]
new_nums = sorted(nums, reverse=True)
new_nums # [8,6,5,4]
# Output
[3,2,1,0]
from typing import List class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
result = {}
for i, n in enumerate(sorted(nums)):
if n not in result:
result[n] = i

return [result[n] for n in nums]
i  n
0 4
1 5
2 6
3 8
answer = []
for n in nums:
answer.append(result[n])
return answer

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store