I will help you out. Let’s walk through how you could do this manually.
Remember, I said to do it without pushing num
to the array.
The algorithm is as follows:
We will iterate through each array number and check if the the second argument of the function is greater than the current number being iterated over in the array. If we track the total count of times where the second argument is greater than the current number being checked, this count IS the index of the array where the second argument would be placed if the sorted array.
Let’s work through getIndexToIns([5, 3, 20, 3], 5)
:
1st iteration of array
current count of times the 2nd argument is greater than an array element: 0
2nd argument (5
) is not greater than first element in array (5
) so the count remains at 0
.
2nd iteration of array
current count of times the 2nd argument is greater than an array element: 0
2nd argument (5
) is greater than first element in array (3
) so the count increments to 1
.
3rd iteration of array
current count of times the 2nd argument is greater than an array element: 1
2nd argument (5
) is not greater than first element in array (20
) so the count remains at 1
.
4th Iteration of array
current count of times the 2nd argument is greater than an array element: 1
2nd argument (5
) is not greater than first element in array (3
) so the count increments to 2
.
Array has been iterated through, so return count value of 2
. This means the second argument 5
would be positioned as the 3rd element in the sorted array. Let’s validate that.
The sorted version of [5, 3, 20, 3]
is [3, 3, 5, 20]
. If we insert the second argument (5
) as the 3rd element of the array, you would end up with [3, 3, 5, 5, 20]
which is correct.