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
function shortestSubarray ( A , N ) { let i ; let left_index ; for ( i = 0 ; i < N - 1 ; i ++ ) { if ( A [ i ] + 1 != A [ i + 1 ] ) break ; } left_index = i ; let right_index ; for ( i = N - 1 ; i >= 1 ; i -- ) { if ( A [ i ] != A [ i - 1 ] + 1 ) break ; } right_index = i ; let updated_right ; let minLength = Math . min ( N - left_index - 1 , right_index ) ; if ( A [ right_index ] <= A [ left_index ] + 1 ) { updated_right = right_index + A [ left_index ] - A [ right_index ] + 1 ; if ( updated_right < N ) minLength = Math . min ( minLength , updated_right - left_index - 1 ) ; } document . write ( minLength ) ; } let arr = [ 1 , 2 , 3 , 7 , 4 , 3 , 5 ] ; let N = arr . length ; shortestSubarray ( arr , N ) ;