I wrote a function in JavaScript that expects an array of integers (negative or positive) and determines if that array has an increasing sequence.
For the sake of better time performance I made the function return
out of the loop with false
as soon as i+1
- i
did not equal 1
or -1
. I used continue
to do this. Here is the function:
const increasingSequence = (arr) => {
for (let i = 0; i < arr.length - 1; i ++) {
if (arr[i+1] - arr[i] === 1 || arr[i+1] - arr[i] === -1) {
continue;
} else {
return false;
}
}
return true;
}
Seems to be producing the desired output:
var arr1 = [1, 2, 3, 4];
var arr2 = [1, 2, 4, 5];
var arr3 = [-4, -3, -2, -1];
var arr4 = [-4, -3, -1, 0];
increasingSequence(arr1); // true
increasingSequence(arr2); // false
increasingSequence(arr3); // true
increasingSequence(arr4); // false
This is actually a helper function to a bigger problem I'm trying to solve, so time complexity is important. Feedback about improving time complexity or any missing edge cases would be greatly appreciated.