#3818
Minimum Prefix Removal to Make Array Strictly Increasing
MediumArrayArrayGreedy
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 prefixes, we can find the last point where the array stops being strictly increasing. This allows us to directly calculate the prefix length to remove.
⚙️
Algorithm
3 steps- 1Step 1: Traverse the array from the end to find the first index where nums[i] >= nums[i + 1].
- 2Step 2: If such an index is found, return index + 1 as the minimum prefix length to remove.
- 3Step 3: If no such index exists, return 0 since the array is already strictly increasing.
solution.py5 lines
1def min_prefix_removal(nums):
2 for i in range(len(nums) - 2, -1, -1):
3 if nums[i] >= nums[i + 1]:
4 return i + 1
5 return 0ℹ
Complexity note: This approach only requires a single pass through the array, leading to linear time complexity.
- 1Identify the last point of non-increasing order.
- 2Removing elements from the start simplifies the problem.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.