easy +10 pts

Shortest Unsorted Continuous Subarray

Find the minimal contiguous segment to sort to make the entire array sorted.

Write a function `find_unsorted_length(nums)` that takes a list of integers `nums` and returns the length of the shortest contiguous subarray such that if you sorted this subarray in ascending order, the entire array would become sorted in non-decreasing order. If the array is already sorted (or has fewer than 2 elements), return 0. For example, `nums = [2,6,4,8,10,9,15]` → the subarray from index 1 to 5 (`[6,4,8,10,9]`) is the shortest, so return `5`. You must implement the function exactly with the signature `def find_unsorted_length(nums: list) -> int:`. The input list may contain duplicates. The function should not modify the input list.

Constraints

- `0 <= len(nums) <= 10^5` - Each element is an integer within `[-10^9, 10^9]`. - Expected time complexity: O(n) or O(n log n).

Example

>>> find_unsorted_length([2,6,4,8,10,9,15])
5
>>> find_unsorted_length([1,2,3,4])
0
>>> find_unsorted_length([1,3,2,2,2])
4
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Think about the leftmost and rightmost positions where the array violates the sorted order.
After finding the first and last out-of-place elements, the answer is not simply the distance between them—why?
Consider using the sorted version of the array and comparing elements from both ends.
The result is the number of elements between the first and last mismatch (inclusive) if any mismatches exist.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.