How many numbers are smaller than the current number
Solution
- Just sort the array, and loop through it
- The index will tell you how many numbers were smaller
- This makes complete logical sense, just think about it, it's not that hard
| Time | Space | Explanation |
|---|
O(n log n) | O(m) | where m is the number of unique numbers in the array |
function smallerNumbersThanCurrent(nums: number[]): number[] {
const sortedNums = nums.slice().sort((a, b) => a - b);
const seen = {}
for(let i = 0; i < sortedNums.length; i++) {
if(!(sortedNums[i] in seen)) {
seen[sortedNums[i]] = i;
}
}
const answer = [];
for(let i = 0; i < nums.length; i++) {
answer.push(seen[nums[i]]);
}
return answer;
};