"Queries to calculate sum by alternating signs of array elements in a given range | Java program to implement the above approach ; Function to build the segment tree ; If current node is a leaf node of the segment tree ; Update tree [ index ] ; Update tree [ index ] ; Divide the segment tree ; Update on L segment tree ; Update on R segment tree ; Find the sum from L subtree and R subtree ; Function to update elements at index pos by val in the segment tree ; If current node is a leaf node ; If current index is even ; Update tree [ index ] ; Update tree [ index ] ; Divide the segment tree elements into L and R subtree ; If element lies in L subtree ; Update tree [ index ] ; Function to find the sum of array elements in the range [ L , R ] ; If start and end not lies in the range [ L , R ] ; If start and end comleately lies in the range [ L , R ] ; Stores sum from left subtree ; Stores sum from right subtree ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void build ( int tree [ ] , int arr [ ] , int start , int end , int index ) { if ( start == end ) { if ( start % 2 == 0 ) { tree [ index ] = arr [ start ] ; } else { tree [ index ] = - arr [ start ] ; } return ; } int mid = start + ( end - start ) / 2 ; build ( tree , arr , start , mid , 2 * index + 1 ) ; build ( tree , arr , mid + 1 , end , 2 * index + 2 ) ; tree [ index ] = tree [ 2 * index + 1 ] + tree [ 2 * index + 2 ] ; } static void update ( int tree [ ] , int index , int start , int end , int pos , int val ) { if ( start == end ) { if ( start % 2 == 0 ) { tree [ index ] = val ; } else { tree [ index ] = - val ; } return ; } int mid = start + ( end - start ) / 2 ; if ( mid >= pos ) { update ( tree , 2 * index + 1 , start , mid , pos , val ) ; } else { update ( tree , 2 * index + 2 , mid + 1 , end , pos , val ) ; } tree [ index ] = tree [ 2 * index + 1 ] + tree [ 2 * index + 2 ] ; } static int FindSum ( int tree [ ] , int start , int end , int L , int R , int index ) { if ( L > end R < start ) { return 0 ; } if ( L <= start && R >= end ) { return tree [ index ] ; } int mid = start + ( end - start ) / 2 ; int X = FindSum ( tree , start , mid , L , R , 2 * index + 1 ) ; int Y = FindSum ( tree , mid + 1 , end , L , R , 2 * index + 2 ) ; return X + Y ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = arr . length ; int tree [ ] = new int [ 4 * N + 5 ] ; Arrays . fill ( tree , 0 ) ; build ( tree , arr , 0 , N - 1 , 0 ) ; int Q [ ] [ ] = { { 2 , 0 , 3 } , { 1 , 1 , 5 } , { 2 , 1 , 2 } } ; int cntQuey = 3 ; for ( int i = 0 ; i < cntQuey ; i ++ ) { if ( Q [ i ] [ 0 ] == 1 ) { update ( tree , 0 , 0 , N - 1 , Q [ i ] [ 1 ] , Q [ i ] [ 2 ] ) ; } else { if ( Q [ i ] [ 1 ] % 2 == 0 ) { System . out . print ( FindSum ( tree , 0 , N - 1 , Q [ i ] [ 1 ] , Q [ i ] [ 2 ] , 0 ) + " ▁ " ) ; } else { System . out . print ( - FindSum ( tree , 0 , N - 1 , Q [ i ] [ 1 ] , Q [ i ] [ 2 ] , 0 ) + " ▁ " ) ; } } } } }


"Queries to calculate sum of array elements consisting of odd number of divisors | java program for the above approach ; Function to get the middle index from the given ranges ; Recursive function to find the sum of values in the given range of the array ; If segment of this node is a part of given range , then return the sum of the segment ; If segment of this node is outside the given range ; If a part of this segment overlaps the given range ; Function to find the sum of elements in the range from index qs ( query start ) to qe ( query end ) ; Invalid ranges ; Recursive function to construct the Segment Tree for array [ ss . . se ] . si is index of current node in tree st ; If there is one element in the array ; Recur for left and right subtrees and store the sum of values in this node ; Function to construct segment tree from the given array ; Allocate memory for the segment tree Height of segment tree ; Maximum size of segment tree ; Allocate memory ; Fill the allocated memory st ; Return the constructed segment tree ; Function to find the sum of elements having odd number of divisors in index range [ L , R ] for Q queries ; Traverse the array , arr [ ] ; Replace elements that are not perfect squares with 0 ; Build segment tree from the given array ; Iterate through all the queries ; Print sum of values in array from index l to r ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; public class GFG { static int getMid ( int s , int e ) { return s + ( e - s ) / 2 ; } static int getSumUtil ( int st [ ] , int ss , int se , int qs , int qe , int si ) { if ( qs <= ss && qe >= se ) return st [ si ] ; if ( se < qs ss > qe ) return 0 ; int mid = getMid ( ss , se ) ; return getSumUtil ( st , ss , mid , qs , qe , 2 * si + 1 ) + getSumUtil ( st , mid + 1 , se , qs , qe , 2 * si + 2 ) ; } static int getSum ( int st [ ] , int n , int qs , int qe ) { if ( qs < 0 qe > n - 1 qs > qe ) { System . out . println ( " Invalid ▁ Input " ) ; return - 1 ; } return getSumUtil ( st , 0 , n - 1 , qs , qe , 0 ) ; } static int constructSTUtil ( int arr [ ] , int ss , int se , int st [ ] , int si ) { if ( ss == se ) { st [ si ] = arr [ ss ] ; return arr [ ss ] ; } int mid = getMid ( ss , se ) ; st [ si ] = constructSTUtil ( arr , ss , mid , st , si * 2 + 1 ) + constructSTUtil ( arr , mid + 1 , se , st , si * 2 + 2 ) ; return st [ si ] ; } static int [ ] constructST ( int arr [ ] , int n ) { int x = ( int ) ( Math . ceil ( Math . log ( n ) / Math . log ( 2 ) ) ) ; int max_size = 2 * ( int ) Math . pow ( 2 , x ) - 1 ; int st [ ] = new int [ max_size ] ; constructSTUtil ( arr , 0 , n - 1 , st , 0 ) ; return st ; } static void OddDivisorsSum ( int n , int q , int arr [ ] , int Query [ ] [ ] ) { for ( int i = 0 ; i < n ; i ++ ) { int sq = ( int ) Math . sqrt ( arr [ i ] ) ; if ( sq * sq != arr [ i ] ) arr [ i ] = 0 ; } int st [ ] = constructST ( arr , n ) ; for ( int i = 0 ; i < q ; i ++ ) { int l = Query [ i ] [ 0 ] ; int r = Query [ i ] [ 1 ] ; System . out . print ( getSum ( st , n , l , r ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 4 , 5 , 6 , 9 } ; int N = arr . length ; int Q = 3 ; int Query [ ] [ ] = { { 0 , 2 } , { 1 , 3 } , { 1 , 4 } } ; OddDivisorsSum ( N , Q , arr , Query ) ; } }


"Queries to calculate sum of array elements consisting of odd number of divisors | package whatever do not write package name here ; Function to find the sum of elements having odd number of divisors in index range [ L , R ] for Q queries ; Initialize the dp [ ] array ; Traverse the array , arr [ ] ; If a [ i ] is a perfect square , then update value of DP [ i ] to a [ i ] ; Find the prefix sum of DP [ ] array ; Iterate through all the queries ; Find the sum for each query ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void OddDivisorsSum ( int n , int q , int [ ] a , int [ ] [ ] Query ) { int [ ] DP = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { int x = ( int ) ( Math . sqrt ( a [ i ] ) ) ; if ( x * x == a [ i ] ) DP [ i ] = a [ i ] ; } for ( int i = 1 ; i < n ; i ++ ) { DP [ i ] = DP [ i - 1 ] + DP [ i ] ; } for ( int i = 0 ; i < q ; i ++ ) { int l = Query [ i ] [ 0 ] ; int r = Query [ i ] [ 1 ] ; if ( l == 0 ) { System . out . print ( DP [ r ] + " ▁ " ) ; } else { System . out . print ( DP [ r ] - DP [ l - 1 ] + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int [ ] arr = { 2 , 4 , 5 , 6 , 9 } ; int N = arr . length ; int Q = 3 ; int [ ] [ ] Query = { { 0 , 2 } , { 1 , 3 } , { 1 , 4 } } ; OddDivisorsSum ( N , Q , arr , Query ) ; } }


"Queries to calculate sum of squares of ASCII values of characters of a substring with updates | Java implementation of the above approach ; Structure of a node of a Segment Tree ; Function to construct the Segment Tree ; If start and end are equal ; Assign squares of positions of the characters ; Stores the mid value of the range [ start , end ] ; Recursive call to left subtree ; Recursive call to right subtree ; Update the current node ; Function to perform the queries of type 2 ; No overlap ; If l <= start and r >= end ; Return the value of treeNode ; Calculate middle of the range [ start , end ] ; Function call to left subtree ; Function call to right subtree ; Return the sum of X and Y ; Function to perform update queries on a Segment Tree ; If start is equal to end and idx is equal to start ; Base Case ; Calculate middle of the range [ start , end ] ; If idx <= mid ; Function call to left subtree ; Otherwise ; Function call to the right subtree ; Update the current node ; Function to perform the given queries ; Stores the segment tree ; Traverse the segment tree ; Assign 0 to each node ; Builds segment tree ; Traverse the query array Q [ ] [ ] ; If query is of type S ; Stores the left boundary ; Stores the right boundary ; Prints the sum of squares of the alphabetic positions of the characters ; Otherwise ; Stores the index of the character to be updated ; Update the segment tree ; Driver Code ; Input ; Function call"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static class treeNode { int square_sum ; treeNode ( int square_sum ) { this . square_sum = square_sum ; } } ; static void buildTree ( char s [ ] , treeNode tree [ ] , int start , int end , int treenode ) { if ( start == end ) { tree [ treenode ] . square_sum = ( int ) Math . pow ( s [ start ] - ' a ' + 1 , 2 ) ; return ; } int mid = start + ( ( end - start ) / 2 ) ; buildTree ( s , tree , start , mid , 2 * treenode ) ; buildTree ( s , tree , mid + 1 , end , 1 + 2 * treenode ) ; tree [ treenode ] . square_sum = tree [ ( 2 * treenode ) ] . square_sum + tree [ ( 2 * treenode ) + 1 ] . square_sum ; } static int querySquareSum ( treeNode tree [ ] , int start , int end , int treenode , int l , int r ) { if ( ( l > end ) || ( r < start ) ) { return 0 ; } if ( ( l <= start ) && ( r >= end ) ) { return tree [ treenode ] . square_sum ; } int mid = start + ( ( end - start ) / 2 ) ; int X = querySquareSum ( tree , start , mid , 2 * treenode , l , r ) ; int Y = + querySquareSum ( tree , mid + 1 , end , 1 + 2 * treenode , l , r ) ; return X + Y ; } static void updateTree ( char s [ ] , treeNode tree [ ] , int start , int end , int treenode , int idx , char X ) { if ( ( start == end ) && ( idx == start ) ) { s [ idx ] = X ; tree [ treenode ] . square_sum = ( int ) Math . pow ( X - ' a ' + 1 , 2 ) ; return ; } int mid = start + ( ( end - start ) / 2 ) ; if ( idx <= mid ) { updateTree ( s , tree , start , mid , ( 2 * treenode ) , idx , X ) ; } else { updateTree ( s , tree , mid + 1 , end , ( 2 * treenode ) + 1 , idx , X ) ; } tree [ treenode ] . square_sum = tree [ ( 2 * treenode ) ] . square_sum + tree [ ( 2 * treenode ) + 1 ] . square_sum ; } static void PerformQuery ( String S , String Q [ ] [ ] ) { int n = S . length ( ) ; treeNode tree [ ] = new treeNode [ ( 4 * n ) + 1 ] ; for ( int i = 0 ; i <= ( 4 * n ) ; i = i + 1 ) { tree [ i ] = new treeNode ( 0 ) ; } char s [ ] = S . toCharArray ( ) ; buildTree ( s , tree , 0 , n - 1 , 1 ) ; for (...


"Queries to calculate sum of the path from root to a given node in given Binary Tree | package whatever do not write package name here ; Function to find the sum of the path from root to the current node ; Sum of nodes in the path ; Iterate until root is reached ; Update the node value ; Print the resultant sum ; Function to print the path sum for each query ; Traverse the queries ; Driver Code ; arraylist to store integers"
How can the above be solved in Java?

import java . io . * ; import java . util . ArrayList ; class GFG { public static void sumOfNodeInAPath ( int node_value ) { int sum_of_node = 0 ; while ( node_value > 0 ) { sum_of_node += node_value ; node_value /= 2 ; } System . out . print ( sum_of_node ) ; } public static void findSum ( ArrayList < Integer > Q ) { for ( int i = 0 ; i < Q . size ( ) ; i ++ ) { int node_value = Q . get ( i ) ; sumOfNodeInAPath ( node_value ) ; System . out . print ( " ▁ " ) ; } } public static void main ( String [ ] args ) { ArrayList < Integer > arr = new ArrayList < > ( ) ; arr . add ( 1 ) ; arr . add ( 5 ) ; arr . add ( 20 ) ; arr . add ( 100 ) ; findSum ( arr ) ; } }


"Queries to calculate the Sum of Array elements in the range [ L , R ] having indices as multiple of K | Java program to implement the above approach ; Structure of a Query ; Function to calculate the sum of array elements at indices from range [ L , R ] which are multiples of K for each query ; Stores Prefix Sum ; prefixSum [ i ] [ j ] : Stores the sum from indices [ 0 , j ] which are multiples of i ; If index j is a multiple of i ; Compute prefix sum ; Otherwise ; Traverse each query ; Sum of all indices upto R which are a multiple of K ; Sum of all indices upto L - 1 which are a multiple of K ; Calculate the difference ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static class Node { int L ; int R ; int K ; } ; static void kMultipleSum ( int arr [ ] , Node Query [ ] , int N , int Q ) { int prefixSum [ ] [ ] = new int [ N + 1 ] [ N ] ; for ( int i = 1 ; i <= N ; i ++ ) { prefixSum [ i ] [ 0 ] = arr [ 0 ] ; for ( int j = 0 ; j < N ; j ++ ) { if ( j % i == 0 ) { if ( j != 0 ) prefixSum [ i ] [ j ] = arr [ j ] + prefixSum [ i ] [ j - 1 ] ; } else { prefixSum [ i ] [ j ] = prefixSum [ i ] [ j - 1 ] ; } } } for ( int i = 0 ; i < Q ; i ++ ) { int last = prefixSum [ Query [ i ] . K ] [ Query [ i ] . R ] ; int first ; if ( Query [ i ] . L == 0 ) { first = prefixSum [ Query [ i ] . K ] [ Query [ i ] . L ] ; } else { first = prefixSum [ Query [ i ] . K ] [ Query [ i ] . L - 1 ] ; } System . out . print ( last - first + "
"); } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int N = arr . length ; int Q = 2 ; Node Query [ ] = new Node [ Q ] ; for ( int i = 0 ; i < Q ; i ++ ) Query [ i ] = new Node ( ) ; Query [ 0 ] . L = 2 ; Query [ 0 ] . R = 5 ; Query [ 0 ] . K = 2 ; Query [ 1 ] . L = 3 ; Query [ 1 ] . R = 5 ; Query [ 1 ] . K = 5 ; kMultipleSum ( arr , Query , N , Q ) ; } }


"Queries to check if a number lies in N ranges of L | Java program to check if the number lies in given range ; Function that answers every query ; container to store all range ; hash the L and R ; Push the element to container and hash the L and R ; sort the elements in container ; each query ; get the number same or greater than integer ; if it lies ; check if greater is hashed as 2 ; else check if greater is hashed as 1 ; Lower bound implementation ; Driver Code ; function call to answer queries"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void answerQueries ( int [ ] [ ] a , int n , int [ ] queries , int q ) { Vector < Integer > v = new Vector < > ( ) ; HashMap < Integer , Integer > mpp = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { v . add ( a [ i ] [ 0 ] ) ; mpp . put ( a [ i ] [ 0 ] , 1 ) ; v . add ( a [ i ] [ 1 ] ) ; mpp . put ( a [ i ] [ 1 ] , 2 ) ; } Collections . sort ( v ) ; for ( int i = 0 ; i < q ; i ++ ) { int num = queries [ i ] ; int ind = lowerBound ( v , num ) ; if ( ind >= 0 && v . elementAt ( ind ) == num ) System . out . println ( " Yes " ) ; else { if ( ind >= 0 && mpp . get ( v . elementAt ( ind ) ) == 2 ) System . out . println ( " Yes " ) ; System . out . println ( " No " ) ; } } } static int lowerBound ( Vector < Integer > array , int value ) { int low = 0 ; int high = array . size ( ) ; while ( low < high ) { final int mid = ( low + high ) / 2 ; if ( value <= array . elementAt ( mid ) ) { high = mid ; } else { low = mid + 1 ; } } return low ; } public static void main ( String [ ] args ) { int [ ] [ ] a = { { 5 , 6 } , { 1 , 3 } , { 8 , 10 } } ; int n = 3 ; int [ ] queries = { 2 , 3 , 4 , 7 } ; int q = queries . length ; answerQueries ( a , n , queries , q ) ; } }


"Queries to check if any pair exists in an array having values at most equal to the given pair | Java program for above approach ; Function that performs binary search to find value less than or equal to first value of the pair ; Perform binary search ; Find the mid ; Update the high ; Else update low ; Return the low index ; Function to modify the second value of each pair ; start from index 1 ; Function to evaluate each query ; Find value less than or equal to the first value of pair ; check if we got the required pair or not ; Function to find a pair whose values is less than the given pairs in query ; Find the size of the vector ; sort the vector based on the first value ; Function Call to modify the second value of each pair ; Traverse each queries ; Evaluate each query ; Print the result ; Driver function ; Function Call"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static int binary_search ( int [ ] [ ] vec , int n , int a ) { int low , high , mid ; low = 0 ; high = n - 1 ; while ( low < high ) { mid = low + ( high - low + 1 ) / 2 ; if ( vec [ mid ] [ 0 ] > a ) { high = mid - 1 ; } else if ( vec [ mid ] [ 1 ] <= a ) { low = mid ; } } return low ; } static void modify_vec ( int [ ] [ ] v , int n ) { for ( int i = 1 ; i < n ; i ++ ) { v [ i ] [ 1 ] = Math . min ( v [ i ] [ 1 ] , v [ i - 1 ] [ 1 ] ) ; } } static int evaluate_query ( int [ ] [ ] v , int n , int m1 , int m2 ) { int temp = binary_search ( v , n , m1 ) ; if ( ( v [ temp ] [ 0 ] <= m1 ) && ( v [ temp ] [ 1 ] <= m2 ) ) { return 1 ; } return 0 ; } static void checkPairs ( int [ ] [ ] v , int [ ] [ ] queries ) { int n = v . length ; Arrays . sort ( v , ( a , b ) -> a [ 0 ] - b [ 0 ] ) ; modify_vec ( v , n ) ; int k = queries . length ; for ( int i = 0 ; i < k ; i ++ ) { int m1 = queries [ i ] [ 0 ] ; int m2 = queries [ i ] [ 1 ] ; int result = evaluate_query ( v , n , m1 , m2 ) ; if ( result > 0 ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } } public static void main ( String [ ] args ) { int [ ] [ ] arr = { { 3 , 5 } , { 2 , 7 } , { 2 , 3 } , { 4 , 9 } } ; int [ ] [ ] queries = { { 3 , 4 } , { 3 , 2 } , { 4 , 1 } , { 3 , 7 } } ; checkPairs ( arr , queries ) ; } }


"Queries to check if array elements from indices [ L , R ] forms an Arithmetic Progression or not | Java program for the above approach ; Function to check if the given range of queries form an AP or not in the given array arr [ ] ; Stores length of the longest subarray forming AP for every array element ; Iterate over the range [ 0 , N ] ; Stores the index of the last element of forming AP ; Iterate until the element at index ( j , j + 1 ) forms AP ; Increment j by 1 ; Traverse the current subarray over the range [ i , j - 1 ] ; Update the length of the longest subarray at index k ; Update the value of i ; Traverse the given queries ; Print the result ; Otherwise ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void findAPSequence ( int arr [ ] , int N , int Q [ ] [ ] , int M ) { int dp [ ] = new int [ N + 5 ] ; for ( int i = 0 ; i + 1 < N ; ) { int j = i + 1 ; while ( j + 1 < N && arr [ j + 1 ] - arr [ j ] == arr [ i + 1 ] - arr [ i ] ) j ++ ; for ( int k = i ; k < j ; k ++ ) { dp [ k ] = j - k ; } i = j ; } for ( int i = 0 ; i < M ; i ++ ) { if ( dp [ Q [ i ] [ 0 ] ] >= Q [ i ] [ 1 ] - Q [ i ] [ 0 ] ) { System . out . println ( " Yes " ) ; } else { System . out . println ( " No " ) ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 5 , 7 , 6 , 5 , 4 , 1 } ; int Q [ ] [ ] = { { 0 , 3 } , { 3 , 4 } , { 2 , 4 } } ; int N = arr . length ; int M = Q . length ; findAPSequence ( arr , N , Q , M ) ; } }


"Queries to check if it is possible to join boxes in a circle | Java implementation of above approach ; Print the answer to each query ; setting the flag for exception ; replacing the greater element in i and j ; checking if that box is not used in previous query . ; checking if connecting to the same box ; case 1 : x < i and y lies between i and j ; case 2 : x lies between i and j and y > j ; if flag is not reset inbetween . ; Driver code"
How can the above be solved in Java?

class GFG { static int MAX = 50 ; static void solveQuery ( int n , int q , int qi [ ] , int qj [ ] ) { int [ ] arr = new int [ MAX ] ; for ( int i = 0 ; i <= n ; i ++ ) arr [ i ] = 0 ; for ( int k = 0 ; k < q ; k ++ ) { int flag = 0 ; if ( qj [ k ] < qi [ k ] ) { int temp = qi [ k ] ; qi [ k ] = qj [ k ] ; qj [ k ] = temp ; } if ( arr [ qi [ k ] ] != 0 arr [ qj [ k ] ] != 0 ) flag = 1 ; else if ( qi [ k ] == qj [ k ] ) flag = 1 ; else { for ( int i = 1 ; i < qi [ k ] ; i ++ ) { if ( arr [ i ] != 0 && arr [ i ] < qj [ k ] && qi [ k ] < arr [ i ] ) { flag = 1 ; break ; } } if ( flag == 0 ) { for ( int i = qi [ k ] + 1 ; i < qj [ k ] ; i ++ ) { if ( arr [ i ] != 0 && arr [ i ] > qj [ k ] ) { flag = 1 ; break ; } } } } if ( flag == 0 ) { System . out . println ( " YES " ) ; arr [ qi [ k ] ] = qj [ k ] ; arr [ qj [ k ] ] = qi [ k ] ; } else System . out . println ( " NO " ) ; } } public static void main ( String [ ] args ) { int n = 10 ; int q = 7 ; int qi [ ] = { 1 , 2 , 2 , 2 , 9 , 10 , 8 } ; int qj [ ] = { 5 , 7 , 3 , 4 , 9 , 9 , 6 } ; solveQuery ( n , q , qi , qj ) ; } }


"Queries to check if string B exists as substring in string A |  ; Dp Array ; String to character array ; initialize matrix with 1 ; for r from 1 to string length ; for c from 1 b string length ; For every query ; print true ; print false ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; import java . lang . * ; import java . io . * ; public class GFG { private static void substringCheck ( String stra , String strb , int [ ] query ) { int [ ] [ ] matrix = new int [ strb . length ( ) ] [ stra . length ( ) ] ; char [ ] charCrr = stra . toCharArray ( ) ; char [ ] charRrr = strb . toCharArray ( ) ; for ( int c = 0 ; c < stra . length ( ) ; c ++ ) { if ( charRrr [ 0 ] == charCrr ) { matrix [ 0 ] = 1 ; } } for ( int r = 1 ; r < charRrr . length ; r ++ ) { char ch = charRrr [ r ] ; for ( int c = 1 ; c < charCrr . length ; c ++ ) { if ( ch == charCrr && matrix [ r - 1 ] == 1 ) { matrix [ r ] = 1 ; } } } for ( int q : query ) { int matLoc = ( q + ( strb . length ( ) - 1 ) ) ; if ( matLoc >= stra . length ( ) ) { System . out . println ( false ) ; } else { if ( matrix [ strb . length ( ) - 1 ] [ matLoc ] == 1 ) { System . out . println ( true ) ; } else { System . out . println ( false ) ; } } } } public static void main ( String [ ] args ) { String stra = " GeeksForGeeks " ; String strb = " Geeks " ; int [ ] query = { 0 , 5 , 8 } ; substringCheck ( stra , strb , query ) ; }


"Queries to check if string B exists as substring in string A | Java implementation of the approach ; Function to return the modular inverse using Fermat 's little theorem ; Function to generate hash ; To store prefix - sum of rolling hash ; Multiplier for different values of i ; Generating hash value for string b ; Generating prefix - sum of hash of a ; Function that returns true if the required sub - string in a is equal to b ; To store hash of required sub - string of A ; If i = 0 then requires hash value ; Required hash if i != 0 ; Comparing hash with hash of B ; Driver code ; Generating hash ; Queries ; Perform queries"
How can the above be solved in Java?

import java . util . * ; class GFG { static int mod = 3803 ; static int d = 26 ; static int hash_b ; static int [ ] hash_a ; static int [ ] mul ; static int mi ( int x ) { int p = mod - 2 ; int s = 1 ; while ( p != 1 ) { if ( p % 2 == 1 ) { s = ( s * x ) % mod ; } x = ( x * x ) % mod ; p /= 2 ; } return ( s * x ) % mod ; } static void genHash ( char [ ] a , char [ ] b ) { hash_a = new int [ a . length ] ; mul = new int [ a . length ] ; for ( int i = b . length - 1 ; i >= 0 ; i -- ) { hash_b = ( hash_b * d + ( b [ i ] - 97 ) ) % mod ; } mul [ 0 ] = 1 ; hash_a [ 0 ] = ( a [ 0 ] - 97 ) % mod ; for ( int i = 1 ; i < a . length ; i ++ ) { mul [ i ] = ( mul [ i - 1 ] * d ) % mod ; hash_a [ i ] = ( hash_a [ i - 1 ] + mul [ i ] * ( a [ i ] - 97 ) ) % mod ; } } static boolean checkEqual ( int i , int len_a , int len_b ) { int x ; if ( i == 0 ) { x = hash_a [ len_b - 1 ] ; } else { x = ( hash_a [ i + len_b - 1 ] - hash_a [ i - 1 ] + 2 * mod ) % mod ; x = ( x * mi ( mul [ i ] ) ) % mod ; } if ( x == hash_b ) { return true ; } return false ; } public static void main ( String [ ] args ) { String a = " abababababa " ; String b = " aba " ; genHash ( a . toCharArray ( ) , b . toCharArray ( ) ) ; int queries [ ] = { 0 , 1 , 2 , 3 } ; int q = queries . length ; for ( int i = 0 ; i < q ; i ++ ) { if ( checkEqual ( queries [ i ] , a . length ( ) , b . length ( ) ) ) { System . out . println ( " Yes " ) ; } else { System . out . println ( " No " ) ; } } } }


"Queries to check if substring [ L ... R ] is palindrome or not | Java implementation of the approach ; Pre - processing function ; Get the size of the string ; Initially mark every position as false ; For the length ; Iterate for every index with length j ; If the length is less than 2 ; If characters are equal ; Check for equal ; Function to answer every query in O ( 1 ) ; Driver code"
How can the above be solved in Java?

class GFG { static int N = 100 ; static void pre_process ( boolean dp [ ] [ ] , char [ ] s ) { int n = s . length ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { dp [ i ] [ j ] = false ; } } for ( int j = 1 ; j <= n ; j ++ ) { for ( int i = 0 ; i <= n - j ; i ++ ) { if ( j <= 2 ) { if ( s [ i ] == s [ i + j - 1 ] ) { dp [ i ] [ i + j - 1 ] = true ; } } else if ( s [ i ] == s [ i + j - 1 ] ) { dp [ i ] [ i + j - 1 ] = dp [ i + 1 ] [ i + j - 2 ] ; } } } } static void answerQuery ( int l , int r , boolean dp [ ] [ ] ) { if ( dp [ l ] [ r ] ) { System . out . println ( " Yes " ) ; } else { System . out . println ( " No " ) ; } } public static void main ( String [ ] args ) { String s = " abaaab " ; boolean [ ] [ ] dp = new boolean [ N ] [ N ] ; pre_process ( dp , s . toCharArray ( ) ) ; int queries [ ] [ ] = { { 0 , 1 } , { 1 , 5 } } ; int q = queries . length ; for ( int i = 0 ; i < q ; i ++ ) { answerQuery ( queries [ i ] [ 0 ] , queries [ i ] [ 1 ] , dp ) ; } } }


"Queries to check if sweets of given type can be eaten on given day or not | Java implementation of the above approach ; Function to find queries to check if a sweet of given type can be eaten on a given day or not ; Stores pairs { priority , quantity } of each sweet - type ; Sorting the order of sweets in decreasing order of their priority ; Stores the window { min_days , max_days } for each sweet - type ; Variables to calculate the windows ; Traverse the array ; Calculating maximum and minimum number of days required to complete the sweets of the current type ; Creating the window and storing it ; Traversing the queries ; x : Type of sweet , y : Day ; Find the window for the sweet of type x ; If the given day lies within the window ; Driver Code ; Quantites of sweets of each type ; Priorites of each type sweet ; Maximum sweet of one type that can be eaten on a day ; Queries ; Calculating number of types"
How can the above be solved in Java?

import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . Comparator ; import java . util . HashMap ; import java . util . Map ; class GFG { static class Pair < K , V > { K first ; V second ; public Pair ( K first , V second ) { this . first = first ; this . second = second ; } public static < K , V > Pair < K , V > of ( K first , V second ) { return new Pair < > ( first , second ) ; } } static void sweetTypeOnGivenDay ( int a [ ] , int b [ ] , int n , int k , ArrayList < Pair < Integer , Integer > > q ) { ArrayList < Pair < Integer , Pair < Integer , Integer > > > v = new ArrayList < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) v . add ( Pair . of ( b [ i ] , Pair . of ( a [ i ] , i + 1 ) ) ) ; Collections . sort ( v , new Comparator < Pair < Integer , Pair < Integer , Integer > > > ( ) { @ Override public int compare ( Pair < Integer , Pair < Integer , Integer > > a , Pair < Integer , Pair < Integer , Integer > > b ) { if ( a . first == b . first ) { if ( a . second . first == b . second . first ) { return b . second . second - a . second . second ; } return b . second . first - a . second . first ; } return b . first - a . first ; } } ) ; Map < Integer , Pair < Integer , Integer > > mp = new HashMap < > ( ) ; int lowerbound = 0 , upperbound = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int maxi_days = v . get ( i ) . second . first ; int mini_days = v . get ( i ) . second . first / k ; if ( v . get ( i ) . second . first % k != 0 ) mini_days ++ ; upperbound += maxi_days ; mp . put ( v . get ( i ) . second . second , Pair . of ( lowerbound , upperbound ) ) ; lowerbound += mini_days ; } for ( int i = 0 ; i < q . size ( ) ; i ++ ) { int x = q . get ( i ) . first , y = q . get ( i ) . second ; int e = mp . get ( x ) . first ; int f = mp . get ( x ) . second ; if ( y >= e && y <= f ) System . out . println ( " Yes ▁ " ) ; else System . out . println ( " No ▁ " ) ; } } public static void main ( String [ ] args ) { int A [ ] = { 6 , 3 , 7 , 5 , 2 } ; int B [ ] =...


"Queries to check if the path between two nodes in a tree is a palindrome | Java implementation of the approach ; Function that returns true if a palindromic string can be formed using the given characters ; Count odd occurring characters ; Return false if odd count is more than 1 , ; Find to find the Lowest Common Ancestor in the tree ; Base case ; Base case ; Initially value - 1 denotes that we need to find the ancestor ; - 1 denotes that we need to find the lca for x and y , values other than x and y will be the LCA of x and y ; Iterating in the child substree of the currentNode ; Next node that will be checked ; Look for the next child subtree ; Both the nodes exist in the different subtrees , in this case parent node will be the lca ; Handle the cases where LCA is already calculated or both x and y are present in the same subtree ; Function to calculate the character count for each path from node i to 1 ( root node ) ; Updating the character count for each node ; Look for the child subtree ; Function that returns true if a palindromic path is possible between the nodes x and y ; If both x and y are same then lca will be the node itself ; Find the lca of x and y ; Calculating the character count for path node x to y ; Checking if we can form the palindrome string with the all character count ; Function to update character count at node v ; Updating the character count at node v ; Function to perform the queries ; If path can be a palindrome ; Driver Code ; Fill the complete array with 0 ; Edge between 1 and 2 labelled " bbc " ; Edge between 1 and 3 labelled " ac " ; Update the character count from root to the ith node ; Perform the queries"
How can the above be solved in Java?

import java . util . * ; @ SuppressWarnings ( " unchecked " ) class GFG { static int MAX_SIZE = 100005 , MAX_CHAR = 26 ; static int [ ] [ ] nodeCharactersCount = new int [ MAX_SIZE ] [ MAX_CHAR ] ; static Vector < Integer > [ ] tree = new Vector [ MAX_SIZE ] ; static boolean canFormPalindrome ( int [ ] charArray ) { int oddCount = 0 ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) { if ( charArray [ i ] % 2 == 1 ) oddCount ++ ; } if ( oddCount >= 2 ) return false ; else return true ; } static int LCA ( int currentNode , int x , int y ) { if ( currentNode == x ) return x ; if ( currentNode == y ) return y ; int xLca , yLca ; xLca = yLca = - 1 ; int gotLca = - 1 ; for ( int l = 0 ; l < tree [ currentNode ] . size ( ) ; l ++ ) { int nextNode = tree [ currentNode ] . elementAt ( l ) ; int out_ = LCA ( nextNode , x , y ) ; if ( out_ == x ) xLca = out_ ; if ( out_ == y ) yLca = out_ ; if ( xLca != - 1 && yLca != - 1 ) return currentNode ; if ( out_ != - 1 ) gotLca = out_ ; } return gotLca ; } static void buildTree ( int i ) { for ( int l = 0 ; l < tree [ i ] . size ( ) ; l ++ ) { int nextNode = tree [ i ] . elementAt ( l ) ; for ( int j = 0 ; j < MAX_CHAR ; j ++ ) { nodeCharactersCount [ nextNode ] [ j ] += nodeCharactersCount [ i ] [ j ] ; } buildTree ( nextNode ) ; } } static boolean canFormPalindromicPath ( int x , int y ) { int lcaNode ; if ( x == y ) lcaNode = x ; else lcaNode = LCA ( 1 , x , y ) ; int [ ] charactersCountFromXtoY = new int [ MAX_CHAR ] ; Arrays . fill ( charactersCountFromXtoY , 0 ) ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) { charactersCountFromXtoY [ i ] = nodeCharactersCount [ x ] [ i ] + nodeCharactersCount [ y ] [ i ] - 2 * nodeCharactersCount [ lcaNode ] [ i ] ; } if ( canFormPalindrome ( charactersCountFromXtoY ) ) return true ; return false ; } static void updateNodeCharactersCount ( String str , int v ) { for ( int i = 0 ; i < str . length ( ) ; i ++ ) nodeCharactersCount [ v ] [ str . charAt ( i ) - ' a ' ] ++ ; } static void performQueries ( int [ ] [ ] queries , int q ) { int i = 0 ; while...


"Queries to check if vertices X and Y are in the same Connected Component of an Undirected Graph | Java Program to implement the above approach ; Maximum number of nodes or vertices that can be present in the graph ; Store the parent of each vertex ; Stores the size of each set ; Function to initialize the parent of each vertices ; Function to find the representative of the set which contain element v ; Path compression technique to optimize the time complexity ; Function to merge two different set into a single set by finding the representative of each set and merge the smallest set with the larger one ; Finding the set representative of each element ; Check if they have different set repersentative ; Compare the set sizes ; Assign parent of smaller set to the larger one ; Add the size of smaller set to the larger one ; Function to check the vertices are on the same set or not ; Check if they have same set representative or not ; Driver Code ; Connected vertices and taking them into single set ; Number of queries ; Function call"
How can the above be solved in Java?

 import java . util . * ; class GFG { static final int MAX_NODES = 100005 ; static int [ ] parent = new int [ MAX_NODES ] ; static int [ ] size_set = new int [ MAX_NODES ] ; static void make_set ( int v ) { parent [ v ] = v ; size_set [ v ] = 1 ; } static int find_set ( int v ) { if ( v == parent [ v ] ) return v ; return parent [ v ] = find_set ( parent [ v ] ) ; } static void union_set ( int a , int b ) { a = find_set ( a ) ; b = find_set ( b ) ; if ( a != b ) { if ( size_set [ a ] < size_set [ b ] ) { a = a + b ; b = a - b ; a = a - b ; } parent [ b ] = a ; size_set [ a ] += size_set [ b ] ; } } static String check ( int a , int b ) { a = find_set ( a ) ; b = find_set ( b ) ; return ( a == b ) ? " Yes " : " No " ; } public static void main ( String [ ] args ) { int n = 5 , m = 3 ; make_set ( 1 ) ; make_set ( 2 ) ; make_set ( 3 ) ; make_set ( 4 ) ; make_set ( 5 ) ; union_set ( 1 , 3 ) ; union_set ( 3 , 4 ) ; union_set ( 3 , 5 ) ; int q = 3 ; System . out . print ( check ( 1 , 5 ) + "
"); System . out . print ( check ( 3 , 2 ) + "
"); System . out . print ( check ( 5 , 2 ) + "
"); } }


"Queries to check whether a given digit is present in the given Range | Java program to answer Queries to check whether a given digit is present in the given range ; Segment Tree with set at each node ; Funtiom to build the segment tree ; Left child node ; Right child node ; Merging child nodes to get parent node . Since set is used , it will remove redundant digits . ; Function to query a range ; Complete Overlapp condition return true if digit is present . else false . ; No Overlapp condition Return false ; If digit is found in any child return true , else False ; Driver Code ; Build the tree ; Query 1 ; Query 2"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int N = 6 ; @ SuppressWarnings ( " unchecked " ) static HashSet < Integer > [ ] Tree = new HashSet [ 6 * N ] ; static { for ( int i = 0 ; i < 6 * N ; i ++ ) Tree [ i ] = new HashSet < > ( ) ; } static void buildTree ( int [ ] arr , int idx , int s , int e ) { if ( s == e ) { Tree [ idx ] . add ( arr [ s ] ) ; return ; } int mid = ( s + e ) / 2 ; buildTree ( arr , 2 * idx , s , mid ) ; buildTree ( arr , 2 * idx + 1 , mid + 1 , e ) ; for ( int it : Tree [ 2 * idx ] ) Tree [ idx ] . add ( it ) ; for ( int it : Tree [ 2 * idx + 1 ] ) Tree [ idx ] . add ( it ) ; } static boolean query ( int idx , int s , int e , int qs , int qe , int x ) { if ( qs <= s && e <= qe ) { if ( Collections . frequency ( Tree [ idx ] , x ) != 0 ) return true ; else return false ; } if ( qe < s e < qs ) return false ; int mid = ( s + e ) / 2 ; boolean LeftAns = query ( 2 * idx , s , mid , qs , qe , x ) ; boolean RightAns = query ( 2 * idx + 1 , mid + 1 , e , qs , qe , x ) ; return ( LeftAns RightAns ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 3 , 3 , 9 , 8 , 7 } ; int n = arr . length ; buildTree ( arr , 1 , 0 , n - 1 ) ; int l , r , x ; l = 0 ; r = 3 ; x = 2 ; if ( query ( 1 , 0 , n - 1 , l , r , x ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; l = 2 ; r = 5 ; x = 3 ; if ( query ( 1 , 0 , n - 1 , l , r , x ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Queries to check whether all the elements can be made positive by flipping signs exactly K times | Java implementation of the approach ; To store the count of negative integers ; Check if zero exists ; Function to find the count of negative integers and check if zero exists in the array ; Function that returns true if array elements can be made positive by changing signs exactly k times ; Driver code ; Pre - processing ; Perform queries"
How can the above be solved in Java?

import java . io . * ; class GFG { static int cnt_neg ; static boolean exists_zero ; static void preProcess ( int [ ] arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < 0 ) cnt_neg ++ ; if ( arr [ i ] == 0 ) exists_zero = true ; } } static boolean isPossible ( int k ) { if ( ! exists_zero ) { if ( k >= cnt_neg && ( k - cnt_neg ) % 2 == 0 ) return true ; else return false ; } else { if ( k >= cnt_neg ) return true ; else return false ; } } public static void main ( String [ ] args ) { int arr [ ] = { - 1 , 2 , - 3 , 4 , 5 } ; int n = arr . length ; preProcess ( arr , n ) ; int queries [ ] = { 1 , 2 , 3 , 4 } ; int q = arr . length ; for ( int i = 0 ; i < q ; i ++ ) { if ( isPossible ( queries [ i ] ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } } }


"Queries to check whether bitwise AND of a subarray is even or odd | Java implementation of the approach ; Function to precompute the count of even and odd numbers ; If the current element is odd then put 1 at odd [ i ] ; If the current element is even then put 1 at even [ i ] ; Taking the prefix sums of these two arrays so we can get the count of even and odd numbers in a range [ L , R ] in O ( 1 ) ; Function that returns true if the bitwise AND of the subarray a [ L ... R ] is odd ; cnt will store the count of odd numbers in the range [ L , R ] ; Check if all the numbers in the range are odd or not ; Function to perform the queries ; Perform queries ; Driver code ; Queries"
How can the above be solved in Java?

class GFG { static final int MAXN = 1000005 ; static int even [ ] = new int [ MAXN ] ; static int odd [ ] = new int [ MAXN ] ; static void precompute ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % 2 == 1 ) odd [ i ] = 1 ; if ( arr [ i ] % 2 == 0 ) even [ i ] = 1 ; } for ( int i = 1 ; i < n ; i ++ ) { even [ i ] = even [ i ] + even [ i - 1 ] ; odd [ i ] = odd [ i ] + odd [ i - 1 ] ; } } static boolean isOdd ( int L , int R ) { int cnt = odd [ R ] ; if ( L > 0 ) cnt -= odd [ L - 1 ] ; if ( cnt == R - L + 1 ) return true ; return false ; } static void performQueries ( int a [ ] , int n , int q [ ] [ ] , int m ) { precompute ( a , n ) ; for ( int i = 0 ; i < m ; i ++ ) { int L = q [ i ] [ 0 ] , R = q [ i ] [ 1 ] ; if ( isOdd ( L , R ) ) System . out . println ( " Odd " ) ; else System . out . println ( " Even " ) ; } } public static void main ( String args [ ] ) { int [ ] a = { 2 , 1 , 5 , 7 , 6 , 8 , 9 } ; int n = a . length ; int q [ ] [ ] = { { 0 , 2 } , { 1 , 2 } , { 2 , 3 } , { 3 , 6 } } ; int m = q . length ; performQueries ( a , n , q , m ) ; } }


"Queries to count Composite Magic Numbers from a given range [ L , R ] | Java program to implement the above approach ; Check if a number is magic number or not ; Check number is composite number or not ; Corner cases ; Check if the number is a multiple of 2 or 3 ; Check for multiples of remaining primes ; Function to find Composite Magic Numbers in given ranges ; dp [ i ] : Stores the count of composite Magic numbers up to i ; Traverse in the range [ 1 , 1e5 ) ; Check if number is Composite number as well as a Magic number or not ; Print results for each query ; Driver Code"
How can the above be solved in Java?

class GFG { static boolean isMagic ( int num ) { return ( num % 9 == 1 ) ; } static boolean isComposite ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return false ; if ( n % 2 == 0 n % 3 == 0 ) return true ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return true ; return false ; } static void find ( int L [ ] , int R [ ] , int q ) { int dp [ ] = new int [ 1000005 ] ; dp [ 0 ] = 0 ; dp [ 1 ] = 0 ; for ( int i = 1 ; i < 1000005 ; i ++ ) { if ( isComposite ( i ) && isMagic ( i ) == true ) { dp [ i ] = dp [ i - 1 ] + 1 ; } else dp [ i ] = dp [ i - 1 ] ; } for ( int i = 0 ; i < q ; i ++ ) System . out . println ( dp [ R [ i ] ] - dp [ L [ i ] - 1 ] ) ; } public static void main ( String [ ] args ) { int L [ ] = { 10 , 3 } ; int R [ ] = { 100 , 2279 } ; int Q = 2 ; find ( L , R , Q ) ; } }


"Queries to count array elements from a given range having a single set bit | JAVA program for the above approach ; Function to check whether only one bit is set or not ; Function to perform Range - query ; Function to count array elements with a single set bit for each range in a query ; Initialize array for Prefix sum ; A Pair class for handling queries in JAVA As , there is no in - built function of Tuple ; Driver code ; Given array ; Size of the array ; Given queries ; Size of queries array"
How can the above be solved in Java?

import java . util . * ; import java . io . * ; import java . math . * ; public class GFG { static int check ( int x ) { if ( ( ( x ) & ( x - 1 ) ) == 0 ) return 1 ; return 0 ; } static int query ( int l , int r , int [ ] pre ) { if ( l == 0 ) return pre [ r ] ; else return pre [ r ] - pre [ l - 1 ] ; } static void countInRange ( int [ ] arr , int N , ArrayList < Pair > queries , int Q ) { int [ ] pre = new int [ N ] ; pre [ 0 ] = check ( arr [ 0 ] ) ; for ( int i = 1 ; i < N ; i ++ ) { pre [ i ] = pre [ i - 1 ] + check ( arr [ i ] ) ; } int c = 0 ; int q = 0 ; while ( q < Q ) { int l = queries . get ( q ) . item1 ; int r = queries . get ( q ) . item2 ; c ++ ; q ++ ; System . out . print ( query ( l , r , pre ) + " ▁ " ) ; } } static class Pair { int item1 , item2 ; Pair ( int item1 , int item2 ) { this . item1 = item1 ; this . item2 = item2 ; } } public static void main ( String args [ ] ) { int [ ] arr = { 12 , 11 , 16 , 8 , 2 , 5 , 1 , 3 , 256 , 1 } ; int N = arr . length ; ArrayList < Pair > queries = new ArrayList < Pair > ( ) ; queries . add ( new Pair ( 4 , 9 ) ) ; queries . add ( new Pair ( 0 , 9 ) ) ; int Q = queries . size ( ) ; countInRange ( arr , N , queries , Q ) ; } }


"Queries to count array elements from a given range having a single set bit | package whatever do not write package name here ; Check if N has only one set bit ; Function to build segment tree ; If se is leaf node ; Update the node ; Stores mid value of segment [ ss , se ] ; Recursive call for left Subtree ; Recursive call for right Subtree ; Update the Current Node ; Function to update a value at Xth index ; If ss is equal to X ; Update the Xth node ; Update the tree ; Stores the mid of segment [ ss , se ] ; Update current node ; Count of numbers having one set bit ; If L > se or R < ss Invalid Range ; If [ ss , se ] lies inside the [ L , R ] ; Stores the mid of segment [ ss , se ] ; Return the sum after recursively traversing left and right subtree ; Function to solve queries ; Initialise Segment tree ; Build segment tree ; Perform queries ; Driver Code ; Input ; Function call to solve queries"
How can the above be solved in Java?

import java . io . * ; class GFG { static int check ( int N ) { if ( Integer . bitCount ( N ) == 1 ) return 1 ; else return 0 ; } static void build_seg_tree ( int ss , int se , int si , int tree [ ] , int arr [ ] ) { if ( ss == se ) { tree [ si ] = check ( arr [ ss ] ) ; return ; } int mid = ( ss + se ) / 2 ; build_seg_tree ( ss , mid , 2 * si + 1 , tree , arr ) ; build_seg_tree ( mid + 1 , se , 2 * si + 2 , tree , arr ) ; tree [ si ] = tree [ 2 * si + 1 ] + tree [ 2 * si + 2 ] ; } static void update ( int ss , int se , int si , int X , int V , int tree [ ] , int arr [ ] ) { if ( ss == se ) { if ( ss == X ) { arr [ X ] = V ; tree [ si ] = check ( V ) ; } return ; } int mid = ( ss + se ) / 2 ; if ( X <= mid ) update ( ss , mid , 2 * si + 1 , X , V , tree , arr ) ; else update ( mid + 1 , se , 2 * si + 2 , X , V , tree , arr ) ; tree [ si ] = tree [ 2 * si + 1 ] + tree [ 2 * si + 2 ] ; } static int query ( int l , int r , int ss , int se , int si , int tree [ ] ) { if ( r < ss l > se ) return 0 ; if ( l <= ss && r >= se ) return tree [ si ] ; int mid = ( ss + se ) / 2 ; return query ( l , r , ss , mid , 2 * si + 1 , tree ) + query ( l , r , mid + 1 , se , 2 * si + 2 , tree ) ; } static void Query ( int arr [ ] , int N , int [ ] [ ] Q ) { int tree [ ] = new int [ 4 * N ] ; build_seg_tree ( 0 , N - 1 , 0 , tree , arr ) ; for ( int i = 0 ; i < Q . length ; i ++ ) { if ( Q [ i ] [ 0 ] == 1 ) System . out . print ( query ( Q [ i ] [ 1 ] , Q [ i ] [ 2 ] , 0 , N - 1 , 0 , tree ) + " ▁ " ) ; else update ( 0 , N - 1 , 0 , Q [ i ] [ 1 ] , Q [ i ] [ 2 ] , tree , arr ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 12 , 11 , 16 , 2 , 32 } ; int [ ] [ ] Q = { { 1 , 0 , 2 } , { 2 , 4 , 24 } , { 1 , 1 , 4 } } ; int N = arr . length ; Query ( arr , N , Q ) ; } }


"Queries to count characters having odd frequency in a range [ L , R ] | Java Program to implement the above problem ; Function to print the number of characters having odd frequencies for each query ; A function to construct the arr [ ] and prefix [ ] ; Stores array length ; Stores the unique powers of 2 associated to each character ; Prefix array to store the XOR values from array elements ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static void queryResult ( int prefix [ ] , pair Q ) { int l = Q . first ; int r = Q . second ; if ( l == 0 ) { int xorval = prefix [ r ] ; System . out . print ( Integer . bitCount ( xorval ) + "
"); } else { int xorval = prefix [ r ] ^ prefix [ l - 1 ] ; System . out . print ( Integer . bitCount ( xorval ) + "
"); } } static void calculateCount ( String S , pair Q [ ] , int m ) { int n = S . length ( ) ; int [ ] arr = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { arr [ i ] = ( 1 << ( S . charAt ( i ) - ' a ' ) ) ; } int [ ] prefix = new int [ n ] ; int x = 0 ; for ( int i = 0 ; i < n ; i ++ ) { x ^= arr [ i ] ; prefix [ i ] = x ; } for ( int i = 0 ; i < m ; i ++ ) { queryResult ( prefix , Q [ i ] ) ; } } public static void main ( String [ ] args ) { String S = " geeksforgeeks " ; pair Q [ ] = { new pair ( 2 , 4 ) , new pair ( 0 , 3 ) , new pair ( 0 , 12 ) } ; calculateCount ( S , Q , 3 ) ; } }


"Queries to count distinct Binary Strings of all lengths from N to M satisfying given properties | Java program to implement the above approach ; Function to calculate the count of possible Strings ; Initialize dp [ 0 ] ; dp [ i ] represents count of Strings of length i ; Add dp [ i - k ] if i >= k ; Update Prefix Sum Array ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int N = ( int ) ( 1e5 + 5 ) ; static int MOD = 1000000007 ; static int [ ] dp = new int [ N ] ; static void countStrings ( int K , int [ ] [ ] Q ) { dp [ 0 ] = 1 ; for ( int i = 1 ; i < N ; i ++ ) { dp [ i ] = dp [ i - 1 ] ; if ( i >= K ) dp [ i ] = ( dp [ i ] + dp [ i - K ] ) % MOD ; } for ( int i = 1 ; i < N ; i ++ ) { dp [ i ] = ( dp [ i ] + dp [ i - 1 ] ) % MOD ; } for ( int i = 0 ; i < Q . length ; i ++ ) { int ans = dp [ Q [ i ] [ 1 ] ] - dp [ Q [ i ] [ 0 ] - 1 ] ; if ( ans < 0 ) ans = ans + MOD ; System . out . print ( ans + "
"); } } public static void main ( String [ ] args ) { int K = 3 ; int [ ] [ ] Q = { { 1 , 4 } , { 3 , 7 } } ; countStrings ( K , Q ) ; } }


"Queries to count frequencies of a given character in a given range of indices | Java program for the above approach ; Function to print count of char y present in the range [ l , r ] ; Length of the string ; Stores the precomputed results ; Iterate the given string ; Increment dp [ i ] [ y - ' a ' ] by 1 ; Pre - compute ; Number of queries ; Traverse each query ; Print the result for each query ; Driver Code ; Given string ; Given Queries ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { static void noOfChars ( String s , char [ ] [ ] queries ) { int n = s . length ( ) ; int dp [ ] [ ] = new int [ n + 1 ] [ 26 ] ; for ( int i = 0 ; i < n ; i ++ ) { dp [ i + 1 ] [ s . charAt ( i ) - ' a ' ] ++ ; for ( int j = 0 ; j < 26 ; j ++ ) { dp [ i + 1 ] [ j ] += dp [ i ] [ j ] ; } } int q = queries . length ; for ( int i = 0 ; i < q ; i ++ ) { int l = ( int ) queries [ i ] [ 0 ] ; int r = ( int ) queries [ i ] [ 1 ] ; int c = queries [ i ] [ 2 ] - ' a ' ; System . out . print ( dp [ r ] - dp [ l - 1 ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { String S = " aabv " ; char queries [ ] [ ] = new char [ ] [ ] { { 1 , 2 , ' a ' } , { 2 , 3 , ' b ' } } ; noOfChars ( S , queries ) ; } }


"Queries to count minimum flips required to fill a binary submatrix with 0 s only | Java program for the above approach ; Function to compute the matrix prefixCnt [ M ] [ N ] from mat [ M ] [ N ] such that prefixCnt [ i ] [ j ] stores the count of 0 's from (0, 0) to (i, j) ; Initialize prefixCnt [ i ] [ j ] with 1 if mat [ i ] [ j ] is 0 ; Otherwise , assign with 0 ; Calculate prefix sum for each row ; Calculate prefix sum for each column ; Function to compute count of 0 's in submatrix from (pi, pj) to (qi, qj) from prefixCnt[M][N] ; Initialize that count of 0 's  in the sub-matrix within  indices (0, 0) to (qi, qj) ; Subtract count of 0 's within  indices (0, 0) and (pi-1, qj) ; Subtract count of 0 's within  indices (0, 0) and (qi, pj-1) ; Add prefixCnt [ pi - 1 ] [ pj - 1 ] because its value has been added ; once but subtracted twice ; Function to count the 0 s in the each given submatrix ; Stores the prefix sum of each row and column ; Compute matrix prefixCnt [ ] [ ] ; Function Call for each query ; Driver Code ; Given matrix ; Function Call"
How can the above be solved in Java?

class GFG { final static int M = 6 ; final static int N = 7 ; static void preCompute ( int mat [ ] [ ] , int prefixCnt [ ] [ ] ) { for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( mat [ i ] [ j ] == 0 ) { prefixCnt [ i ] [ j ] = 1 ; } else { prefixCnt [ i ] [ j ] = 0 ; } } } for ( int i = 0 ; i < M ; i ++ ) for ( int j = 1 ; j < N ; j ++ ) prefixCnt [ i ] [ j ] += prefixCnt [ i ] [ j - 1 ] ; for ( int i = 1 ; i < M ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) prefixCnt [ i ] [ j ] += prefixCnt [ i - 1 ] [ j ] ; } static int countQuery ( int prefixCnt [ ] [ ] , int pi , int pj , int qi , int qj ) { int cnt = prefixCnt [ qi ] [ qj ] ; if ( pi > 0 ) cnt -= prefixCnt [ pi - 1 ] [ qj ] ; if ( pj > 0 ) cnt -= prefixCnt [ qi ] [ pj - 1 ] ; if ( pi > 0 && pj > 0 ) cnt += prefixCnt [ pi - 1 ] [ pj - 1 ] ; return cnt ; } static void count0s ( int mat [ ] [ ] , int Q [ ] [ ] , int sizeQ ) { int prefixCnt [ ] [ ] = new int [ M ] [ N ] ; preCompute ( mat , prefixCnt ) ; for ( int i = 0 ; i < sizeQ ; i ++ ) { System . out . print ( countQuery ( prefixCnt , Q [ i ] [ 0 ] , Q [ i ] [ 1 ] , Q [ i ] [ 2 ] , Q [ i ] [ 3 ] ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int mat [ ] [ ] = { { 0 , 1 , 0 , 1 , 1 , 1 , 0 } , { 1 , 0 , 1 , 1 , 1 , 0 , 1 } , { 1 , 1 , 0 , 0 , 1 , 1 , 0 } , { 1 , 1 , 1 , 1 , 1 , 0 , 1 } , { 0 , 0 , 1 , 0 , 1 , 1 , 1 } , { 1 , 1 , 0 , 1 , 1 , 0 , 1 } } ; int Q [ ] [ ] = { { 0 , 1 , 3 , 2 } , { 2 , 2 , 4 , 5 } , { 4 , 3 , 5 , 6 } } ; int sizeQ = Q . length ; count0s ( mat , Q , sizeQ ) ; } }


"Queries to count numbers from a given range which are divisible the sum of their digits | java program for the above approach ; Function to check if the number x is divisible by its sum of digits ; Stores sum of digits of x ; Temporarily store x ; Calculate sum of digits of x ; If x is not divisible by sum ; Otherwise ; Function to perform the precomputation ; Iterate from i equals 1 to 1e5 ; Check if i is divisible by sum of its digits ; Convert arr [ ] to prefix sum array ; Driver Code ; Given queries ; Using inclusion - exclusion principle , calculate the result"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; public class GFG { static int arr [ ] = new int [ 100005 ] ; static boolean isDivisible ( int x ) { int sum = 0 ; int temp = x ; while ( x != 0 ) { sum += x % 10 ; x /= 10 ; } if ( temp % sum != 0 ) return false ; else return true ; } static void precompute ( ) { for ( int i = 1 ; i <= 100000 ; i ++ ) { if ( isDivisible ( i ) ) arr [ i ] = 1 ; else arr [ i ] = 0 ; } for ( int i = 1 ; i <= 100000 ; i ++ ) { arr [ i ] = arr [ i ] + arr [ i - 1 ] ; } } public static void main ( String [ ] args ) { int Q [ ] [ ] = { { 5 , 9 } , { 5 , 20 } } ; precompute ( ) ; for ( int q [ ] : Q ) { System . out . println ( arr [ q [ 1 ] ] - arr [ q [ 0 ] - 1 ] ) ; } } }


"Queries to count numbers from a range which does not contain digit K in their decimal or octal representation | Java program for the above approach ; Function to check if the given digit ' K ' is present in the decimal and octal representations of num or not ; Stores if the digit exists or not ; Iterate till nums is non - zero ; Find the remainder ; If the remainder is K ; Function to count the numbers in the range [ 1 , N ] such that it doesn ' t ▁ ▁ contain ▁ the ▁ digit ▁ ' K ' in its decimal  and octal representation ; Stores count of numbers in the range [ 0 , i ] that contains the digit ' K ' in its octal or decimal representation ; Traverse the range [ 0 , 1e6 + 5 ] ; Check if i contains the digit ' K ' in its decimal or octal representation ; Update pref [ i ] ; Print the answer of queries ; Driver code ; Function Call"
How can the above be solved in Java?

import java . util . * ; public class GFG { static boolean contains ( int num , int K , int Base ) { boolean isThere = false ; while ( num > 0 ) { int remainder = num % Base ; if ( remainder == K ) { isThere = true ; } num /= Base ; } return isThere ; } static void count ( int n , int k , Vector < Vector < Integer > > v ) { int [ ] pref = new int [ 1000005 ] ; for ( int i = 1 ; i < 1e6 + 5 ; i ++ ) { boolean present = contains ( i , k , 10 ) || contains ( i , k , 8 ) ; if ( present ) { pref [ i ] += pref [ i - 1 ] + 1 ; } } System . out . print ( ( v . get ( 0 ) . get ( 1 ) - v . get ( 0 ) . get ( 0 ) + 1 - ( pref [ v . get ( 0 ) . get ( 1 ) ] - pref [ v . get ( 0 ) . get ( 0 ) - 1 ] ) ) + " ▁ " ) ; System . out . print ( ( v . get ( 1 ) . get ( 1 ) - v . get ( 1 ) . get ( 0 ) - ( pref [ v . get ( 1 ) . get ( 1 ) ] - pref [ v . get ( 1 ) . get ( 0 ) - 1 ] ) ) + " ▁ " ) ; } public static void main ( String [ ] args ) { int K = 7 ; Vector < Vector < Integer > > Q = new Vector < Vector < Integer > > ( ) ; Q . add ( new Vector < Integer > ( ) ) ; Q . get ( 0 ) . add ( 2 ) ; Q . get ( 0 ) . add ( 5 ) ; Q . add ( new Vector < Integer > ( ) ) ; Q . get ( 1 ) . add ( 1 ) ; Q . get ( 1 ) . add ( 15 ) ; int N = Q . size ( ) ; count ( N , K , Q ) ; } }


"Queries to count numbers from given range which are divisible by all its digits | Java program to implement the above approach ; Function to check if a number is divisible by all of its non - zero digits or not ; Stores the number ; Iterate over the digits of the numbers ; If digit of number is non - zero ; If number is not divisible by its current digit ; Update n ; Function to count of numbers which are divisible by all of its non - zero digits in the range [ 1 , i ] ; Stores count of numbers which are divisible by all of its non - zero digits in the range [ 1 , i ] ; Iterate over the range [ 1 , Max ] ; Update ; Traverse the array , arr [ ] ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { public static int Max = 1000005 ; static boolean CheckDivByAllDigits ( int number ) { int n = number ; while ( n > 0 ) { if ( n % 10 != 0 ) if ( number % ( n % 10 ) != 0 ) { return false ; } n /= 10 ; } return true ; } static void cntNumInRang ( int arr [ ] [ ] , int N ) { int prefCntDiv [ ] = new int [ Max + 1 ] ; for ( int i = 1 ; i <= Max ; i ++ ) { int ans = 0 ; if ( CheckDivByAllDigits ( i ) ) ans = 1 ; prefCntDiv [ i ] = prefCntDiv [ i - 1 ] + ans ; } for ( int i = 0 ; i < N ; i ++ ) System . out . print ( ( prefCntDiv [ arr [ i ] [ 1 ] ] - prefCntDiv [ arr [ i ] [ 0 ] - 1 ] ) + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] [ ] = { { 1 , 5 } , { 12 , 14 } } ; int N = arr . length ; cntNumInRang ( arr , N ) ; } }


"Queries to count points lying on or inside an isosceles Triangle with given length of equal sides | Java implementation of above approach ; Function to find answer of each query ; Stores the count of points with sum less than or equal to their indices ; Traverse the array ; If both x and y - coordinate < 0 ; Stores the sum of co - ordinates ; Increment count of sum by 1 ; Prefix array ; Perform queries ; Drivers Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MAX = ( int ) ( 1e6 + 5 ) ; static void query ( double [ ] [ ] arr , int [ ] Q ) { int pre [ ] = new int [ MAX ] ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( arr [ i ] [ 0 ] < 0 arr [ i ] [ 1 ] < 0 ) continue ; int sum = ( int ) Math . ceil ( ( arr [ i ] [ 0 ] + arr [ i ] [ 1 ] ) ) ; pre [ sum ] ++ ; } for ( int i = 1 ; i < MAX ; i ++ ) pre [ i ] += pre [ i - 1 ] ; for ( int i = 0 ; i < Q . length ; i ++ ) { System . out . print ( pre [ Q [ i ] ] + " ▁ " ) ; } System . out . println ( ) ; } public static void main ( String [ ] args ) { double [ ] [ ] arr = { { 2.1 , 3.0 } , { 3.7 , 1.2 } , { 1.5 , 6.5 } , { 1.2 , 0.0 } } ; int [ ] Q = { 2 , 8 , 5 } ; int N = arr . length ; int M = Q . length ; query ( arr , Q ) ; } }


"Queries to count sum of rows and columns of a Matrix present in given ranges | Java program for the above approach ; Function to preprocess the matrix to execute the queries ; Stores the sum of each row ; Stores the sum of each col ; Traverse the matrix and calculate sum of each row and column ; Insert all row sums in sum_list ; Insert all column sums in sum_list ; Sort the array in ascending order ; Traverse the array queries [ ] [ ] ; Search the leftmost index of L ; Search the rightmost index of R ; Function to search for the leftmost index of given number ; Initialize low , high and ans ; Stores mid ; If A [ mid ] >= num ; Function to search for the rightmost index of given number ; Initialise low , high and ans ; Stores mid ; If A [ mid ] <= num ; Update ans ; Update mid ; Update high ; Driver Code ; Given dimensions of matrix ; Given matrix ; Given number of queries ; Given queries ; Function call to count the number row - sums and column - sums present in the given ranges"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void totalCount ( int [ ] [ ] A , int N , int M , int [ ] [ ] queries , int Q ) { int row_sum [ ] = new int [ N ] ; int col_sum [ ] = new int [ M ] ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { row_sum [ i ] += A [ i ] [ j ] ; col_sum [ j ] += A [ i ] [ j ] ; } } ArrayList < Integer > sum_list = new ArrayList < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) sum_list . add ( row_sum [ i ] ) ; for ( int i = 0 ; i < M ; i ++ ) sum_list . add ( col_sum [ i ] ) ; Collections . sort ( sum_list ) ; for ( int i = 0 ; i < Q ; i ++ ) { int L = queries [ i ] [ 0 ] ; int R = queries [ i ] [ 1 ] ; int l = left_search ( sum_list , L ) ; int r = right_search ( sum_list , R ) ; System . out . print ( r - l + 1 + " ▁ " ) ; } } static int left_search ( ArrayList < Integer > A , int num ) { int low = 0 , high = A . size ( ) - 1 ; int ans = 0 ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( A . get ( mid ) >= num ) { ans = mid ; high = mid - 1 ; } else { low = mid + 1 ; } } return ans ; } static int right_search ( ArrayList < Integer > A , int num ) { int low = 0 , high = A . size ( ) - 1 ; int ans = high ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( A . get ( mid ) <= num ) { ans = mid ; low = mid + 1 ; } else { high = mid - 1 ; } } return ans ; } public static void main ( String [ ] args ) { int N = 3 , M = 2 ; int A [ ] [ ] = { { 13 , 3 } , { 9 , 4 } , { 6 , 10 } } ; int Q = 2 ; int queries [ ] [ ] = { { 10 , 20 } , { 25 , 35 } } ; totalCount ( A , N , M , queries , Q ) ; } }


"Queries to count the number of unordered co | Java program to find number of unordered coprime pairs of integers from 1 to N ; to store euler 's totient function ; to store required answer ; Computes and prints totient of all numbers smaller than or equal to N . ; Initialise the phi [ ] with 1 ; Compute other Phi values ; If phi [ p ] is not computed already , then number p is prime ; Phi of a prime number p is always equal to p - 1. ; Update phi values of all multiples of p ; Add contribution of p to its multiple i by multiplying with ( 1 - 1 / p ) ; function to compute number coprime pairs ; function call to compute euler totient function ; prefix sum of all euler totient function values ; Driver code ; function call"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static final int N = 100005 ; static int [ ] phi ; static int [ ] S ; static void computeTotient ( ) { for ( int i = 1 ; i < N ; i ++ ) phi [ i ] = i ; for ( int p = 2 ; p < N ; p ++ ) { if ( phi [ p ] == p ) { phi [ p ] = p - 1 ; for ( int i = 2 * p ; i < N ; i += p ) { phi [ i ] = ( phi [ i ] / p ) * ( p - 1 ) ; } } } } static void CoPrimes ( ) { computeTotient ( ) ; for ( int i = 1 ; i < N ; i ++ ) S [ i ] = S [ i - 1 ] + phi [ i ] ; } public static void main ( String args [ ] ) { phi = new int [ N ] ; S = new int [ N ] ; CoPrimes ( ) ; int q [ ] = { 3 , 4 } ; int n = q . length ; for ( int i = 0 ; i < n ; i ++ ) System . out . println ( "Number of unordered coprime " ▁ + ▁ " pairs of integers from 1 to " ▁ + ▁ q [ i ] ▁ + ▁ " are " + S[q[i]] ); } }


"Queries to find Kth greatest character in a range [ L , R ] from a string with updates | Java Program to implement the above approach ; Maximum Size of a String ; Fenwick Tree to store the frequencies of 26 alphabets ; Size of the String . ; Function to update Fenwick Tree for Character c at index val ; Add val to current node Fenwick Tree ; Move index to parent node in update View ; Function to get sum of frequencies of character c till index ; Stores the sum ; Add current element of Fenwick tree to sum ; Move index to parent node in getSum View ; Function to create the Fenwick tree ; Function to print the kth largest character in the range of l to r ; Stores the count of characters ; Stores the required character ; Calculate frequency of C in the given range ; Increase count ; If count exceeds K ; Required character found ; Function to update character at pos by character s ; 0 based index system ; Driver Code ; Makes the String 1 - based indexed ; Number of queries ; Construct the Fenwick Tree"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int maxn = 100005 ; static int [ ] [ ] BITree = new int [ 26 ] [ maxn ] ; static int N ; static void update_BITree ( int index , char C , int val ) { while ( index <= N ) { BITree [ C - ' a ' ] [ index ] += val ; index += ( index & - index ) ; } } static int sum_BITree ( int index , char C ) { int s = 0 ; while ( index > 0 ) { s += BITree [ C - ' a ' ] [ index ] ; index -= ( index & - index ) ; } return s ; } static void buildTree ( String str ) { for ( int i = 1 ; i <= N ; i ++ ) { update_BITree ( i , str . charAt ( i ) , 1 ) ; } System . out . println ( ) ; } static char printCharacter ( String str , int l , int r , int k ) { int count = 0 ; char ans = 0 ; for ( char C = ' z ' ; C >= ' a ' ; C -- ) { int times = sum_BITree ( r , C ) - sum_BITree ( l - 1 , C ) ; count += times ; if ( count >= k ) { ans = C ; break ; } } return ans ; } static void updateTree ( String str , int pos , char s ) { int index = pos ; update_BITree ( index , str . charAt ( index ) , - 1 ) ; str = str . substring ( 0 , index ) + s + str . substring ( index + 1 ) ; update_BITree ( index , s , 1 ) ; } public static void main ( String [ ] args ) { String str = " abcddef " ; N = str . length ( ) ; str = ' / ' + str ; int Q = 3 ; buildTree ( str ) ; System . out . print ( printCharacter ( str , 1 , 2 , 2 ) + "
"); updateTree ( str , 4 , ' g ' ) ; System . out . print ( printCharacter ( str , 1 , 5 , 4 ) + "
"); } }


"Queries to find Kth greatest character in a range [ L , R ] from a string with updates | Java Program to implement the above approach include " bits / stdJava . h " ; Function to find the kth greatest character from the strijng ; Sorting the String in non - increasing Order ; Function to print the K - th character from the subString S [ l ] . . S [ r ] ; 0 - based indexing ; SubString of str from the indices l to r . ; Extract kth Largest character ; Function to replace character at pos of str by the character s ; Index of S to be updated . ; Character to be replaced at index in S ; Driver Code ; Given String ; Count of queries ; Queries"
How can the above be solved in Java?

 import java . util . * ; class GFG { static char find_kth_largest ( char [ ] str , int k ) { Arrays . sort ( str ) ; reverse ( str ) ; return str [ k - 1 ] ; } static char [ ] reverse ( char a [ ] ) { int i , n = a . length ; char t ; for ( i = 0 ; i < n / 2 ; i ++ ) { t = a [ i ] ; a [ i ] = a [ n - i - 1 ] ; a [ n - i - 1 ] = t ; } return a ; } static char printCharacter ( String str , int l , int r , int k ) { l = l - 1 ; r = r - 1 ; String temp = str . substring ( l , r - l + 1 ) ; char ans = find_kth_largest ( temp . toCharArray ( ) , k ) ; return ans ; } static void updateString ( char [ ] str , int pos , char s ) { int index = pos - 1 ; char c = s ; str [ index ] = c ; } public static void main ( String [ ] args ) { String str = " abcddef " ; int Q = 3 ; System . out . print ( printCharacter ( str , 1 , 2 , 2 ) + "
"); updateString ( str . toCharArray ( ) , 4 , ' g ' ) ; System . out . print ( printCharacter ( str , 1 , 5 , 4 ) + "
"); } }


"Queries to find distance between two nodes of a Binary tree | Java program to find distance between two nodes for multiple queries ; A tree node structure ; Array to store level of each node ; Utility Function to store level of all nodes ; queue to hold tree node with level ; let root node be at level 0 ; Do level Order Traversal of tree ; Node p . first is on level p . second ; If left child exits , put it in queue with current_level + 1 ; If right child exists , put it in queue with current_level + 1 ; Stores Euler Tour ; index in Euler array ; Find Euler Tour ; store current node 's data ; If left node exists ; traverse left subtree ; store parent node 's data ; If right node exists ; traverse right subtree ; store parent node 's data ; checks for visited nodes ; Stores level of Euler Tour ; Stores indices of first occurrence of nodes in Euler tour ; Preprocessing Euler Tour for finding LCA ; If node is not visited before ; Add to first occurrence ; Mark it visited ; Stores values and positions ; Utility function to find minimum of pair type values ; Utility function to build segment tree ; Utility function to find LCA ; Function to return distance between two nodes n1 and n2 ; Maintain original Values ; Get First Occurrence of n1 ; Get First Occurrence of n2 ; Swap if low > high ; Get position of minimum value ; Extract value out of Euler tour ; return calculated distance ; Build Tree ; Store Levels ; Find L and H array ; Build segment Tree ; Driver Code ; Number of nodes ; Constructing tree given in the above figure ; Function to do all preprocessing"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int MAX = 100001 ; static class Node { int data ; Node left , right ; Node ( int data ) { this . data = data ; this . left = this . right = null ; } } static class Pair < T , V > { T first ; V second ; Pair ( ) { } Pair ( T first , V second ) { this . first = first ; this . second = second ; } } static int [ ] level = new int [ MAX ] ; static void findLevels ( Node root ) { if ( root == null ) return ; Queue < Pair < Node , Integer > > q = new LinkedList < > ( ) ; q . add ( new Pair < Node , Integer > ( root , 0 ) ) ; Pair < Node , Integer > p = new Pair < Node , Integer > ( ) ; while ( ! q . isEmpty ( ) ) { p = q . poll ( ) ; level [ p . first . data ] = p . second ; if ( p . first . left != null ) q . add ( new Pair < Node , Integer > ( p . first . left , p . second + 1 ) ) ; if ( p . first . right != null ) q . add ( new Pair < Node , Integer > ( p . first . right , p . second + 1 ) ) ; } } static int [ ] Euler = new int [ MAX ] ; static int idx = 0 ; static void eulerTree ( Node root ) { Euler [ ++ idx ] = root . data ; if ( root . left != null ) { eulerTree ( root . left ) ; Euler [ ++ idx ] = root . data ; } if ( root . right != null ) { eulerTree ( root . right ) ; Euler [ ++ idx ] = root . data ; } } static int [ ] vis = new int [ MAX ] ; static int [ ] L = new int [ MAX ] ; static int [ ] H = new int [ MAX ] ; static void preprocessEuler ( int size ) { for ( int i = 1 ; i <= size ; i ++ ) { L [ i ] = level [ Euler [ i ] ] ; if ( vis [ Euler [ i ] ] == 0 ) { H [ Euler [ i ] ] = i ; vis [ Euler [ i ] ] = 1 ; } } } @ SuppressWarnings ( " unchecked " ) static Pair < Integer , Integer > [ ] seg = ( Pair < Integer , Integer > [ ] ) new Pair [ 4 * MAX ] ; static Pair < Integer , Integer > min ( Pair < Integer , Integer > a , Pair < Integer , Integer > b ) { if ( a . first <= b . first ) return a ; return b ; } static Pair < Integer , Integer > buildSegTree ( int low , int high , int pos ) { if ( low == high ) { seg [ pos ] . first = L [ low...


"Queries to find frequencies of a string within specified substrings | Java program to find frequency of a string K in a substring [ L , R ] in S ; Store the frequency of string for each index ; Compute and store frequencies for every index ; Driver code"
How can the above be solved in Java?

class GFG { static int max_len = 100005 ; static int cnt [ ] = new int [ max_len ] ; public static void precompute ( String s , String K ) { int n = s . length ( ) ; for ( int i = 0 ; i < n - 2 ; i ++ ) { cnt [ i + 1 ] = cnt [ i ] ; if ( s . substring ( i , i + K . length ( ) ) . equals ( K ) ) { cnt [ i + 1 ] += 1 ; } } cnt [ n - 2 + 1 ] = cnt [ n - 2 ] ; } public static void main ( String [ ] args ) { String s = " ABCABCABABC " ; String K = " ABC " ; precompute ( s , K ) ; int Q [ ] [ ] = { { 1 , 6 } , { 5 , 11 } } ; for ( int it = 0 ; it < Q . length ; it ++ ) { System . out . println ( cnt [ Q [ it ] [ 1 ] - 1 ] - cnt [ Q [ it ] [ 0 ] - 1 ] ) ; } } }


"Queries to find maximum sum contiguous subarrays of given length in a rotating array | Java program for the above approach ; Function to calculate the maximum sum of length k ; Calculating the max sum for the first k elements ; Find subarray with maximum sum ; Update the sum ; Return maximum sum ; Function to calculate gcd of the two numbers n1 and n2 ; Base Case ; Recursively find the GCD ; Function to rotate the array by Y ; For handling k >= N ; Dividing the array into number of sets ; Rotate the array by Y ; Update arr [ j ] ; Return the rotated array ; Function that performs the queries on the given array ; Traverse each query ; If query of type X = 1 ; Print the array ; If query of type X = 2 ; Driver Code ; Given array arr [ ] ; Given Queries ; Function Call"
How can the above be solved in Java?

 class GFG { static int MaxSum ( int [ ] arr , int n , int k ) { int i , max_sum = 0 , sum = 0 ; for ( i = 0 ; i < k ; i ++ ) { sum += arr [ i ] ; } max_sum = sum ; while ( i < n ) { sum = sum - arr [ i - k ] + arr [ i ] ; if ( max_sum < sum ) { max_sum = sum ; } i ++ ; } return max_sum ; } static int gcd ( int n1 , int n2 ) { if ( n2 == 0 ) { return n1 ; } else { return gcd ( n2 , n1 % n2 ) ; } } static int [ ] RotateArr ( int [ ] arr , int n , int d ) { int i = 0 , j = 0 ; d = d % n ; int no_of_sets = gcd ( d , n ) ; for ( i = 0 ; i < no_of_sets ; i ++ ) { int temp = arr [ i ] ; j = i ; while ( true ) { int k = j + d ; if ( k >= n ) k = k - n ; if ( k == i ) break ; arr [ j ] = arr [ k ] ; j = k ; } arr [ j ] = temp ; } return arr ; } static void performQuery ( int [ ] arr , int Q [ ] [ ] , int q ) { int N = arr . length ; for ( int i = 0 ; i < q ; i ++ ) { if ( Q [ i ] [ 0 ] == 1 ) { arr = RotateArr ( arr , N , Q [ i ] [ 1 ] ) ; for ( int t : arr ) { System . out . print ( t + " ▁ " ) ; } System . out . print ( "
"); } else { System . out . print ( MaxSum ( arr , N , Q [ i ] [ 1 ] ) + "
"); } } } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 } ; int q = 5 ; int Q [ ] [ ] = { { 1 , 2 } , { 2 , 3 } , { 1 , 3 } , { 1 , 1 } , { 2 , 4 } } ; performQuery ( arr , Q , q ) ; } }


"Queries to find minimum absolute difference between adjacent array elements in given ranges | Java program for the above approach ; Stores the index for the minimum value in the subarray arr [ i , j ] ; Structure for query range ; Function to fill the lookup array lookup [ ] [ ] in the bottom up manner ; Initialize M for the intervals with length 1 ; Find the values from smaller to bigger intervals ; Compute minimum value for all intervals with size 2 ^ j ; For arr [ 2 ] [ 10 ] , compare arr [ lookup [ 0 ] [ 3 ] ] and arr [ lookup [ 3 ] [ 3 ] ] ; Otherwise ; Function find minimum of absolute difference of all adjacent element in subarray arr [ L . . R ] ; For [ 2 , 10 ] , j = 3 ; For [ 2 , 10 ] , compare arr [ lookup [ 0 ] [ 3 ] ] and arr [ lookup [ 3 ] [ 3 ] ] , ; Function to find the minimum of the ranges for M queries ; Fills table lookup [ n ] [ Log n ] ; Compute sum of all queries ; Left and right boundaries of current range ; Print sum of current query range ; Function to find the minimum absolute difference in a range ; diff [ ] is to stores the absolute difference of adjacent elements ; Call Min_difference to get minimum difference of adjacent elements ; Driver Code"
How can the above be solved in Java?

import java . util . * ; import javax . management . Query ; class GFG { static final int MAX = 500 ; static int [ ] [ ] lookup = new int [ MAX ] [ MAX ] ; static class Query { int L , R ; public Query ( int l , int r ) { super ( ) ; L = l ; R = r ; } } ; static void preprocess ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) lookup [ i ] [ 0 ] = i ; for ( int j = 1 ; ( 1 << j ) <= n ; j ++ ) { for ( int i = 0 ; ( i + ( 1 << j ) - 1 ) < n ; i ++ ) { if ( arr [ lookup [ i ] [ j - 1 ] ] < arr [ lookup [ i + ( 1 << ( j - 1 ) ) ] [ j - 1 ] ] ) lookup [ i ] [ j ] = lookup [ i ] [ j - 1 ] ; else lookup [ i ] [ j ] = lookup [ i + ( 1 << ( j - 1 ) ) ] [ j - 1 ] ; } } } static int query ( int arr [ ] , int L , int R ) { int j = ( int ) Math . log ( R - L + 1 ) ; if ( arr [ lookup [ L ] [ j ] ] <= arr [ lookup [ R - ( 1 << j ) + 1 ] [ j ] ] ) return arr [ lookup [ L ] [ j ] ] ; else return arr [ lookup [ R - ( 1 << j ) + 1 ] [ j ] ] ; } static void Min_difference ( int arr [ ] , int n , Query q [ ] , int m ) { preprocess ( arr , n ) ; for ( int i = 0 ; i < m ; i ++ ) { int L = q [ i ] . L , R = q [ i ] . R ; System . out . println ( query ( arr , L , R - 1 ) ) ; } } static void minimumDifference ( int arr [ ] , Query q [ ] , int N , int m ) { int [ ] diff = new int [ N ] ; for ( int i = 0 ; i < N - 1 ; i ++ ) diff [ i ] = Math . abs ( arr [ i ] - arr [ i + 1 ] ) ; Min_difference ( diff , N - 1 , q , m ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 6 , 1 , 8 , 3 , 4 } ; int N = arr . length ; Query Q [ ] = { new Query ( 0 , 3 ) , new Query ( 1 , 5 ) , new Query ( 4 , 5 ) } ; int M = Q . length ; minimumDifference ( arr , Q , N , M ) ; } }


"Queries to find minimum absolute difference between adjacent array elements in given ranges | Java program for the above approach ; Structure for query range ; Function to find the minimum difference between adjacent array element over the given range [ L , R ] for Q Queries ; Find the sum of all queries ; Left and right boundaries of current range ; Print the sum of the current query range ; Function to find the minimum absolute difference of adjacent array elements for the given range ; Stores the absolute difference of adjacent elements ; Find the minimum difference of adjacent elements ; Driver Code"
How can the above be solved in Java?

class GFG { static class Query { int L , R ; public Query ( int l , int r ) { super ( ) ; L = l ; R = r ; } } ; static int MAX = 5000 ; static void minDifference ( int arr [ ] , int n , Query q [ ] , int m ) { for ( int i = 0 ; i < m ; i ++ ) { int L = q [ i ] . L , R = q [ i ] . R ; int ans = MAX ; for ( int j = L ; j < R ; j ++ ) { ans = Math . min ( ans , arr [ j ] ) ; } System . out . println ( ans ) ; } } static void minimumDifference ( int arr [ ] , Query q [ ] , int N , int m ) { int [ ] diff = new int [ N ] ; for ( int i = 0 ; i < N - 1 ; i ++ ) diff [ i ] = Math . abs ( arr [ i ] - arr [ i + 1 ] ) ; minDifference ( diff , N - 1 , q , m ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 6 , 1 , 8 , 3 , 4 } ; int N = arr . length ; Query Q [ ] = { new Query ( 0 , 3 ) , new Query ( 1 , 5 ) , new Query ( 4 , 5 ) } ; int M = Q . length ; minimumDifference ( arr , Q , N , M ) ; } }


"Queries to find minimum sum of array elements from either end of an array | Java implementation of the above approach ; Function to calculate the minimum sum from either end of the arrays for the given queries ; Traverse the query [ ] array ; Stores sum from start and end of the array ; Calculate distance from start ; Calculate distance from end ; Driver Code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; public class GFG { static void calculateQuery ( int arr [ ] , int N , int query [ ] , int M ) { for ( int i = 0 ; i < M ; i ++ ) { int X = query [ i ] ; int sum_start = 0 , sum_end = 0 ; for ( int j = 0 ; j < N ; j ++ ) { sum_start += arr [ j ] ; if ( arr [ j ] == X ) break ; } for ( int j = N - 1 ; j >= 0 ; j -- ) { sum_end += arr [ j ] ; if ( arr [ j ] == X ) break ; } System . out . print ( Math . min ( sum_end , sum_start ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 6 , 7 , 4 , 5 , 30 } ; int queries [ ] = { 6 , 5 } ; int N = arr . length ; int M = queries . length ; calculateQuery ( arr , N , queries , M ) ; } }


"Queries to find minimum sum of array elements from either end of an array | Java implementation of the above approach ; Function to find the minimum sum for the given queries ; Stores prefix and suffix sums ; Stores pairs of prefix and suffix sums ; Traverse the array ; Add element to prefix ; Store prefix for each element ; Traverse the array in reverse ; Add element to suffix ; Storing suffix for each element ; Traverse the array queries [ ] ; Minimum of suffix and prefix sums ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static class pair < E , P > { E first ; P second ; public pair ( E first , P second ) { this . first = first ; this . second = second ; } } @ SuppressWarnings ( { " unchecked " , " rawtypes " } ) static void calculateQuery ( int arr [ ] , int N , int query [ ] , int M ) { int prefix = 0 , suffix = 0 ; HashMap < Integer , pair > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { prefix += arr [ i ] ; mp . put ( arr [ i ] , new pair ( prefix , 0 ) ) ; } for ( int i = N - 1 ; i >= 0 ; i -- ) { suffix += arr [ i ] ; mp . put ( arr [ i ] , new pair ( mp . get ( arr [ i ] ) . first , suffix ) ) ; } for ( int i = 0 ; i < M ; i ++ ) { int X = query [ i ] ; System . out . print ( Math . min ( ( int ) mp . get ( X ) . first , ( int ) mp . get ( X ) . second ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 6 , 7 , 4 , 5 , 30 } ; int queries [ ] = { 6 , 5 } ; int N = arr . length ; int M = queries . length ; calculateQuery ( arr , N , queries , M ) ; } }


"Queries to find minimum swaps required to sort given array with updates | Java program for the above approach ; Function to return the position of the given value using binary search ; Return 0 if every value is greater than the given value ; Return N - 1 if every value is smaller than the given value ; Perform Binary Search ; Iterate till start < end ; Find the mid ; Update start and end ; Return the position of the given value ; Function to return the number of make the array sorted ; Index x to update ; Increment value by y ; Set newElement equals to x + y ; Compute the new index ; Print the minimum number of swaps ; Driver Code ; Given array arr [ ] ; Given Queries ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int computePos ( int arr [ ] , int n , int value ) { if ( value < arr [ 0 ] ) return 0 ; if ( value > arr [ n - 1 ] ) return n - 1 ; int start = 0 ; int end = n - 1 ; while ( start < end ) { int mid = ( start + end + 1 ) / 2 ; if ( arr [ mid ] >= value ) end = mid - 1 ; else start = mid ; } return start ; } static void countShift ( int arr [ ] , int n , Vector < Vector < Integer > > queries ) { for ( Vector < Integer > q : queries ) { int index = q . get ( 0 ) ; int update = q . get ( 1 ) ; int newElement = arr [ index ] + update ; int newIndex = computePos ( arr , n , newElement ) ; System . out . print ( Math . abs ( newIndex - index ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 4 , 5 , 6 } ; int N = arr . length ; Vector < Vector < Integer > > queries = new Vector < > ( ) ; Vector < Integer > v = new Vector < > ( ) ; Vector < Integer > v1 = new Vector < > ( ) ; v . add ( 0 ) ; v . add ( - 1 ) ; queries . add ( v ) ; v1 . add ( 4 ) ; v1 . add ( - 11 ) ; queries . add ( v1 ) ; countShift ( arr , N , queries ) ; } }


"Queries to find number of connected grid components of given sizes in a Matrix | Java implementation for the above approach ; stores information about which cell are already visited in a particular BFS ; Stores the final result grid ; Stores the count of cells in the largest connected component ; Function checks if a cell is valid , i . e . it is inside the grid and equal to 1 ; Map to count the frequency of each connected component ; function to calculate the largest connected component ; Iterate over every cell ; Stores the indices of the matrix cells ; Mark the starting cell as visited and push it into the queue ; Iterate while the queue is not empty ; Go to the adjacent cells ; Drivers Code ; Given input array of 1 s and 0 s ; queries array ; sizeof queries array ; Count the frequency of each connected component ; Iterate over the given queries array and And answer the queries"
How can the above be solved in Java?

import java . util . * ; class GFG { static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static int n = 6 ; static int m = 6 ; static int dx [ ] = { 0 , 1 , - 1 , 0 } ; static int dy [ ] = { 1 , 0 , 0 , - 1 } ; static int [ ] [ ] visited = new int [ n ] [ m ] ; static int [ ] [ ] result = new int [ n ] [ m ] ; static int COUNT ; static boolean is_valid ( int x , int y , int matrix [ ] [ ] ) { if ( x < n && y < m && x >= 0 && y >= 0 ) { if ( visited [ x ] [ y ] == 0 && matrix [ x ] [ y ] == 1 ) return true ; else return false ; } else return false ; } static HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; static void findComponentSize ( int matrix [ ] [ ] ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( visited [ i ] [ j ] == 0 && matrix [ i ] [ j ] == 1 ) { COUNT = 0 ; Queue < pair > q = new LinkedList < > ( ) ; q . add ( new pair ( i , j ) ) ; visited [ i ] [ j ] = 1 ; while ( ! q . isEmpty ( ) ) { pair p = q . peek ( ) ; q . remove ( ) ; int x = p . first , y = p . second ; COUNT ++ ; for ( int k = 0 ; k < 4 ; k ++ ) { int newX = x + dx [ k ] ; int newY = y + dy [ k ] ; if ( is_valid ( newX , newY , matrix ) ) { q . add ( new pair ( newX , newY ) ) ; visited [ newX ] [ newY ] = 1 ; } } } if ( mp . containsKey ( COUNT ) ) { mp . put ( COUNT , mp . get ( COUNT ) + 1 ) ; } else { mp . put ( COUNT , 1 ) ; } } } } } public static void main ( String [ ] args ) { int matrix [ ] [ ] = { { 1 , 1 , 1 , 1 , 1 , 1 } , { 1 , 1 , 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 1 , 1 , 1 } , { 0 , 0 , 0 , 1 , 1 , 1 } , { 0 , 0 , 1 , 0 , 0 , 0 } , { 1 , 0 , 0 , 0 , 0 , 0 } } ; int queries [ ] = { 6 , 1 , 8 , 2 } ; int N = queries . length ; findComponentSize ( matrix ) ; for ( int i = 0 ; i < N ; i ++ ) System . out . print ( ( mp . get ( queries [ i ] ) != null ? mp . get ( queries [ i ] ) : 0 ) + " ▁ " ) ; } }


"Queries to find sum of distance of a given node to every leaf node in a Weighted Tree | Java program for the above problem ; MAX size ; Graph with { destination , weight } ; ; For storing the sum for ith node ; Leaves in subtree of ith . ; dfs to find sum of distance of leaves in the subtree of a node ; Flag is the node is leaf or not ; ; Skipping if parent ; Setting flag to false ; Doing dfs call ; Doing calculation in postorder . ; If the node is leaf then we just increment the no . of leaves under the subtree of a node ; Adding num of leaves ; Calculating answer for the sum in the subtree ; dfs function to find the sum of distance of leaves outside the subtree ; Number of leaves other than the leaves in the subtree of i ; Adding the contribution of leaves outside to the ith node ; Adding the leafs outside to ith node 's leaves. ; Calculating the sum of distance of leaves in the subtree of a node assuming the root of the tree is 1 ; Calculating the sum of distance of leaves outside the subtree of node assuming the root of the tree is 1 ; Answering the queries ; ; Driver code ; 1 ( 4 ) / \ ( 2 ) / \ 4 2 ( 5 ) / \ ( 3 ) / \ 5 3 ; Initialising tree ; System . out . println ( v ) ;"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static class pair { int first , second ; pair ( int f , int s ) { this . first = f ; this . second = s ; } } static final int N = ( int ) 1e5 + 5 ; static ArrayList < ArrayList < pair > > v ; static int [ ] dp = new int [ N ] ; static int [ ] leaves = new int [ N ] ; static int n ; static void dfs ( int a , int par ) { int leaf = 1 ; for ( pair i : v . get ( a ) ) { if ( i . first == par ) continue ; leaf = 0 ; dfs ( i . first , a ) ; } if ( leaf == 1 ) { leaves [ a ] += 1 ; } else { for ( pair i : v . get ( a ) ) { if ( i . first == par ) continue ; leaves [ a ] += leaves [ i . first ] ; dp [ a ] = dp [ a ] + dp [ i . first ] + leaves [ i . first ] * i . second ; } } } static void dfs2 ( int a , int par ) { for ( pair i : v . get ( a ) ) { if ( i . first == par ) continue ; int leafOutside = leaves [ a ] - leaves [ i . first ] ; dp [ i . first ] += ( dp [ a ] - dp [ i . first ] ) ; dp [ i . first ] += i . second * ( leafOutside - leaves [ i . first ] ) ; leaves [ i . first ] += leafOutside ; dfs2 ( i . first , a ) ; } } static void answerQueries ( int [ ] queries ) { dfs ( 1 , 0 ) ; dfs2 ( 1 , 0 ) ; for ( int i = 0 ; i < queries . length ; i ++ ) { System . out . println ( dp [ queries [ i ] ] ) ; } } public static void main ( String [ ] args ) { n = 5 ; v = new ArrayList < > ( ) ; for ( int i = 0 ; i <= n ; i ++ ) v . add ( new ArrayList < pair > ( ) ) ; v . get ( 1 ) . add ( new pair ( 4 , 4 ) ) ; v . get ( 4 ) . add ( new pair ( 1 , 4 ) ) ; v . get ( 1 ) . add ( new pair ( 2 , 2 ) ) ; v . get ( 2 ) . add ( new pair ( 1 , 2 ) ) ; v . get ( 2 ) . add ( new pair ( 3 , 3 ) ) ; v . get ( 3 ) . add ( new pair ( 2 , 3 ) ) ; v . get ( 2 ) . add ( new pair ( 5 , 5 ) ) ; v . get ( 5 ) . add ( new pair ( 2 , 5 ) ) ; int [ ] queries = { 1 , 3 , 5 } ; answerQueries ( queries ) ; } }


"Queries to find the Lower Bound of K from Prefix Sum Array with updates using Fenwick Tree | Java program to implement the above approach ; Function to calculate and return the sum of arr [ 0. . index ] ; Traverse ancestors of BITree [ index ] ; Update the sum of current element of BIT to ans ; Update index to that of the parent node in getSum ( ) view by subtracting LSB ( Least Significant Bit ) ; Function to update the Binary Index Tree by replacing all ancestors of index by their respective sum with val ; Traverse all ancestors and sum with ' val ' . ; Add ' val ' to current node of BIT ; Update index to that of the parent node in updateBit ( ) view by adding LSB ( Least Significant Bit ) ; Function to construct the Binary Indexed Tree for the given array ; Initialize the Binary Indexed Tree ; Store the actual values in BITree [ ] using update ( ) ; Function to obtain and return the index of lower_bound of k ; Store the Binary Indexed Tree ; Solve each query in Q ; Update the values of all ancestors of idx ; Driver Code"
How can the above be solved in Java?

import java . util . * ; import java . io . * ; class GFG { static int getSum ( int BITree [ ] , int index ) { int ans = 0 ; index += 1 ; while ( index > 0 ) { ans += BITree [ index ] ; index -= index & ( - index ) ; } return ans ; } static void updateBIT ( int BITree [ ] , int n , int index , int val ) { index = index + 1 ; while ( index <= n ) { BITree [ index ] += val ; index += index & ( - index ) ; } } static int [ ] constructBITree ( int arr [ ] , int n ) { int [ ] BITree = new int [ n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) BITree [ i ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) updateBIT ( BITree , n , i , arr [ i ] ) ; return BITree ; } static int getLowerBound ( int BITree [ ] , int [ ] arr , int n , int k ) { int lb = - 1 ; int l = 0 , r = n - 1 ; while ( l <= r ) { int mid = l + ( r - l ) / 2 ; if ( getSum ( BITree , mid ) >= k ) { r = mid - 1 ; lb = mid ; } else l = mid + 1 ; } return lb ; } static void performQueries ( int A [ ] , int n , int q [ ] [ ] ) { int [ ] BITree = constructBITree ( A , n ) ; for ( int i = 0 ; i < q . length ; i ++ ) { int id = q [ i ] [ 0 ] ; if ( id == 1 ) { int idx = q [ i ] [ 1 ] ; int val = q [ i ] [ 2 ] ; A [ idx ] += val ; updateBIT ( BITree , n , idx , val ) ; } else { int k = q [ i ] [ 1 ] ; int lb = getLowerBound ( BITree , A , n , k ) ; System . out . println ( lb ) ; } } } public static void main ( String [ ] args ) { int A [ ] = { 1 , 2 , 3 , 5 , 8 } ; int n = A . length ; int [ ] [ ] q = { { 1 , 0 , 2 } , { 2 , 5 } , { 1 , 3 , 5 } } ; performQueries ( A , n , q ) ; } }


"Queries to find the XOR of an Array after replacing all occurrences of X by Y | Java Program to implement the above approach ; Stores the bitwise XOR of array elements ; Function to find the total xor ; Loop to find the xor of all the elements ; Function to find the XOR after replacing all occurrences of X by Y for Q queries ; Remove contribution of X from total_xor ; Adding contribution of Y to total_xor ; Print total_xor ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int total_xor ; static void initialize_xor ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { total_xor = total_xor ^ arr [ i ] ; } } static void find_xor ( int X , int Y ) { total_xor = total_xor ^ X ; total_xor = total_xor ^ Y ; System . out . print ( total_xor + "
"); } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 7 , 8 , 9 } ; int n = arr . length ; initialize_xor ( arr , n ) ; int [ ] [ ] Q = { { 5 , 6 } , { 8 , 1 } } ; for ( int i = 0 ; i < Q . length ; i ++ ) { find_xor ( Q [ i ] [ 0 ] , Q [ i ] [ 1 ] ) ; } } }


"Queries to find the count of characters preceding the given location | Java implementation of the approach ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void Count ( int [ ] temp ) { int [ ] query = { 9 , 3 , 2 } ; int Q = query . length ; for ( int i = 0 ; i < Q ; i ++ ) { int pos = query [ i ] ; System . out . println ( temp [ pos - 1 ] ) ; } } static int [ ] processing ( String s , int len ) { int [ ] temp = new int [ len ] ; HashMap < Character , Integer > d = new HashMap < Character , Integer > ( ) ; for ( int i = 0 ; i < len ; i ++ ) { if ( ! d . containsKey ( s . charAt ( i ) ) ) { d . put ( s . charAt ( i ) , i ) ; } else { temp [ i ] = temp [ d . get ( s . charAt ( i ) ) ] + 1 ; d . put ( s . charAt ( i ) , i ) ; } } return temp ; } public static void main ( String [ ] args ) { String s = " abacsddaa " ; int n = s . length ( ) ; int [ ] temp = processing ( s , n ) ; Count ( temp ) ; } }


"Queries to find the count of characters preceding the given location | Java implementation of the approach ; returns character at index pos - 1 ; Driver Code"
How can the above be solved in Java?

class GFG { static int Count ( String s , int pos ) { int c = s . charAt ( pos - 1 ) ; int counter = 0 ; for ( int i = 0 ; i < pos - 1 ; i ++ ) { if ( s . charAt ( i ) == c ) counter = counter + 1 ; } return counter ; } public static void main ( String [ ] args ) { String s = " abacsddaa " ; int pos ; int n = s . length ( ) ; int query [ ] = { 9 , 3 , 2 } ; int Q = query . length ; for ( int i = 0 ; i < Q ; i ++ ) { pos = query [ i ] ; System . out . println ( Count ( s , pos ) ) ; } } }


"Queries to find the count of connected Non | Java program to implement the above approach ; Count of connected cells ; Function to return the representative of the Set to which x belongs ; If x is parent of itself ; x is representative of the Set ; Otherwise ; Path Compression ; Unites the set that includes x and the set that includes y ; Find the representatives ( or the root nodes ) for x an y ; If both are in the same set ; Decrement count ; If x ' s ▁ rank ▁ is ▁ less ▁ than ▁ y ' s rank ; Otherwise ; Then move x under y ( doesn 't matter which one goes where) ; And increment the result tree 's  rank by 1 ; Function to count the number of connected cells in the matrix ; Store result for queries ; Store representative of each element ; Initially , all elements are in their own set ; Stores the rank ( depth ) of each node ; If the grid [ x * m + y ] is already set , store the result ; Set grid [ x * m + y ] to 1 ; Increment count . ; Check for all adjacent cells to do a Union with neighbour 's  set if neighbour is also 1 ; Store result . ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int ctr = 0 ; static int find ( int [ ] parent , int x ) { if ( parent [ x ] == x ) return x ; parent [ x ] = find ( parent , parent [ x ] ) ; return parent [ x ] ; } static void setUnion ( int [ ] parent , int [ ] rank , int x , int y ) { int parentx = find ( parent , x ) ; int parenty = find ( parent , y ) ; if ( parenty == parentx ) return ; ctr -- ; if ( rank [ parentx ] < rank [ parenty ] ) { parent [ parentx ] = parenty ; } else if ( rank [ parentx ] > rank [ parenty ] ) { parent [ parenty ] = parentx ; } else { parent [ parentx ] = parenty ; rank [ parenty ] ++ ; } } static int [ ] solve ( int n , int m , int [ ] [ ] query ) { int [ ] result = new int [ query . length ] ; int [ ] parent = new int [ n * m ] ; for ( int i = 0 ; i < n * m ; i ++ ) parent [ i ] = i ; int [ ] rank = new int [ n * m ] ; Arrays . fill ( rank , 1 ) ; boolean [ ] grid = new boolean [ n * m ] ; for ( int i = 0 ; i < query . length ; i ++ ) { int x = query [ i ] [ 0 ] ; int y = query [ i ] [ 1 ] ; if ( grid [ m * x + y ] == true ) { result [ i ] = ctr ; continue ; } grid [ m * x + y ] = true ; ctr ++ ; if ( x > 0 && grid [ m * ( x - 1 ) + y ] == true ) setUnion ( parent , rank , m * x + y , m * ( x - 1 ) + y ) ; if ( y > 0 && grid [ m * ( x ) + y - 1 ] == true ) setUnion ( parent , rank , m * x + y , m * ( x ) + y - 1 ) ; if ( x < n - 1 && grid [ m * ( x + 1 ) + y ] == true ) setUnion ( parent , rank , m * x + y , m * ( x + 1 ) + y ) ; if ( y < m - 1 && grid [ m * ( x ) + y + 1 ] == true ) setUnion ( parent , rank , m * x + y , m * ( x ) + y + 1 ) ; result [ i ] = ctr ; } return result ; } public static void main ( String [ ] args ) { int N = 3 , M = 3 , K = 4 ; int [ ] [ ] query = { { 0 , 0 } , { 1 , 1 } , { 1 , 0 } , { 1 , 2 } } ; int [ ] result = solve ( N , M , query ) ; for ( int i = 0 ; i < K ; i ++ ) System . out . print ( result [ i ] + " ▁ " ) ; } }


"Queries to find the count of vowels in the substrings of the given string | Java implementation of the approach ; Function that returns true if ch is a vowel ; Function to return the count of vowels in the substring str [ l ... r ] ; To store the count of vowels ; For every character in the index range [ l , r ] ; If the current character is a vowel ; For every query ; Find the count of vowels for the current query ; Driver code"
How can the above be solved in Java?

class GFG { static int N = 2 ; static boolean isVowel ( char ch ) { return ( ch == ' a ' ch == ' e ' ch == ' i ' ch == ' o ' ch == ' u ' ) ; } static int countVowels ( String str , int l , int r ) { int cnt = 0 ; for ( int i = l ; i <= r ; i ++ ) { if ( isVowel ( str . charAt ( i ) ) ) cnt ++ ; } return cnt ; } static void performQueries ( String str , int queries [ ] [ ] , int q ) { for ( int i = 0 ; i < q ; i ++ ) { System . out . println ( countVowels ( str , queries [ i ] [ 0 ] , queries [ i ] [ 1 ] ) ) ; } } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; int queries [ ] [ ] = { { 1 , 3 } , { 2 , 4 } , { 1 , 9 } } ; int q = queries . length ; performQueries ( str , queries , q ) ; } }