The Non-decreasing Array problem asks: given an integer array, can you make it non-decreasing by modifying at most one element? This Non-decreasing Array coding problem requires careful case analysis — when you find a violation (where arr[i] > arr[i+1]), you must decide whether to decrease arr[i] or increase arr[i+1] to fix it without creating new violations.
Cashfree, Meta, Walmart Labs, and Google ask this to test linear scan with careful case analysis. The naive approach — try all single-element changes — is O(n²). The O(n) solution requires reasoning about which element to modify when a violation is found. The array interview pattern is demonstrated here with precision.
Greedy single-pass with violation tracking. Traverse the array. On finding arr[i] > arr[i+1]: increment a modification counter. Then decide: if i > 0 and arr[i-1] > arr[i+1], we must increase arr[i+1] to arr[i] (can't decrease arr[i] below arr[i-1]). Otherwise, decrease arr[i] to arr[i+1]. If modifications > 1, return false. After the loop, return true.
Array: [4, 2, 3]. Violation at i=0 (4>2).
Array: [3, 4, 2, 3]. Violation at i=1 (4>2).
arr[i-1] > arr[i+1] when deciding which element to modify.The key insight for this problem is the greedy choice when a violation is found: prefer decreasing arr[i] (preserve the smaller arr[i+1]) unless the previous element forces you to increase arr[i+1]. Always update the effective value of the modified element so subsequent comparisons are correct. Practice this problem with multiple violation types to build confidence in the case analysis. It's a good O(n) greedy warm-up before harder interval problems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| All Divisions With the Highest Score of a Binary Array | Medium | Solve | |
| Remove Interval | Medium | Solve | |
| Insert Interval | Medium | Solve | |
| Maximum Value of an Ordered Triplet II | Medium | Solve | |
| Maximize Distance to Closest Person | Medium | Solve |