Skip to content

Instantly share code, notes, and snippets.

@JbIPS
Created April 13, 2022 16:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JbIPS/5f1e7d45548cb6d4eaca686b4abc18ed to your computer and use it in GitHub Desktop.
Save JbIPS/5f1e7d45548cb6d4eaca686b4abc18ed to your computer and use it in GitHub Desktop.
How much are smaller than I 2
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