Solving JS Algorithm Problem: How Many Numbers Are Smaller Than the Current Number
The algorithm problem is as follows:
Given the array nums
, for each nums[i]
find out how many numbers in the array are smaller than it. That is, for each nums[i]
you have to count the number of valid j's
such that j != i
and nums[j] < nums[i]
.
Return the answer in an array.
Example 1:
const smallerNumbersThanCurrent = (nums) => {
};
nums = [8,1,2,2,3]
Step #1: Starting off, we know that we will be using the forEach method within our answer since when reading the problem, we get a clue from “for each nums[i]
“. But first, we will define our new array.
let newArray = […nums];
We define our newArray variable by using a spread syntax (…) followed by the beginning array nums. The spread syntax lays out all elements within the nums array.
Step #2: We will need to sort the amounts within the nums array in ascending order to know how many numbers are smaller than the number in question.
For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3).
For nums[1]=1 does not exist any smaller number than it.
For nums[2]=2 there exist one smaller number than it (1).
For nums[3]=2 there exist one smaller number than it (1).
For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).
nums.sort((a, b) => a — b)
Step #3: We will refer back the newArray and use the forEach method and pass in our current value which is the current element being processed in the array (num) and the index of the current value in the array. Within the arrow function, we set our newArray index to equal the nums array index and setting the num with the starting index order from the nums array.
newArray.forEach((num, index) => {
newArray[index] = nums.indexOf(num);
}
Step #4: Once we defined the forEach method from our newArray, we must then return the newArray after our forEach method in order for our output to be printed.
return newArray;
The following is the overall answer to our problem:
const smallerNumbersThanCurrent = (nums) => {
let newArray = […nums];nums.sort((a, b) => a — b)
newArray.forEach((num, index) => {
newArray[index] = nums.indexOf(num);
})return newArray
};
The terminal prints our output as:
[4,0,1,1,3]
This matches our intended answer.