Created
April 13, 2022 16:12
-
-
Save JbIPS/5f1e7d45548cb6d4eaca686b4abc18ed to your computer and use it in GitHub Desktop.
How much are smaller than I 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node { | |
constructor(value) { | |
this.val = value; | |
this.left = null; | |
this.right = null; | |
this.elemCount = 1 | |
this.leftCount = 0 | |
} | |
} | |
class Tree { | |
constructor(root) { | |
this.root = root; | |
} | |
insert(node) { | |
let current = this.root; | |
let count = 0; | |
let prev; | |
while(current !== null) { | |
prev = current; | |
if(node.val > current.val) { | |
count += (current.elemCount + current.leftCount); | |
current = current.right; | |
} else if(node.val < current.val) { | |
current.leftCount += 1; | |
current = current.left; | |
} else { | |
current = null; | |
prev.elemCount += 1 | |
} | |
} | |
if(prev.val > node.val) prev.left = node | |
else if(prev.val < node.val) prev.right = node | |
else return count + prev.leftCount; | |
return count | |
} | |
} | |
function smaller(arr) { | |
const t = new Tree(new Node(arr[arr.length - 1])) | |
const ans = [0] | |
for(let i = arr.length-2; i > -1; i--) { | |
ans.push(t.insert(new Node(arr[i]))) | |
} | |
return ans.reverse(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment