This question below given is driving me nuts.If anyone can help, please.
"Given an array Num of 'n' elements return an array A of length 'n' in which A[i] contains number of elements greater than Num[i] to its right in the initial array"
I saw an SO answer here but its contains solution of O(n^2). I need a solution of O(nlogn).
I have solution for "Count smaller elements to left of self". But modifying it didn't give me the required solution(refer for code below).
Any help is appreciated:)
class BinarySearchTreeNode(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.count = 1
self.leftTreeSize = 0
class BinarySearchTree(object):
def __init__(self):
self.root = None
def insert(self, val, root):
if not root:
self.root = BinarySearchTreeNode(val)
return 0
if val == root.val:
root.count += 1
return root.leftTreeSize
if val < root.val:
root.leftTreeSize += 1
if not root.left:
root.left = BinarySearchTreeNode(val)
return 0
return self.insert(val, root.left)
if not root.right:
root.right = BinarySearchTreeNode(val)
return root.count + root.leftTreeSize
return root.count + root.leftTreeSize + self.insert(val, root.right)
class Solution(object):
def countSmaller(self, nums):
tree = BinarySearchTree()
return [
tree.insert(nums[i], tree.root)
for i in range(len(nums) - 1, -1, -1)
][::-1]
print(Solution().countSmaller(nums = [1, 4, 2, 7]))
Example:
Given array [10, 7, 2, 6, 5]
then smaller to right count array is [4, 3, 0, 1, 0]
greater to left count array is [0, 1, 2, 2, 3]
Hope this helps...