loading...

Solving "Where do I Belong" / freeCodeCamp Algorithm Challenges

virenb profile image Viren B Originally published at virenb.cc ・5 min read

Solving freeCodeCamp's Algorithm Challenges (37 Part Series)

1) FCC Algorithm Challenges / Convert Celsius to Fahrenheit 2) FCC Algorithm Challenges / Reverse a String 3 ... 35 3) FCC Algorithm Challenges / Factorialize a Number 4) FCC Algorithm Challenges / Find the Longest Word in a String 5) FCC Algorithm Challenges / Return Largest Numbers in Arrays 6) Solving "Confirm the Ending" / FreeCodeCamp Algorithm Challenges 7) Solving "Repeat a String Repeat a String" / FreeCodeCamp Algorithm Challenges 8) Solving "Truncate a String" / freeCodeCamp Algorithm Challenges 9) Solving "Finders Keepers" / freeCodeCamp Algorithm Challenges 10) Solving "Boo who" / freeCodeCamp Algorithm Challenges 11) Solving "Title Case a Sentence" / freeCodeCamp Algorithm Challenges 12) Solving "Slice and Splice" / freeCodeCamp Algorithm Challenges 13) Solving "Falsy Bouncer" / freeCodeCamp Algorithm Challenges 14) Solving "Where do I Belong" / freeCodeCamp Algorithm Challenges 15) Solving "Mutations" / freeCodeCamp Algorithm Challenges 16) Solving "Chunky Monkey" / freeCodeCamp Algorithm Challenges 17) Solving "Sum All Numbers in a Range" / freeCodeCamp Algorithm Challenges 18) Solving "Diff Two Arrays" / freeCodeCamp Algorithm Challenges 19) Solving "Seek and Destroy" / freeCodeCamp Algorithm Challenges 20) Solving "Wherefore art thou" / freeCodeCamp Algorithm Challenges 21) Solving "Spinal Tap Case" / freeCodeCamp Algorithm Challenges 22) Solving "Pig Latin" / freeCodeCamp Algorithm Challenges 23) Solving "Search and Replace" / freeCodeCamp Algorithm Challenges 24) Solving "DNA Pairing" / freeCodeCamp Algorithm Challenges 25) Solving "Missing letters" / freeCodeCamp Algorithm Challenges 26) Solving "Sorted Union" / freeCodeCamp Algorithm Challenges 27) Solving "Convert HTML Entities" / freeCodeCamp Algorithm Challenges 28) Solving "Sum All Odd Fibonacci Numbers" / freeCodeCamp Algorithm Challenges 29) Solving "Sum All Primes" / freeCodeCamp Algorithm Challenges 30) Solving "Smallest Common Multiple" / freeCodeCamp Algorithm Challenges 31) Solving "Drop it" / freeCodeCamp Algorithm Challenges 32) Solving "Steamroller" / freeCodeCamp Algorithm Challenges 33) Solving "Binary Agents" / freeCodeCamp Algorithm Challenges 34) Solving "Everything Be True" / freeCodeCamp Algorithm Challenges 35) Solving "Arguments Optional" / freeCodeCamp Algorithm Challenges 36) Solving "Make a Person" / freeCodeCamp Algorithm Challenges 37) Solving "Map the Debris" / freeCodeCamp Algorithm Challenges

'Where do I Belong'

Let's solve freeCodeCamp's basic algorithm scripting challenge, 'Where do I Belong'.

Starter Code

function getIndexToIns(arr, num) {
  return num;
}

getIndexToIns([40, 60], 50);

Instructions

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 (index 0), but less than 2 (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).

Tests

getIndexToIns([10, 20, 30, 40, 50], 35) should return 3.
getIndexToIns([10, 20, 30, 40, 50], 35) should return a number.
getIndexToIns([10, 20, 30, 40, 50], 30) should return 2.
getIndexToIns([10, 20, 30, 40, 50], 30) should return a number.
getIndexToIns([40, 60], 50) should return 1.
getIndexToIns([40, 60], 50) should return a number.
getIndexToIns([3, 10, 5], 3) should return 0.
getIndexToIns([3, 10, 5], 3) should return a number.
getIndexToIns([5, 3, 20, 3], 5) should return 2.
getIndexToIns([5, 3, 20, 3], 5) should return a number.
getIndexToIns([2, 20, 10], 19) should return 2.
getIndexToIns([2, 20, 10], 19) should return a number.
getIndexToIns([2, 5, 10], 15) should return 3.
getIndexToIns([2, 5, 10], 15) should return a number.
getIndexToIns([], 1) should return 0.
getIndexToIns([], 1) should return a number.

Our Approach

Read everything first. Read the instructions clearly, read the starter code we're given, and read the tests and understand what has to be returned.

  • The function takes in two arguments, one being an arr being an array, second being num, a number.
  • arr's length varies, it contains numbers or is empty (from the test cases).
  • We have to return a number. This number will be an index of arr. We do not want an array or an item within of the array being returned.

Now that we understand what we are given and what we want to output, let's see how we can solve this.

In short, what we want our function to do: sort arr in order, smallest to largest, evaluate num and insert the value into arr.

arr = [1, 2, 3, 4]
num = 1.5

[1, 1.5, 2, 3, 4]

In the above code block, we have arr, which is already in order from smallest to largest. We have to determine where 1.5 fits in. It is bigger than 0th index and smaller than 1st index so we want to insert it into 1st index.

Our function should be returning 1, the index where num now sits.

So our first action is to arrange arr from smallest to biggest. Array's have a built-in method, sort(), which would be helpful.

Array.prototype.sort() on MDN

The sort() method may not work how you think it would. From MDN documentation, it takes in an optional argument, compareFunction.

arr.sort([compareFunction])

If you are trying to sort numbers in order without providing a compareFunction, things can get a little funky.

"If compareFunction is not supplied, all non-undefined array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order. All undefined elements are sorted to the end of the array."

Quick example:

let arr = [1, 100, 3, 31, 219, 66]
arr.sort()
Result: [ 1, 100, 219, 3, 31, 66 ]

We have to provide the sort() method with two arguments to be compared in order to get the smallest to biggest order we're looking for.

let arr = [1, 100, 3, 31, 219, 66]
arr.sort((a, b) => a - b)
Result: [ 1, 3, 31, 66, 100, 219 ]

So one hurdle in solving this is complete. We will have to loop through the sorted array, compare if num is smaller or larger than each index in order to find the right index to insert at.

Before getting to the looping, from reading the tests, we have to deal with handling an empty array as arr. We want to return a 0 if arr is empty.

We can run a quick if statement, see if the arr.length is 0, to return 0.

if (arr.length === 0) return 0;

We can use a for loop on the sorted array and we will have to include an if statement to see where to insert num. Once we find the correct index, we can use splice() to insert it.

splice(index, 0 *values to remove*, num)

An edge case which we have to handle is if num is bigger than any value in arr, then we would have to insert it at the end. So let's put an else if in our for loop.

Remember, we want to return the index of where num will be inserted so we will return indexOf(num).

Let's write out this loop and if statement in some broken pseudo code (some JS/pseudo code).

function getIndexToIns(arr, num) {
    if arr's length is 0
        return 0; 

    sortedArr = arr.sort((a,b) => a - b)

    for (let i = 0; i < sortedArr.length; i++) {
        if (num >= sortedArr[i] && num <= sortedArr[i + 1)
        {
            insert num into sortedArr[i + 1]
            return index of num in sortedArr
            exit
        }
        else if (num > sortedArr[sortedArr.length - 1]) 
        {
            add num to end of sortedArr
            return index of num in sortedArr
            exit
        }
    }
}

So, to summarize:

  • We check if arr is empty. If it is empty, we return 0 and exit the function
  • If arr is not empty, we run sort() to get sortedArr sorted from smallest to biggest
  • Run a loop based on sortedArr's length.
  • Check with an if statement, num against each index in sortedArr and the next index. If it is true, we run splice() to insert it into sortedArr
  • We return indexOf(num)
  • If it runs each time and the if statement is not found to be true, it is concluded that num is bigger than any value in sortedArr so we run push() to add it to the end of sortedArr
  • We return indexOf(num)

Our Solution [SPOILER: CONTAINS ANSWER]

function getIndexToIns(arr, num) {
  if (arr.length === 0) return 0;

  let sortedArr = arr.sort((a, b) => a - b);

  for (let i = 0; i < sortedArr.length; i++) {
    if (num >= sortedArr[i] && num <= sortedArr[i + 1]) {
      sortedArr.splice(i + 1, 0, num);
      return sortedArr.indexOf(num);
    }
    else if (num > sortedArr[sortedArr.length - 1]) {
      sortedArr.push(num);
      return sortedArr.indexOf(num);
    }
  }
}

Links & Resources

'Where do I Belong' Challenge on fCC

freeCodeCamp

Donate to FCC!

Solution on my GitHub

Thank you for reading!

Solving freeCodeCamp's Algorithm Challenges (37 Part Series)

1) FCC Algorithm Challenges / Convert Celsius to Fahrenheit 2) FCC Algorithm Challenges / Reverse a String 3 ... 35 3) FCC Algorithm Challenges / Factorialize a Number 4) FCC Algorithm Challenges / Find the Longest Word in a String 5) FCC Algorithm Challenges / Return Largest Numbers in Arrays 6) Solving "Confirm the Ending" / FreeCodeCamp Algorithm Challenges 7) Solving "Repeat a String Repeat a String" / FreeCodeCamp Algorithm Challenges 8) Solving "Truncate a String" / freeCodeCamp Algorithm Challenges 9) Solving "Finders Keepers" / freeCodeCamp Algorithm Challenges 10) Solving "Boo who" / freeCodeCamp Algorithm Challenges 11) Solving "Title Case a Sentence" / freeCodeCamp Algorithm Challenges 12) Solving "Slice and Splice" / freeCodeCamp Algorithm Challenges 13) Solving "Falsy Bouncer" / freeCodeCamp Algorithm Challenges 14) Solving "Where do I Belong" / freeCodeCamp Algorithm Challenges 15) Solving "Mutations" / freeCodeCamp Algorithm Challenges 16) Solving "Chunky Monkey" / freeCodeCamp Algorithm Challenges 17) Solving "Sum All Numbers in a Range" / freeCodeCamp Algorithm Challenges 18) Solving "Diff Two Arrays" / freeCodeCamp Algorithm Challenges 19) Solving "Seek and Destroy" / freeCodeCamp Algorithm Challenges 20) Solving "Wherefore art thou" / freeCodeCamp Algorithm Challenges 21) Solving "Spinal Tap Case" / freeCodeCamp Algorithm Challenges 22) Solving "Pig Latin" / freeCodeCamp Algorithm Challenges 23) Solving "Search and Replace" / freeCodeCamp Algorithm Challenges 24) Solving "DNA Pairing" / freeCodeCamp Algorithm Challenges 25) Solving "Missing letters" / freeCodeCamp Algorithm Challenges 26) Solving "Sorted Union" / freeCodeCamp Algorithm Challenges 27) Solving "Convert HTML Entities" / freeCodeCamp Algorithm Challenges 28) Solving "Sum All Odd Fibonacci Numbers" / freeCodeCamp Algorithm Challenges 29) Solving "Sum All Primes" / freeCodeCamp Algorithm Challenges 30) Solving "Smallest Common Multiple" / freeCodeCamp Algorithm Challenges 31) Solving "Drop it" / freeCodeCamp Algorithm Challenges 32) Solving "Steamroller" / freeCodeCamp Algorithm Challenges 33) Solving "Binary Agents" / freeCodeCamp Algorithm Challenges 34) Solving "Everything Be True" / freeCodeCamp Algorithm Challenges 35) Solving "Arguments Optional" / freeCodeCamp Algorithm Challenges 36) Solving "Make a Person" / freeCodeCamp Algorithm Challenges 37) Solving "Map the Debris" / freeCodeCamp Algorithm Challenges

Posted on by:

virenb profile

Viren B

@virenb

Self-taught developer, always looking to learn more.

Discussion

markdown guide
 

Another way:

const getIndexToIns = (arr, num) => 
  arr
  .sort((a, b) => a - b)
  .filter(e => e < num)
  .length