Skip to content

1909. Remove One Element to Make the Array Strictly Increasing

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  bool canBeIncreasing(vector<int>& nums) {
    bool removed = false;

    for (int i = 1; i < nums.size(); ++i)
      if (nums[i - 1] >= nums[i]) {
        if (removed)
          return false;
        removed = true;  // Remove nums[i - 1].
        if (i > 1 && nums[i - 2] >= nums[i])
          nums[i] = nums[i - 1];  // Remove nums[i] instead.
      }

    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public boolean canBeIncreasing(int[] nums) {
    boolean removed = false;

    for (int i = 1; i < nums.length; ++i)
      if (nums[i - 1] >= nums[i]) {
        if (removed)
          return false;
        removed = true; // Remove nums[i - 1].
        if (i > 1 && nums[i - 2] >= nums[i])
          nums[i] = nums[i - 1]; // Remove nums[i] instead.
      }

    return true;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def canBeIncreasing(self, nums: list[int]) -> bool:
    removed = False

    for i in range(1, len(nums)):
      if nums[i - 1] >= nums[i]:
        if removed:
          return False
        removed = True  # Remove nums[i - 1].
        if i > 1 and nums[i - 2] >= nums[i]:
          nums[i] = nums[i - 1]  # Remove nums[i] instead.

    return True