All problems
0582MediumArrayTwo PointersStackGreedySortingMonotonic Stack

Shortest Stretch to Re-sort

Tracked in this browser only
Write code

Trains the technique from

LeetCode 581Shortest Unsorted Continuous Subarray

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def find_unsorted_subarray(nums: list[int]) -> int:
Java
public int findUnsortedSubarray(int[] nums)
September 7
Apply