freeCodeCamp Algorithm Challenge Guide: Where do I Belong

freeCodeCamp Algorithm Challenge Guide: Where do I Belong
0

#1

:triangular_flag_on_post: Remember to use Read-Search-Ask if you get stuck. Try to pair program :busts_in_silhouette: and write your own code :pencil:

:checkered_flag: Problem Explanation:

This can be a tricky problem to understand. You need to find where in the array a number should be inserted by order, and return the index where it should go.

Relevant Links

:speech_balloon: Hint: 1

The first thing to do is sort the array from lower to bigger, just to make the code easier. This is where sort comes in, it needs a callback function so you have to create it.

try to solve the problem now

:speech_balloon: Hint: 2

Once the array is sorted, then just check for the first number that is bigger and return the index.

try to solve the problem now

:speech_balloon: Hint: 3

If there is no index for that number then you will have to deal with that case too.

try to solve the problem now

Spoiler Alert!

687474703a2f2f7777772e796f75726472756d2e636f6d2f796f75726472756d2f696d616765732f323030372f31302f31302f7265645f7761726e696e675f7369676e5f322e676966.gif

Solution ahead!

:beginner: Basic Code Solution:

function getIndexToIns(arr, num) {
  arr.sort(function(a, b) {
    return a - b;
  });

  for (var a = 0; a < arr.length; a++) {
    if (arr[a] >= num)
      return a;
  }

  return arr.length;
}

:rocket: Run Code

Code Explanation:

  • First I sort the array using .sort(callbackFuntion) to sort it by lowest to highest, from left to right.
  • Then I use a for loop to compare the items in the array starting from the smallest one. When an item on the array is greater than the number we are comparing against, then we return the index as an integer.

Relevant Links

:beginner: Basic Code Solution:

function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  var times = arr.length; // runs the for loop once for each thing in the array
  var count = 0; 
  for (i=0;i<times;i++){
    if(num>arr[i]){count++;} } // counts how many array numbers are smaller than num
    return count; // the above equals num's position in a sorted array
}

getIndexToIns([40, 60], 50);

:rocket: Run Code

Code Explanation:

  • I do not sort the arr input array
  • I run a for loop counting whenever the num input is bigger than an arr input number.
  • This number is equivalent to what num’s position would be in a sorted array.

:beginner: Basic Code Solution:

by @HarinaPana

function getIndexToIns(arr, num) {

  arr.sort(function(a, b) {
  return a - b;
  });

  var i = 0;
  while (num > arr[i]) {
  i++;
  }

  return i;
}

getIndexToIns([40, 60], 50);

:rocket: Run Code

Code Explanation:

  • Sort existing array.
  • Iterate through the array while checking if num is bigger.
  • The loop will stop when num isn’t bigger than i and return the last element checked.

:sunflower: Intermediate Code Solution:

by @faustodc

function getIndexToIns(arr, num) {
  arr.push(num);
  arr.sort(function(a, b){return a-b});
  return arr.indexOf(num);
}

:rocket: Run Code

Code Explanation:

  • First we add the number num to the array using push() which adds it as the last element of the array.
  • Then we use sort() with the callback function function(a, b){return a-b} to sort the numbers in ascending order.
  • Lastly we return the postion or index of num in the array with the indexOf() function.

Relevant Links

:sunflower: Intermediate Code Solution:

Using .findIndex()

function getIndexToIns(arr, num) {
  // sort and find right index
  var index = arr.sort((curr, next) => curr > next)
    .findIndex((currNum)=> num <= currNum);
  // Returns proper answer
  return index === -1 ? arr.length : index;
}

getIndexToIns([40, 60], 500);

:rocket: Run Code

Code Explanation:

  • First sort the array in ascending order, this is currently done using array functions for minimal footprint.
  • Once the array it is sorted, we directly apply the .findIndex() where we are going to compare every element in the array until we find where num <= currNum meaning where the number we want to insert is less or equal to the current number number in the iteration.
  • Then we use ternary operations to check whether we got an index returned or -1. We only get -1 when the index was not found meaning when we get a false for all elements int he array, and for such case, it would mean that num should be inserted at the end of the list hence why we use arr.length.

Relevant Links

:clipboard: NOTES FOR CONTRIBUTIONS:

  • :warning: DO NOT add solutions that are similar to any existing solutions. If you think it is similar but better, then try to merge (or replace) the existing similar solution.
  • Add an explanation of your solution.
  • Categorize the solution in one of the following categories — Basic, Intermediate and Advanced. :traffic_light:
  • Please add your username only if you have added any relevant main contents. (:warning: DO NOT remove any existing usernames)

See :point_right: Wiki Challenge Solution Template for reference.


#2

#3

#4

I added my solution, it’s intermediate ok? or should it be something else?


#5

Not sure why parseInt() is used in the basic solution. Variable ‘a’ is initialized to 0 and then incremented with a++ until arr.length. So variable ‘a’ will always remain an integer.


#6

haha I was checking my answer on github/wiki and noticed the suggested solutions were more complex than they needed to be. So I came to add my elegant solution but @faustodc, like me discovered this and, has already added it :smiley:
Yep seems best to just push, sort(a-b), return indexOf num.
To respond to your post @faustodc about what “category” your solution should go in. I feel, the simplest solution should be considered the “ideal/best” solution. It’s confusing how they label them basic-advanced. I feel like basic should mean “best”. LOL. Maybe they should instead label them where there is one “ideal/best” solution. And all other solutions are just “alternative” solutions. Meaning, they aren’t as great, but are still acceptable. And of course the ideal solution should could be easily determined by which is the best combination of speed of program and length(shortness) of program :slight_smile:
What do you think?


#7

This solution is not present on the obsolete FCC Wiki on Github that’s when I found out about this forum where you beat me to adding it :wink:. I think it is the simplest solution and should be in the Basic Code Solution: since it only uses those methods that have been taught/used in the previous challenges in FCC whereas the already present Basic Code Solution should go under the intermediate category.


#8

@CraftyClark & @tanmay7270 - Well yes the wiki it’s now obsolete and got moved to the forum (not sure if that was a good transition given how both are completely different formats to access information), and they should make the whole code contribution more clear, it’s very ambiguous, @CraftyClark’s idea is great, hopefully the powers that be read our concerns and act upon them. :sweat_smile:

Edit: Fixed the “Run Code” link, was redirecting to a different solution.


#9

I saw that there wasn’t anything similar solution I came up with on this so I added it under Basic solutions. I hope that’s fine.


#10

I came up with just a 2 line code, I thought is was nice to mention that code from faustodc could be even smaller :wink:

function getIndexToIns(arr, num) {
var a = arr.concat(num).sort(function(a,b) { return a-b});
return a.indexOf(num);
}


#11

This is my solution, but it seems not to work on the last query. getIndexToIns([2, 5, 10], 15);

I can see there are some great answers, and my attempt is pretty weak :stuck_out_tongue: but I still want to do this my way. Or learn how my approach went wrong. Also is having a function inside another function wrong?

function getIndexToIns(arr, num) {
// Find my place in this sorted array.

arr.sort(function(a, b) {
return a - b;
});

function isBigEnough(element) {

while ((num <= element) !== -1)
  { 

return num <= element;
}

return arr.length;

}

return arr.findIndex(isBigEnough);
}

getIndexToIns([2, 5, 10], 15);


#12

Quick ES6 implementation

function getIndexToIns(arr, num) {
  arr.push(num);
  return arr.sort((a,b)=>a-b).indexOf(num);
}

#13

My solution:

function getIndexToIns(arr, num) {
  
  var newArr = [];
  newArr = arr.filter(function(val) {
  return val < num;
});
return newArr.length;
}

#14

I did exactly the same, it’s short and does what it suppose to =)


#15

I was worried until I saw that you had used the same solution as me. . . #greatMinds


#16

Does anyone know why return arr.push(num) gives here different answer than following:

arr.push(num);
return arr;

#17

Let us supppose that arr = [1,2,3]
and num = 10

arr.push(num) method adds num to the end of the arr and returns the length of changed arr which has now increased. so,
return arr.push(num); actually returns the length of the changed arr ( which is 4) instead of the new changed (mutated) arr which is [1,2,3,10] .

arr.push(num); // Adds num to arr but nothing hooks on to its return value
return arr; //returns the new changed (mutated) arr which is [1,2,3,10].

#18

My solution:

function getIndexToIns(arr, num) {

 return arr.concat(num)
    .sort(function(a,b) { return a-b; })
       .indexOf(num);
}

#19

…which can be read from apis… :blush: thnx for your help! :thumbsup:


#21

HI! This is my solution. I did it in five steps.

  1. I created the array args
  2. I did two var whit the args’s argumets.
  3. I concated these vars
  4. I sorted this new var
  5. I asked by the position with indexOf
function getIndexToIns(arr, num) {
  var args = Array.prototype.slice.call(arguments);
  var myvar = args[0];
  var suma = args [1];
  var newArray = myvar.concat(suma);
  var buena = newArray.sort(function(a,b){
  return a - b;
});
  var result = buena.indexOf(num); 
  return result;
}