315-count-of-smaller-numbers-after-self

Try it on leetcode

Description

You are given an integer array nums and you have to return a new counts array. The counts array has the property 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

Solution(Python)

class SelfBST:
    def __init__(self, arr, n):
        self.n = n
        self.cntArray = [0] * n

    def cntArr(self):
        return self.cntArray


class Solution:
    def countSmaller(self, nums: List[int]) -> List[int]:
        return self.selfBalanceBst(nums)

    # Time Complexity: O(n^2)
    # Space Complexity: O(n)
    def naive(self, nums: List[int]) -> List[int]:
        n = len(nums)
        res = [0] * n
        for i in range(n):
            for j in range(i + 1, n):
                if nums[j] < nums[i]:
                    res[i] += 1
        return res

    # Time Complexity: O(nlogn)
    # Space Complexity: O(n)
    def selfBalanceBst(self, nums: List[int]) -> List[int]:
        rank, N, res = {val: i + 1 for i,
                        val in enumerate(sorted(nums))}, len(nums), []
        BITree = [0] * (N + 1)

        def update(i):
            while i <= N:
                BITree[i] += 1
                i += i & -i

        def getSum(i):
            s = 0
            while i:
                s += BITree[i]
                i -= i & -i
            return s

        for x in reversed(nums):
            res += (getSum(rank[x] - 1),)
            update(rank[x])
        return res[::-1]