diff --git a/Easy/Array/1365.how-many-numbers-are-smaller-than-the-current-number.js b/Easy/Array/1365.how-many-numbers-are-smaller-than-the-current-number.js index faaded9..3ed3996 100644 --- a/Easy/Array/1365.how-many-numbers-are-smaller-than-the-current-number.js +++ b/Easy/Array/1365.how-many-numbers-are-smaller-than-the-current-number.js @@ -50,9 +50,28 @@ */ var smallerNumbersThanCurrent = function (nums) { - // Step 1: count the frequency of each number + // Step 1: Begin by initializing a [Frequency Map]() const freq = {}; - for (let x of nums) freq[x] = (freq[x] || 0) + 1; + for (let n of nums) freq[n] = (freq[n] || 0) + 1; - return nums.map((x) => freq[x] || 0); + // Step 2: Sort the numbers by ascending order + const sorted = Object.keys(freq).sort((a, b) => a - b); + + // Step 3: Init a count of numbers smaller than the active number + let count = 0; + + // Step 4: Init a map to track number of values smaller for each number + const smaller = {}; + + // Step 5: Iterate over the sorted list + for (let num of sorted) { + // Set count for active number + smaller[num] = count; + + // Update the count by frequency + count += freq[num]; + } + + // Step 6: Use original list and find number of smaller values than it + return nums.map((n) => smaller[n]); };