Shortest Unsorted Continuous Subarray
MediumArrays & Hashingtwo pointers
Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.
Practice this as a mock interviewFree to start, no account neededProblem
Given an integer array nums, find the shortest contiguous subarray such that sorting just that subarray in ascending order makes the entire array sorted in non-decreasing order.
Return the length of that subarray. If the array is already sorted, return 0. Target O(n) time and O(1) extra space.
Examples
Input: nums = [2,6,4,8,10,9,15]
Output: 5
Sorting [6,4,8,10,9] makes the whole array sorted.
Input: nums = [1,2,3,4]
Output: 0
The array is already sorted.
Input: nums = [1]
Output: 0
A single element is already sorted.
Constraints
- 1 <= nums.length <= 10^4
- -10^5 <= nums[i] <= 10^5
What the interviewer grades
A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.