Shortest Unsorted Continuous Subarray in Python

Given an integer array, we need to find the shortest continuous subarray that, when sorted, makes the entire array sorted. For example, in the array [2,6,4,8,10,9,15], the subarray [6,4,8,10,9] needs to be sorted to make the whole array sorted, so the answer is 5.

Approach

We compare the original array with its sorted version to identify positions where elements differ. The shortest subarray spans from the first differing position to the last differing position.

Algorithm Steps

  • Create a sorted copy of the input array

  • Compare each element with its sorted position

  • Store indices where elements differ

  • Return the distance between first and last differing indices

Implementation

class Solution:
    def findUnsortedSubarray(self, nums):
        sorted_nums = sorted(nums)
        differing_indices = []
        
        # Find all positions where elements differ
        for i in range(len(nums)):
            if nums[i] != sorted_nums[i]:
                differing_indices.append(i)
        
        # If no differences, array is already sorted
        if len(differing_indices) == 0:
            return 0
        
        # If only one difference, minimum subarray length is 1
        if len(differing_indices) == 1:
            return 1
        
        # Return length of subarray from first to last difference
        return differing_indices[-1] - differing_indices[0] + 1

# Test the solution
solution = Solution()
result = solution.findUnsortedSubarray([2,6,4,8,10,9,15])
print(f"Length of shortest unsorted subarray: {result}")
Length of shortest unsorted subarray: 5

How It Works

Let's trace through the example [2,6,4,8,10,9,15]:

nums = [2,6,4,8,10,9,15]
sorted_nums = [2,4,6,8,9,10,15]

# Comparing positions:
# Index 0: 2 == 2 ?
# Index 1: 6 != 4 ? (add index 1)
# Index 2: 4 != 6 ? (add index 2)  
# Index 3: 8 == 8 ?
# Index 4: 10 != 9 ? (add index 4)
# Index 5: 9 != 10 ? (add index 5)
# Index 6: 15 == 15 ?

differing_indices = [1, 2, 4, 5]
result = 5 - 1 + 1 = 5

Example with Already Sorted Array

solution = Solution()
result1 = solution.findUnsortedSubarray([1, 2, 3, 4])
result2 = solution.findUnsortedSubarray([2, 1])
print(f"Already sorted array: {result1}")
print(f"Two element unsorted array: {result2}")
Already sorted array: 0
Two element unsorted array: 2

Time and Space Complexity

  • Time Complexity: O(n log n) due to sorting the array

  • Space Complexity: O(n) for storing the sorted array and differing indices

Conclusion

This solution efficiently finds the shortest unsorted subarray by comparing the original array with its sorted version. The approach is straightforward and handles edge cases like already sorted arrays and single-element differences.

Updated on: 2026-03-25T07:30:39+05:30

385 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements