findNonConsecutiveNum.js (8kyu 31)

Codewars 알고리즘 풀이


Description

  • Your task is to find the first element of an array that is not consecutive.
    • 연속되지 않는 배열의 첫 번째 element를 반환한다.
  • By not consecutive we mean not exactly 1 larger than the previous element of the array.
    • 연속되지 않다는 것은, 배열의 이전 element보다 정확히 1이 크지 않다는 것을 의미한다.
  • If the whole array is consecutive then return ‘null’.
    • 배열의 element가 연속적인 경우 ‘null’을 반환한다.



Solution 01

function findNonConsecutiveNum(arr) {
  for (let i = 0; i < arr.length - 1; i++) {
    if (arr[i] + 1 !== arr[i + 1]) {
      return arr[i + 1];
    }
  }
  
  return null;
}

findNonConsecutiveNum([1, 2, 3, 4]);  // null
findNonConsecutiveNum([1, 2, 3, 5]);  // 5
findNonConsecutiveNum([1, 3, 4, 5]);  // 3


Solution 02

function findNonConsecutiveNum(arr) {
  for (let i = 1; i < arr.length; i++) {
    let current = arr[i];
    let previous = arr[i - 1];
    
    if (current - previous > 1) {
      return current;
    }
  }
  
  return null;
}

findNonConsecutiveNum([1, 2, 3, 4]);  // null
findNonConsecutiveNum([1, 2, 3, 5]);  // 5
findNonConsecutiveNum([1, 3, 4, 5]);  // 3


Solution 03

function findNonConsecutiveNum(arr) {
  let result = arr.find((i, index) => i !== index + arr[0]);
  
  return Number.isInteger(result) ? result : null;
}

findNonConsecutiveNum([1, 2, 3, 4]);  // null
findNonConsecutiveNum([1, 2, 3, 5]);  // 5
findNonConsecutiveNum([1, 3, 4, 5]);  // 3