Inelegant JavaScript solution


  • 0
    const checkPossibility = (nums) => {
        const left = nums.slice(0)
        const right = nums.slice(0)
        const i = nums.findIndex((a, i) => a > nums[i + 1])
        if (~i) left.splice(i, 1)
        if (~i) right.splice(i + 1, 1)
        return !left.some((a, i) => a > left[i + 1]) || !right.some((a, i) => a > right[i + 1])
    };
    

    Find the index before the first decrease and see if removing either element creates a non-decreasing array. O(n) time and O(n) space.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.