Non-decreasing Array in Python

A non-decreasing array is one where each element is less than or equal to the next element: array[i] <= array[i + 1]. The challenge is to determine if we can make an array non-decreasing by modifying at most one element.

For example, the array [4, 2, 3] can become non-decreasing by changing 4 to 1, resulting in [1, 2, 3].

Algorithm

The approach is to find violations where nums[i] > nums[i+1] and count them ?

  • If the array has 2 or fewer elements, return True

  • Track violations using a boolean flag

  • For each violation, decide whether to modify nums[i] or nums[i+1]

  • If more than one violation exists, return False

Implementation

def checkPossibility(nums):
    if len(nums) <= 2:
        return True
    
    violation_found = False
    
    for i in range(len(nums) - 1):
        if nums[i] > nums[i + 1]:
            # If we already found a violation, return False
            if violation_found:
                return False
            else:
                violation_found = True
            
            # Decide which element to modify
            if i > 0:
                if nums[i - 1] > nums[i + 1]:
                    nums[i + 1] = nums[i]  # Modify nums[i+1]
    
    return True

# Test examples
print(checkPossibility([4, 2, 3]))     # True
print(checkPossibility([4, 2, 1]))     # False
print(checkPossibility([1, 2, 3]))     # True
True
False
True

How It Works

The algorithm handles two cases when a violation nums[i] > nums[i+1] is found ?

  • Case 1: If i == 0 or nums[i-1] <= nums[i+1], we can modify nums[i]

  • Case 2: If nums[i-1] > nums[i+1], we modify nums[i+1] to equal nums[i]

Examples with Different Cases

# Case 1: Modify the larger element
arr1 = [4, 2, 3]
print(f"Array: {arr1}")
print(f"Can be non-decreasing: {checkPossibility(arr1.copy())}")

# Case 2: Modify the smaller element  
arr2 = [1, 3, 2, 4]
print(f"Array: {arr2}")
print(f"Can be non-decreasing: {checkPossibility(arr2.copy())}")

# Case 3: Multiple violations
arr3 = [4, 2, 1]
print(f"Array: {arr3}")
print(f"Can be non-decreasing: {checkPossibility(arr3.copy())}")
Array: [4, 2, 3]
Can be non-decreasing: True
Array: [1, 3, 2, 4]
Can be non-decreasing: True
Array: [4, 2, 1]
Can be non-decreasing: False

Conclusion

The solution tracks violations in the array and strategically modifies elements to maintain the non-decreasing property. If more than one violation exists, the array cannot be fixed with a single modification.

Updated on: 2026-03-25T07:30:58+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements