Shortest Subarray to be Removed to Make Array Sorted — LeetCode 1574 Python Solution

MediumStackArrayTwo PointersBinary SearchMonotonic Stack
Problem
#1574
Pattern
Stack
Reading time
3 min

The problem

Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing. Return the length of the shortest subarray to remove.

Example

Input
arr = [1,2,3,10,4,2,3,5]
Output
3
Explanation
The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.

Python solution

Python
class Solution:
    def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
        n = len(arr)
        i, j = 0, n - 1
        while i + 1 < n and arr[i] <= arr[i + 1]:
            i += 1
        while j - 1 >= 0 and arr[j - 1] <= arr[j]:
            j -= 1
        if i >= j:
            return 0
        ans = min(n - i - 1, j)
        for l in range(i + 1):
            r = bisect_left(arr, arr[l], lo=j)
            ans = min(ans, r - l - 1)
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log n), where n is the length of the array
SpaceO(1) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1574. Shortest Subarray to be Removed to Make Array Sorted is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1574. Shortest Subarray to be Removed to Make Array Sorted?
LeetCode 1574. Shortest Subarray to be Removed to Make Array Sorted is rated Medium on LeetCode.
What is the time complexity of LeetCode 1574. Shortest Subarray to be Removed to Make Array Sorted?
The Python solution on this page runs in O(n \times \log n), where n is the length of the array.
What is the space complexity of LeetCode 1574. Shortest Subarray to be Removed to Make Array Sorted?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1574. Shortest Subarray to be Removed to Make Array Sorted cover?
LeetCode 1574. Shortest Subarray to be Removed to Make Array Sorted is tagged Stack, Array, Two Pointers, Binary Search and Monotonic Stack on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview