Program to find shortest sublist so after sorting that entire list will be sorted in Python

Sometimes we need to find the shortest sublist that, when sorted, makes the entire list sorted. This problem involves comparing the original list with its sorted version to identify the boundaries of the unsorted region.

So, if the input is like nums = [1,2,5,4,9,10], then the output will be 2, as sorting the sublist [5,4] would make the entire list sorted: [1,2,4,5,9,10].

Algorithm

To solve this, we will follow these steps −

  • Initialize first := -1, last := -1 to track the boundaries
  • Create a sorted version of the input list
  • Compare each element with its sorted position
  • Mark the first and last positions where elements differ
  • Return the length of the sublist between these boundaries

Implementation

class Solution:
    def solve(self, nums):
        first = -1
        last = -1
        sorted_nums = sorted(nums)
        
        for i in range(len(nums)):
            if nums[i] != sorted_nums[i]:
                if first == -1:
                    first = i
                else:
                    last = i
        
        # If no differences found, array is already sorted
        if last == -1 and first == -1:
            return 0
        
        # If only one element differs, sublist length is 1
        if last == -1:
            return 1
            
        return last - first + 1

# Test the solution
ob = Solution()
result = ob.solve([1, 2, 5, 4, 9, 10])
print("Length of shortest sublist:", result)
Length of shortest sublist: 2

How It Works

The algorithm compares the original list [1,2,5,4,9,10] with its sorted version [1,2,4,5,9,10]. Elements at indices 2 and 3 differ (5?4 and 4?5), so the shortest sublist to sort is from index 2 to 3, which has length 2.

Example with Different Input

# Test with already sorted array
ob = Solution()
print("Already sorted:", ob.solve([1, 2, 3, 4, 5]))

# Test with completely unsorted array
print("Completely unsorted:", ob.solve([5, 4, 3, 2, 1]))

# Test with single element out of place
print("Single element:", ob.solve([1, 3, 2, 4, 5]))
Already sorted: 0
Completely unsorted: 5
Single element: 2

Conclusion

This solution compares the original array with its sorted version to find the boundaries of the unsorted region. The time complexity is O(n log n) due to sorting, and space complexity is O(n) for the sorted copy.

Updated on: 2026-03-25T10:30:57+05:30

301 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements