Menu Close

Sort a sub-array which makes whole array sorted…FTC

Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.

Return the shortest such subarray and output its length.

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

Output: 5

Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
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):
        L=list(range(L[0],L[-1]+1,1))
        l1 = []
        l1 = arr[L[0]:L[-1]+1]
        l1.sort()
        return len(l1)
    else:
        return 0

A=list(map(int,input("Array: ").split(" ")))
print(shortsub(A))

INPUT_1:
Array:  2  6  4  8  10  9  15

OUTPUT:
5


INPUT_2:
Array:  1  2  3  4

OUTPUT:
0


INPUT_3:
Array:  1

OUTPUT:
0


 


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


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

OUTPUT:
4


ILLUSTRATION

EXECUTED USING PYTHON3 LINUX