JavaScript Coding Challenge: "Where do I belong?"

Some of you might not know the following thing about me: I LOVE CODING CHALLENGES and I've been "playing" around with them for a long time now...

This helped me pass multiple Coding Interviews with ease for some really interesting Job Interviews (if you are interested, I could tell you more about this in another post, just let me know emoji-wink ).

I even wrote in the past some blog posts on Medium about how I solved some Coding Challenges using JavaScript (which is my GO-TO language for this type of tasks).

There are a couple of sites which I used to improve my skills, some of them are: CodeSignal, HackerRank, FreeCodeCamp and recently I found CodeWars.

Ok... enough with the chit-chat, let's get into the coding!

Typing GIF

For today I picked a very simple coding challenge, just to warm up. You can find it on FreeCodeCamp. It says:

Return the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted. The returned value should be a number.

For example, getIndexToIns([1, 2, 3, 4], 1.5) should return 1 because it is greater than 1 (which has index 0), but less than 2 (which has index 1).

Likewise, getIndexToIns([20, 3, 5], 19) should return 2 because once the array has been sorted it will look like [3, 5, 20] and 19 is less than 20 (index 2) and greater than 5 (index 1).

Note: If you haven't completed this challenge yet, I would HIGHLY recommend and also it would be very helpful for you to go and solve it on your own first, then you can come back and see my solutions.

Note 2: You might saw that I wrote solutions and that's because I have two extra solutions which are a little more advanced. This is for those of you which are more experienced and want to spice it up a little bit. You can skip to that part. emoji-smiley

First solution - the beginner friendly way

The first thing you must do when you want to solve a coding challenge is to make sure you understand exactly what they want you to do. So it's useful to create a list of small, specific tasks which are easy to tackle (Divide and Conquer):

  1. Create a function which will take two arguments - an array of numbers and a number
  2. Insert the number into the array
  3. Sort the array
  4. Return the position (index) at which the number is located into the sorted array

As the problem is pretty easy I'm going to write down the entire JavaScript code and write the steps in the comments:

// Step 1.
function getIndexToIns(arr, num) {
    // Step 2.
    arr.push(num);

    // Step 3.
    const sortedArr = arr.sort(function(a, b) {
        return a - b;
    });

    // Step 4.
    return sortedArr.indexOf(num);
}

This is pretty much it...

Easy Gif

The only thing that I want to point out is that I used a custom function inside the sort function because by default the sort function will not sort an array of numbers very well... For example if you have an array like: [3, 1, 10, 2, 20, 4], after sorting it will look like: [1, 10, 2, 20, 3, 4], which is not what we want. For that reason we used a custom function above - Problem Solved! emoji-clap emoji-clap

Second solution - the "fancy" way

After I finish a coding challenge I like to stop for a moment and think for a better/clever way to solve it again! I do this for fun but sometimes I discover new ways to approach a problem.

For this particular problem I noticed some "improvements" I could make:

  1. I can use the Spread operator to combine the array and the number into a new array
  2. I could use Reduce to save the searched index into the accumulator
  3. I could directly return the result, saving a few key strokes :P

The final result looks like this:

// Step 3.
const getIndexToIns = (arr, num) =>
    // Step 1.
    [...arr, num]
        .sort((a, b) => a - b)
        // Step 2.
        .reduce(
            (acc, current, i) => (current === num && acc === -1 ? i : acc),
            -1
        );

First time my reduce function looked like this:

    .reduce((acc, current, i) => (current === num ? i : acc), -1)

But I realized soon that if the number occurs multiple times in the array, it will return the last index and they wanted the first index, so I added the && acc === -1 part of the code which is making sure that if the number was found, it should not "save" another index so therefore is returning that value.

Third solution - the "fast" way

After posting this, some of you pointed out that we can go one step further and we can improve the solution by reducing the number of times we loop through the array. We can solve this with only one iteration! ^_^

Basically while we loop through the array we'll check if the number is higher than the current value from the array. If it is, we simply increase a counter.

I used the reduce method as it is pretty straightforward (and it's a one-liner :P ):

let getIndexToIns = (arr, num) =>
    arr.reduce((acc, current) => (num > current ? ++acc : acc), 0);

Conclusion

What do you think of my solution to this particular challenge? Did you find another approach? Let me know, I'd love to hear it!

At the end I'm going to say it again: I LOVE CODING CHALLENGES! The reason is that when you manage to solve a challenge it gives you such a good feeling... It makes you feel smarted. (at least for a while emoji-laughing ).

I remember that I spent hours and hours on some coding challenges, sometimes I even spent several hours in a night just to find the solution and... oh boy, how happy I was when I finaly did it. emoji-smile

Maybe is just me, or maybe you feel the same... nevertheless let me know if you like this sort of blog posts and I'd be happy to write more in the future. emoji-wink

Tagged with javascript, challenge, beginner, freecodecamp, array, sort, indexOf, spread, reduce, es6