How should I be doing the exercises?

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?

Would you link to the challenge itself

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.

Hi @rainseahorse !

Welcome to the forum!

I edited your post to wrap your solution in spoiler tags for those who have not worked on the challenge.

I agree with @caryaharper that your approach with the for loop works well.

I wouldn’t automatically assume that the solutions in the guide are the best solutions.
There are just another way to solve the problem.

Sometimes the guide solutions will show you some creative approaches that you want to try out.

Other times, the guide solutions will be more complex then your approach.

My advice is to first solve the problem in the most direct and simple manner like you did.

Then you can experiment with different methods.

You can explore MDN docs for other methods not brought up in the curriculum.

Hope that helps!

Thank you for letting me know, while I still need some time before I understand what you mean by time complexities!

Thank you for helping me out, I think I understand!

This is what I’m referring to:


I’ll read on it, thank you~

There are also plenty of great video resources on Big O.

Here is one by FCC.
Big O starts at the 4:28 mark.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.