Non-decreasing Array - Problem

Imagine you're a quality control engineer for a data visualization company. You receive arrays of numerical data that should display as smooth, ascending charts - but sometimes there's exactly one data point that's out of place!

Given an array nums with n integers, determine if you can make it non-decreasing by modifying at most one element. An array is considered non-decreasing when nums[i] <= nums[i + 1] for every valid index i.

Your mission: Return true if the array can be fixed with one change (or is already perfect), false otherwise.

Example: [4,2,3] → Change the 4 to 1, getting [1,2,3]
[4,2,1] → Would need to change both 4 and 2 ❌

Input & Output

example_1.py — Basic Case
$ Input: nums = [4,2,3]
Output: true
💡 Note: You can modify the first element from 4 to 1 to get [1,2,3], which is non-decreasing.
example_2.py — Multiple Violations
$ Input: nums = [4,2,1]
Output: false
💡 Note: You would need to modify more than one element. Both 4>2 and 2>1 are violations, requiring at least 2 changes.
example_3.py — Already Valid
$ Input: nums = [1,2,3,4]
Output: true
💡 Note: The array is already non-decreasing, so no modifications are needed.

Visualization

Tap to expand
Smart Staircase Repair Strategy1OK4Too High!23Violation!Decision ProcessProblem: Step 4 > Step 2 (violation)Option 1: Lower step 4 to 2 ✓Option 2: Raise step 2 to 4 (would create [1,4,4] - less optimal)Choice: Lower step 4 because step 1 ≤ step 212Fixed!23Perfect Staircase: [1,2,2,3] ✓
Understanding the Visualization
1
Inspect Each Step
Walk through the staircase checking each transition
2
Find Problem
When step i is higher than step i+1, we have a violation
3
Smart Decision
Choose whether to lower step i or raise step i+1 based on step i-1
4
Apply Fix
Make the modification and continue inspection
Key Takeaway
🎯 Key Insight: When fixing a violation, always consider which modification maintains better consistency with neighboring elements. This greedy choice leads to the optimal solution!

Time & Space Complexity

Time Complexity
⏱️
O(n)

Single pass through the array, each element visited once

n
2n
Linear Growth
Space Complexity
O(1)

Only using constant extra space for counters and variables

n
2n
Linear Space

Constraints

  • 1 ≤ nums.length ≤ 104
  • -105 ≤ nums[i] ≤ 105
  • At most one element can be modified
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
67.5K Views
Medium Frequency
~25 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen