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 poleters 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
function subarrayLength ( A , R , N , M ) { for ( let i = 0 ; i < M ; ++ i ) { let l = R [ i ] [ 0 ] , r = R [ i ] [ 1 ] + 1 ; l -- ; r -- ; A [ l ] ++ ; if ( r < N ) A [ r ] -- ; } for ( let i = 1 ; i < N ; ++ i ) { A [ i ] += A [ i - 1 ] ; } let count = 0 ; let s = new Set ( ) ; for ( let i = 0 ; i < N ; ++ i ) { if ( ! s . has ( A [ i ] ) ) count ++ ; s . add ( A [ i ] ) ; } let repeat = Array . from ( { length : count + 1 } , ( _ , i ) => 0 ) ; let ans = N ; let counter = 0 , left = 0 , right = 0 ; while ( right < N ) { let cur_element = A [ right ] ; repeat [ cur_element ] += 1 ; if ( repeat [ cur_element ] == 1 ) ++ counter ; while ( counter == count ) { ans = Math . min ( ans , right - left + 1 ) ; cur_element = A [ left ] ; repeat [ cur_element ] -= 1 ; ++ left ; if ( repeat [ cur_element ] == 0 ) -- counter ; } ++ right ; } return ans ; } let N = 8 , queries = 6 ; let Q = [ [ 1 , 4 ] , [ 3 , 4 ] , [ 4 , 5 ] , [ 5 , 5 ] , [ 7 , 8 ] , [ 8 , 8 ] ] ; let A = Array . from ( { length : N } , ( _ , i ) => 0 ) ; document . write ( subarrayLength ( A , Q , N , queries ) ) ;