Given an integer array, find the smallest window sorting which will make the entire array sorted in increasing order.

For example,

Input:  { 1, 2, 3, 7, 5, 6, 4, 8 }
Output: Sort the array from index 3 to 6
 
 
Input:  { 1, 3, 2, 7, 5, 6, 4, 8 }
Output: Sort the array from index 1 to 6

Practice this problem

We can easily solve this problem in linear time. Following is the complete algorithm:

  1. Traverse array from left to right keeping track of maximum so far and note the last encountered index j which is less than the maximum so far.
  2. Traverse array from right to left keeping track of minimum so far and note the last encountered index i, which is more than the minimum so far.
  3. Finally, sort the array from index i to j.

For example, consider array { 1, 2, 3, 7, 5, 6, 4, 8 }. If we traverse the array from left to right, the last encountered index, which is less than the maximum so far, is 6. Similarly, if we traverse the array from right to left, the last encountered index, which is more than the minimum so far, is 3. So, we need to sort the array from index 3 to 6.

 
Following is the C++, Java, and Python implementation based on the above idea:

C++


Download  Run Code

Output:

Sort array from index 1 to 6

Java


Download  Run Code

Output:

Sort array from index 1 to 6

Python


Download  Run Code

Output:

Sort list from index 1 to 6

The time complexity of the above solution is O(n) and doesn’t require any extra space, where n is the size of the input.