Skip to content

Commit c1f98ee

Browse files
committed
feat: Implement solution for "How Many Numbers Are Smaller Than the Current Number" problem
1 parent 1797278 commit c1f98ee

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Problem: https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/
2+
// Doc: https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/solutions/5503382/efficient-count-of-smaller-numbers-than-current/
3+
const smallerNumbersThanCurrent = (nums: number[]): number[] => {
4+
const counterMap: Record<number, number> = {};
5+
const sortedNums = [...nums].sort((a, b) => a - b);
6+
for (let i = 0; i < sortedNums.length; i++) {
7+
const num = sortedNums[i];
8+
if (!(num in counterMap)) counterMap[num] = i;
9+
}
10+
11+
return nums.map((num) => counterMap[num]);
12+
};
13+
14+
describe('How Many Numbers Are Smaller Than the Current Number', () => {
15+
it('#1 should return [4, 0, 1, 1, 3]', () => {
16+
const nums = [8, 1, 2, 2, 3];
17+
expect(smallerNumbersThanCurrent(nums)).toStrictEqual([4, 0, 1, 1, 3]);
18+
});
19+
20+
it('#2 should return [2, 1, 0, 3]', () => {
21+
const nums = [6, 5, 4, 8];
22+
expect(smallerNumbersThanCurrent(nums)).toStrictEqual([2, 1, 0, 3]);
23+
});
24+
25+
it('#3 should return [0, 0, 0, 0]', () => {
26+
const nums = [7, 7, 7, 7];
27+
expect(smallerNumbersThanCurrent(nums)).toStrictEqual([0, 0, 0, 0]);
28+
});
29+
30+
it('#4 should return [0, 0, 0, 0, 0]', () => {
31+
const nums = [1, 1, 1, 1, 1];
32+
expect(smallerNumbersThanCurrent(nums)).toStrictEqual([0, 0, 0, 0, 0]);
33+
});
34+
});

0 commit comments

Comments
 (0)