problem: https://leetcode.com/problems/shortest-unsorted-continuous-subarray/
not working for the test case [2,1]
answer should be [0,1]
it is returning [-1,-1]
problem: https://leetcode.com/problems/shortest-unsorted-continuous-subarray/
not working for the test case [2,1]
answer should be [0,1]
it is returning [-1,-1]
This is because in this case your smallest is equal to int max, what’s the logic you are using?
find the smallest and largest values from the unsorted array and then find their appropriate positions in the whole array and return those indices if already sorted return -1 -1 this is an edge case, the code is passing for other cases
And how are you doing this , I mean what logic?
first for loop mainly this
`
if(array[i + 1] < array[i] || array[i] < array[i - 1]){
smallest = min(smallest,array[i]);
largest = max(largest,array[i]);
}
In the other 2 while loops I put the smallest to the left and largest towards the right at their appropriate positions
Logic is correct, just side cases in for loop is issuing trouble. Is it working fine for array size equal to 3? Like [1,3,2] how many test cases is it getting passed?
Single for loop, won’t be sufficient for all checks, find minimum element whenever you encounter a downfall, starting from 0 till n-1. Then find maximum whenever you find uprise. From n-2 till 0 , if element at n-1 pos is smaller then the maximum element you have found in range from 0 - n-2, then n-1 will also be in subarray and need to be sorted. See this to find better insight,