5 line O(n) Two pointer Solution without modifying input


  • 1
    Y
    class Solution {
    public:
        bool checkPossibility(vector<int>& nums) {
            int l = 0;
            int r = nums.size() - 1;
            for (; l != r && nums[l] <= nums[l + 1]; l++);
            for (; l != r && nums[r - 1] <= nums[r]; r--);
            return r - l <= 1 && (l == 0 || nums[l - 1] <= nums[r] || r + 1 == nums.size() || nums[l] <= nums[r + 1]);
        }
    };
    

Log in to reply
 

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