-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Implement solution for "How Many Numbers Are Smaller Than the C…
…urrent Number" problem
- Loading branch information
1 parent
1797278
commit c1f98ee
Showing
1 changed file
with
34 additions
and
0 deletions.
There are no files selected for viewing
34 changes: 34 additions & 0 deletions
34
easy/how-many-numbers-are-smaller-than-the-current-number.test.ts
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
// Problem: https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/ | ||
// Doc: https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/solutions/5503382/efficient-count-of-smaller-numbers-than-current/ | ||
const smallerNumbersThanCurrent = (nums: number[]): number[] => { | ||
const counterMap: Record<number, number> = {}; | ||
const sortedNums = [...nums].sort((a, b) => a - b); | ||
for (let i = 0; i < sortedNums.length; i++) { | ||
const num = sortedNums[i]; | ||
if (!(num in counterMap)) counterMap[num] = i; | ||
} | ||
|
||
return nums.map((num) => counterMap[num]); | ||
}; | ||
|
||
describe('How Many Numbers Are Smaller Than the Current Number', () => { | ||
it('#1 should return [4, 0, 1, 1, 3]', () => { | ||
const nums = [8, 1, 2, 2, 3]; | ||
expect(smallerNumbersThanCurrent(nums)).toStrictEqual([4, 0, 1, 1, 3]); | ||
}); | ||
|
||
it('#2 should return [2, 1, 0, 3]', () => { | ||
const nums = [6, 5, 4, 8]; | ||
expect(smallerNumbersThanCurrent(nums)).toStrictEqual([2, 1, 0, 3]); | ||
}); | ||
|
||
it('#3 should return [0, 0, 0, 0]', () => { | ||
const nums = [7, 7, 7, 7]; | ||
expect(smallerNumbersThanCurrent(nums)).toStrictEqual([0, 0, 0, 0]); | ||
}); | ||
|
||
it('#4 should return [0, 0, 0, 0, 0]', () => { | ||
const nums = [1, 1, 1, 1, 1]; | ||
expect(smallerNumbersThanCurrent(nums)).toStrictEqual([0, 0, 0, 0, 0]); | ||
}); | ||
}); |