#1909
Remove One Element to Make the Array Strictly Increasing
EasyArrayTwo PointersArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of checking all possible arrays, we can traverse the array once and count the number of violations of the strictly increasing condition. If there’s more than one violation, we can't fix it by removing just one element.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a counter for violations of the strictly increasing condition.
- 2Step 2: Traverse the array and check for violations (where nums[i] <= nums[i - 1]).
- 3Step 3: If there is more than one violation, return false. If there is one or none, return true.
solution.py10 lines
1def canBeMadeIncreasing(nums):
2 count = 0
3 for i in range(1, len(nums)):
4 if nums[i] <= nums[i - 1]:
5 count += 1
6 if count > 1:
7 return False
8 if i > 1 and nums[i] <= nums[i - 2] and i + 1 < len(nums) and nums[i + 1] <= nums[i - 1]:
9 return False
10 return Trueℹ
Complexity note: The time complexity is O(n) because we only traverse the array once, and the space complexity is O(1) since we use a fixed amount of extra space.
- 1Removing one element can fix at most one violation of the strictly increasing condition.
- 2If there are multiple violations, the array cannot be made strictly increasing by removing just one element.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.