Non-decreasing Array - Problem

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 is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that 0 <= i <= n - 2.

Input & Output

Example 1 — Single Violation
$ Input: nums = [4,2,3]
Output: true
💡 Note: We can modify nums[0] = 2 to get [2,2,3] which is non-decreasing, or nums[1] = 4 to get [4,4,3] but that creates another violation. The first option works.
Example 2 — Multiple Violations
$ Input: nums = [4,2,1]
Output: false
💡 Note: We have violations at indices 0->1 (4>2) and 1->2 (2>1). Since we can only modify one element, we cannot fix both violations.
Example 3 — Already Sorted
$ Input: nums = [1,2,3,4]
Output: true
💡 Note: Array is already non-decreasing, no modifications needed.

Constraints

  • 2 ≤ nums.length ≤ 104
  • -105 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Non-decreasing Array Problem OverviewInput Array4234 > 2 (violation)AnalysisCount violations: 1Can fix? Check neighborsnums[i-1] ≤ nums[i+1]? No i-1nums[i] ≤ nums[i+2]? No i+2At boundary, can fix!Fixed Array2232 ≤ 2 ≤ 3 ✓Change nums[0] = 2Result: true (can be fixed with 1 modification)
Understanding the Visualization
1
Input
Array [4,2,3] with violation at 4>2
2
Process
Identify violations and apply smart fixing
3
Output
Return true if fixable with ≤1 modification
Key Takeaway
🎯 Key Insight: Count violations first - if more than one, impossible to fix with single modification
Asked in
Google 15 Facebook 12 Microsoft 8
180.0K Views
Medium Frequency
~25 min Avg. Time
3.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