1

yes I know there are a few similar questions about this problem that's why I will skip the intro about it. All of them have different codes but nothing identical to mine and I couldn't understand and fix the problem with my code. So the problem with my code is that it can pass 35 of the 38 tests but it can't pass the performance tests. I tried to stop the iterations to make it faster but it still fails. What can I do to make it faster?

function solution(sequence) {
    const min = 2
    let countFalse = 0
    let dblCheck = false

    const dblFind = sequence => sequence.filter((item, index) => sequence.indexOf(item) !== index)
    const dblFalse = dblFind(sequence)

if (sequence.length === min) {
    return true
} else if (dblFalse.length > 1){
    return false
} else {
    let start = sequence[0]
    for (var i=0; i < sequence.length-1; i++) {
        if (start < sequence[i+1]){
            start = sequence[i+1]          
        } else {
            countFalse++           
            start = sequence[i+1]
            if (countFalse >=2){ 
                return false
             }
            if (sequence[i+1] < sequence[i+2] && sequence[i-1] > sequence[i+2]) {
                dblCheck = true
                return false
            }
        }
    }
}
 return true

}

console.log(solution([1,3,2,1])) //false
console.log(solution([1,3,2])) //true
console.log(solution([40, 50, 60, 10, 20, 30])) //false
elsartz
  • 11
  • 3
  • Given that your code fails some of the tests, you should actually explain what the objective is. We won't be able to infer it from failing code. – Patrick Roberts Sep 02 '22 at 16:15
  • Thank you for your reply. The objective of this algorithm is "Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array." Unfortunately for my bug, the only clue I have is the result from the site which says: "Tests passed: 35/38. Execution time limit exceeded on test 36: Program exceeded the execution time limit. Make sure that it completes execution in a few seconds for any possible input." – elsartz Sep 02 '22 at 18:29
  • You don't need the `dblFalse` thing as it adds extra `filter` loop, while the same check is being performed in your `for` loop. – Kosh Sep 02 '22 at 18:50
  • A `filter` with a nested `indexOf` is not particularly efficient. Keep in mind that `indexOf` takes an optional second parameter, you should take advantage of that. – Patrick Roberts Sep 02 '22 at 18:55

0 Answers0