Easy to follow Python solution that beats 80% of submissions


  • 1
    A

    Two examples:
    0 6 3 4 - when we're checking 3, then 6 should be changed, because 3 is more than 0 (3 > 0)
    4 6 3 4 - when we're checking 3, then 3 should be changed, because 3 is not more than 4 (3 < 4)

    Thus we can make two rules:

    • In case current value is less than a previous one then when we're on index i, change nums[i-1] (preceding) if nums[i] > nums[i - 2] or change nums[i] (current) otherwise.

    • When you change a value, make it equal to a previous one. This will ensure the sequence stays non-decreasing or in other words will guarantee that changing previous elements won't affect the earlier checks.

    class Solution(object):
        def checkPossibility(self, nums):
            n = len(nums)
            if n < 3:
                return True
    
            c = int(nums[0] > nums[1])
            for i in range(2, n):
                if nums[i] < nums[i - 1]:
                    if c > 0:
                        return False
                    
                    c += 1
    
                    if nums[i] > nums[i - 2]:
                        nums[i - 1] = nums[i - 2]
                    else:
                        nums[i] = nums[i - 1]
    
            return True
    

Log in to reply
 

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