Search code examples
javascriptarrayssortingfor-loopoff-by-one

Javascript: Check array of numbers for number of missing numbers needed to make the array consecutive


Working on some Javascript challenges on Code Signal and I'm having an issue solving this:

Ratiorg got statues of different sizes as a present from CodeMaster for his birthday, each statue having an non-negative integer size. Since he likes to make things perfect, he wants to arrange them from smallest to largest so that each statue will be bigger than the previous one exactly by 1. He may need some additional statues to be able to accomplish that. Help him figure out the minimum number of additional statues needed. Example For statues = [6, 2, 3, 8], the output should be makeArrayConsecutive2(statues) = 3. Ratiorg needs statues of sizes 4, 5 and 7.

My approach:

  • Sort the array smallest to largest
  • Create counter variable to store number of missing numbers
  • Iterate through array
  • Subtract [i + 1] element from [i] element
  • If it equals 1, numbers are consecutive, if not the numbers are not consecutive (increment counter variable)
  • Return counter variable

Here is my code:

function makeArrayConsecutive2(statues) {
    // Sorts array numerically smallest to largest
    statues.sort((a, b) => a - b);

    let counter = 0;

    // If array only contains one number return 0
    if(statues.length === 1) {
        return 0;
    }

    /* Iterate through array, subtract the current element from the next element, if it 
       equals 1 the numbers are consecutive, if it doesn't equal one increment the counter 
       variable */
    for(let i = 0; i <= statues.length -1; i++) {
        if(statues[i] !== statues.length -1 && statues[i + 1] - statues[i] != 1) {
           counter++;
        }

       console.log(statues[i]);
       console.log('counter : ' + counter);
    }

    return counter;       
}

When statues contains [5, 4, 6] the output is this:

4
counter : 0
5
counter : 0
6
counter : 1

I think the problem is when array is on the last element, in this case 6, it's attempting to look at statues[i + 1] when that element doesn't exist. I added statues[i] !== statues.length -1 to my if statement to address that but it doesn't appear to be working. What's wrong with my code and why is the final element incrementing the counter variable?


Solution

  • I'd approach it by building the target array which goes from the min+1 to the max-1 of the input by ones, excluding members of the input.....

    function missingConseq(input) {
      let min = Math.min.apply(null, input)
      let max = Math.max.apply(null, input)
      let result = []
    
      for (i = min+1; i < max; i++) {
        if (!input.includes(i)) result.push(i)
      }
      return result
    }
    
    let array = [6, 2, 3, 8]
    console.log(missingConseq(array))