"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 ; pre [ i ] will store the count of vowels in the subString str [ 0. . . i ] ; Fill the pre [ ] array ; If current character is a vowel ; If its a consonant ; 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 final int N = 2 ; static Boolean isVowel ( char ch ) { return ( ch == ' a ' ch == ' e ' ch == ' i ' ch == ' o ' ch == ' u ' ) ; } static void performQueries ( String str , int len , int queries [ ] [ ] , int q ) { int [ ] pre = new int [ len ] ; if ( isVowel ( str . charAt ( 0 ) ) ) pre [ 0 ] = 1 ; else pre [ 0 ] = 0 ; for ( int i = 1 ; i < len ; i ++ ) { if ( isVowel ( str . charAt ( i ) ) ) pre [ i ] = 1 + pre [ i - 1 ] ; else pre [ i ] = pre [ i - 1 ] ; } for ( int i = 0 ; i < q ; i ++ ) { if ( queries [ i ] [ 0 ] == 0 ) { System . out . println ( pre [ queries [ i ] [ 1 ] ] ) ; } else { System . out . println ( ( pre [ queries [ i ] [ 1 ] ] - pre [ queries [ i ] [ 0 ] - 1 ] ) ) ; } } } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; int len = str . length ( ) ; int queries [ ] [ ] = { { 1 , 3 } , { 2 , 4 } , { 1 , 9 } } ; int q = queries . length ; performQueries ( str , len , queries , q ) ; } }


"Queries to find the first non | Java implementation of the approach ; Maximum distinct characters possible ; To store the frequency of the characters ; Function to pre - calculate the frequency array ; Only the first character has frequency 1 till index 0 ; Starting from the second character of the string ; For every possible character ; Current character under consideration ; If it is equal to the character at the current index ; Function to return the frequency of the given character in the sub - string str [ l ... r ] ; Function to return the first non - repeating character in range [ l . . r ] ; Starting from the first character ; Current character ; If frequency of the current character is 1 then return the character ; All the characters of the sub - string are repeating ; Driver code ; Pre - calculate the frequency array"
How can the above be solved in Java?

public class GFG { static final int MAX = 256 ; static int freq [ ] [ ] ; static void preCalculate ( String str , int n ) { freq [ ( int ) str . charAt ( 0 ) ] [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { char ch = str . charAt ( i ) ; for ( int j = 0 ; j < MAX ; j ++ ) { char charToUpdate = ( char ) j ; if ( charToUpdate == ch ) freq [ j ] [ i ] = freq [ j ] [ i - 1 ] + 1 ; else freq [ j ] [ i ] = freq [ j ] [ i - 1 ] ; } } } static int getFrequency ( char ch , int l , int r ) { if ( l == 0 ) return freq [ ( int ) ch ] [ r ] ; else return ( freq [ ( int ) ch ] [ r ] - freq [ ( int ) ch ] [ l - 1 ] ) ; } static String firstNonRepeating ( String str , int n , int l , int r ) { for ( int i = l ; i < r ; i ++ ) { char ch = str . charAt ( i ) ; if ( getFrequency ( ch , l , r ) == 1 ) return ( " " + ch ) ; } return " - 1" ; } public static void main ( String [ ] args ) { String str = " GeeksForGeeks " ; int n = str . length ( ) ; int queries [ ] [ ] = { { 0 , 3 } , { 2 , 3 } , { 5 , 12 } } ; int q = queries . length ; freq = new int [ MAX ] [ n ] ; preCalculate ( str , n ) ; for ( int i = 0 ; i < q ; i ++ ) { System . out . println ( firstNonRepeating ( str , n , queries [ i ] [ 0 ] , queries [ i ] [ 1 ] ) ) ; } } }


"Queries to find the last non | Java implementation of the approach ; Maximum distinct characters possible ; To store the frequency of the characters ; Function to pre - calculate the frequency array ; Only the first character has frequency 1 till index 0 ; Starting from the second character of the string ; For every possible character ; Current character under consideration ; If it is equal to the character at the current index ; Function to return the frequency of the given character in the sub - string str [ l ... r ] ; Function to return the last non - repeating character ; Starting from the last character ; Current character ; If frequency of the current character is 1 then return the character ; All the characters of the sub - string are repeating ; Driver code ; Pre - calculate the frequency array"
How can the above be solved in Java?

public class GFG { static final int MAX = 256 ; static int freq [ ] [ ] ; static void preCalculate ( String str , int n ) { freq [ ( int ) str . charAt ( 0 ) ] [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { char ch = str . charAt ( i ) ; for ( int j = 0 ; j < MAX ; j ++ ) { char charToUpdate = ( char ) j ; if ( charToUpdate == ch ) freq [ j ] [ i ] = freq [ j ] [ i - 1 ] + 1 ; else freq [ j ] [ i ] = freq [ j ] [ i - 1 ] ; } } } static int getFrequency ( char ch , int l , int r ) { if ( l == 0 ) return freq [ ( int ) ch ] [ r ] ; else return ( freq [ ( int ) ch ] [ r ] - freq [ ( int ) ch ] [ l - 1 ] ) ; } static String lastNonRepeating ( String str , int n , int l , int r ) { for ( int i = r ; i >= l ; i -- ) { char ch = str . charAt ( i ) ; if ( getFrequency ( ch , l , r ) == 1 ) return ( " " + ch ) ; } return " - 1" ; } public static void main ( String [ ] args ) { String str = " GeeksForGeeks " ; int n = str . length ( ) ; int queries [ ] [ ] = { { 2 , 9 } , { 2 , 3 } , { 0 , 12 } } ; int q = queries . length ; freq = new int [ MAX ] [ n ] ; preCalculate ( str , n ) ; for ( int i = 0 ; i < q ; i ++ ) { System . out . println ( lastNonRepeating ( str , n , queries [ i ] [ 0 ] , queries [ i ] [ 1 ] ) ) ; } } }


"Queries to find the maximum Xor value between X and the nodes of a given level of a perfect binary tree | Java implementation of the approach ; Function to solve queries of the maximum xor value between the nodes in a given level L of a perfect binary tree and a given value X ; Initialize result ; Initialize array to store bits ; Initialize a copy of X and size of array ; Storing the bits of X in the array a [ ] ; Filling the array b [ ] ; Initializing variable which gives maximum xor ; Getting the maximum xor value ; Return the result ; Driver code ; Perform queries"
How can the above be solved in Java?

class GFG { static int MAXN = 60 ; static int solveQuery ( int L , int X ) { int res ; int [ ] a = new int [ MAXN ] ; int [ ] b = new int [ L ] ; int refer = X , size_a = 0 ; while ( refer > 0 ) { a [ size_a ] = refer % 2 ; refer /= 2 ; size_a ++ ; } for ( int i = 0 ; i < Math . min ( size_a , L ) ; i ++ ) { if ( a [ i ] == 1 ) b [ i ] = 0 ; else b [ i ] = 1 ; } for ( int i = Math . min ( size_a , L ) ; i < L ; i ++ ) b [ i ] = 1 ; b [ L - 1 ] = 1 ; int temp = 0 , p = 1 ; for ( int i = 0 ; i < L ; i ++ ) { temp += b [ i ] * p ; p *= 2 ; } res = temp ^ X ; return res ; } static public void main ( String args [ ] ) { int [ ] [ ] queries = { { 2 , 5 } , { 3 , 15 } } ; int q = queries . length ; for ( int i = 0 ; i < q ; i ++ ) System . out . println ( solveQuery ( queries [ i ] [ 0 ] , queries [ i ] [ 1 ] ) ) ; } }


"Queries to find the maximum and minimum array elements excluding elements from a given range | Java program for the above approach ; Function to find the maximum and minimum array elements up to the i - th index ; Traverse the array ; Compare current value with maximum and minimum values up to previous index ; Function to find the maximum and minimum array elements from i - th index ; Traverse the array in reverse ; Compare current value with maximum and minimum values in the next index ; Function to find the maximum and minimum array elements for each query ; If no index remains after excluding the elements in a given range ; Find maximum and minimum from from the range [ R + 1 , N - 1 ] ; Find maximum and minimum from from the range [ 0 , N - 1 ] ; Find maximum and minimum values from the ranges [ 0 , L - 1 ] and [ R + 1 , N - 1 ] ; Print the maximum and minimum value ; Function to perform queries to find the minimum and maximum array elements excluding elements from a given range ; Size of the array ; Size of query array ; prefix [ i ] [ 0 ] : Stores the maximum prefix [ i ] [ 1 ] : Stores the minimum value ; suffix [ i ] [ 0 ] : Stores the maximum suffix [ i ] [ 1 ] : Stores the minimum value ; Function calls to store maximum and minimum values for respective ranges ; Driver Code ; Given array"
How can the above be solved in Java?

public class GFG { static void prefixArr ( int arr [ ] , int prefix [ ] [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { if ( i == 0 ) { prefix [ i ] [ 0 ] = arr [ i ] ; prefix [ i ] [ 1 ] = arr [ i ] ; } else { prefix [ i ] [ 0 ] = Math . max ( prefix [ i - 1 ] [ 0 ] , arr [ i ] ) ; prefix [ i ] [ 1 ] = Math . min ( prefix [ i - 1 ] [ 1 ] , arr [ i ] ) ; } } } static void suffixArr ( int arr [ ] , int suffix [ ] [ ] , int N ) { for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( i == N - 1 ) { suffix [ i ] [ 0 ] = arr [ i ] ; suffix [ i ] [ 1 ] = arr [ i ] ; } else { suffix [ i ] [ 0 ] = Math . max ( suffix [ i + 1 ] [ 0 ] , arr [ i ] ) ; suffix [ i ] [ 1 ] = Math . min ( suffix [ i + 1 ] [ 1 ] , arr [ i ] ) ; } } } static void maxAndmin ( int prefix [ ] [ ] , int suffix [ ] [ ] , int N , int L , int R ) { int maximum , minimum ; if ( L == 0 && R == N - 1 ) { System . out . println ( " No ▁ maximum ▁ and ▁ minimum ▁ value " ) ; return ; } else if ( L == 0 ) { maximum = suffix [ R + 1 ] [ 0 ] ; minimum = suffix [ R + 1 ] [ 1 ] ; } else if ( R == N - 1 ) { maximum = prefix [ L - 1 ] [ 0 ] ; minimum = prefix [ R - 1 ] [ 1 ] ; } else { maximum = Math . max ( prefix [ L - 1 ] [ 0 ] , suffix [ R + 1 ] [ 0 ] ) ; minimum = Math . min ( prefix [ L - 1 ] [ 1 ] , suffix [ R + 1 ] [ 1 ] ) ; } System . out . println ( maximum + " ▁ " + minimum ) ; } static void MinMaxQueries ( int a [ ] , int Q [ ] [ ] ) { int N = a . length ; int q = Q . length ; int prefix [ ] [ ] = new int [ N ] [ 2 ] ; int suffix [ ] [ ] = new int [ N ] [ 2 ] ; prefixArr ( a , prefix , N ) ; suffixArr ( a , suffix , N ) ; for ( int i = 0 ; i < q ; i ++ ) { int L = Q [ i ] [ 0 ] ; int R = Q [ i ] [ 1 ] ; maxAndmin ( prefix , suffix , N , L , R ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 1 , 8 , 3 , 5 , 7 , 4 } ; int queries [ ] [ ] = { { 4 , 6 } , { 0 , 4 } , { 3 , 7 } , { 2 , 5 } } ; MinMaxQueries ( arr , queries ) ; } }


"Queries to find the maximum array element after removing elements from a given range | Java program for the above approach ; Function to find the maximum element after removing elements in range [ l , r ] ; Store prefix maximum element ; Store suffix maximum element ; Prefix max till first index is first index itself ; Traverse the array to fill prefix max array ; Store maximum till index i ; Suffix max till last index is last index itself ; Traverse the array to fill suffix max array ; Store maximum till index i ; Traverse all queries ; Store the starting and the ending index of the query ; Edge Cases ; Otherwise ; Driver Code"
How can the above be solved in Java?

 class GFG { static void findMaximum ( int arr [ ] , int N , int Q , int queries [ ] [ ] ) { int prefix_max [ ] = new int [ N + 1 ] ; int suffix_max [ ] = new int [ N + 1 ] ; prefix_max [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { prefix_max [ i ] = Math . max ( prefix_max [ i - 1 ] , arr [ i ] ) ; } suffix_max [ N - 1 ] = arr [ N - 1 ] ; for ( int i = N - 2 ; i >= 0 ; i -- ) { suffix_max [ i ] = Math . max ( suffix_max [ i + 1 ] , arr [ i ] ) ; } for ( int i = 0 ; i < Q ; i ++ ) { int l = queries [ i ] [ 0 ] ; int r = queries [ i ] [ 1 ] ; if ( l == 0 && r == ( N - 1 ) ) System . out . print ( "0
"); else if ( l == 0 ) System . out . print ( suffix_max [ r + 1 ] + "
"); else if ( r == ( N - 1 ) ) System . out . print ( prefix_max [ l - 1 ] + "
"); else System . out . print ( Math . max ( prefix_max [ l - 1 ] , suffix_max [ r + 1 ] ) + "
"); } } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 6 , 8 , 10 , 15 } ; int N = arr . length ; int queries [ ] [ ] = { { 0 , 1 } , { 0 , 2 } , { 1 , 4 } } ; int Q = queries . length ; findMaximum ( arr , N , Q , queries ) ; } }


"Queries to find the minimum array sum possible by removing elements from either end | Java program for the above approach ; Function to find the minimum sum for each query after removing element from either ends till each value Q [ i ] ; Stores the prefix sum from both the ends of the array ; Traverse the array from front ; Insert it into the map m1 ; Traverse the array in reverse ; Insert it into the map m2 ; Traverse the query array ; Print the minimum of the two values as the answer ; Driver code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void minOperations ( int [ ] arr , int N , int [ ] Q , int M ) { Map < Integer , Integer > m1 = new HashMap < Integer , Integer > ( ) ; Map < Integer , Integer > m2 = new HashMap < Integer , Integer > ( ) ; int front = 0 , rear = 0 ; for ( int i = 0 ; i < N ; i ++ ) { front += arr [ i ] ; m1 . put ( arr [ i ] , front ) ; } for ( int i = N - 1 ; i >= 0 ; i -- ) { rear += arr [ i ] ; m2 . put ( arr [ i ] , rear ) ; } for ( int i = 0 ; i < M ; i ++ ) { System . out . print ( Math . min ( m1 . get ( Q [ i ] ) , m2 . get ( Q [ i ] ) ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 2 , 3 , 6 , 7 , 4 , 5 , 1 } ; int N = arr . length ; int [ ] Q = { 7 , 6 } ; int M = Q . length ; minOperations ( arr , N , Q , M ) ; } }


"Queries to find the minimum array sum possible by removing elements from either end | Java program for the above approach ; Function to find the minimum sum for each query after removing elements from either ends ; Traverse the query array ; Traverse the array from the front ; If element equals val , then break out of loop ; Traverse the array from rear ; If element equals val , break ; Print the minimum of the two as the answer ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void minSum ( int arr [ ] , int N , int Q [ ] , int M ) { for ( int i = 0 ; i < M ; i ++ ) { int val = Q [ i ] ; int front = 0 , rear = 0 ; for ( int j = 0 ; j < N ; j ++ ) { front += arr [ j ] ; if ( arr [ j ] == val ) { break ; } } for ( int j = N - 1 ; j >= 0 ; j -- ) { rear += arr [ j ] ; if ( arr [ j ] == val ) { break ; } } System . out . print ( Math . min ( front , rear ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 6 , 7 , 4 , 5 , 1 } ; int N = arr . length ; int Q [ ] = { 7 , 6 } ; int M = Q . length ; minSum ( arr , N , Q , M ) ; } }


"Queries to find the minimum index in a range [ L , R ] having at least value X with updates | Java program to implement the above approach ; Stores nodes value of the Tree ; Function to build segment tree ; Base Case ; Find the value of mid ; Update for left subtree ; Update for right subtree ; Update the value at the current index ; Function for finding the index of the first element at least x ; If current range does not lie in query range ; If current range is inside of query range ; Maximum value in this range is less than x ; Finding index of first value in this range ; Update the value of the minimum index ; Find mid of the current range ; Left subtree ; If it does not lie in left subtree ; Function for updating segment tree ; Update the value , we reached leaf node ; Find the mid ; If pos lies in the left subtree ; pos lies in the right subtree ; Update the maximum value in the range ; Function to print the answer for the given queries ; Build segment tree ; Find index of first value atleast 2 in range [ 0 , n - 1 ] ; Update value at index 2 to 5 ; Find index of first value atleast 4 in range [ 0 , n - 1 ] ; Find index of first value atleast 0 in range [ 0 , n - 1 ] ; Driver code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maxN = 100 ; static int Tree [ ] = new int [ 4 * maxN ] ; static void build ( int arr [ ] , int index , int s , int e ) { if ( s == e ) Tree [ index ] = arr [ s ] ; else { int m = ( s + e ) / 2 ; build ( arr , 2 * index , s , m ) ; build ( arr , 2 * index + 1 , m + 1 , e ) ; Tree [ index ] = Math . max ( Tree [ 2 * index ] , Tree [ 2 * index + 1 ] ) ; } } static int atleast_x ( int index , int s , int e , int ql , int qr , int x ) { if ( ql > e qr < s ) return - 1 ; if ( s <= ql && e <= qr ) { if ( Tree [ index ] < x ) return - 1 ; while ( s != e ) { int m = ( s + e ) / 2 ; if ( Tree [ 2 * index ] >= x ) { e = m ; index = 2 * index ; } else { s = m + 1 ; index = 2 * index + 1 ; } } return s ; } int m = ( s + e ) / 2 ; int val = atleast_x ( 2 * index , s , m , ql , qr , x ) ; if ( val != - 1 ) return val ; return atleast_x ( 2 * index + 1 , m + 1 , e , ql , qr , x ) ; } static void update ( int index , int s , int e , int new_val , int pos ) { if ( s == e ) Tree [ index ] = new_val ; else { int m = ( s + e ) / 2 ; if ( pos <= m ) { update ( 2 * index , s , m , new_val , pos ) ; } else { update ( 2 * index + 1 , m + 1 , e , new_val , pos ) ; } Tree [ index ] = Math . max ( Tree [ 2 * index ] , Tree [ 2 * index + 1 ] ) ; } } static void printAnswer ( int [ ] arr , int n ) { build ( arr , 1 , 0 , n - 1 ) ; System . out . println ( atleast_x ( 1 , 0 , n - 1 , 0 , n - 1 , 2 ) ) ; arr [ 2 ] = 5 ; update ( 1 , 0 , n - 1 , 5 , 2 ) ; System . out . println ( atleast_x ( 1 , 0 , n - 1 , 0 , n - 1 , 4 ) ) ; System . out . println ( atleast_x ( 1 , 0 , n - 1 , 0 , n - 1 , 0 ) ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 2 , 4 , 6 } ; int N = arr . length ; printAnswer ( arr , N ) ; } }


"Queries to find the minimum index in given array having at least value X | Java program for above approach ; Function to find the smallest index of an array element whose value is less than or equal to Q [ i ] ; Stores size of array ; Stores coun of queries ; Store array elements along with the index ; Store smallest index of an array element whose value is greater than or equal to i ; Traverse the array ; Insert { arr [ i ] , i } into storeArrIdx [ ] ; Sort the array ; Sort the storeArrIdx ; Stores index of arr [ N - 1 ] in sorted order ; Traverse the array storeArrIdx [ ] ; Update minIdx [ i ] ; Traverse the array Q [ ] ; Store the index of lower_bound of Q [ i ] ; If no index found whose value greater than or equal to arr [ i ] ; Print smallest index whose value greater than or equal to Q [ i ] ; Driver function"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class pair { int element , index ; pair ( int element , int index ) { this . element = element ; this . index = index ; } } class GFG { static void minimumIndex ( int [ ] arr , int [ ] Q ) { int N = arr . length ; int M = Q . length ; ArrayList < pair > storeArrIdx = new ArrayList < > ( ) ; int [ ] minIdx = new int [ N ] ; for ( int i = 0 ; i < N ; ++ i ) { storeArrIdx . add ( new pair ( arr [ i ] , i ) ) ; } Arrays . sort ( arr ) ; Collections . sort ( storeArrIdx , ( a , b ) -> a . element - b . element ) ; minIdx [ N - 1 ] = storeArrIdx . get ( N - 1 ) . index ; for ( int i = N - 2 ; i >= 0 ; i -- ) { minIdx [ i ] = Math . min ( minIdx [ i + 1 ] , storeArrIdx . get ( i ) . index ) ; } for ( int i = 0 ; i < M ; i ++ ) { int pos = lower_bound ( arr , Q [ i ] ) ; if ( pos == N ) { System . out . print ( " - 1" + " ▁ " ) ; continue ; } System . out . print ( minIdx [ pos ] + " ▁ " ) ; } } static int lower_bound ( int [ ] arr , int element ) { for ( int i = 0 ; i < arr . length ; i ++ ) if ( element <= arr [ i ] ) return i ; return arr . length ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 9 } ; int [ ] Q = { 7 , 10 , 0 } ; minimumIndex ( arr , Q ) ; } }


"Queries to find the sum of weights of all nodes with vertical width from given range in a Binary Tree | Java program for the above approach ; Structure of a node ; Function to create new node ; Function to pre - compute the sum of weights at each width position ; Base Case ; Update the current width position weight ; Recursive Call to its left ; Recursive Call to its right ; Function to find the sum of the weights of nodes whose vertical widths lies over the range [ L , R ] for Q queries ; Stores the weight sum of each width position ; Function Call to fill um ; Stores the sum of all previous nodes , while traversing Map ; Traverse the Map um ; Iterate over all queries ; Print the result for the current query [ l , r ] ; Driver Code ; Given Tree"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static class Node { int data ; Node left ; Node right ; } static Node newNode ( int d ) { Node n = new Node ( ) ; n . data = d ; n . left = null ; n . right = null ; return n ; } static void findwt ( Node root , int wt [ ] , TreeMap < Integer , Integer > um , int width ) { if ( root == null ) { return ; } if ( um . containsKey ( width ) ) { um . put ( width , um . get ( width ) + wt [ root . data ] ) ; } else { um . put ( width , wt [ root . data ] ) ; } findwt ( root . left , wt , um , width - 1 ) ; findwt ( root . right , wt , um , width + 1 ) ; } static void solveQueries ( int wt [ ] , Node root , int [ ] [ ] queries ) { TreeMap < Integer , Integer > um = new TreeMap < Integer , Integer > ( ) ; findwt ( root , wt , um , 0 ) ; int x = 0 ; for ( Map . Entry < Integer , Integer > it : um . entrySet ( ) ) { x += it . getValue ( ) ; um . put ( it . getKey ( ) , x ) ; } for ( int i = 0 ; i < queries . length ; i ++ ) { int l = queries [ i ] [ 0 ] ; int r = queries [ i ] [ 1 ] ; int ans = 0 ; if ( um . containsKey ( r ) ) { ans = um . get ( r ) ; } if ( um . containsKey ( l - 1 ) ) { ans -= um . get ( l - 1 ) ; } System . out . println ( ans ) ; } } public static void main ( String [ ] args ) { int N = 8 ; Node root = newNode ( 1 ) ; root . left = newNode ( 3 ) ; root . left . left = newNode ( 5 ) ; root . left . right = newNode ( 6 ) ; root . right = newNode ( 2 ) ; root . right . right = newNode ( 4 ) ; root . right . right . left = newNode ( 7 ) ; root . right . right . right = newNode ( 0 ) ; int wt [ ] = { 8 , 6 , 4 , 5 , 1 , 2 , 9 , 1 } ; int queries [ ] [ ] = { { - 1 , 1 } , { - 2 , - 1 } , { 0 , 3 } } ; solveQueries ( wt , root , queries ) ; } }


"Queries to find whether a number has exactly four distinct factors or not | Java program to check whether number has exactly four distinct factors or not ; Initialize global variable according to given condition so that it can be accessible to all function ; Function to calculate all number having four distinct distinct factors ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Initialize prime [ ] array which will contains all the primes from 1 - N ; Iterate over all the prime numbers ; Mark cube root of prime numbers ; Mark product of prime numbers ; Driver program"
How can the above be solved in Java?

import java . util . * ; class GFG { static int N = ( int ) 1E6 ; static boolean [ ] fourDiv = new boolean [ N + 1 ] ; static void fourDistinctFactors ( ) { boolean [ ] primeAll = new boolean [ N + 1 ] ; for ( int p = 2 ; p * p <= N ; p ++ ) { if ( primeAll [ p ] == false ) { for ( int i = p * 2 ; i <= N ; i += p ) primeAll [ i ] = true ; } } ArrayList < Integer > prime = new ArrayList < Integer > ( ) ; for ( int p = 2 ; p <= N ; p ++ ) if ( ! primeAll [ p ] ) prime . add ( p ) ; for ( int i = 0 ; i < prime . size ( ) ; ++ i ) { int p = prime . get ( i ) ; if ( 1L * p * p * p <= N ) fourDiv [ p * p * p ] = true ; for ( int j = i + 1 ; j < prime . size ( ) ; ++ j ) { int q = prime . get ( j ) ; if ( 1L * p * q > N ) break ; fourDiv [ p * q ] = true ; } } } public static void main ( String [ ] args ) { fourDistinctFactors ( ) ; int num = 10 ; if ( fourDiv [ num ] ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; num = 12 ; if ( fourDiv [ num ] ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Queries to flip characters of a binary string in given range | Java program to implement the above approach ; Function to find the binary String by performing all the given queries ; Stores length of the String ; prefixCnt [ i ] : Stores number of times str [ i ] toggled by performing all the queries ; Update prefixCnt [ Q [ i ] [ 0 ] ] ; Update prefixCnt [ Q [ i ] [ 1 ] + 1 ] ; Calculate prefix sum of prefixCnt [ i ] ; Traverse prefixCnt [ ] array ; If ith element toggled odd number of times ; Toggled i - th element of binary String ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static String toggleQuery ( char [ ] str , int Q [ ] [ ] , int M ) { int N = str . length ; int prefixCnt [ ] = new int [ N + 1 ] ; for ( int i = 0 ; i < M ; i ++ ) { prefixCnt [ Q [ i ] [ 0 ] ] += 1 ; prefixCnt [ Q [ i ] [ 1 ] + 1 ] -= 1 ; } for ( int i = 1 ; i <= N ; i ++ ) { prefixCnt [ i ] += prefixCnt [ i - 1 ] ; } for ( int i = 0 ; i < N ; i ++ ) { if ( prefixCnt [ i ] % 2 == 1 ) { str [ i ] = ( char ) ( '1' - str [ i ] + '0' ) ; } } return String . valueOf ( str ) ; } public static void main ( String [ ] args ) { String str = "101010" ; int Q [ ] [ ] = { { 0 , 1 } , { 2 , 5 } , { 2 , 3 } , { 1 , 4 } , { 0 , 5 } } ; int M = Q . length ; System . out . print ( toggleQuery ( str . toCharArray ( ) , Q , M ) ) ; } }


"Queries to replace every array element by its XOR with a given value with updates | Java program of the above approach ; Function to insert an element into the array ; Function to update every array element a [ i ] by a [ i ] ^ x ; Function to compute the final results after the operations ; Driver Code ; Queries ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static Vector < Integer > arr = new Vector < Integer > ( ) ; static int effect ; static void add ( int x ) { arr . add ( x ) ; } static void update ( int x ) { effect = effect ^ x ; } static void computeResults ( ) { for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { arr . set ( i , arr . get ( i ) ^ effect ) ; System . out . print ( arr . get ( i ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { arr = new Vector < Integer > ( ) ; arr . add ( 0 ) ; effect = 0 ; add ( 5 ) ; update ( 2 ) ; computeResults ( ) ; } }


"Queries to return the absolute difference between L | Java implementation of the approach ; pair class ; Function to return the result for a particular query ; Get the difference between the indices of L - th and the R - th smallest element ; Return the answer ; Function that performs all the queries ; Store the array numbers and their indices ; Sort pair ; Sort the array elements ; Answer all the queries ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . util . Comparator ; class GFG { static class pair { int first , second ; pair ( int f , int s ) { first = f ; second = s ; } } static int answerQuery ( pair arr [ ] , int l , int r ) { int answer = Math . abs ( arr [ l - 1 ] . second - arr [ r - 1 ] . second ) ; return answer ; } static void solveQueries ( int a [ ] , int n , int q [ ] [ ] , int m ) { pair arr [ ] = new pair [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { arr [ i ] = new pair ( 0 , 0 ) ; arr [ i ] . first = a [ i ] ; arr [ i ] . second = i ; } Comparator < pair > comp = new Comparator < pair > ( ) { public int compare ( pair e1 , pair e2 ) { if ( e1 . first < e2 . first ) { return - 1 ; } else if ( e1 . first > e2 . first ) { return 1 ; } else { return 0 ; } } } ; Arrays . sort ( arr , comp ) ; for ( int i = 0 ; i < m ; i ++ ) System . out . println ( answerQuery ( arr , q [ i ] [ 0 ] , q [ i ] [ 1 ] ) ) ; } public static void main ( String args [ ] ) { int a [ ] = { 1 , 5 , 4 , 2 , 8 , 6 , 7 } ; int n = a . length ; int q [ ] [ ] = { { 2 , 5 } , { 1 , 3 } , { 1 , 5 } , { 3 , 6 } } ; int m = q . length ; solveQueries ( a , n , q , m ) ; } }


"Queries to update array by adding or multiplying array elements and print the element present at specified index | Java program for the above approach ; Function to modify the array by performing given queries ; Stores the multiplication of all integers of type 1 ; Stores the value obtained after performing queries of type 1 & 2 ; Iterate over the queries ; Query of type 0 ; Update the value of add ; Query of type 1 ; Update the value of mul ; Update the value of add ; Otherwise ; Store the element at index Q [ i ] [ 1 ] ; Print the result for the current query ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; public class GFG { static void Query ( int arr [ ] , int N , int Q [ ] [ ] ) { int mul = 1 ; int add = 0 ; for ( int i = 0 ; i < Q . length ; i ++ ) { if ( Q [ i ] [ 0 ] == 0 ) { add = add + Q [ i ] [ 1 ] ; } else if ( Q [ i ] [ 0 ] == 1 ) { mul = mul * Q [ i ] [ 1 ] ; add = add * Q [ i ] [ 1 ] ; } else { int ans = arr [ Q [ i ] [ 1 ] ] * mul + add ; System . out . print ( ans + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 1 , 23 , 45 , 100 } ; int N = arr . length ; int Q [ ] [ ] = { { 1 , 2 } , { 0 , 10 } , { 2 , 3 } , { 1 , 5 } , { 2 , 4 } } ; Query ( arr , N , Q ) ; } }


"Queries to update array elements in a range [ L , R ] to satisfy given conditions | Java program to implement the above approach ; Function to print the array ; Function to perform the query in range [ L , R ] such that arr [ i ] += i - L + 1 ; Initialize array ; Traverse the query array ; Stores range in 1 - based index ; Update arr1 [ L ] ; Update arr1 [ R + 1 ] ; Update arr2 [ R + 1 ] ; Calculate prefix sum ; Traverse the array , arr2 [ ] ; Copy arr2 [ ] into arr [ ] ; Driver Code ; Given array ; Size of the array ; Stores count of query ; Function Call"
How can the above be solved in Java?

class GFG { static void printArray ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } static void modifyArray ( int arr [ ] , int N , int Q [ ] [ ] , int cntQuery ) { int arr1 [ ] = new int [ N + 2 ] ; int arr2 [ ] = new int [ N + 2 ] ; for ( int i = 0 ; i < cntQuery ; i ++ ) { int L = Q [ i ] [ 0 ] + 1 , R = Q [ i ] [ 1 ] + 1 ; arr1 [ L ] ++ ; arr1 [ R + 1 ] -- ; arr2 [ R + 1 ] -= R - L + 1 ; } for ( int i = 1 ; i <= N ; i ++ ) arr1 [ i ] += arr1 [ i - 1 ] ; for ( int i = 1 ; i <= N ; i ++ ) arr2 [ i ] += arr2 [ i - 1 ] + arr1 [ i ] ; for ( int i = 1 ; i <= N ; i ++ ) arr [ i - 1 ] = arr2 [ i ] ; printArray ( arr , N ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 0 , 0 , 0 , 0 } ; int N = arr . length ; int Q [ ] [ ] = { { 1 , 3 } , { 0 , 1 } } ; int cntQuery = Q . length ; modifyArray ( arr , N , Q , cntQuery ) ; } }


"Query for ancestor | Java program to query whether two node has ancestor - descendant relationship or not ; Utility dfs method to assign in and out time to each node ; Assign In - time to node u ; Call dfs over all neighbors except parent ; Assign Out - time to node u ; Method to preprocess all nodes for assigning time ; Conarray of vector data structure for tree ; Call dfs method from root ; Method returns " yes " if u is a ancestor node of v ; Driver code"
How can the above be solved in Java?

import java . util . Vector ; class GFG { static int cnt ; static void dfs ( Vector < Integer > [ ] g , int u , int parent , int [ ] timeIn , int [ ] timeOut ) { timeIn [ u ] = cnt ++ ; for ( int i = 0 ; i < g [ u ] . size ( ) ; i ++ ) { int v = g [ u ] . get ( i ) ; if ( v != parent ) dfs ( g , v , u , timeIn , timeOut ) ; } timeOut [ u ] = cnt ++ ; } static void preProcess ( int [ ] [ ] edges , int V , int [ ] timeIn , int [ ] timeOut ) { @ SuppressWarnings ( " unchecked " ) Vector < Integer > [ ] g = new Vector [ V ] ; for ( int i = 0 ; i < g . length ; i ++ ) g [ i ] = new Vector < Integer > ( ) ; for ( int i = 0 ; i < V - 1 ; i ++ ) { int u = edges [ i ] [ 0 ] ; int v = edges [ i ] [ 1 ] ; g [ u ] . add ( v ) ; g [ v ] . add ( u ) ; } cnt = 0 ; dfs ( g , 0 , - 1 , timeIn , timeOut ) ; } static String isAncestor ( int u , int v , int [ ] timeIn , int [ ] timeOut ) { boolean b = ( timeIn [ u ] <= timeIn [ v ] && timeOut [ v ] <= timeOut [ u ] ) ; return ( b ? " yes " : " no " ) ; } public static void main ( String [ ] args ) { int edges [ ] [ ] = { { 0 , 1 } , { 0 , 2 } , { 1 , 3 } , { 1 , 4 } , { 2 , 5 } , { 4 , 6 } , { 5 , 7 } } ; int E = edges . length ; int V = E + 1 ; int [ ] timeIn = new int [ V ] ; int [ ] timeOut = new int [ V ] ; preProcess ( edges , V , timeIn , timeOut ) ; int u = 1 ; int v = 6 ; System . out . println ( isAncestor ( u , v , timeIn , timeOut ) ) ; u = 1 ; v = 7 ; System . out . println ( isAncestor ( u , v , timeIn , timeOut ) ) ; } }


"Query to find length of the longest subarray consisting only of 1 s | Java Program for the above approach ; Arrays to store prefix sums , suffix and MAX 's node respectively ; Function to conSegment Tree ; MAX array for node MAX ; Array for prefix sum node ; Array for suffix sum node ; Calculate MAX node ; Function to update Segment Tree ; Update at position ; Update sums from bottom to the top of Segment Tree ; Update MAX tree ; Update pref tree ; Update suf tree ; Function to perform given queries ; Stores count of queries ; Traverse each query ; Print longest length of subarray in [ 1 , N ] ; Flip the character ; Driver Code ; Size of array ; Given array ; Given queries ; Number of queries"
How can the above be solved in Java?

import java . util . * ; class GFG { static final int INF = 1000000 ; static int [ ] pref = new int [ 500005 ] ; static int [ ] suf = new int [ 500005 ] ; static int [ ] MAX = new int [ 500005 ] ; static void build ( int a [ ] , int tl , int tr , int v ) { if ( tl == tr ) { MAX [ v ] = a [ tl ] ; pref [ v ] = a [ tl ] ; suf [ v ] = a [ tl ] ; } else { int tm = ( tl + tr ) / 2 ; build ( a , tl , tm , v * 2 ) ; build ( a , tm + 1 , tr , v * 2 + 1 ) ; MAX [ v ] = Math . max ( MAX [ v * 2 ] , Math . max ( MAX [ v * 2 + 1 ] , suf [ v * 2 ] + pref [ v * 2 + 1 ] ) ) ; pref [ v ] = Math . max ( pref [ v * 2 ] , pref [ 2 * v ] + ( pref [ 2 * v ] == ( tm - tl + 1 ) ? 1 : 0 ) * pref [ v * 2 + 1 ] ) ; suf [ v ] = Math . max ( suf [ v * 2 + 1 ] , suf [ 2 * v + 1 ] + suf [ v * 2 ] * ( suf [ 2 * v + 1 ] == ( tr - tm ) ? 1 : 0 ) ) ; } } static void update ( int a [ ] , int pos , int tl , int tr , int v ) { if ( tl > pos tr < pos ) { return ; } if ( tl == tr && tl == pos ) { MAX [ v ] = a [ pos ] ; pref [ v ] = a [ pos ] ; suf [ v ] = a [ pos ] ; } else { int tm = ( tl + tr ) / 2 ; update ( a , pos , tl , tm , v * 2 ) ; update ( a , pos , tm + 1 , tr , v * 2 + 1 ) ; MAX [ v ] = Math . max ( MAX [ v * 2 ] , Math . max ( MAX [ v * 2 + 1 ] , suf [ v * 2 ] + pref [ v * 2 + 1 ] ) ) ; pref [ v ] = Math . max ( pref [ v * 2 ] , pref [ 2 * v ] + ( pref [ 2 * v ] == ( tm - tl + 1 ) ? 1 : 0 ) * pref [ v * 2 + 1 ] ) ; suf [ v ] = Math . max ( suf [ v * 2 + 1 ] , suf [ 2 * v + 1 ] + ( suf [ 2 * v + 1 ] == ( tr - tm ) ? 1 : 0 ) * suf [ v * 2 ] ) ; } } static void solveQueries ( int arr [ ] , int n , int [ ] [ ] Q , int k ) { int cntQuery = Q . length ; build ( arr , 0 , n - 1 , 1 ) ; for ( int i = 0 ; i < cntQuery ; i ++ ) { if ( Q [ i ] [ 0 ] == 1 ) { System . out . print ( MAX [ 1 ] + " ▁ " ) ; } else { arr [ Q [ i ] [ 1 ] - 1 ] ^= 1 ; update ( arr , Q [ i ] [ 1 ] - 1 , 0 , n - 1 , 1 ) ; } } } public static void main ( String [ ] args ) { int N = 10 ; int arr [ ] = { 1 , 1 , 0 , 1 , 1 , 1 , 0 , 0 , 1 , 1 } ; int [ ] [ ] Q = { { 1 } , {...


"Query to find length of the longest subarray consisting only of 1 s | Java Program for the above approach ; Function to calculate the longest subarray consisting of 1 s only ; Stores the maximum length of subarray containing 1 s only ; Traverse the array ; If current element is '1' ; Increment length ; Otherwise ; Reset length ; Update maximum subarray length ; Function to perform given queries ; Stores count of queries ; Traverse each query ; Flip the character ; Driver Code ; Size of array ; Given array ; Given queries ; Number of queries"
How can the above be solved in Java?

import java . util . * ; public class Main { static int longestsubarray ( int a [ ] , int N ) { int maxlength = 0 , sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( a [ i ] == 1 ) { sum ++ ; } else { sum = 0 ; } maxlength = Math . max ( maxlength , sum ) ; } return maxlength ; } static void solveQueries ( int arr [ ] , int n , Vector < Vector < Integer > > Q , int k ) { int cntQuery = Q . size ( ) ; for ( int i = 0 ; i < cntQuery ; i ++ ) { if ( Q . get ( i ) . get ( 0 ) == 1 ) { System . out . print ( longestsubarray ( arr , n ) + " ▁ " ) ; } else { arr [ Q . get ( i ) . get ( 1 ) - 1 ] ^= 1 ; } } } public static void main ( String [ ] args ) { int N = 10 ; int arr [ ] = { 1 , 1 , 0 , 1 , 1 , 1 , 0 , 0 , 1 , 1 } ; Vector < Vector < Integer > > Q = new Vector < Vector < Integer > > ( ) ; Vector < Integer > v1 = new Vector < Integer > ( ) ; Vector < Integer > v2 = new Vector < Integer > ( ) ; Vector < Integer > v3 = new Vector < Integer > ( ) ; v1 . add ( 1 ) ; v2 . add ( 2 ) ; v2 . add ( 3 ) ; v3 . add ( 1 ) ; Q . add ( v1 ) ; Q . add ( v2 ) ; Q . add ( v3 ) ; int K = 3 ; solveQueries ( arr , N , Q , K ) ; } }


"Query to find length of the longest subarray consisting only of 1 s | Java Program for the above approach ; Function to calculate the longest subarray consisting of 1 s only ; Stores the maximum length of subarray containing 1 s only ; Traverse the array ; If current element is '1' ; Increment length ; Otherwise ; Reset length ; Update maximum subarray length ; Function to perform given queries ; Stores count of queries ; Traverse each query ; Flip the character ; Size of array ; Given array ; Given queries ; Number of queries"
How can the above be solved in Java?


"Query to find the maximum and minimum weight between two nodes in the given tree using LCA . | Java Program to find the maximum and minimum weight between two nodes in the given tree using LCA ; Math . log ( MAX ) ; Array to store the level of each node ; Vector to store tree ; Array to store weight of nodes ; Pre - Processing to calculate values of lca [ ] [ ] , MinWeight [ ] [ ] and MaxWeight [ ] [ ] ; Using recursion formula to calculate the values of lca [ ] [ ] ; Storing the level of each node ; Using recursion formula to calculate the values of lca [ ] [ ] , MinWeight [ ] [ ] and MaxWeight [ ] [ ] ; Function to find the minimum and maximum weights in the given range ; The node which is present farthest from the root node is taken as v If u is farther from root node then swap the two ; Finding the ancestor of v which is at same level as u ; Calculating Minimum and Maximum Weight of node v till its 2 ^ i - th ancestor ; If u is the ancestor of v then u is the LCA of u and v ; Finding the node closest to the root which is not the common ancestor of u and v i . e . a node x such that x is not the common ancestor of u and v but lca [ x ] [ 0 ] is ; Calculating the minimum of MinWeight of v to its 2 ^ i - th ancestor and MinWeight of u to its 2 ^ i - th ancestor ; Calculating the maximum of MaxWeight of v to its 2 ^ i - th ancestor and MaxWeight of u to its 2 ^ i - th ancestor ; Calculating the Minimum of first ancestor of u and v ; Calculating the maximum of first ancestor of u and v ; Driver Code ; Number of nodes ; Add edges ; Initialising lca values with - 1 Initialising MinWeight values with Integer . MAX_VALUE Initialising MaxWeight values with Integer . MIN_VALUE ; Perform DFS ; Query 1 : { 1 , 3 } ; Query 2 : { 2 , 4 } ; Query 3 : { 3 , 5 }"
How can the above be solved in Java?

 import java . util . * ; class GFG { static final int MAX = 1000 ; static final int log = 10 ; static int [ ] level = new int [ MAX ] ; static int [ ] [ ] lca = new int [ MAX ] [ log ] ; static int [ ] [ ] minWeight = new int [ MAX ] [ log ] ; static int [ ] [ ] maxWeight = new int [ MAX ] [ log ] ; static Vector < Integer > [ ] graph = new Vector [ MAX ] ; static int [ ] weight = new int [ MAX ] ; private static void swap ( int x , int y ) { int temp = x ; x = y ; y = temp ; } static void addEdge ( int u , int v ) { graph [ u ] . add ( v ) ; graph [ v ] . add ( u ) ; } static void dfs ( int node , int parent , int h ) { lca [ node ] [ 0 ] = parent ; level [ node ] = h ; if ( parent != - 1 ) { minWeight [ node ] [ 0 ] = Math . min ( weight [ node ] , weight [ parent ] ) ; maxWeight [ node ] [ 0 ] = Math . max ( weight [ node ] , weight [ parent ] ) ; } for ( int i = 1 ; i < log ; i ++ ) { if ( lca [ node ] [ i - 1 ] != - 1 ) { lca [ node ] [ i ] = lca [ lca [ node ] [ i - 1 ] ] [ i - 1 ] ; minWeight [ node ] [ i ] = Math . min ( minWeight [ node ] [ i - 1 ] , minWeight [ lca [ node ] [ i - 1 ] ] [ i - 1 ] ) ; maxWeight [ node ] [ i ] = Math . max ( maxWeight [ node ] [ i - 1 ] , maxWeight [ lca [ node ] [ i - 1 ] ] [ i - 1 ] ) ; } } for ( int i : graph [ node ] ) { if ( i == parent ) continue ; dfs ( i , node , h + 1 ) ; } } static void findMinMaxWeight ( int u , int v ) { int minWei = Integer . MAX_VALUE ; int maxWei = Integer . MIN_VALUE ; if ( level [ u ] > level [ v ] ) swap ( u , v ) ; for ( int i = log - 1 ; i >= 0 ; i -- ) { if ( lca [ v ] [ i ] != - 1 && level [ lca [ v ] [ i ] ] >= level [ u ] ) { minWei = Math . min ( minWei , minWeight [ v ] [ i ] ) ; maxWei = Math . max ( maxWei , maxWeight [ v ] [ i ] ) ; v = lca [ v ] [ i ] ; } } if ( v == u ) { System . out . print ( minWei + " ▁ " + maxWei + "
"); } else { for ( int i = log - 1 ; i >= 0 ; i -- ) { if ( v == - 1 ) v ++ ; if ( lca [ v ] [ i ] != lca [ u ] [ i ] ) { minWei = Math . min ( minWei , Math . min ( minWeight [ v ] [ i ] , minWeight [ u...


"Querying maximum number of divisors that a number in a given range has | Java implementation of the above idea to process queries of finding a number with maximum divisors . ; Finds smallest prime factor of all numbersin range [ 1 , maxn ) and stores them in smallest_prime [ ] , smallest_prime [ i ] should contain the smallest prime that divides i ; Initialize the smallest_prime factors of all to infinity ; to be built like eratosthenes sieve ; prime number will have its smallest_prime equal to itself ; if ' i ' is the first prime number reaching ' j ' ; number of divisors of n = ( p1 ^ k1 ) * ( p2 ^ k2 ) . . . ( pn ^ kn ) are equal to ( k1 + 1 ) * ( k2 + 1 ) . . . ( kn + 1 ) this function finds the number of divisors of all numbersin range [ 1 , maxn ) and stores it in divisors [ ] divisors [ i ] stores the number of divisors i has ; we can obtain the prime factorization of the number n , n = ( p1 ^ k1 ) * ( p2 ^ k2 ) . . . ( pn ^ kn ) using the smallest_prime [ ] array , we keep dividing n by its smallest_prime until it becomes 1 , whilst we check if we have need to set k zero ; use p ^ k , initialize k to 0 ; builds segment tree for divisors [ ] array ; leaf node ; build left and right subtree ; combine the information from left and right subtree at current node ; returns the maximum number of divisors in [ l , r ] ; If current node 's range is disjoint  with query range ; If the current node stores information for the range that is completely inside the query range ; Returns maximum number of divisors from left or right subtree ; Driver Code ; First find smallest prime divisors for all the numbers ; Then build the divisors [ ] array to store the number of divisors ; Build segment tree for the divisors [ ] array"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maxn = 10005 ; static int INF = 999999 ; static int [ ] smallest_prime = new int [ maxn ] ; static int [ ] divisors = new int [ maxn ] ; static int [ ] segmentTree = new int [ 4 * maxn ] ; static void findSmallestPrimeFactors ( ) { for ( int i = 0 ; i < maxn ; i ++ ) smallest_prime [ i ] = INF ; for ( int i = 2 ; i < maxn ; i ++ ) { if ( smallest_prime [ i ] == INF ) { smallest_prime [ i ] = i ; for ( int j = i * i ; j < maxn ; j += i ) if ( smallest_prime [ j ] > i ) smallest_prime [ j ] = i ; } } } static void buildDivisorsArray ( ) { for ( int i = 1 ; i < maxn ; i ++ ) { divisors [ i ] = 1 ; int n = i , p = smallest_prime [ i ] , k = 0 ; while ( n > 1 ) { n = n / p ; k ++ ; if ( smallest_prime [ n ] != p ) { divisors [ i ] = divisors [ i ] * ( k + 1 ) ; k = 0 ; } p = smallest_prime [ n ] ; } } } static void buildSegtmentTree ( int node , int a , int b ) { if ( a == b ) { segmentTree [ node ] = divisors [ a ] ; return ; } buildSegtmentTree ( 2 * node , a , ( a + b ) / 2 ) ; buildSegtmentTree ( 2 * node + 1 , ( ( a + b ) / 2 ) + 1 , b ) ; segmentTree [ node ] = Math . max ( segmentTree [ 2 * node ] , segmentTree [ 2 * node + 1 ] ) ; } static int query ( int node , int a , int b , int l , int r ) { if ( l > b a > r ) return - 1 ; if ( a >= l && b <= r ) return segmentTree [ node ] ; return Math . max ( query ( 2 * node , a , ( a + b ) / 2 , l , r ) , query ( 2 * node + 1 , ( ( a + b ) / 2 ) + 1 , b , l , r ) ) ; } public static void main ( String [ ] args ) { findSmallestPrimeFactors ( ) ; buildDivisorsArray ( ) ; buildSegtmentTree ( 1 , 1 , maxn - 1 ) ; System . out . println ( " Maximum ▁ divisors ▁ that ▁ a ▁ number ▁ " + " has ▁ in ▁ [ 1 , ▁ 100 ] ▁ are ▁ " + query ( 1 , 1 , maxn - 1 , 1 , 100 ) ) ; System . out . println ( " Maximum ▁ divisors ▁ that ▁ a ▁ number ▁ " + " has ▁ in ▁ [ 10 , ▁ 48 ] ▁ are ▁ " + query ( 1 , 1 , maxn - 1 , 10 , 48 ) ) ; System . out . println ( " Maximum ▁ divisors ▁ that ▁ a ▁ number ▁ " + " has ▁ in ▁ [ 1 , ▁ 10 ] ▁ are ▁ " +...


"Queue using Stacks | Java program to implement Queue using two stacks with costly enQueue ( ) ; Move all elements from s1 to s2 ; Push item into s1 ; Push everything back to s1 ; Dequeue an item from the queue ; if first stack is empty ; Return top of s1 ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static class Queue { static Stack < Integer > s1 = new Stack < Integer > ( ) ; static Stack < Integer > s2 = new Stack < Integer > ( ) ; static void enQueue ( int x ) { while ( ! s1 . isEmpty ( ) ) { s2 . push ( s1 . pop ( ) ) ; s1 . pop ( ) ; } s1 . push ( x ) ; while ( ! s2 . isEmpty ( ) ) { s1 . push ( s2 . pop ( ) ) ; s2 . pop ( ) ; } } static int deQueue ( ) { if ( s1 . isEmpty ( ) ) { System . out . println ( " Q ▁ is ▁ Empty " ) ; System . exit ( 0 ) ; } int x = s1 . peek ( ) ; s1 . pop ( ) ; return x ; } } ; public static void main ( String [ ] args ) { Queue q = new Queue ( ) ; q . enQueue ( 1 ) ; q . enQueue ( 2 ) ; q . enQueue ( 3 ) ; System . out . println ( q . deQueue ( ) ) ; System . out . println ( q . deQueue ( ) ) ; System . out . println ( q . deQueue ( ) ) ; } }


"Quick way to check if all the characters of a string are same | Java program for above approach ; Function to check is all the characters in string are or not ; Insert characters in the set ; If all characters are same Size of set will always be 1 ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { public static void allCharactersSame ( String s ) { Set < Character > s1 = new HashSet < Character > ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) s1 . add ( s . charAt ( i ) ) ; if ( s1 . size ( ) == 1 ) System . out . println ( " YES " ) ; else System . out . println ( " NO " ) ; } public static void main ( String [ ] args ) { String str = " nnnn " ; allCharactersSame ( str ) ; } }


"QuickSelect ( A Simple Iterative Implementation ) | Java program for iterative implementation of QuickSelect ; Standard Lomuto partition function ; Implementation of QuickSelect ; Partition a [ left . . right ] around a pivot and find the position of the pivot ; If pivot itself is the k - th smallest element ; If there are more than k - 1 elements on left of pivot , then k - th smallest must be on left side . ; Else k - th smallest is on right side . ; Driver Code"
How can the above be solved in Java?

class GFG { static int partition ( int arr [ ] , int low , int high ) { int temp ; int pivot = arr [ high ] ; int i = ( low - 1 ) ; for ( int j = low ; j <= high - 1 ; j ++ ) { if ( arr [ j ] <= pivot ) { i ++ ; temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; } } temp = arr [ i + 1 ] ; arr [ i + 1 ] = arr [ high ] ; arr [ high ] = temp ; return ( i + 1 ) ; } static int kthSmallest ( int a [ ] , int left , int right , int k ) { while ( left <= right ) { int pivotIndex = partition ( a , left , right ) ; if ( pivotIndex == k - 1 ) return a [ pivotIndex ] ; else if ( pivotIndex > k - 1 ) right = pivotIndex - 1 ; else left = pivotIndex + 1 ; } return - 1 ; } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 4 , 5 , 8 , 11 , 6 , 26 } ; int n = arr . length ; int k = 5 ; System . out . println ( " K - th ▁ smallest ▁ element ▁ is ▁ " + kthSmallest ( arr , 0 , n - 1 , k ) ) ; } }


"QuickSort Tail Call Optimization ( Reducing worst case space to Log n ) | A Simple implementation of QuickSort that makes two recursive calls . ; pi is partitioning index , arr [ p ] is now at right place ; Separately sort elements before partition and after partition"
How can the above be solved in Java?

static void quickSort ( int arr [ ] , int low , int high ) { if ( low < high ) { int pi = partition ( arr , low , high ) ; quickSort ( arr , low , pi - 1 ) ; quickSort ( arr , pi + 1 , high ) ; } }


"QuickSort | Java implementation of QuickSort ; A utility function to swap two elements ; This function takes last element as pivot , places the pivot element at its correct position in sorted array , and places all smaller ( smaller than pivot ) to left of pivot and all greater elements to right of pivot ; pivot ; Index of smaller element and indicates the right position of pivot found so far ; If current element is smaller than the pivot ; Increment index of smaller element ; The main function that implements QuickSort arr [ ] -- > Array to be sorted , low -- > Starting index , high -- > Ending index ; pi is partitioning index , arr [ p ] is now at right place ; Separately sort elements before partition and after partition ; Function to print an array ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void swap ( int [ ] arr , int i , int j ) { int temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; } static int partition ( int [ ] arr , int low , int high ) { int pivot = arr [ high ] ; int i = ( low - 1 ) ; for ( int j = low ; j <= high - 1 ; j ++ ) { if ( arr [ j ] < pivot ) { i ++ ; swap ( arr , i , j ) ; } } swap ( arr , i + 1 , high ) ; return ( i + 1 ) ; } static void quickSort ( int [ ] arr , int low , int high ) { if ( low < high ) { int pi = partition ( arr , low , high ) ; quickSort ( arr , low , pi - 1 ) ; quickSort ( arr , pi + 1 , high ) ; } } static void printArray ( int [ ] arr , int size ) { for ( int i = 0 ; i < size ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; System . out . println ( ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 10 , 7 , 8 , 9 , 1 , 5 } ; int n = arr . length ; quickSort ( arr , 0 , n - 1 ) ; System . out . println ( " Sorted ▁ array : ▁ " ) ; printArray ( arr , n ) ; } }


"Quickly find multiple left rotations of an array | Set 1 | Java implementation of left rotation of an array K number of times ; Fills temp [ ] with two copies of arr [ ] ; Store arr [ ] elements at i and i + n ; Function to left rotate an array k time ; Starting position of array after k rotations in temp [ ] will be k % n ; Print array after k rotations ; Driver program"
How can the above be solved in Java?

 class LeftRotate { static void preprocess ( int arr [ ] , int n , int temp [ ] ) { for ( int i = 0 ; i < n ; i ++ ) temp [ i ] = temp [ i + n ] = arr [ i ] ; } static void leftRotate ( int arr [ ] , int n , int k , int temp [ ] ) { int start = k % n ; for ( int i = start ; i < start + n ; i ++ ) System . out . print ( temp [ i ] + " ▁ " ) ; System . out . print ( "
"); } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 5 , 7 , 9 } ; int n = arr . length ; int temp [ ] = new int [ 2 * n ] ; preprocess ( arr , n , temp ) ; int k = 2 ; leftRotate ( arr , n , k , temp ) ; k = 3 ; leftRotate ( arr , n , k , temp ) ; k = 4 ; leftRotate ( arr , n , k , temp ) ; } }


"Quickly find multiple left rotations of an array | Set 1 | Java implementation of left rotation of an array K number of times ; Function to left rotate an array k times ; Print array after k rotations ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void leftRotate ( int arr [ ] , int n , int k ) { for ( int i = k ; i < k + n ; i ++ ) System . out . print ( arr [ i % n ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 5 , 7 , 9 } ; int n = arr . length ; int k = 2 ; leftRotate ( arr , n , k ) ; System . out . println ( ) ; k = 3 ; leftRotate ( arr , n , k ) ; System . out . println ( ) ; k = 4 ; leftRotate ( arr , n , k ) ; System . out . println ( ) ; } }


"Quickselect Algorithm | Java program of Quick Select ; partition function similar to quick sort Considers last element as pivot and adds elements with less value to the left and high value to the right and also changes the pivot position to its respective position in the final array . ; inserting elements of less value to the left of the pivot location ; swapping pivot to the final pivot location ; finds the kth position ( of the sorted array ) in a given unsorted array i . e this function can be used to find both kth largest and kth smallest element in the array . ASSUMPTION : all elements in arr [ ] are distinct ; find the partition ; if partition value is equal to the kth position , return value at k . ; if partition value is less than kth position , search right side of the array . ; if partition value is more than kth position , search left side of the array . ; Driver Code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { public static int partition ( int [ ] arr , int low , int high ) { int pivot = arr [ high ] , pivotloc = low ; for ( int i = low ; i <= high ; i ++ ) { if ( arr [ i ] < pivot ) { int temp = arr [ i ] ; arr [ i ] = arr [ pivotloc ] ; arr [ pivotloc ] = temp ; pivotloc ++ ; } } int temp = arr [ high ] ; arr [ high ] = arr [ pivotloc ] ; arr [ pivotloc ] = temp ; return pivotloc ; } public static int kthSmallest ( int [ ] arr , int low , int high , int k ) { int partition = partition ( arr , low , high ) ; if ( partition == k - 1 ) return arr [ partition ] ; else if ( partition < k - 1 ) return kthSmallest ( arr , partition + 1 , high , k ) ; else return kthSmallest ( arr , low , partition - 1 , k ) ; } public static void main ( String [ ] args ) { int [ ] array = new int [ ] { 10 , 4 , 5 , 8 , 6 , 11 , 26 } ; int [ ] arraycopy = new int [ ] { 10 , 4 , 5 , 8 , 6 , 11 , 26 } ; int kPosition = 3 ; int length = array . length ; if ( kPosition > length ) { System . out . println ( " Index ▁ out ▁ of ▁ bound " ) ; } else { System . out . println ( " K - th ▁ smallest ▁ element ▁ in ▁ array ▁ : ▁ " + kthSmallest ( arraycopy , 0 , length - 1 , kPosition ) ) ; } } }


"Quotient and remainder dividing by 2 ^ k ( a power of 2 ) | Java to find remainder and quotient ; function to print remainder and quotient ; print Remainder by n AND ( m - 1 ) ; print quotient by right shifting n by ( log2 ( m ) ) times ; driver program"
How can the above be solved in Java?

import java . io . * ; public class GFG { static void divide ( int n , int m ) { System . out . println ( " Remainder ▁ = ▁ " + ( ( n ) & ( m - 1 ) ) ) ; System . out . println ( " Quotient ▁ = ▁ " + ( n >> ( int ) ( Math . log ( m ) / Math . log ( 2 ) ) ) ) ; } static public void main ( String [ ] args ) { int n = 43 , m = 8 ; divide ( n , m ) ; } }


"Quotient | Java program to implement Quotient - Remainder Sort ; max_element finds maximum element in an array ; min_element finds minimum element in an array ; Creating a ROW * COL matrix of all zeros ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void QRsort ( int arr [ ] , int size ) { int MAX = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; int MIN = Arrays . stream ( arr ) . min ( ) . getAsInt ( ) ; System . out . println ( " Maximum ▁ Element ▁ found ▁ is ▁ : ▁ " + MAX ) ; System . out . println ( " Minimum ▁ Element ▁ found ▁ is ▁ : ▁ " + MIN ) ; int COL = MIN ; int ROW = MAX / MIN + 1 ; int [ ] [ ] matrix = new int [ ROW ] [ COL ] ; for ( int i = 0 ; i < size ; i ++ ) { int quotient = arr [ i ] / MIN ; int remainder = arr [ i ] % MIN ; matrix [ quotient ] [ remainder ] = arr [ i ] ; } int k = 0 ; for ( int i = 0 ; i < ROW ; i ++ ) { for ( int j = 0 ; j < COL ; j ++ ) { if ( matrix [ i ] [ j ] != 0 ) { arr [ k ++ ] = matrix [ i ] [ j ] ; } } } } static void printArray ( int arr [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } System . out . println ( ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 3 , 7 , 4 , 8 , 2 , 6 } ; int size = arr . length ; System . out . println ( " Initial ▁ Array ▁ : ▁ " ) ; printArray ( arr , size ) ; QRsort ( arr , size ) ; System . out . println ( " Array ▁ after ▁ sorting ▁ : ▁ " ) ; printArray ( arr , size ) ; } }


"Rabin | Following program is a Java implementation of Rabin Karp Algorithm given in the CLRS book ; d is the number of characters in the input alphabet ; pat -> pattern txt -> text q -> A prime number ; hash value for pattern ; hash value for txt ; The value of h would be " pow ( d , ▁ M - 1 ) % q " ; Calculate the hash value of pattern and first window of text ; Slide the pattern over text one by one ; Check the hash values of current window of text and pattern . If the hash values match then only check for characters on by one ; Check for characters one by one ; if p == t and pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; Calculate hash value for next window of text : Remove leading digit , add trailing digit ; We might get negative value of t , converting it to positive ; Driver Code ; A prime number ; Function Call"
How can the above be solved in Java?

public class Main { public final static int d = 256 ; static void search ( String pat , String txt , int q ) { int M = pat . length ( ) ; int N = txt . length ( ) ; int i , j ; int p = 0 ; int t = 0 ; int h = 1 ; for ( i = 0 ; i < M - 1 ; i ++ ) h = ( h * d ) % q ; for ( i = 0 ; i < M ; i ++ ) { p = ( d * p + pat . charAt ( i ) ) % q ; t = ( d * t + txt . charAt ( i ) ) % q ; } for ( i = 0 ; i <= N - M ; i ++ ) { if ( p == t ) { for ( j = 0 ; j < M ; j ++ ) { if ( txt . charAt ( i + j ) != pat . charAt ( j ) ) break ; } if ( j == M ) System . out . println ( " Pattern ▁ found ▁ at ▁ index ▁ " + i ) ; } if ( i < N - M ) { t = ( d * ( t - txt . charAt ( i ) * h ) + txt . charAt ( i + M ) ) % q ; if ( t < 0 ) t = ( t + q ) ; } } } public static void main ( String [ ] args ) { String txt = " GEEKS ▁ FOR ▁ GEEKS " ; String pat = " GEEK " ; int q = 101 ; search ( pat , txt , q ) ; } }


"Rabin | Following program is a Java implementation of Rabin Karp Algorithm given in the CLRS book ; d is the number of characters in the input alphabet ; pat -> pattern txt -> text q -> A prime number ; int p = 0 ; hash value for pattern int t = 0 ; hash value for txt ; The value of h would be " pow ( d , ▁ M - 1 ) % q " ; Calculate the hash value of pattern and first window of text ; Slide the pattern over text one by one ; Check the hash values of current window of text and pattern . If the hash values match then only check for characters on by one ; Check for characters one by one ; if p == t and pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; Calculate hash value for next window of text : Remove leading digit , add trailing digit ; We might get negative value of t , converting it to positive ; Driver Code ; A prime number ; Function Call"
How can the above be solved in Java?

public class Main { public final static int d = 256 ; static void search ( String pat , String txt , int q ) { int M = pat . length ( ) ; int N = txt . length ( ) ; int i , j ; int h = 1 ; for ( i = 0 ; i < M - 1 ; i ++ ) h = ( h * d ) % q ; for ( i = 0 ; i < M ; i ++ ) { p = ( d * p + pat . charAt ( i ) ) % q ; t = ( d * t + txt . charAt ( i ) ) % q ; } for ( i = 0 ; i <= N - M ; i ++ ) { if ( p == t ) { for ( j = 0 ; j < M ; j ++ ) { if ( txt . charAt ( i + j ) != pat . charAt ( j ) ) break ; } if ( j == M ) System . out . println ( " Pattern ▁ found ▁ at ▁ index ▁ " + i ) ; } if ( i < N - M ) { t = ( d * ( t - txt . charAt ( i ) * h ) + txt . charAt ( i + M ) ) % q ; if ( t < 0 ) t = ( t + q ) ; } } } public static void main ( String [ ] args ) { String txt = " GEEKS ▁ FOR ▁ GEEKS " ; String pat = " GEEK " ; int q = 101 ; search ( pat , txt , q ) ; } }


"Radius of a circle having area equal to the sum of area of the circles having given radii | Java program to implement the above approach ; Function to calculate radius of the circle having area equal to sum of the area of two circles with given radii ; Area of first circle ; Area of second circle ; Area of third circle ; Radius of third circle ; Driver code ; Given radius ; Prints the radius of the required circle"
How can the above be solved in Java?

import java . util . * ; class GFG { static double findRadius ( double r1 , double r2 ) { double a1 , a2 , a3 , r3 ; a1 = 3.14 * r1 * r1 ; a2 = 3.14 * r2 * r2 ; a3 = a1 + a2 ; r3 = Math . sqrt ( a3 / 3.14 ) ; return r3 ; } public static void main ( String [ ] args ) { double r1 = 8 , r2 = 6 ; System . out . println ( ( int ) findRadius ( r1 , r2 ) ) ; } }


"Radius of the inscribed circle within three tangent circles | Java implementation of the approach ; Driver code ; Radius of the 3 given circles declared as double . ; Taking r1 , r2 , r3 as input ; Calculation of r4 using formula given above"
How can the above be solved in Java?

class GFG { public static void main ( String [ ] args ) { double r1 , r2 , r3 ; r1 = 1 ; r2 = 2 ; r3 = 3 ; double r4 = ( r1 * r2 * r3 ) / ( r1 * r2 + r2 * r3 + r1 * r3 + 2.0 * Math . sqrt ( r1 * r2 * r3 * ( r1 + r2 + r3 ) ) ) ; System . out . printf ( " % .6f " , r4 ) ; } }


"Radius of the inscribed circle within three tangent circles | Java implementation of the approach ; Radius of the 3 given circles declared as double . ; Calculation of area of a triangle by Heron 's formula ; Applying binary search to find the radius r4 of the required circle ; Area of main triangle ; Loop runs until l and h becomes approximately equal ; Area of smaller triangles ; If sum of smaller triangles is less than main triangle ; If sum of smaller triangles is greater than or equal to main triangle ; Driver code ; Taking r1 , r2 , r3 as input ; Call to function binary search"
How can the above be solved in Java?

import java . util . * ; class GFG { static double r1 , r2 , r3 ; static double area ( double a , double b , double c ) { double p = ( a + b + c ) / 2 ; return Math . sqrt ( p ) * Math . sqrt ( p - a ) * Math . sqrt ( p - b ) * Math . sqrt ( p - c ) ; } static double binary_search ( ) { double s = area ( r1 + r2 , r2 + r3 , r3 + r1 ) ; double l = 0 , h = s / ( r1 + r2 + r3 ) ; while ( h - l >= 1.e-7 ) { double mid = ( l + h ) / 2 ; double s1 = area ( mid + r1 , mid + r2 , r1 + r2 ) ; double s2 = area ( mid + r1 , mid + r3 , r1 + r3 ) ; double s3 = area ( mid + r2 , mid + r3 , r2 + r3 ) ; if ( s1 + s2 + s3 < s ) { l = mid ; } else { h = mid ; } } return ( l + h ) / 2 ; } public static void main ( String [ ] args ) { r1 = 1.0 ; r2 = 2.0 ; r3 = 3.0 ; System . out . printf ( " % .6f " , binary_search ( ) ) ; } }


"Radix Sort | Radix sort Java implementation ; A utility function to get maximum value in arr [ ] ; A function to do counting sort of arr [ ] according to the digit represented by exp . ; output array ; Store count of occurrences in count [ ] ; Change count [ i ] so that count [ i ] now contains actual position of this digit in output [ ] ; Build the output array ; Copy the output array to arr [ ] , so that arr [ ] now contains sorted numbers according to current digit ; The main function to that sorts arr [ ] of size n using Radix Sort ; Find the maximum number to know number of digits ; Do counting sort for every digit . Note that instead of passing digit number , exp is passed . exp is 10 ^ i where i is current digit number ; A utility function to print an array ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class Radix { static int getMax ( int arr [ ] , int n ) { int mx = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] > mx ) mx = arr [ i ] ; return mx ; } static void countSort ( int arr [ ] , int n , int exp ) { int output [ ] = new int [ n ] ; int i ; int count [ ] = new int [ 10 ] ; Arrays . fill ( count , 0 ) ; for ( i = 0 ; i < n ; i ++ ) count [ ( arr [ i ] / exp ) % 10 ] ++ ; for ( i = 1 ; i < 10 ; i ++ ) count [ i ] += count [ i - 1 ] ; for ( i = n - 1 ; i >= 0 ; i -- ) { output [ count [ ( arr [ i ] / exp ) % 10 ] - 1 ] = arr [ i ] ; count [ ( arr [ i ] / exp ) % 10 ] -- ; } for ( i = 0 ; i < n ; i ++ ) arr [ i ] = output [ i ] ; } static void radixsort ( int arr [ ] , int n ) { int m = getMax ( arr , n ) ; for ( int exp = 1 ; m / exp > 0 ; exp *= 10 ) countSort ( arr , n , exp ) ; } static void print ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 170 , 45 , 75 , 90 , 802 , 24 , 2 , 66 } ; int n = arr . length ; radixsort ( arr , n ) ; print ( arr , n ) ; } }


"Railway Station | TCS CodeVita 2020 | Java program for the above approach ; Dp table for memoization ; Function to count the number of ways to N - th station ; Base Cases ; If current state is already evaluated ; Count ways in which train 1 can be chosen ; Count ways in which train 2 can be chosen ; Count ways in which train 3 can be chosen ; Store the current state ; Return the number of ways ; Driven Code ; Given Input ; Initialize DP table with - 1 ; Function call to count the number of ways to reach the n - th station"
How can the above be solved in Java?

import java . util . * ; class GFG { static int dp [ ] = new int [ 100000 ] ; static int findWays ( int x ) { if ( x < 0 ) return 0 ; if ( x == 0 ) return 1 ; if ( x == 1 ) return 2 ; if ( x == 2 ) return 4 ; if ( dp [ x ] != - 1 ) return dp [ x ] ; int count = findWays ( x - 1 ) ; count += findWays ( x - 2 ) ; count += findWays ( x - 3 ) ; dp [ x ] = count ; return dp [ x ] ; } public static void main ( String [ ] args ) { int n = 4 ; Arrays . fill ( dp , - 1 ) ; System . out . print ( findWays ( n ) ) ; } }


"Ramanujan Prime | Java program to find Ramanujan numbers ; FUnction to return a vector of primes ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked . ; Print all prime numbers ; Function to find number of primes less than or equal to x ; Binary search to find out number of primes less than or equal to x ; Function to find the nth ramanujan prime ; For n >= 1 , a ( n ) < 4 * n * log ( 4 n ) ; We start from upperbound and find where pi ( i ) - pi ( i / 2 ) < n the previous number being the nth ramanujan prime ; Function to find first n Ramanujan numbers ; Get the prime numbers ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MAX = 1000000 ; static Vector < Integer > addPrimes ( ) { int n = MAX ; boolean [ ] prime = new boolean [ n + 1 ] ; Arrays . fill ( prime , true ) ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= n ; i += p ) prime [ i ] = false ; } } Vector < Integer > ans = new Vector < Integer > ( ) ; for ( int p = 2 ; p <= n ; p ++ ) if ( prime [ p ] ) ans . add ( p ) ; return ans ; } static int pi ( int x , Vector < Integer > v ) { int l = 0 , r = v . size ( ) - 1 , m , in = - 1 ; while ( l <= r ) { m = ( l + r ) / 2 ; if ( v . get ( m ) <= x ) { in = m ; l = m + 1 ; } else { r = m - 1 ; } } return in + 1 ; } static int Ramanujan ( int n , Vector < Integer > v ) { int upperbound = ( int ) ( 4 * n * ( Math . log ( 4 * n ) / Math . log ( 2 ) ) ) ; for ( int i = upperbound ; ; i -- ) { if ( pi ( i , v ) - pi ( i / 2 , v ) < n ) return 1 + i ; } } static void Ramanujan_Numbers ( int n ) { int c = 1 ; Vector < Integer > v = addPrimes ( ) ; for ( int i = 1 ; i <= n ; i ++ ) { System . out . print ( Ramanujan ( i , v ) ) ; if ( i != n ) System . out . print ( " , ▁ " ) ; } } public static void main ( String [ ] args ) { int n = 10 ; Ramanujan_Numbers ( n ) ; } }


"Random list of M non | Java implementation of the approach ; Utility function to print the elements of an array ; Function to generate a list of m random non - negative integers whose sum is n ; Create an array of size m where every element is initialized to 0 ; To make the sum of the final list as n ; Increment any random element from the array by 1 ; Print the generated list ; Driver code"
How can the above be solved in Java?

class GFG { static void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } static void randomList ( int m , int n ) { int arr [ ] = new int [ m ] ; for ( int i = 0 ; i < n ; i ++ ) { arr [ ( int ) ( Math . random ( ) * m ) ] ++ ; } printArr ( arr , m ) ; } public static void main ( String args [ ] ) { int m = 4 , n = 8 ; randomList ( m , n ) ; } }


"Random number generator in arbitrary probability distribution fashion | Java program to generate random numbers according to given frequency distribution ; Utility function to find ceiling of r in arr [ l . . h ] ; Same as mid = ( l + h ) / 2 ; The main function that returns a random number from arr [ ] according to distribution array defined by freq [ ] . n is size of arrays . ; Create and fill prefix array ; prefix [ n - 1 ] is sum of all frequencies . Generate a random number with value from 1 to this sum ; Find index of ceiling of r in prefix arrat ; Driver code ; Let us generate 10 random numbers accroding to given distribution"
How can the above be solved in Java?

class GFG { static int findCeil ( int arr [ ] , int r , int l , int h ) { int mid ; while ( l < h ) { mid = l + ( ( h - l ) >> 1 ) ; if ( r > arr [ mid ] ) l = mid + 1 ; else h = mid ; } return ( arr [ l ] >= r ) ? l : - 1 ; } static int myRand ( int arr [ ] , int freq [ ] , int n ) { int prefix [ ] = new int [ n ] , i ; prefix [ 0 ] = freq [ 0 ] ; for ( i = 1 ; i < n ; ++ i ) prefix [ i ] = prefix [ i - 1 ] + freq [ i ] ; int r = ( ( int ) ( Math . random ( ) * ( 323567 ) ) % prefix [ n - 1 ] ) + 1 ; int indexc = findCeil ( prefix , r , 0 , n - 1 ) ; return arr [ indexc ] ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int freq [ ] = { 10 , 5 , 20 , 100 } ; int i , n = arr . length ; for ( i = 0 ; i < 5 ; i ++ ) System . out . println ( myRand ( arr , freq , n ) ) ; } }


"Randomized Binary Search Algorithm | Java program to implement iterative randomized algorithm . ; To generate random number between x and y ie . . [ x , y ] ; A iterative randomized binary search function . It returns location of x in given array arr [ l . . r ] if present , otherwise - 1 ; Here we have defined middle as random index between l and r ie . . [ l , r ] ; Check if x is present at mid ; If x greater , ignore left half ; If x is smaller , ignore right half ; if we reach here , then element was not present ; Driver code"
How can the above be solved in Java?

class GFG { static int getRandom ( int x , int y ) { return ( int ) ( x + Math . random ( ) * 10 % ( y - x + 1 ) ) ; } static int randomizedBinarySearch ( int arr [ ] , int l , int r , int x ) { while ( l <= r ) { int m = getRandom ( l , r ) ; if ( arr [ m ] == x ) return m ; if ( arr [ m ] < x ) l = m + 1 ; else r = m - 1 ; } return - 1 ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 4 , 10 , 40 } ; int n = arr . length ; int x = 10 ; int result = randomizedBinarySearch ( arr , 0 , n - 1 , x ) ; if ( result == - 1 ) System . out . printf ( " Element ▁ is ▁ not ▁ present ▁ in ▁ array " ) ; else System . out . printf ( " Element ▁ is ▁ present ▁ at ▁ index ▁ % d " , result ) ; } }


"Randomized Binary Search Algorithm | Java program to implement recursive randomized algorithm . ; To generate random number between x and y ie . . [ x , y ] ; A recursive randomized binary search function . It returns location of x in given array arr [ l . . r ] is present , otherwise - 1 ; Here we have defined middle as random index between l and r ie . . [ l , r ] ; If the element is present at the middle itself ; If element is smaller than mid , then it can only be present in left subarray ; Else the element can only be present in right subarray ; We reach here when element is not present in array ; Driver code"
How can the above be solved in Java?

public class RandomizedBinarySearch { public static int getRandom ( int x , int y ) { return ( x + ( int ) ( Math . random ( ) % ( y - x + 1 ) ) ) ; } public static int randomizedBinarySearch ( int arr [ ] , int low , int high , int key ) { if ( high >= low ) { int mid = getRandom ( low , high ) ; if ( arr [ mid ] == key ) return mid ; if ( arr [ mid ] > key ) return randomizedBinarySearch ( arr , low , mid - 1 , key ) ; return randomizedBinarySearch ( arr , mid + 1 , high , key ) ; } return - 1 ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 4 , 10 , 40 } ; int n = arr . length ; int key = 10 ; int result = randomizedBinarySearch ( arr , 0 , n - 1 , key ) ; System . out . println ( ( result == - 1 ) ? " Element ▁ is ▁ not ▁ present ▁ in ▁ array " : " Element ▁ is ▁ present ▁ at ▁ index ▁ " + result ) ; } }


"Range Minimum Query ( Square Root Decomposition and Sparse Table ) | Java program to do range minimum query in O ( 1 ) time with O ( n * n ) extra space and O ( n * n ) preprocessing time . ; lookup [ i ] [ j ] is going to store index of minimum value in arr [ i . . j ] ; Structure to represent a query range ; Fills lookup array lookup [ n ] [ n ] for all possible values of query ranges ; Initialize lookup [ ] [ ] for the intervals with length 1 ; Fill rest of the entries in bottom up manner ; To find minimum of [ 0 , 4 ] , we compare minimum of arr [ lookup [ 0 ] [ 3 ] ] with arr [ 4 ] . ; Prints minimum of given m query ranges in arr [ 0. . n - 1 ] ; Fill lookup table for all possible input queries ; One by one compute sum of all queries ; Left and right boundaries of current range ; Print sum of current query range ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MAX = 500 ; static int [ ] [ ] lookup = new int [ MAX ] [ MAX ] ; static class Query { int L , R ; public Query ( int L , int R ) { this . L = L ; this . R = R ; } } ; static void preprocess ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) lookup [ i ] [ i ] = i ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) if ( arr [ lookup [ i ] [ j - 1 ] ] < arr [ j ] ) lookup [ i ] [ j ] = lookup [ i ] [ j - 1 ] ; else lookup [ i ] [ j ] = j ; } } static void RMQ ( 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 ( " Minimum ▁ of ▁ [ " + L + " , ▁ " + R + " ] ▁ is ▁ " + arr [ lookup [ L ] [ R ] ] ) ; } } public static void main ( String [ ] args ) { int a [ ] = { 7 , 2 , 3 , 0 , 5 , 10 , 3 , 12 , 18 } ; int n = a . length ; Query q [ ] = { new Query ( 0 , 4 ) , new Query ( 4 , 7 ) , new Query ( 7 , 8 ) } ; int m = q . length ; RMQ ( a , n , q , m ) ; } }


"Range Minimum Query ( Square Root Decomposition and Sparse Table ) | Java program to do range minimum query in O ( 1 ) time with O ( n Log n ) extra space and O ( n Log n ) preprocessing time ; lookup [ i ] [ j ] is going to store index of minimum value in arr [ i . . j ] . Ideally lookup table size should not be fixed and should be determined using n Log n . It is kept constant to keep code simple . ; Structure to represent a query range ; Fills lookup array lookup [ ] [ ] in bottom up manner . ; Initialize M for the intervals with length 1 ; Compute values from smaller to bigger intervals ; Compute minimum value for all intervals with size 2 ^ j ; For arr [ 2 ] [ 10 ] , we compare arr [ lookup [ 0 ] [ 3 ] ] and arr [ lookup [ 3 ] [ 3 ] ] ; Returns minimum of arr [ L . . R ] ; For [ 2 , 10 ] , j = 3 ; For [ 2 , 10 ] , we compare arr [ lookup [ 0 ] [ 3 ] ] and arr [ lookup [ 3 ] [ 3 ] ] , ; Prints minimum of given m query ranges in arr [ 0. . n - 1 ] ; Fills table lookup [ n ] [ Log n ] ; One by one compute sum of all queries ; Left and right boundaries of current range ; Print sum of current query range ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MAX = 500 ; static int [ ] [ ] lookup = new int [ MAX ] [ MAX ] ; static class Query { int L , R ; public Query ( int L , int R ) { this . L = L ; this . 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 RMQ ( 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 ( " Minimum ▁ of ▁ [ " + L + " , ▁ " + R + " ] ▁ is ▁ " + query ( arr , L , R ) ) ; } } public static void main ( String [ ] args ) { int a [ ] = { 7 , 2 , 3 , 0 , 5 , 10 , 3 , 12 , 18 } ; int n = a . length ; Query q [ ] = { new Query ( 0 , 4 ) , new Query ( 4 , 7 ) , new Query ( 7 , 8 ) } ; int m = q . length ; RMQ ( a , n , q , m ) ; } }


"Range Queries for Longest Correct Bracket Subsequence Set | 2 | Java code to answer the query in constant time ; Function for precomputation ; Create a stack and push - 1 as initial index to it . ; Traverse all characters of given String ; If opening bracket , push index of it ; If closing bracket , i . e . , str [ i ] = ' ) ' ; If closing bracket , i . e . , str [ i ] = ' ) ' && stack is not empty then mark both " open ▁ & ▁ close " bracket indexs as 1 . Pop the previous opening bracket 's index ; If stack is empty . ; Function return output of each query in O ( 1 ) ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void constructBlanceArray ( int BOP [ ] , int BCP [ ] , String str , int n ) { Stack < Integer > stk = new Stack < > ( ) ; ; for ( int i = 0 ; i < n ; i ++ ) { if ( str . charAt ( i ) == ' ( ' ) stk . add ( i ) ; else { if ( ! stk . isEmpty ( ) ) { BCP [ i ] = 1 ; BOP [ stk . peek ( ) ] = 1 ; stk . pop ( ) ; } else BCP [ i ] = 0 ; } } for ( int i = 1 ; i < n ; i ++ ) { BCP [ i ] += BCP [ i - 1 ] ; BOP [ i ] += BOP [ i - 1 ] ; } } static int query ( int BOP [ ] , int BCP [ ] , int s , int e ) { if ( BOP [ s - 1 ] == BOP [ s ] ) { return ( BCP [ e ] - BOP [ s ] ) * 2 ; } else { return ( BCP [ e ] - BOP [ s ] + 1 ) * 2 ; } } public static void main ( String [ ] args ) { String str = " ( ) ) ( ( ) ) ( ( ) ) ( " ; int n = str . length ( ) ; int BCP [ ] = new int [ n + 1 ] ; int BOP [ ] = new int [ n + 1 ] ; constructBlanceArray ( BOP , BCP , str , n ) ; int startIndex = 5 , endIndex = 11 ; System . out . print ( " Maximum ▁ Length ▁ Correct ▁ " + " Bracket ▁ Subsequence ▁ between ▁ " + startIndex + " ▁ and ▁ " + endIndex + " ▁ = ▁ " + query ( BOP , BCP , startIndex , endIndex ) + "
"); startIndex = 4 ; endIndex = 5 ; System . out . print ( " Maximum ▁ Length ▁ Correct ▁ " + " Bracket ▁ Subsequence ▁ between ▁ " + startIndex + " ▁ and ▁ " + endIndex + " ▁ = ▁ " + query ( BOP , BCP , startIndex , endIndex ) + "
"); startIndex = 1 ; endIndex = 5 ; System . out . print ( " Maximum ▁ Length ▁ Correct ▁ " + " Bracket ▁ Subsequence ▁ between ▁ " + startIndex + " ▁ and ▁ " + endIndex + " ▁ = ▁ " + query ( BOP , BCP , startIndex , endIndex ) + "
"); } }


"Range Queries for count of Armstrong numbers in subarray using MO 's algorithm | Java implementation to count the number of Armstrong numbers in subarray using MOaTMs algorithm ; Variable to represent block size . ; Class to represent a query range ; Count of Armstrong numbers ; To store the count of Armstrong numbers ; sort all queries so that all queries of the same block are arranged together and within a block , queries are sorted in increasing order of R values . ; Different blocks , sort by block . ; Same block , sort by R value ; sort all queries in order of their index value so that results of queries can be printed in same order as of input ) ; ; Function that return true if num is armstrong else return false ; Function to Add elements of current range ; If a [ currL ] is a Armstrong number then increment count_Armstrong ; Function to remove elements of previous range ; If a [ currL ] is a Armstrong number then decrement count_Armstrong ; Function to generate the result of queries ; Initialize count_Armstrong to 0 ; Find block size ; Initialize current L , current R and current result ; L and R values of current range ; Add Elements of current range ; Remove element of previous range ; Function to display the results of queries in their initial order ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; static int block ; class Query { int L , R , index ; int armstrong ; Query ( int L , int R , int index , int armstrong ) { this . L = L ; this . R = R ; this . index = index ; this . armstrong = armstrong ; } } class GFG { static int count_Armstrong ; Arrays . sort ( q , ( Query x , Query y ) -> { if ( x . L / block != y . L / block ) return x . L / block - y . L / block ; return x . R - y . R ; } ) ; x . index - y . index ) ; for ( int i = 0 ; i < m ; i ++ ) { System . out . println ( q [ i ] . armstrong ) ; } } static boolean isArmstrong ( int x ) { int n = String . valueOf ( x ) . length ( ) ; int sum1 = 0 ; int temp = x ; while ( temp > 0 ) { int digit = temp % 10 ; sum1 += Math . pow ( digit , n ) ; temp /= 10 ; } if ( sum1 == x ) return true ; return false ; } static void add ( int currL , int a [ ] ) { if ( isArmstrong ( a [ currL ] ) ) count_Armstrong ++ ; } static void remove ( int currR , int a [ ] ) { if ( isArmstrong ( a [ currR ] ) ) count_Armstrong -- ; } static void queryResults ( int a [ ] , int n , Query q [ ] , int m ) { count_Armstrong = 0 ; block = ( int ) ( Math . sqrt ( n ) ) ; int currL = 0 , currR = 0 ; for ( int i = 0 ; i < m ; i ++ ) { int L = q [ i ] . L , R = q [ i ] . R ; while ( currR <= R ) { add ( currR , a ) ; currR ++ ; } while ( currL > L ) { add ( currL - 1 , a ) ; currL -- ; } while ( currR > R + 1 ) { remove ( currR - 1 , a ) ; currR -- ; } while ( currL < L ) { remove ( currL , a ) ; currL ++ ; } q [ i ] . armstrong = count_Armstrong ; } } static void printResults ( Query q [ ] , int m ) { Arrays . sort ( q , ( Query x , Query y ) -> public static void main ( String [ ] args ) { int arr [ ] = { 18 , 153 , 8 , 9 , 14 , 5 } ; int n = arr . length ; Query q [ ] = new Query [ 2 ] ; q [ 0 ] = new Query ( 0 , 5 , 0 , 0 ) ; q [ 1 ] = new Query ( 3 , 5 , 1 , 0 ) ; int m = q . length ; queryResults ( arr , n , q , m ) ; printResults ( q , m ) ; } }


"Range Queries for finding the Sum of all even parity numbers | Java program to find the sum of all Even Parity numbers in the given range ; pref [ ] array to precompute the sum of all Even Parity Numbers ; Function that returns true if count of set bits in x is even ; Parity will store the count of set bits ; Function to precompute the sum of all even parity numbers upto 100000 ; isEvenParity ( ) return the number i if i has even parity else return 0 ; Function to print sum for each query ; Function to print sum of all even parity numbers between [ L , R ] ; Function that pre computes the sum of all even parity numbers ; Iterate over all Queries to print sum ; Driver code ; Queries ; Function that print the sum of all even parity numbers in Range [ L , R ]"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int [ ] pref = new int [ 100001 ] ; static int isEvenParity ( int num ) { int parity = 0 ; int x = num ; while ( x != 0 ) { if ( ( x & 1 ) == 1 ) parity ++ ; x = x >> 1 ; } if ( parity % 2 == 0 ) return num ; else return 0 ; } static void preCompute ( ) { for ( int i = 1 ; i < 100001 ; i ++ ) { pref [ i ] = pref [ i - 1 ] + isEvenParity ( i ) ; } } static void printSum ( int L , int R ) { System . out . println ( pref [ R ] - pref [ L - 1 ] ) ; } static void printSum ( int arr [ ] [ ] , int Q ) { preCompute ( ) ; for ( int i = 0 ; i < Q ; i ++ ) { printSum ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ) ; } } public static void main ( String [ ] args ) { int N = 2 ; int [ ] [ ] Q = { { 1 , 10 } , { 121 , 211 } } ; printSum ( Q , N ) ; } }


"Range queries for alternatively addition and subtraction on given Array | Java program for the above approach ; Structure to represent a query ; This function fills the Prefix Array ; Initialise the prefix array ; Iterate all the element of arr [ ] and update the prefix array ; If n is even then , add the previous value of prefix array with the current value of arr ; if n is odd , then subtract the previous value of prefix Array from current value ; Function to find the result of alternatively adding and subtracting elements in the range [ L < R ] ; Case 1 : when L is zero ; Case 2 : When L is non zero ; If L is odd means range starts from odd position multiply result by - 1 ; Return the final result ; Function to find the sum of all alternative add and subtract between ranges [ L , R ] ; Declare prefix array ; Function Call to fill prefix arr [ ] ; Iterate for each query ; Driver Code ; Given array ; Given Queries ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static class Query { int L , R ; public Query ( int l , int r ) { super ( ) ; L = l ; R = r ; } } ; static void fillPrefixArray ( int arr [ ] , int n , int prefixArray [ ] ) { prefixArray [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { if ( i % 2 == 0 ) { prefixArray [ i ] = prefixArray [ i - 1 ] + arr [ i ] ; } else { prefixArray [ i ] = prefixArray [ i - 1 ] - arr [ i ] ; } } } static int findResultUtil ( int prefixArray [ ] , int L , int R ) { int result ; if ( L == 0 ) { result = prefixArray [ R ] ; } else { result = prefixArray [ R ] - prefixArray [ L - 1 ] ; } if ( L % 2 == 1 ) { result = result * ( - 1 ) ; } return result ; } static void findResult ( int arr [ ] , int n , Query q [ ] , int m ) { int [ ] prefixArray = new int [ n ] ; fillPrefixArray ( arr , n , prefixArray ) ; for ( int i = 0 ; i < m ; i ++ ) { System . out . print ( findResultUtil ( prefixArray , q [ i ] . L , q [ i ] . R ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 13 , 15 , 2 , 45 , 31 , 22 , 3 , 27 } ; int n = arr . length ; Query q [ ] = { new Query ( 2 , 5 ) , new Query ( 6 , 8 ) , new Query ( 1 , 7 ) , new Query ( 4 , 8 ) , new Query ( 0 , 5 ) } ; int m = q . length ; findResult ( arr , n , q , m ) ; } }


"Range queries for alternatively addition and subtraction on given Array | Java program for the above approach ; Structure to represent a range query ; Function to find the result of alternatively adding and subtracting elements in the range [ L , R ] ; A boolean variable flag to alternatively add and subtract ; Iterate from [ L , R ] ; If flag is false , then add & toggle the flag ; If flag is true subtract and toggle the flag ; Return the final result ; Function to find the value for each query ; Iterate for each query ; Driver Code ; Given array ; Given Queries ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static class Query { int L , R ; public Query ( int l , int r ) { super ( ) ; L = l ; R = r ; } } ; static int findResultUtil ( int arr [ ] , int L , int R ) { int result = 0 ; boolean flag = false ; for ( int i = L ; i <= R ; i ++ ) { if ( flag == false ) { result = result + arr [ i ] ; flag = true ; } else { result = result - arr [ i ] ; flag = false ; } } return result ; } static void findResult ( int arr [ ] , int n , Query q [ ] , int m ) { for ( int i = 0 ; i < m ; i ++ ) { System . out . print ( findResultUtil ( arr , q [ i ] . L , q [ i ] . R ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 13 , 15 , 2 , 45 , 31 , 22 , 3 , 27 } ; int n = arr . length ; Query q [ ] = { new Query ( 2 , 5 ) , new Query ( 6 , 8 ) , new Query ( 1 , 7 ) , new Query ( 4 , 8 ) , new Query ( 0 , 5 ) } ; int m = q . length ; findResult ( arr , n , q , m ) ; } }


"Range query for count of set bits | Java program to Range query for Count number of set bits ; 2 - D array that will stored the count of bits set in element of array ; Function store the set bit count in BitCount Array ; traverse over all bits ; mark elements with i 'th bit set ; Check whether the current bit is set or not if it 's  set then mark it. ; store cumulative sum of bits ; Function to process queries ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int BitCount [ ] = new int [ 10000 ] ; static void fillSetBitsMatrix ( int arr [ ] , int n ) { for ( int i = 0 ; i < 32 ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { long temp = arr [ j ] >> i ; if ( temp % 2 != 0 ) BitCount [ j ] += 1 ; } } for ( int i = 1 ; i < n ; i ++ ) BitCount [ i ] += BitCount [ i - 1 ] ; } static void Query ( int Q [ ] [ ] , int q ) { for ( int i = 0 ; i < q ; i ++ ) System . out . println ( ( BitCount [ Q [ i ] [ 1 ] ] - BitCount [ Q [ i ] [ 0 ] - 1 ] ) ) ; } public static void main ( String [ ] args ) { int Arr [ ] = { 1 , 5 , 6 , 10 , 9 , 4 , 67 } ; int n = Arr . length ; fillSetBitsMatrix ( Arr , n ) ; int q = 2 ; int Q [ ] [ ] = { { 1 , 5 } , { 2 , 6 } } ; Query ( Q , q ) ; } }


"Range sum queries based on given conditions | Java program for the above approach ; Function to calculate the sum between the given range as per value of m ; Stores the sum ; Condition for a to print the sum between ranges [ a , b ] ; Return sum ; Function to precalculate the sum of both the vectors ; Make Prefix sum array ; Function to compute the result for each query ; Take a dummy vector and copy the element of arr in brr ; Sort the dummy vector ; Compute prefix sum of both vectors ; Performs operations ; Function call to find sum ; Function call to find sum ; Driver Code ; Given arr [ ] ; Number of queries ; Given queries ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int range_sum ( int [ ] arr , int a , int b ) { int sum = 0 ; if ( a - 2 < 0 ) sum = arr [ b - 1 ] ; else sum = arr [ b - 1 ] - arr [ a - 2 ] ; return sum ; } static void precompute_sum ( int [ ] arr , int [ ] brr ) { int N = ( int ) arr . length ; for ( int i = 1 ; i < N ; i ++ ) { arr [ i ] = arr [ i ] + arr [ i - 1 ] ; brr [ i ] = brr [ i ] + brr [ i - 1 ] ; } } static void find_sum ( int [ ] arr , int q , int Queries [ ] [ ] ) { int [ ] brr = arr . clone ( ) ; int N = ( int ) arr . length ; Arrays . sort ( brr ) ; precompute_sum ( arr , brr ) ; for ( int i = 0 ; i < q ; i ++ ) { int m = Queries [ i ] [ 0 ] ; int a = Queries [ i ] [ 1 ] ; int b = Queries [ i ] [ 2 ] ; if ( m == 1 ) { System . out . print ( range_sum ( arr , a , b ) + " ▁ " ) ; } else if ( m == 2 ) { System . out . print ( range_sum ( brr , a , b ) + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int [ ] arr = { 0 , 6 , 4 , 2 , 7 , 2 , 7 } ; int Q = 1 ; int Queries [ ] [ ] = { { 2 , 3 , 6 } } ; find_sum ( arr , Q , Queries ) ; } }


"Range sum queries for anticlockwise rotations of Array by K indices | Java program to calculate range sum queries for anticlockwise rotations of array by K ; Function to execute the queries ; Construct a new array of size 2 * N to store prefix sum of every index ; Copy elements to the new array ; Calculate the prefix sum for every index ; Set start pointer as 0 ; Query to perform anticlockwise rotation ; Query to answer range sum ; If pointing to 1 st index ; Display the sum upto start + R ; Subtract sum upto start + L - 1 from sum upto start + R ; Driver code ; Number of query ; Store all the queries"
How can the above be solved in Java?

 class GFG { static void rotatedSumQuery ( int arr [ ] , int n , int [ ] [ ] query , int Q ) { int [ ] prefix = new int [ 2 * n ] ; for ( int i = 0 ; i < n ; i ++ ) { prefix [ i ] = arr [ i ] ; prefix [ i + n ] = arr [ i ] ; } for ( int i = 1 ; i < 2 * n ; i ++ ) prefix [ i ] += prefix [ i - 1 ] ; int start = 0 ; for ( int q = 0 ; q < Q ; q ++ ) { if ( query [ q ] [ 0 ] == 1 ) { int k = query [ q ] [ 1 ] ; start = ( start + k ) % n ; } else if ( query [ q ] [ 0 ] == 2 ) { int L , R ; L = query [ q ] [ 1 ] ; R = query [ q ] [ 2 ] ; if ( start + L == 0 ) System . out . print ( prefix [ start + R ] + "
"); else System . out . print ( prefix [ start + R ] - prefix [ start + L - 1 ] + "
"); } } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int Q = 5 ; int [ ] [ ] query = { { 2 , 1 , 3 } , { 1 , 3 } , { 2 , 0 , 3 } , { 1 , 4 } , { 2 , 3 , 5 } } ; int n = arr . length ; rotatedSumQuery ( arr , n , query , Q ) ; } }


"Range sum queries without updates | Java program to find sum between two indexes when there is no update . ; Returns sum of elements in arr [ i . . j ] It is assumed that i <= j ; Driver code ; Function call"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { public static void preCompute ( int arr [ ] , int n , int pre [ ] ) { pre [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) pre [ i ] = arr [ i ] + pre [ i - 1 ] ; } public static int rangeSum ( int i , int j , int pre [ ] ) { if ( i == 0 ) return pre [ j ] ; return pre [ j ] - pre [ i - 1 ] ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = arr . length ; int pre [ ] = new int [ n ] ; preCompute ( arr , n , pre ) ; System . out . println ( rangeSum ( 1 , 3 , pre ) ) ; System . out . println ( rangeSum ( 2 , 4 , pre ) ) ; } }


"Rank of all elements in a Stream in descending order when they arrive | Java program to rank of all elements in a Stream in descending order when they arrive ; FindRank function to find rank ; Rank of first element is always 1 ; Iterate over array ; As element let say its rank is 1 ; Element is compared with previous elements ; If greater than previous than rank is incremented ; print rank ; Driver code ; array named arr ; length of arr"
How can the above be solved in Java?

import java . util . * ; class GFG { static void FindRank ( int arr [ ] , int length ) { System . out . print ( "1" + " ▁ " ) ; for ( int i = 1 ; i < arr . length ; i ++ ) { int rank = 1 ; for ( int j = 0 ; j < i ; j ++ ) { if ( arr [ j ] > arr [ i ] ) rank ++ ; } System . out . print ( rank + " ▁ " ) ; } } public static void main ( String args [ ] ) { int arr [ ] = { 88 , 14 , 69 , 30 , 29 , 89 } ; int len = arr . length ; FindRank ( arr , len ) ; } }


"Rank of all elements in an array | Java Code to find rank of elements ; Function to print m Maximum elements ; Rank Vector ; Sweep through all elements in A for each element count the number of less than and equal elements separately in r and s ; Use formula to obtain rank ; Driver code"
How can the above be solved in Java?

public class GfG { public static void rankify ( int A [ ] , int n ) { float R [ ] = new float [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { int r = 1 , s = 1 ; for ( int j = 0 ; j < n ; j ++ ) { if ( j != i && A [ j ] < A [ i ] ) r += 1 ; if ( j != i && A [ j ] == A [ i ] ) s += 1 ; } R [ i ] = r + ( float ) ( s - 1 ) / ( float ) 2 ; } for ( int i = 0 ; i < n ; i ++ ) System . out . print ( R [ i ] + " ▁ " ) ; } public static void main ( String args [ ] ) { int A [ ] = { 1 , 2 , 5 , 2 , 1 , 25 , 2 } ; int n = A . length ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( A [ i ] + " ▁ " ) ; System . out . println ( ) ; rankify ( A , n ) ; } }


"Rank of an element in a stream | Java program to find rank of an element in a stream . ; Driver code"
How can the above be solved in Java?

class GFG { public static void main ( String [ ] args ) { int a [ ] = { 5 , 1 , 14 , 4 , 15 , 9 , 7 , 20 , 11 } ; int key = 20 ; int arraySize = a . length ; int count = 0 ; for ( int i = 0 ; i < arraySize ; i ++ ) { if ( a [ i ] <= key ) { count += 1 ; } } System . out . println ( " Rank ▁ of ▁ " + key + " ▁ in ▁ stream ▁ is : ▁ " + ( count - 1 ) ) ; } }


"Rank of an element in a stream | Java program to find rank of an element in a stream . ; Inserting a new Node . ; Updating size of left subtree . ; Function to get Rank of a Node x . ; Step 1. ; Step 2. ; Step 3. ; Driver code"
How can the above be solved in Java?

class GfG { static class Node { int data ; Node left , right ; int leftSize ; } static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . left = null ; temp . right = null ; temp . leftSize = 0 ; return temp ; } static Node insert ( Node root , int data ) { if ( root == null ) return newNode ( data ) ; if ( data <= root . data ) { root . left = insert ( root . left , data ) ; root . leftSize ++ ; } else root . right = insert ( root . right , data ) ; return root ; } static int getRank ( Node root , int x ) { if ( root . data == x ) return root . leftSize ; if ( x < root . data ) { if ( root . left == null ) return - 1 ; else return getRank ( root . left , x ) ; } else { if ( root . right == null ) return - 1 ; else { int rightSize = getRank ( root . right , x ) ; if ( rightSize == - 1 ) return - 1 ; return root . leftSize + 1 + rightSize ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 1 , 4 , 4 , 5 , 9 , 7 , 13 , 3 } ; int n = arr . length ; int x = 4 ; Node root = null ; for ( int i = 0 ; i < n ; i ++ ) root = insert ( root , arr [ i ] ) ; System . out . println ( " Rank ▁ of ▁ " + x + " ▁ in ▁ stream ▁ is ▁ : ▁ " + getRank ( root , x ) ) ; x = 13 ; System . out . println ( " Rank ▁ of ▁ " + x + " ▁ in ▁ stream ▁ is ▁ : ▁ " + getRank ( root , x ) ) ; } }