Find the count of distinct numbers in a range | Java Program to find the distinct elements in a range ; Function to perform queries in a range ; No overlap ; Totally Overlap ; Partial Overlap ; Finding the Answer for the left Child ; Finding the Answer for the right Child ; Combining the BitMasks ; Function to perform update operation in the Segment seg ; Forming the BitMask ; Updating the left Child ; Updating the right Child ; Updating the BitMask ; Building the Segment Tree ; Building the Initial BitMask ; Building the left seg tree ; Building the right seg tree ; Forming the BitMask ; Utility Function to answer the queries ; Counting the set bits which denote the distinct elements ; Updating the value ; Driver Code
import java . util . * ; class GFG { static long query ( int start , int end , int left , int right , int node , long seg [ ] ) { if ( end < left start > right ) { return 0 ; } else if ( start >= left && end <= right ) { return seg [ node ] ; } else { int mid = ( start + end ) / 2 ; long leftChild = query ( start , mid , left , right , 2 * node , seg ) ; long rightChild = query ( mid + 1 , end , left , right , 2 * node + 1 , seg ) ; return ( leftChild rightChild ) ; } } static void update ( int left , int right , int index , int Value , int node , int ar [ ] , long seg [ ] ) { if ( left == right ) { ar [ index ] = Value ; seg [ node ] = ( 1L << Value ) ; return ; } int mid = ( left + right ) / 2 ; if ( index > mid ) { update ( mid + 1 , right , index , Value , 2 * node + 1 , ar , seg ) ; } else { update ( left , mid , index , Value , 2 * node , ar , seg ) ; } seg [ node ] = ( seg [ 2 * node ] seg [ 2 * node + 1 ] ) ; } static void build ( int left , int right , int node , int ar [ ] , long seg [ ] ) { if ( left == right ) { seg [ node ] = ( 1L << ar [ left ] ) ; return ; } int mid = ( left + right ) / 2 ; build ( left , mid , 2 * node , ar , seg ) ; build ( mid + 1 , right , 2 * node + 1 , ar , seg ) ; seg [ node ] = ( seg [ 2 * node ] seg [ 2 * node + 1 ] ) ; } static void getDistinctCount ( int [ ] [ ] queries , int ar [ ] , long seg [ ] , int n ) { for ( int i = 0 ; i < queries . length ; i ++ ) { int op = queries [ i ] [ 0 ] ; if ( op == 2 ) { int l = queries [ i ] [ 1 ] , r = queries [ i ] [ 2 ] ; long tempMask = query ( 0 , n - 1 , l - 1 , r - 1 , 1 , seg ) ; int countOfBits = 0 ; for ( int s = 63 ; s >= 0 ; s -- ) { if ( ( tempMask & ( 1L << s ) ) > 0 ) { countOfBits ++ ; } } System . out . println ( countOfBits ) ; } else { int index = queries [ i ] [ 1 ] ; int val = queries [ i ] [ 2 ] ; update ( 0 , n - 1 , index - 1 , val , 1 , ar , seg ) ; } } } public static void main ( String [ ] args ) { int n = 7 ; int ar [ ] = { 1 , 2 , 1 , 3 , 1 , 2 , 1 } ; long seg [ ] = new long [ 4 * n ] ; build ( 0 , n - 1 , 1 , ar , seg ) ; int [ ] [ ] queries = { { 2 , 1 , 4 } , { 1 , 4 , 2 } , { 1 , 5 , 2 } , { 2 , 4 , 6 } , { 2 , 1 , 7 } } ; getDistinctCount ( queries , ar , seg , n ) ; } }