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 - Smart Violation Handling INPUT Array nums: i=0 i=1 i=2 4 2 3 Violation! 4 > 2 Problem: Can we make array non-decreasing by modifying at most ONE element? ALGORITHM STEPS 1 Scan Array Find nums[i] > nums[i+1] 2 Count Violations Track violation count 3 Smart Fix Check Modify nums[i] or nums[i+1] 4 Return Result violations <= 1 --> true Fix Options for [4,2,3]: Option A: Change 4-->2 [2,2,3] OK Option B: Change 2-->4 [4,4,3] X (4>3) FINAL RESULT Modified Array: 2 2 3 <= <= Output: true Verification: Only 1 modification needed (change 4 to 2) Key Insight: When we find a violation (nums[i] > nums[i+1]), we have two fix options: 1) Decrease nums[i] to nums[i+1], or 2) Increase nums[i+1] to nums[i]. Choose wisely based on surrounding elements. If violations > 1, return false. TutorialsPoint - Non-decreasing Array | Smart Violation Handling Approach
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