#K57847. Find the Unsorted Subarray

    ID: 30511 Type: Default 1000ms 256MiB

Find the Unsorted Subarray

Find the Unsorted Subarray

You are given an array of integers. Your task is to find the smallest continuous subarray such that if you sort this subarray, the whole array becomes sorted. If the array is already sorted, output -1 -1.

More formally, you need to find indices l and r such that sorting the subarray arr[l...r] results in the entire array being in non-decreasing order. If no such subarray exists because the array is already sorted, output -1 -1.

Note: The boundaries of the subarray may need to be extended if there are elements outside the initially identified unsorted region that would disrupt the sorted order after sorting the subarray.

Example:

If arr = [1, 2, 4, 5, 3, 5, 6], then the output should be 2 4 because sorting the subarray from index 2 to 4 (0-indexed) gives a fully sorted array.

inputFormat

The input is read from stdin and consists of:

  • An integer n denoting the number of elements in the array.
  • n space-separated integers representing the array.

For example:

7
1 2 4 5 3 5 6

outputFormat

Output to stdout two integers separated by a space: the starting and ending indices (0-indexed) of the smallest subarray that must be sorted. If the array is already sorted, output -1 -1.

For example:

2 4
## sample
7
1 2 4 5 3 5 6
2 4