FunctionRacerProblemsRace

Shortest Span to Sort

MediumArraysPython, JavaScript, TypeScript, Java, C++

Find the shortest stretch of consecutive items of nums such that sorting only that stretch in non-decreasing order makes the whole list non-decreasing.

Return the length of that stretch. When nums is already in non-decreasing order (an empty list counts), return 0.

Example 1

nums [2,6,4,8,10,9,15]
returns 5

Sorting 6, 4, 8, 10, 9 gives 2, 4, 6, 8, 9, 10, 15. No shorter stretch works, since both the 4 and the 9 are out of place.

Example 2

nums [1,2,3]
returns 0

Already sorted.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Arrays problems