Minimum length subarray containing all unique elements after Q operations | Function to find minimum size subarray of all array elements ; Updating the array after processing each query ; Making it to 0 - indexing ; Prefix sum array concept is used to obtain the count array ; Iterating over the array to get the final array ; Variable to get count of all unique elements ; Hash to maintain perviously occurred elements ; Loop to find the all unique elements ; Array to maintain counter of encountered elements ; Variable to store answer ; Using two pointers approach ; Increment counter if occurred once ; When all unique elements are found ; update answer with minimum size ; Decrement count of elements from left ; Decrement counter ; Driver code
def subarrayLength ( A , R , N , M ) : NEW_LINE INDENT for i in range ( M ) : NEW_LINE INDENT l = R [ i ] [ 0 ] NEW_LINE r = R [ i ] [ 1 ] + 1 NEW_LINE l -= 1 NEW_LINE r -= 1 NEW_LINE A [ l ] += 1 NEW_LINE if ( r < N ) : NEW_LINE INDENT A [ r ] -= 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT A [ i ] += A [ i - 1 ] NEW_LINE DEDENT count = 0 NEW_LINE s = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( A [ i ] not in s ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT s . append ( A [ i ] ) NEW_LINE DEDENT repeat = [ 0 ] * ( count + 1 ) NEW_LINE ans = N NEW_LINE counter , left , right = 0 , 0 , 0 NEW_LINE while ( right < N ) : NEW_LINE INDENT cur_element = A [ right ] NEW_LINE repeat [ cur_element ] += 1 NEW_LINE if ( repeat [ cur_element ] == 1 ) : NEW_LINE INDENT counter += 1 NEW_LINE DEDENT while ( counter == count ) : NEW_LINE INDENT ans = min ( ans , right - left + 1 ) NEW_LINE cur_element = A [ left ] NEW_LINE repeat [ cur_element ] -= 1 NEW_LINE left += 1 NEW_LINE if ( repeat [ cur_element ] == 0 ) : NEW_LINE INDENT counter -= 1 NEW_LINE DEDENT DEDENT right += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N , queries = 8 , 6 NEW_LINE Q = [ [ 1 , 4 ] , [ 3 , 4 ] , [ 4 , 5 ] , [ 5 , 5 ] , [ 7 , 8 ] , [ 8 , 8 ] ] NEW_LINE A = [ 0 ] * N NEW_LINE print ( subarrayLength ( A , Q , N , queries ) ) NEW_LINE DEDENT