Minimum Prefix Removal to Make Array Strictly Increasing Problem
#3818
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 3818.
You are given an integer array nums.
You need to remove exactly one prefix (possibly empty) from nums.
Return an integer denoting the minimum length of the removed prefix such that the remaining array is strictly increasing.
Example 1:
Input: nums = [1,-1,2,3,3,4,5]
Output: 4
Explanation:
Removing the prefix = [1, -1, 2, 3] leaves the remaining array [3, 4, 5] which is strictly increasing.
Example 2:
Input: nums = [4,3,-2,-5]
Output: 3
Explanation:
Removing the prefix = [4, 3, -2] leaves the remaining array [-5] which is strictly increasing.
Example 3:
Input: nums = [1,2,3,4]
Output: 0
Explanation:
The array nums = [1, 2, 3, 4] is already strictly increasing so removing an empty prefix is sufficient.
Constraints:
1 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9
Solution
Approach: Reverse Traversal
The part we keep must be a suffix, so walk from the end of the array toward the front and find the last position i where nums[i - 1] >= nums[i]. Everything up to and including nums[i - 1] has to go, so the answer is i.
If no such position exists, the array is already strictly increasing and the answer is 0.
Complexity: O(n) time and O(1) extra space, where n is the length of nums.
class Solution:
def minimumPrefixLength(self, nums: List[int]) -> int:
for i in range(len(nums) - 1, 0, -1):
if nums[i - 1] >= nums[i]:
return i
return 0