Python 1574.py
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
# pad very small and very big numbers to simplify my algorithm
arr = [ -1 ] + arr + [ 10**10 ]
size = len(arr)
left = 0
right = size - 1
# find left and right part of the array that is properly sorted
while left < right and arr[left] <= arr[left + 1]:
left += 1
while left < right and arr[right - 1] <= arr[right]:
right -= 1
# everything's sorted
if left == right:
return 0
# worst case: remove all but one element
result = size - 1
# even though arr[0...left] and arr[right...size-1] are properly sorted,
# there might be a mismatch between arr[left] and arr[right]
for l in reversed(range(left + 1)):
for r in range(right, size):
length = r - l - 1
if length >= result: # no improvement
break
if arr[l] <= arr[r]: # yep, all sorted now
result = length
return result
Difficulty
and has an acceptance rate of about 51% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
- Monotonic Stack
- Stack
- Two Pointers
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The routine determines the minimal number of contiguous elements that must be removed from an integer list so that the remaining sequence is non-decreasing. It works by first extending the original list with sentinel values that simplify boundary conditions, then locating the longest sorted prefix and suffix, and finally attempting to join these two parts while scanning a reduced search space.
Key Steps
The algorithm begins by inserting a very small sentinel at the front and a very large sentinel at the end. This guarantees that any comparison involving the first or last real element will never fail because of missing neighbours.
arr = [ -1 ] + arr + [ 10**10 ]
size = len(arr)
Next, two pointers are moved inward to identify the longest sorted prefix (left) and the longest sorted suffix (right). The left pointer stops at the first position where the non-decreasing order breaks, while the right pointer stops at the last position where the order breaks when scanning from the end.
left = 0
right = size - 1
while left < right and arr[left] <= arr[left + 1]:
left += 1
while left < right and arr[right - 1] <= arr[right]:
right -= 1
If the two pointers meet, the entire array (including the sentinels) is already sorted, and no removal is necessary.
if left == right:
return 0
When the array is not fully sorted, the algorithm assumes the worst case: removing all elements except one. The initial result is therefore set to the length of the array minus one (the sentinels are not counted in the final answer).
result = size - 1
The core of the method is a double loop that tries to connect a prefix ending at index l with a suffix starting at index r. The outer loop iterates l backwards from left down to 0, and the inner loop iterates r forwards from right up to size. For each pair, the length of the segment that would be removed is r - l - 1. If this length is already no better than the current best (result), the inner loop breaks early because further increases of r can only make the removal longer. When the values at the two boundaries satisfy arr[l] <= arr[r], the combined prefix and suffix are non-decreasing, and the result is updated.
for l in reversed(range(left + 1)):
for r in range(right, size):
length = r - l - 1
if length >= result: # no improvement possible
break
if arr[l] <= arr[r]: # prefix and suffix can be joined
result = length
Finally, the minimal removal length is returned.
return result
Edge Cases Handled
The sentinel values -1 and 10**10 ensure that comparisons at the extreme ends never cause index errors, even when the original list is empty or contains a single element. The early exit if left == right: return 0 captures the situation where the original array is already sorted, including the case of a single-element array. Because the sentinels are smaller than any possible input value on the left and larger on the right, the algorithm correctly treats duplicate values as valid non-decreasing elements; the condition arr[l] <= arr[r] permits equality. The inner loop’s break condition prevents unnecessary work when the candidate removal length cannot improve the current best, which implicitly handles scenarios where the unsorted region is already minimal.
Performance Optimizations
Padding the array eliminates the need for explicit boundary checks inside the main loops, allowing the pointer movements and comparisons to be expressed without additional conditionals. By locating the longest sorted prefix and suffix before entering the double loop, the algorithm restricts the search space to the region that actually needs attention, avoiding a full O(n²) scan of the entire array. The outer loop iterates only over indices up to left, and the inner loop starts at right, both of which are typically far inside the array for partially sorted inputs. The early termination if length >= result: break stops the inner loop as soon as the removal length cannot beat the current optimum, cutting off many unnecessary iterations. Using reversed(range(...)) for the left index ensures that larger prefixes are examined first, which often yields a good result early and triggers the break condition sooner. These choices collectively reduce the number of element comparisons and loop iterations, leading to a faster execution on typical inputs.
ELI5 - Simplified Explanation
Imagine a long row of numbered toy blocks. Some are already in order from smallest to biggest, but some are messy and jumbled in the middle. The goal is to take away as few blocks as possible so that the ones left sitting on the floor are all perfectly lined up in order.
First, the code adds two special blocks to the ends, a tiny one at the start and a giant one at the end, just to make counting easier. Then, the code starts looking from the left side and moves forward as long as the numbers keep getting bigger, and it does the same thing starting from the right side moving backward. If the two sides meet in the middle, it means all the blocks are already perfect and nothing needs to be removed.
Otherwise, the code starts testing different ways to bridge the gap between the good left side and the good right side. It tries swapping out the middle part by checking every combination of where the left side could end and the right side could begin. If a piece fits, it checks to see if that way of connecting the two sides uses fewer removed blocks than the previous way. By looking at all these small pieces, the code finds the smallest set of blocks that must be taken away to leave a perfectly ordered line.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | C++ | JS | Java | Python | Go | TS | |||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| Shamik07 | Dart | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| withaarzoo | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| Shamik07 | Dart | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| withaarzoo | C++ |
Videos
Similar Problems
- problem 2970: Count the Number of Incremovable Subarrays I
- problem 2972: Count the Number of Incremovable Subarrays II
Solved On The Same Day
- problem 1462: Course Schedule IV
- problem 1497: Check If Array Pairs Are Divisible by k
- problem 1590: Make Sum Divisible by P
- problem 1654: Minimum Jumps to Reach Home
- problem 1733: Minimum Number of People to Teach
- problem 1750: Minimum Length of String After Deleting Similar Ends
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality