Length of smallest subarray to be removed such that the remaining array is sorted | Python3 program for the above approach ; Find the length of the shortest subarray ; To store the result ; Calculate the possible length of the sorted subarray from left ; Array is sorted ; Calculate the possible length of the sorted subarray from left ; Update the result ; Calculate the possible length in the middle we can delete and update the result ; Update the result ; Return the result ; Driver Code ; Function Call
import sys NEW_LINE def findLengthOfShortestSubarray ( arr ) : NEW_LINE INDENT minlength = sys . maxsize NEW_LINE left = 0 NEW_LINE right = len ( arr ) - 1 NEW_LINE while left < right and arr [ left + 1 ] >= arr [ left ] : NEW_LINE INDENT left += 1 NEW_LINE DEDENT if left == len ( arr ) - 1 : NEW_LINE INDENT return 0 NEW_LINE DEDENT while right > left and arr [ right - 1 ] <= arr [ right ] : NEW_LINE INDENT right -= 1 NEW_LINE DEDENT minlength = min ( len ( arr ) - left - 1 , right ) NEW_LINE j = right NEW_LINE for i in range ( left + 1 ) : NEW_LINE INDENT if arr [ i ] <= arr [ j ] : NEW_LINE INDENT minlength = min ( minlength , j - i - 1 ) NEW_LINE DEDENT elif j < len ( arr ) - 1 : NEW_LINE INDENT j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return minlength NEW_LINE DEDENT arr = [ 6 , 3 , 10 , 11 , 15 , 20 , 13 , 3 , 18 , 12 ] NEW_LINE print ( findLengthOfShortestSubarray ( arr ) ) NEW_LINE