text: Queries for number of distinct elements from a given index till last index in an array | Java implementation of the approach ; 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
code: import java . util . * ; class GFG { static int MAX = 100001 ; static void find_distinct ( int a [ ] , int n , int q , int queries [ ] ) { int [ ] check = new int [ MAX ] ; int [ ] idx = new int [ MAX ] ; int cnt = 1 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( check [ a [ i ] ] == 0 ) { idx [ i ] = cnt ; check [ a [ i ] ] = 1 ; cnt ++ ; } else { idx [ i ] = cnt - 1 ; } } for ( int i = 0 ; i < q ; i ++ ) { int m = queries [ i ] ; System . out . print ( idx [ m ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int a [ ] = { 1 , 2 , 3 , 1 , 2 , 3 , 4 , 5 } ; int n = a . length ; int queries [ ] = { 0 , 3 , 5 , 7 } ; int q = queries . length ; find_distinct ( a , n , q , queries ) ; } }