Connect with us

LeetCode

LeetCode 1365: How Many Numbers Are Smaller Than the Current Number – Python Solution

This code sorts the input list and returns a list where each element represents the count of numbers in the original list that are smaller than it.

Published

on

This code below is the Python solution for the LeetCode 1365 problem called ‘How Many Numbers Are Smaller Than the Current Number’. It sorts the input list and uses the sorted list to determine how many numbers in the original list are smaller than each element.

class Solution:
    def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
        # sorted() returns a new list
        sorted_list = sorted(nums)
        return [sorted_list.index(num) for num in nums]

It first creates a sorted version of the input list using sorted(), which ensures the list’s elements are in ascending order (i.e., small to large values). For each element in the original list, it proceeds to find its position in the sorted list. The position of an element in the sorted list indicates how many elements are smaller than it, because the list is sorted. This method constructs a new list with these positions and returns it.

For example, given nums = [8, 1, 2, 2, 3], sorting it results in [1, 2, 2, 3, 8]. This Python algorithm therefore finds the index of each element in the original list within this sorted list, producing [4, 0, 1, 1, 3]. This final list indicates the number of smaller elements for each corresponding element in the original list. It must be noted that this example is taken directly from the original LeetCode 1365 question.

Trending