Length of smallest subarray required to be removed to make remaining elements consecutive | Function to find the length of the smallest subarray to be removed to make remaining array elements consecutive ; Store the ending index of the longest prefix consecutive array ; Traverse the array to find the longest prefix consecutive sequence ; A [ 0. . . left_index ] is the prefix consecutive sequence ; Store the starting index of the longest suffix consecutive sequence ; Traverse the array to find the longest suffix consecutive sequence ; A [ right_index ... N - 1 ] is the consecutive sequence ; Store the smallest subarray required to be removed ; Check if subarray from the middle can be removed ; Update the right index s . t . A [ 0 , N - 1 ] is consecutive ; If updated_right < N , then update the minimumLength ; Print the required result ; Driver Code
def shortestSubarray ( A , N ) : NEW_LINE INDENT i = 0 NEW_LINE left_index = 0 NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( A [ i ] + 1 != A [ i + 1 ] ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT left_index = i NEW_LINE right_index = 0 NEW_LINE i = N - 1 NEW_LINE while ( i >= 1 ) : NEW_LINE INDENT if ( A [ i ] != A [ i - 1 ] + 1 ) : NEW_LINE INDENT break NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT right_index = i NEW_LINE updated_right = 0 NEW_LINE minLength = min ( N - left_index - 1 , right_index ) NEW_LINE if ( A [ right_index ] <= A [ left_index ] + 1 ) : NEW_LINE INDENT updated_right = ( right_index + A [ left_index ] - A [ right_index ] + 1 ) NEW_LINE if ( updated_right < N ) : NEW_LINE INDENT minLength = min ( minLength , updated_right - left_index - 1 ) NEW_LINE DEDENT DEDENT print ( minLength ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 7 , 4 , 3 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE shortestSubarray ( arr , N ) NEW_LINE DEDENT