Maximum Unsorted Subarray
1 min readOct 7, 2019
You are given an array (zero-indexed) of N non-negative integers, A0, A1 ,…, AN-1.
Find the minimum sub-array Al, Al+1 ,…, Ar so if we sort(in ascending order) that sub-array, then the whole array should get sorted.
If A is already sorted, output -1.
Get jatin grover’s stories in your inbox
Join Medium for free to get updates from this writer.
Example :
Input 1:A = [1, 3, 2, 4, 5]Return: [1, 2]Input 2:A = [1, 2, 3, 4, 5]Return: [-1]
Solution:
Steps:
- Find the first fluctuation going from left to right (“lpos”)
- Find the first fluctuation going from right to left (“rpos”)
- If no fluctuations return -1;
- Find “min” and “max” between “lpos” and “rpos”.
- Check the index from 0 to “lpos” which is having a value greater than the value at “min”. That index will be new “lpos”.
- Check index from “rpos+1” to n-1 which is having a value less than the value at “max”. That index will be new “rpos”.
- Return “lpos” and “rpos”.








