Remove One Element to Make the Array Strictly Increasing Problem
#1909
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1909.
Given a 0-indexed integer array nums, return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true.
The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length).
Example 1:
Input: nums = [1,2,10,5,7]
Output: true
Explanation: By removing 10 at index 2 from nums, it becomes [1,2,5,7].
[1,2,5,7] is strictly increasing, so return true.
Example 2:
Input: nums = [2,3,1,2]
Output: false
Explanation:
[3,1,2] is the result of removing the element at index 0.
[2,1,2] is the result of removing the element at index 1.
[2,3,2] is the result of removing the element at index 2.
[2,3,1] is the result of removing the element at index 3.
No resulting array is strictly increasing, so return false.
Example 3:
Input: nums = [1,1,1]
Output: false
Explanation: The result of removing any element is [1,1].
[1,1] is not strictly increasing, so return false.
Constraints:
2 <= nums.length <= 10001 <= nums[i] <= 1000
Solution
Approach: Find the First Violation
Scan for the first index i with nums[i] >= nums[i + 1]. If there is none, the array is already strictly increasing, and removing any element keeps it so, so return true.
Otherwise the removed element must be nums[i] or nums[i + 1]. Try both removals and check whether the rest is strictly increasing; return true if either works.
Complexity: O(n) time and O(1) extra space.
class Solution:
def canBeIncreasing(self, nums: List[int]) -> bool:
def check(k: int) -> bool:
pre = 0
for i, x in enumerate(nums):
if i == k:
continue
if pre >= x:
return False
pre = x
return True
i = 0
while i + 1 < len(nums) and nums[i] < nums[i + 1]:
i += 1
return check(i) or check(i + 1)