Skip to content

Instantly share code, notes, and snippets.

@Jefferson-Aggor
Created July 23, 2025 11:52
Show Gist options
  • Select an option

  • Save Jefferson-Aggor/c75e30bdc427ee9df8ed45a6e6392249 to your computer and use it in GitHub Desktop.

Select an option

Save Jefferson-Aggor/c75e30bdc427ee9df8ed45a6e6392249 to your computer and use it in GitHub Desktop.
This is an implementation of counting the smaller numbers
const countSmallerToRight = (nums) => {
// Helper: Binary Indexed Tree O(nlog(n))
function BIT(size) {
const tree = new Array(size + 1).fill(0);
return {
// Update the tree: add 'delta' at the given index
update(index, delta) {
index += 1;
while (index < tree.length) {
tree[index] += delta;
index += index & -index;
}
},
// Query the prefix sum from index 0 to 'index'
query(index) {
index += 1;
let sum = 0;
while (index > 0) {
sum += tree[index];
index -= index & -index;
}
return sum;
},
};
}
// Main function to count smaller numbers to the right of each element.
const sorted = [...new Set(nums)].sort((a, b) => a - b);
const rank = new Map();
// Assign each unique value a rank (index in the sorted array)
for (let i = 0; i < sorted.length; i++) {
rank.set(sorted[i], i);
}
const bit = BIT(sorted.length);
const result = new Array(nums.length);
// Step 2: Traverse from right to left
for (let i = nums.length - 1; i >= 0; i--) {
const r = rank.get(nums[i]);
result[i] = bit.query(r - 1);
bit.update(r, 1);
}
return result;
};
console.log(countSmallerToRight([5, 4, 3, 2, 1]));
//This is the brute force approach
const countSmallerToRight = (arr) => {
let n = arr.length;
let countSmaller = new Array(n);
for (let i = 0; i < n; i++) {
countSmaller[i] = 0; // Time Complexity - O(n)
}
// Time Complexity - O(n^2)
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
if (arr[j] < arr[i]) {
countSmaller[i]++;
}
}
}
return countSmaller;
};
let arr = [5, 4, 3, 2, 1];
console.log(countSmallerToRight(arr));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment