Given an integer array nums
, 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.
Return the shortest such subarray and output its length.
Here is the implementation using the sorting and comparison approach:
def findUnsortedSubarray(nums):
sorted_nums = sorted(nums)
start, end = 0, len(nums) - 1
while start < len(nums) and nums[start] == sorted_nums[start]:
start += 1
while end > start and nums[end] == sorted_nums[end]:
end -= 1
return end - start + 1 if end > start else 0
# Test cases
print(findUnsortedSubarray([2,6,4,8,10,9,15])) # Output: 5
print(findUnsortedSubarray([1,2,3,4])) # Output: 0
print(findUnsortedSubarray([1])) # Output: 0
Alternatively, if we implement the two pointers approach, it will have O(n) time complexity:
def findUnsortedSubarray(nums):
n = len(nums)
start, end = 0, -1
min_val, max_val = float('inf'), float('-inf')
for i in range(n):
if nums[i] < max_val:
end = i
else:
max_val = nums[i]
for i in range(n-1, -1, -1):
if nums[i] > min_val:
start = i
else:
min_val = nums[i]
return end - start + 1 if end > start else 0
# Test cases
print(findUnsortedSubarray([2,6,4,8,10,9,15])) # Output: 5
print(findUnsortedSubarray([1,2,3,4])) # Output: 0
print(findUnsortedSubarray([1])) # Output: 0
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?