When I do problems like “Where Do I Belong” in the javascript curriculum, I end up with a solution like
function getIndexToIns(arr, num) {
let smallerCount = 0;
for(let ind = 0; ind < arr.length; ind ++){
if(arr[ind] < num)
smallerCount ++;
}
return smallerCount;
}
getIndexToIns([40, 60], 50);
, only to find that the best solutions involve methods I don’t remember like .sort(). How should I be approaching these problems to arrive at these solutions? Should I be looking through what I’ve done in the curriculum for methods I should be using?
I see nothing wrong with your approach, and I don’t think sort would be any better. You could sort the array, but you would still being sorting the full array which can have varying time complexities although it is generally O(n log n) which can be faster if my understanding is correct, but the fact the you can do a single loop with O(n) time complexity it is more than fine, and may very well be faster with small arrays.
The sort approach I think would require you have to have a secondary loop anyhow so I think you really do have the best solution. You’ve proven the array does need to be sorted.