Suppose we have an integer array, we need to find one continuous subarray such that, if we only sort that subarray in ascending order, then the whole array will be sorted too. We need to find the shortest such subarray and output its length. So if the array is [2,6,4,8,10,9,15], then the output will be 5. The array will be [6,4,8,10,9]
To solve this, we will follow these steps −
res := sort the nums as an array
ans := 0
set r as a linked list
for i in range 0 to the length of res
if nums[i] is not same as res[i], then insert i into the r
if the length of r is 0, then return 0, if the length of r is 1, then return 1
return the last element of r – first element of r + 1
Example (Python)
Let us see the following implementation to get a better understanding −
class Solution(object): def findUnsortedSubarray(self, nums): res = sorted(nums) ans = 0 r = [] for i in range(len(res)): if nums[i] != res[i]: r.append(i) if not len(r): return 0 if len(r) == 1: return 1 return r[-1]-r[0]+1 ob1 = Solution() print(ob1.findUnsortedSubarray([2,6,4,8,10,9,15]))
Input
[2,6,4,8,10,9,15]
Output
5