A coding challenge on a website says to determine if an array would have an increasing sequence if one element were removed from that array.
Here is the function:
const almostIncreasingSequence = sequence => {
const increasingSequence = arr => {
for (let i = 0; i < arr.length; i++) {
if (arr[i - 1] >= arr[i]) {
return false;
}
}
return true;
};
for (let i = 0; i < sequence.length; i++) {
const left = sequence.slice(0, i);
const right = sequence.slice(i + 1);
const newArr = left.concat(right);
if (increasingSequence(newArr)) {
return true;
}
}
return false;
};
The function produces the exact same output as all of the visible tests on the site:
var toTest = [
[1, 3, 2, 1],
[1, 3, 2],
[1, 2, 1, 2],
[1, 4, 10, 4, 2],
[10, 1, 2, 3, 4, 5],
[1, 1, 1, 2, 3],
[0, -2, 5, 6],
[1, 2, 3, 4, 5, 3, 5, 6],
[40, 50, 60, 10, 20, 30],
[1, 1],
[1, 2, 5, 3, 5],
[1, 2, 5, 5, 5],
[10, 1, 2, 3, 4, 5, 6, 1],
[1, 2, 3, 4, 3, 6],
[1, 2, 3, 4, 99, 5, 6],
[123, -17, -5, 1, 2, 3, 12, 43, 45],
[3, 5, 67, 98, 3]
];
for (let i = 0; i < toTest.length; i++) {
console.log(almostIncreasingSequence(toTest[i]));
}
Outputs:
false
true
false
false
true
false
true
false
false
true
true
false
false
true
true
true
true
But then a hidden error triggers upon submission telling me that the execution time is longer than the maximum of 4 seconds. How can I improve the time complexity of this algorithm?
i-1
is greater than or equal to the item ati+1
. \$\endgroup\$i-1
is greater than or equal to the item ati
. Couple of options. Complete the loop, return the count and then return false ifcount>1
. Or break the loop and return false ifcount>1
(return true otherwise). With your solution, firstly you are comparing the wrong two elements, and you are returning false at the first instance, not the second instance. \$\endgroup\$-1
,+1
) method, you are not checking the item in between and you could get inconsistent results - I haven't followed that logic all the way through, but keep it simple and direct. But you see a difference in approach? You are asking what happens if we have removed something, I am asking if we can remove something. \$\endgroup\$4,5,6,1,2,3
. \$\endgroup\$