Sitemap
jatin grover

jatin grover

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:

  1. Find the first fluctuation going from left to right (“lpos”)
  2. Find the first fluctuation going from right to left (“rpos”)
  3. If no fluctuations return -1;
  4. Find “min” and “max” between “lpos” and “rpos”.
  5. Check the index from 0 to “lpos” which is having a value greater than the value at “min”. That index will be new “lpos”.
  6. 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”.
  7. Return “lpos” and “rpos”.

Code:

--

--