Simple Java Solution, sort and trim edges


  • 1

    The idea is to sort a copy of the array, and trim the edges to find the first and the last mismatch between both the arrays.
    This gives the minimum subarray that requires sorting.

    public static int findUnsortedSubarray(int[] nums) {
            int[] nums2 = Arrays.copyOf(nums, nums.length);
            Arrays.sort(nums2);
            int st = 0;
            int end = nums.length - 1;
    
            while(st < nums.length) {
                if(nums[st] != nums2[st]) break;
                st++;
            }
    
            while(end > -1) {
                if(nums[end] != nums2[end]) break;
                end--;
            }
    
            if(st > end)
                return 0;
            return end - st + 1;
        }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.