Menu Close

Find the start and end index of unsorted sub-array

Find the start and end index of unsorted subarray such that sorting this subarray can sort all the array.

Input: [2,6,4,8,10,9,15]                    

Output: 1 5
#Starting Index is 1 and Ending index is 5
def shortsub(arr):
    N=len(arr)
    L,arr1 = [],arr[:]
    arr1.sort()
    for i in range(N):
        if(arr[i]!=arr1[i]):
            L.append(i)
    if bool(L):
        return [L[0],L[-1]]
    else:
        return 0

A=list(map(int,input("Array: ").split(" ")))
L=shortsub(A)
print(L[0],L[1]) if L!=0 else print(None)

INPUT_1:
Array:  2  6  4  8  10  9  15

OUTPUT:
1  5


INPUT_2:
Array:  1  2  3  4

OUTPUT:
None


INPUT_3:
Array:  1

OUTPUT:
None



INPUT_4:
Array:  10  12  20  30  25  40  32  31  35  50  60

OUTPUT:
3  8


INPUT_5:
Array:  0  1  15  25  6  7  30  40  50

OUTPUT:
2  5


ILLUSTRATION

EXECUTED USING PYTHON3

Morae Q!