Skip to content

Instantly share code, notes, and snippets.

@bgadrian
Created August 15, 2017 20:06
Show Gist options
  • Save bgadrian/3447f4580b917d97e32715a337318bc3 to your computer and use it in GitHub Desktop.
Save bgadrian/3447f4580b917d97e32715a337318bc3 to your computer and use it in GitHub Desktop.
Count the number of smaller numbers from my right (array)
//given an array arr, you have to return the amount of numbers that are smaller than arr[i] to the right.
// BSTree, complexity O(n squared)
var smaller = function (nums) {
var res = [], count = 0, i = nums.length - 2,thisCount = 0;
if (nums == null || nums.length == 0) return res;
var root = NewTreeNode(nums[nums.length - 1]);
res.push(0);
for (; i >= 0; i--) {
res.push(insertNodeAndCount(root, nums[i]));
}
//mutates&returns
return res.reverse();
}
var insertNodeAndCount = function (root, val) {
thisCount = 0;
while (true) {
if (val <= root.val) {
root.count++;
if (root.sm == null) {
root.sm = NewTreeNode(val); break;
} else {
root = root.sm;
}
} else {
thisCount += root.count;
if (root.big == null) {
root.big = NewTreeNode(val); break;
} else {
root = root.big;
}
}
}
return thisCount;
}
var NewTreeNode = function(val) {
return {
sm: undefined,
big: undefined,
val,
count: 1
}
}
console.log(smaller([5, 4, 3, 2, 1]), [4, 3, 2, 1, 0]);
console.log(smaller([1, 2, 3]), [0, 0, 0]);
console.log(smaller([1, 2, 0]), [1, 1, 0]);
console.log(smaller([1, 2, 1]), [0, 1, 0]);
console.log(smaller([1, 1, -1, 0, 0]), [3, 3, 0, 0, 0]);
console.log(smaller([5, 4, 7, 9, 2, 4, 4, 5, 6]), [4, 1, 5, 5, 0, 0, 0, 0, 0]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment