Given an array nums
with n
integers, your task is to check if it could become non-decreasing by modifying at most one element.
We define an array as non-decreasing if nums[i] <= nums[i + 1]
holds for every i
(0-based) such that 0 <= i <= n - 2
.
Example 1:
Input: nums = [4,2,3]
Output: true
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.
Example 2:
Input: nums = [4,2,1]
Output: false
Explanation: You can't get a non-decreasing array by modifying at most one element.
Example 3:
Input: nums = [3,4,2,3]
Output: false
Explanation: You can't get a non-decreasing array by modifying at most one element.
true
since no modification is needed.nums[i] > nums[i + 1]
.false
. If exactly one violation is found:
nums[i]
to nums[i + 1]
or modifying nums[i + 1]
to nums[i]
results in a non-decreasing array.def checkPossibility(nums):
n = len(nums)
if n <= 1:
return True
count = 0 # Count of modifications needed
for i in range(n - 1):
if nums[i] > nums[i + 1]:
if count == 1:
return False
count += 1
# Deciding whether to change nums[i] or nums[i + 1]
if i == 0 or nums[i - 1] <= nums[i + 1]:
nums[i] = nums[i + 1] # Modify nums[i]
else:
nums[i + 1] = nums[i] # Modify nums[i + 1]
return True
# Example usage:
nums = [4, 2, 3]
print(checkPossibility(nums)) # Output: True
The time complexity for this approach is O(n)
, where n
is the length of the array. This is because we only traverse the array once to check for violations and possible fixes.
The space complexity is O(1)
since we only use a few auxiliary variables (count
) and modify the array in-place without requiring extra space.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?