Queries for number of distinct elements from a given index till last index in an array | Function to perform queries to find number of distinct elements from a given index till last index in an array ; Check if current element already visited or not ; If not visited store current counter and increment it and mark check as 1 ; Otherwise if visited simply store current counter ; Perform queries ; Driver code
function find_distinct ( a , n , q , queries ) { let MAX = 100001 ; let check = new Array ( MAX ) . fill ( 0 ) ; let idx = new Array ( MAX ) . fill ( 0 ) ; let cnt = 1 ; let i = n - 1 ; while ( i >= 0 ) { if ( check [ a [ i ] ] == 0 ) { idx [ i ] = cnt ; check [ a [ i ] ] = 1 ; cnt ++ ; } else { idx [ i ] = cnt - 1 ; } i -- ; } for ( let i = 0 ; i < q ; i ++ ) { let m = queries [ i ] ; document . write ( idx [ m ] + " " ) ; } } let a = [ 1 , 2 , 3 , 1 , 2 , 3 , 4 , 5 ] ; let n = a . length ; let queries = [ 0 , 3 , 5 , 7 ] ; let q = queries . length ; find_distinct ( a , n , q , queries ) ;