Skip to content

315. Count Of Smaller Numbers After Self

Array Binary Search Divide and Conquer Binary Indexed Tree Segment Tree Merge Sort Ordered Set

Problem - Count Of Smaller Numbers After Self

Hard

Given an integer array nums, return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i].

 

Example 1:

Input: nums = [5,2,6,1]
Output: [2,1,1,0]
Explanation:
To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.

Example 2:

Input: nums = [-1]
Output: [0]

Example 3:

Input: nums = [-1,-1]
Output: [0,0]

 

Constraints:

  • 1 <= nums.length <= 105
  • -104 <= nums[i] <= 104

Solutions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class BinaryTree:
    def __init__(self, num):
        self.n = num
        self.c = [0] * (num + 1)

    @staticmethod
    def lowbit(x):
        return x & -x

    def update(self, x, delta):
        while x <= self.n:
            self.c[x] += delta
            x += BinaryTree.lowbit(x)

    def query(self, x):
        s = 0
        while x > 0:
            s += self.c[x]
            x -= BinaryTree.lowbit(x)
        return s

class Solution:
    def countSmaller(self, nums: List[int]) -> List[int]:
        sorted_nums = sorted(set(nums))
        maped_nums = {val: i for i, val in enumerate(sorted_nums, 1)}
        tree = BinaryTree(len(maped_nums))
        result = []

        for val in nums[::-1]:
            x = maped_nums[val]
            tree.update(x, 1)
            result.append(tree.query(x - 1))

        return result[::-1]

Submission Stats:

  • Runtime: 820 ms (77.64%)
  • Memory: 37.9 MB (43.75%)