JSFiddle - React, Tailwind, and code Playground

by Derek Anderson

JavaScript

function missing(inputArray) {
	// use quick sort to determine what is missing
  // we know the list is sorted we only need to do this once
  // by employing a pivot
  
  // assume we pivot at page 1
  var currentPivot = 1;
  
  // our list of missing items
  var missing = [];
  
  // we only need to iterate one time, no matter how big the list
  // thanks to being sorted
  for (var i = 0; i <= inputArray.length; i++) { // O(n)
  
    // get our current sorted value  
    var sortedValue = inputArray[i];
    
    // as long as our sorted value isn't the pivot
    if (currentPivot !== sortedValue) {
    
    	// get the wall we are going to meet from the pivot
      var sortedValueWall = sortedValue - 1 || 1000;
      
      // if the wall is not the pivot, then we need to 
      // use an inclusive string Page N - Page N
      if (sortedValueWall != currentPivot) {
        missing.push(currentPivot + '-' + sortedValueWall);
      } else {
      	// otherwise if the pivot is the wall, this is a single missing page
        // not a range
        missing.push(currentPivot);
      }
    }
    
    // increase our pivot by one
    currentPivot = sortedValue + 1;
  }
  
  // return as a string with comma seperation
  return missing.join(',');
}


document.body.innerHTML += missing([2, 4, 7]);
document.body.innerHTML += "<br>";
document.body.innerHTML += missing([1, 3, 5, 8]);