Blog Details

Shortest Unsorted Continuous Subarray

1. Description

Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.

You need to find the shortest such subarray and output its length.

Example 1:

Input: [2, 6, 4, 8, 10, 9, 15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.

2. Solution

Have one sorted array, and find the starting difference and ending difference.

class Solution {
    public int findUnsortedSubarray(int[] nums) {
        int[] sortedNums = nums.clone();
        Arrays.sort(sortedNums);
        int start = 0;
        int end = 0;
        for(int i = 0; i < nums.length; i ++) {
            if(nums[i] != sortedNums[i]) {
                start = i;
                break;
            }
        }
        
        for(int i = nums.length - 1; i >= 0; i --) {
            if(nums[i] != sortedNums[i]) {
                end = i;
                break;
            }
        }
        return end==0?0:end-start+1;
        // time O(nlogn): sort alg, space: O(n)
    }
}

3. Complexity

Time complexity: O(n)

Space: O(n)