firstNonConsecutive.js (8kyu 67)

Codewars 알고리즘 풀이


Problem

  • Your task is to find the first element of an array that is not consecutive.
    • 배열에서 연속되지 않는 첫 번째 element를 반환한다.
  • If the whole array is consecutive then return null.
    • 배열 전체가 연속되는 경우 null을 반환한다.


Solution 01

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

firstNonConsecutive([1, 2, 3, 4]);  // null
firstNonConsecutive([1, 2, 3, 8]);  // 8
firstNonConsecutive([6, 7, 8, 1]);  // 1


Solution 02

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

firstNonConsecutive([1, 2, 3, 4]);  // null
firstNonConsecutive([1, 2, 3, 8]);  // 8
firstNonConsecutive([6, 7, 8, 1]);  // 1