Shortest Unsorted Continuous Subarray
Real-world version: Shortest Stretch to Re-sortThe statement here is our own: the same inputs, outputs and technique.
A conveyor presents parts in the order given by nums, where nums[i] is the signed weight offset of the part in slot i. Offsets may be negative and two parts may share an offset.
An operator may pick out one unbroken stretch of slots, sort the parts inside it into non-decreasing order of offset, and put them back into the same slots. The goal is for the whole line, read from slot 0 to the last slot, to end up non-decreasing.
Return the length of the shortest stretch that achieves this. If the line is already non-decreasing, return 0.
Examples
Example 1
- Input
- nums = [1, 3, 5, 4, 2, 6]
- Output
- 4
Sorting slots 1 through 4, which hold 3, 5, 4 and 2, puts 2, 3, 4, 5 there and the line reads 1, 2, 3, 4, 5, 6. That stretch is four slots long, and no stretch of three or fewer slots leaves the line non-decreasing.
Example 2
- Input
- nums = [4, 4, 6, 8, 8]
- Output
- 0
Every slot already holds an offset at least as large as the one before it, so nothing has to be picked out.
Example 3
- Input
- nums = [-5, -5, -6, 4, 10, 10, 9]
- Output
- 7
Slot 2 holds -6, which has to move ahead of both -5s, and slot 6 holds 9, which has to move ahead of both 10s, so the stretch runs from slot 0 to slot 6 and covers all seven slots.
Constraints
- 1 <= nums.length <= 10^4
- -10^5 <= nums[i] <= 10^5
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def find_unsorted_subarray(nums: list[int]) -> int:public int findUnsortedSubarray(int[] nums)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 11 test cases: 11 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Max Chunks To Make SortedReal-world version: Most Blocks a Line Can Be Cut IntoMedium
- Create Maximum NumberReal-world version: The Largest Reading From Two TapesHard
- Max Chunks To Make Sorted IIReal-world version: Cutting the Row Into the Most BlocksHard
- Assign CookiesReal-world version: Scratch Space HandoutEasy