Skip to content
Problem 665 · LeetCode 665(opens in a new tab)

Non-decreasing Array

MediumArrays

You get an array of integers, nums. You may replace at most one of its values with any integer you like.

Return true if, after that, every value is less than or equal to the one after it (the array never goes down). Otherwise return false.

Example 1

Input:  nums = [3, 5, 2, 6]
Output: true
Why:    change the 2 to 5, giving 3, 5, 5, 6
2 more examples and the constraints

Example 2

Input:  nums = [6, 3, 2]
Output: false
Why:    there are two drops, and one change fixes only one

Example 3

Input:  nums = [1, 4, 2, 3]
Output: true
Why:    change the 4 to 2, giving 1, 2, 2, 3

Constraints

  • 1 ≤ length of nums ≤ 10,000
  • −100,000 ≤ nums[i] ≤ 100,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try each indexO(n²)
  2. One pass, one repairO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 valuesVerdict
Try each indexO(n²)
Clear, but rescans n times
One pass, one repairO(n)
Best; decide the fix on the spot

n = length of nums.

Edge cases to test

  • One or two values. [7] and [4, 2] are always true: one change fixes any single pair.
  • Drop at the very start. [5, 1, 2, 3]: there is no nums[i − 2], so lower the 5.
  • Lowering is not allowed. [3, 4, 2, 3]: lowering 4 breaks 3 ≤ 2; raising 2 makes a new drop. False.
  • Equal neighbours. [2, 3, 3, 2, 4]: equal values are fine; raise the last 2 to 3.
  • Two separate drops. [1, 5, 4, 6, 7, 10, 8, 9] has two drops far apart, so false.

Common mistakes

  • Only counting drops, which says true for [3, 4, 2, 3].
  • Always lowering the left value, even when nums[i − 2] is bigger than nums[i].
  • Forgetting to write the repair back, so the next comparison uses the old value.

How to talk through it

  1. 1Clarify. Is ≤ allowed between neighbours? Can the new value be anything, even negative?
  2. 2Give the brute force. Try each index as the one to change and check the rest: O(n²).
  3. 3Spot the choice. At a drop, either the left value goes down or the right one goes up.
  4. 4State the rule. Lower the left one when nums[i − 2] allows it; else raise the right one. A second drop fails.
  5. 5Test out loud. Run [3, 4, 2, 3] and [5, 1, 2, 3] before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?