"Sort an Array which contain 1 to N values in O ( N ) using Cycle Sort | Java program for the above approach ; Function to print array element ; Traverse the array ; Function to sort the array in O ( N ) ; Traverse the array ; If the current element is at correct position ; Else swap the current element with it 's correct position ; Swap the value of arr [ i ] and arr [ arr [ i ] - 1 ] ; Driver Code ; Function call to sort the array ; Function call to print the array"
Solution in Java:

class Main { public static void printArray ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } public static void sortArray ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; ) { if ( arr [ i ] == i + 1 ) { i ++ ; } else { int temp1 = arr [ i ] ; int temp2 = arr [ arr [ i ] - 1 ] ; arr [ i ] = temp2 ; arr [ temp1 - 1 ] = temp1 ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 1 , 5 , 3 , 4 } ; int N = arr . length ; sortArray ( arr , N ) ; printArray ( arr , N ) ; } }


"Sorting element of an array by frequency in decreasing order | Java program to sort an array in decreasing order of their frequency ; Function that return the index upto all the array elements are updated . ; Initialise maxE = - 1 ; Find the maximum element of arr [ ] ; Create frequency array freq [ ] ; Update the frequency array as per the occurrence of element in arr [ ] ; Initialise cnt to 0 ; Traversing freq [ ] ; If freq of an element is greater than 0 update the value of arr [ ] at index cnt & increment cnt ; Return cnt ; Function that print array arr [ ] elements in sorted order ; Traversing arr [ ] till index cnt ; Find frequency of elements ; Find value at index i ; Traversing till frequency to print value at index i ; Driver code ; Size of array arr [ ] ; Function call to get cnt ; Sort the arr [ ] in decreasing order ; Function that prints elements in decreasing order"
Solution in Java:

import java . util . * ; class GFG { static int sortByFreq ( Integer [ ] arr , int n ) { int maxE = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { maxE = Math . max ( maxE , arr [ i ] ) ; } int freq [ ] = new int [ maxE + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) { freq [ arr [ i ] ] ++ ; } int cnt = 0 ; for ( int i = 0 ; i <= maxE ; i ++ ) { if ( freq [ i ] > 0 ) { int value = 100000 - i ; arr [ cnt ] = 100000 * freq [ i ] + value ; cnt ++ ; } } return cnt ; } static void printSortedArray ( Integer [ ] arr , int cnt ) { for ( int i = 0 ; i < cnt ; i ++ ) { int frequency = arr [ i ] / 100000 ; int value = 100000 - ( arr [ i ] % 100000 ) ; for ( int j = 0 ; j < frequency ; j ++ ) { System . out . print ( value + " ▁ " ) ; } } } public static void main ( String [ ] args ) { Integer arr [ ] = { 4 , 4 , 5 , 6 , 4 , 2 , 2 , 8 , 5 } ; int n = arr . length ; int cnt = sortByFreq ( arr , n ) ; Arrays . sort ( arr , Collections . reverseOrder ( ) ) ; printSortedArray ( arr , cnt ) ; } }


"Space and time efficient Binomial Coefficient | Program to calculate C ( n , k ) in java ; Returns value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- -- * 1 ] ; Driver program to test above function"
Solution in Java:

class BinomialCoefficient { static int binomialCoeff ( int n , int k ) { int res = 1 ; if ( k > n - k ) k = n - k ; for ( int i = 0 ; i < k ; ++ i ) { res *= ( n - i ) ; res /= ( i + 1 ) ; } return res ; } public static void main ( String [ ] args ) { int n = 8 ; int k = 2 ; System . out . println ( " Value ▁ of ▁ C ( " + n + " , ▁ " + k + " ) ▁ " + " is " + " ▁ " + binomialCoeff ( n , k ) ) ; } }


"Split a Binary String such that count of 0 s and 1 s in left and right substrings is maximum | Java program to implement the above approach ; Function to find the maximum sum of count of 0 s in the left subString and count of 1 s in the right subString by splitting the String ; Stores count of 1 s the in binary String ; Traverse the binary String ; If current character is '1' ; Update cntOne ; Stores count of 0 s ; Stores count of 1 s ; Stores maximum sum of count of 0 s and 1 s by splitting the String ; Traverse the binary String ; If current character is '0' ; Update zero ; If current character is '1' ; Update one ; Update res ; Driver Code"
Solution in Java:

import java . util . * ; class GFG { static int maxSumbySplittingString ( String str , int N ) { int cntOne = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( str . charAt ( i ) == '1' ) { cntOne ++ ; } } int zero = 0 ; int one = 0 ; int res = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( str . charAt ( i ) == '0' ) { zero ++ ; } else { one ++ ; } res = Math . max ( res , zero + cntOne - one ) ; } return res ; } public static void main ( String [ ] args ) { String str = "00111" ; int N = str . length ( ) ; System . out . print ( maxSumbySplittingString ( str , N ) ) ; } }


"Split a given string into substrings of length K with equal sum of ASCII values | Java program to check if a given string can be split into substrings of size K having an equal sum of ASCII values . ; Function for checking string ; Check if the string can be split into substrings of K length only ; Compute the sum of first substring of length K ; Compute the sum of remaining substrings ; Check if sum is equal to that of the first substring ; Since all sums are not equal , return false ; All sums are equal , Return true ; All substrings cannot be of size K ; Driver code"
Solution in Java:

class GFG { static boolean check ( String str , int K ) { if ( str . length ( ) % K == 0 ) { int sum = 0 , i ; for ( i = 0 ; i < K ; i ++ ) { sum += str . charAt ( i ) ; } for ( int j = i ; j < str . length ( ) ; j += K ) { int s_comp = 0 ; for ( int p = j ; p < j + K ; p ++ ) s_comp += str . charAt ( p ) ; if ( s_comp != sum ) return false ; } return true ; } return false ; } public static void main ( String args [ ] ) { int K = 3 ; String str = " abdcbbdba " ; if ( check ( str , K ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"String obtained by reversing and complementing a Binary string K times | Java program to perform K operations upon the String and find the modified String ; Function to perform K operations upon the String and find modified String ; Number of reverse operations ; Number of complement operations ; If rev is odd parity ; If complement is odd parity ; Complementing each position ; Return the modified String ; Driver Code ; Function call"
Solution in Java:

class GFG { static String ReverseComplement ( char [ ] s , int n , int k ) { int rev = ( k + 1 ) / 2 ; int complement = k - rev ; if ( rev % 2 == 1 ) s = reverse ( s ) ; if ( complement % 2 == 1 ) { for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == '0' ) s [ i ] = '1' ; else s [ i ] = '0' ; } } return String . valueOf ( s ) ; } static char [ ] reverse ( char a [ ] ) { int i , n = a . length ; char t ; for ( i = 0 ; i < n / 2 ; i ++ ) { t = a [ i ] ; a [ i ] = a [ n - i - 1 ] ; a [ n - i - 1 ] = t ; } return a ; } public static void main ( String [ ] args ) { String str = "10011" ; int k = 5 ; int n = str . length ( ) ; System . out . print ( ReverseComplement ( str . toCharArray ( ) , n , k ) ) ; } }


"Subset Sum Problem in O ( sum ) space |  ; initializing with 1 as sum 0 is always possible ; loop to go through every element of the elements array ; to change the values of all possible sum values to 1 ; if sum is possible then return 1 ; Driver code"
Solution in Java:

import java . io . * ; import java . util . * ; class GFG { static boolean isPossible ( int elements [ ] , int sum ) { int dp [ ] = new int [ sum + 1 ] ; dp [ 0 ] = 1 ; for ( int i = 0 ; i < elements . length ; i ++ ) { for ( int j = sum ; j >= elements [ i ] ; j -- ) { if ( dp [ j - elements [ i ] ] == 1 ) dp [ j ] = 1 ; } } if ( dp [ sum ] == 1 ) return true ; return false ; } public static void main ( String [ ] args ) throws Exception { int elements [ ] = { 6 , 2 , 5 } ; int sum = 7 ; if ( isPossible ( elements , sum ) ) System . out . println ( " YES " ) ; else System . out . println ( " NO " ) ; } }


"Subset Sum Problem in O ( sum ) space | Java Program to get a subset with a with a sum provided by the user ; Returns true if there exists a subset with given sum in arr [ ] ; The value of subset [ i % 2 ] [ j ] will be true if there exists a subset of sum j in arr [ 0 , 1 , ... . , i - 1 ] ; A subset with sum 0 is always possible ; If there exists no element no sum is possible ; Driver code"
Solution in Java:

public class Subset_sum { static boolean isSubsetSum ( int arr [ ] , int n , int sum ) { boolean subset [ ] [ ] = new boolean [ 2 ] [ sum + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) { for ( int j = 0 ; j <= sum ; j ++ ) { if ( j == 0 ) subset [ i % 2 ] [ j ] = true ; else if ( i == 0 ) subset [ i % 2 ] [ j ] = false ; else if ( arr [ i - 1 ] <= j ) subset [ i % 2 ] [ j ] = subset [ ( i + 1 ) % 2 ] [ j - arr [ i - 1 ] ] || subset [ ( i + 1 ) % 2 ] [ j ] ; else subset [ i % 2 ] [ j ] = subset [ ( i + 1 ) % 2 ] [ j ] ; } } return subset [ n % 2 ] [ sum ] ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 2 , 5 } ; int sum = 7 ; int n = arr . length ; if ( isSubsetSum ( arr , n , sum ) == true ) System . out . println ( " There ▁ exists ▁ a ▁ subset ▁ with " + " given ▁ sum " ) ; else System . out . println ( " No ▁ subset ▁ exists ▁ with " + " given ▁ sum " ) ; } }


"Subtract 1 without arithmetic operators | Driver code"
Solution in Java:

class GFG { static int subtractOne ( int x ) { return ( ( x << 1 ) + ( ~ x ) ) ; } public static void main ( String [ ] args ) { System . out . printf ( " % d " , subtractOne ( 13 ) ) ; } }


"Subtract 1 without arithmetic operators | Java code to subtract one from a given number ; Flip all the set bits until we find a 1 ; flip the rightmost 1 bit ; Driver Code"
Solution in Java:

import java . io . * ; class GFG { static int subtractOne ( int x ) { int m = 1 ; while ( ! ( ( x & m ) > 0 ) ) { x = x ^ m ; m <<= 1 ; } x = x ^ m ; return x ; } public static void main ( String [ ] args ) { System . out . println ( subtractOne ( 13 ) ) ; } }


"Sum of Area of all possible square inside a rectangle | Java program to calculate the sum of area of all possible squares that comes inside the rectangle ; Function to calculate the sum of area of all possible squares that comes inside the rectangle ; Square with max size possible ; calculate total square of a given size ; calculate area of squares of a particular size ; total area ; increment size ; Driver Code"
Solution in Java:

class GFG { static int calculateAreaSum ( int l , int b ) { int size = 1 ; int maxSize = Math . min ( l , b ) ; int totalArea = 0 ; for ( int i = 1 ; i <= maxSize ; i ++ ) { int totalSquares = ( l - size + 1 ) * ( b - size + 1 ) ; int area = totalSquares * size * size ; totalArea += area ; size ++ ; } return totalArea ; } public static void main ( String [ ] args ) { int l = 4 , b = 3 ; System . out . println ( calculateAreaSum ( l , b ) ) ; } }


"Sum of Bitwise AND of each array element with the elements of another array | Java program for the above approach ; Driver Code ; Given arr1 [ ] ; Given arr2 [ ] ; Size of arr1 [ ] ; Size of arr2 [ ] ; Function Call ; Function to compute the AND sum for each element of an array ; Declaring an array of size 32 for storing the count of each bit ; Traverse the array arr2 [ ] and store the count of a bit in frequency array ; Current bit position ; While num is greater than 0 ; Checks if ith bit is set or not ; Increment the count of bit by one ; Increment the bit position by one ; Right shift the num by one ; Traverse in the arr2 [ ] ; Store the ith bit value ; Total required sum ; Traverse in the range [ 0 , 31 ] ; Checks if current bit is set ; Increment the bitwise sum by frequency [ bit_position ] * value_at_that_bit ; ; Right shift num by one ; Left shift vale_at_that_bit by one ; Print the sum obtained for ith number in arr1 [ ]"
Solution in Java:

import java . io . * ; class GFG { public static void main ( String [ ] args ) { int [ ] arr1 = { 1 , 2 , 3 } ; int [ ] arr2 = { 1 , 2 , 3 } ; int N = arr1 . length ; int M = arr2 . length ; Bitwise_AND_sum_i ( arr1 , arr2 , M , N ) ; } static void Bitwise_AND_sum_i ( int arr1 [ ] , int arr2 [ ] , int M , int N ) { int [ ] frequency = new int [ 32 ] ; for ( int i = 0 ; i < N ; i ++ ) { int bit_position = 0 ; int num = arr1 [ i ] ; while ( num != 0 ) { if ( ( num & 1 ) != 0 ) { frequency [ bit_position ] += 1 ; } bit_position += 1 ; num >>= 1 ; } } for ( int i = 0 ; i < M ; i ++ ) { int num = arr2 [ i ] ; int value_at_that_bit = 1 ; int bitwise_AND_sum = 0 ; for ( int bit_position = 0 ; bit_position < 32 ; bit_position ++ ) { if ( ( num & 1 ) != 0 ) { bitwise_AND_sum += frequency [ bit_position ] * value_at_that_bit ; } num >>= 1 ; value_at_that_bit <<= 1 ; } System . out . print ( bitwise_AND_sum + " ▁ " ) ; } } }


"Sum of Fibonacci Numbers with alternate negatives | Java Program to find alternate sum of Fibonacci numbers ; Computes value of first fibonacci numbers and stores their alternate sum ; Initialize result ; Add remaining terms ; For even terms ; For odd terms ; Return the alternating sum ; Driver code ; Get n ; Find the alternating sum"
Solution in Java:

public class GFG { static double calculateAlternateSum ( int n ) { if ( n <= 0 ) return 0 ; int fibo [ ] = new int [ n + 1 ] ; fibo [ 0 ] = 0 ; fibo [ 1 ] = 1 ; double sum = Math . pow ( fibo [ 0 ] , 2 ) + Math . pow ( fibo [ 1 ] , 2 ) ; for ( int i = 2 ; i <= n ; i ++ ) { fibo [ i ] = fibo [ i - 1 ] + fibo [ i - 2 ] ; if ( i % 2 == 0 ) sum -= fibo [ i ] ; else sum += fibo [ i ] ; } return sum ; } public static void main ( String args [ ] ) { int n = 8 ; System . out . println ( " Alternating ▁ Fibonacci ▁ Sum ▁ upto ▁ " + n + " ▁ terms : ▁ " + calculateAlternateSum ( n ) ) ; } }


"Sum of all nodes with smaller values at a distance K from a given node in a BST | Java program for the above approach ; Structure of Tree ; Constructor ; Function to add the node to the sum below the target node ; Base Case ; If Kth distant node is reached ; Recur for the left and the right subtrees ; Function to find the K distant nodes from target node , it returns - 1 if target node is not present in tree ; Base Case 1 ; If target is same as root . ; Recurr for the left subtree ; Tree is BST so reduce the search space ; Check if target node was found in left subtree ; If root is at distance k from the target ; Node less than target will be present in left ; When node is not present in the left subtree ; If Kth distant node is reached ; Node less than target at k distance maybe present in the left tree ; If target was not present in the left nor in right subtree ; Function to insert a node in BST ; If root is null ; Insert the data in right half ; Insert the data in left half ; Return the root node ; Function to find the sum of K distant nodes from the target node having value less than target node ; Stores the sum of nodes having values < target at K distance ; Print the resultant sum ; Driver Code ; Create the Tree"
Solution in Java:

import java . util . * ; public class GFG { static int sum ; static class TreeNode { int data ; TreeNode left ; TreeNode right ; TreeNode ( int data ) { this . data = data ; this . left = null ; this . right = null ; } } ; static void kDistanceDownSum ( TreeNode root , int k ) { if ( root == null k < 0 ) return ; if ( k == 0 ) { sum += root . data ; return ; } kDistanceDownSum ( root . left , k - 1 ) ; kDistanceDownSum ( root . right , k - 1 ) ; } static int kDistanceSum ( TreeNode root , int target , int k ) { if ( root == null ) return - 1 ; if ( root . data == target ) { kDistanceDownSum ( root . left , k - 1 ) ; return 0 ; } int dl = - 1 ; if ( target < root . data ) { dl = kDistanceSum ( root . left , target , k ) ; } if ( dl != - 1 ) { if ( dl + 1 == k ) sum += root . data ; return - 1 ; } int dr = - 1 ; if ( target > root . data ) { dr = kDistanceSum ( root . right , target , k ) ; } if ( dr != - 1 ) { if ( dr + 1 == k ) sum += root . data ; else kDistanceDownSum ( root . left , k - dr - 2 ) ; return 1 + dr ; } return - 1 ; } static TreeNode insertNode ( int data , TreeNode root ) { if ( root == null ) { TreeNode node = new TreeNode ( data ) ; return node ; } else if ( data > root . data ) { root . right = insertNode ( data , root . right ) ; } else if ( data <= root . data ) { root . left = insertNode ( data , root . left ) ; } return root ; } static void findSum ( TreeNode root , int target , int K ) { sum = 0 ; kDistanceSum ( root , target , K ) ; System . out . print ( sum ) ; } public static void main ( String [ ] args ) { TreeNode root = null ; int N = 11 ; int tree [ ] = { 3 , 1 , 7 , 0 , 2 , 5 , 10 , 4 , 6 , 9 , 8 } ; for ( int i = 0 ; i < N ; i ++ ) { root = insertNode ( tree [ i ] , root ) ; } int target = 7 ; int K = 2 ; findSum ( root , target , K ) ; } }


"Sum of all odd length palindromic numbers within the range [ L , R ] | Java program to find the sum of all odd length palindromic numbers within the given range ; Function that returns true if the given number is a palindrome ; Here we are generating a new number ( reverse_num ) * by reversing the digits of original input number ; If the original input number ( num ) is equal to * to its reverse ( reverse_num ) then its palindrome * else it is not . ; Function that returns true if the given number is of odd length ; Function to return the sum of all odd length palindromic numbers within the given range ; if number is palindrome and of odd length ; Driver code"
Solution in Java:

class GFG { static boolean isPalindrome ( int num ) { int reverse_num = 0 , remainder , temp ; temp = num ; while ( temp != 0 ) { remainder = temp % 10 ; reverse_num = reverse_num * 10 + remainder ; temp /= 10 ; } if ( reverse_num == num ) { return true ; } return false ; } static boolean isOddLength ( int num ) { int count = 0 ; while ( num > 0 ) { num /= 10 ; count ++ ; } if ( count % 2 != 0 ) { return true ; } return false ; } static long sumOfAllPalindrome ( int L , int R ) { long sum = 0 ; if ( L <= R ) for ( int i = L ; i <= R ; i ++ ) { if ( isPalindrome ( i ) && isOddLength ( i ) ) { sum += i ; } } return sum ; } public static void main ( String [ ] args ) { int L = 110 , R = 1130 ; System . out . println ( sumOfAllPalindrome ( L , R ) ) ; } }


"Sum of all the Composite Numbers from Odd indices of the given array | Java implementation to find the sum of all the composite numbers from odd indices of the given array ; Function to check for composite numbers ; Check if the factors are greater than 2 ; Check if the number is composite or not ; Function to print the sum of all composite numbers in the array ; Iterate for odd indices in the array ; Check if the number is composite then add it to sum ; return the sum ; Driver code"
Solution in Java:

 class GFG { static int composite ( int n ) { int flag = 0 ; int c = 0 ; for ( int j = 1 ; j <= n ; j ++ ) { if ( n % j == 0 ) { c += 1 ; } } if ( c >= 3 ) flag = 1 ; return flag ; } static void odd_indices ( int arr [ ] , int n ) { int sum = 0 ; for ( int k = 0 ; k < n ; k += 2 ) { int check = composite ( arr [ k ] ) ; if ( check == 1 ) sum += arr [ k ] ; } System . out . print ( sum + "
"); } public static void main ( String [ ] args ) { int arr [ ] = { 13 , 5 , 8 , 16 , 25 } ; int n = arr . length ; odd_indices ( arr , n ) ; } }


"Sum of bit differences for numbers from 0 to N | Java program for the above approach ; Function to implement fast exponentiation ; Function to return the value for powers of 2 ; Function to convert N into binary ; To store the binary representation ; Iterate each digit of n ; Return binary representation ; Function to find difference in bits ; Get binary representation ; total number of bit differences from 0 to N ; Iterate over each binary bit ; If current bit is '1' then add the count of current bit ; Driver code ; Given number ; Function Call"
Solution in Java:

import java . io . * ; import java . lang . Math ; class GFG { static int binpow ( int a , int b ) { int res = 1 ; while ( b > 0 ) { if ( b % 2 == 1 ) res = res * a ; a = a * a ; b /= 2 ; } return res ; } static int find ( int x ) { if ( x == 0 ) return 0 ; int p = ( int ) ( Math . log ( x ) / Math . log ( 2 ) ) ; return binpow ( 2 , p + 1 ) - 1 ; } static String getBinary ( int n ) { String ans = " " ; while ( n > 0 ) { int dig = n % 2 ; ans += dig ; n /= 2 ; } return ans ; } static int totalCountDifference ( int n ) { String ans = getBinary ( n ) ; int req = 0 ; for ( int i = 0 ; i < ans . length ( ) ; i ++ ) { if ( ans . charAt ( i ) == '1' ) { req += find ( binpow ( 2 , i ) ) ; } } return req ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . print ( totalCountDifference ( n ) ) ; } }


"Sum of decimals that are binary representations of first N natural numbers | / Java program for the above approach ; Function to find the sum of first N natural numbers represented in binary representation ; Stores the resultant sum ; Iterate until the value of N is greater than 0 ; If N is less than 2 ; Store the MSB position of N ; Iterate in the range [ 1 , x ] and add the contribution of the numbers from 1 to ( 2 ^ x - 1 ) ; Update the value of the cur and add ; Add the cur to ans ; Store the remaining numbers ; Add the contribution by MSB by the remaining numbers ; The next iteration will be repeated for 2 ^ x - 1 ; Print the result ; Driver Code"
Solution in Java:

import java . io . * ; import java . lang . * ; class GFG { static final int MOD = 1000000007 ; static void sumOfBinaryNumbers ( int n ) { int ans = 0 ; int one = 1 ; while ( true ) { if ( n <= 1 ) { ans = ( ans + n ) % MOD ; break ; } int x = ( int ) ( Math . log ( n ) / Math . log ( 2 ) ) ; int cur = 0 ; int add = ( int ) ( Math . pow ( 2 , ( x - 1 ) ) ) ; for ( int i = 1 ; i <= x ; i ++ ) { cur = ( cur + add ) % MOD ; add = ( add * 10 % MOD ) ; } ans = ( ans + cur ) % MOD ; int rem = n - ( int ) ( Math . pow ( 2 , x ) ) + 1 ; int p = ( int ) Math . pow ( 10 , x ) ; p = ( p * ( rem % MOD ) ) % MOD ; ans = ( ans + p ) % MOD ; n = rem - 1 ; } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int N = 3 ; sumOfBinaryNumbers ( N ) ; } }


"Sum of elements in an array having composite frequency | Java program to find sum of elements in an array having composite frequency ; Function to create Sieve to check primes ; If composite [ p ] is not changed , then it is a prime ; Update all multiples of p , set them to composite ; Function to return the sum of elements in an array having composite frequency ; Map is used to store element frequencies ; To store sum ; Traverse the map using iterators ; Count the number of elements having composite frequencies ; Driver code ; Function call"
Solution in Java:

import java . util . * ; class GFG { static final int N = 10005 ; static void SieveOfEratosthenes ( Vector < Boolean > composite ) { for ( int i = 0 ; i < N ; i ++ ) { composite . add ( i , false ) ; } for ( int p = 2 ; p * p < N ; p ++ ) { if ( ! composite . get ( p ) ) { for ( int i = p * 2 ; i < N ; i += p ) { composite . add ( i , true ) ; } } } } static int sumOfElements ( int arr [ ] , int n ) { Vector < Boolean > composite = new Vector < Boolean > ( ) ; for ( int i = 0 ; i < N ; i ++ ) composite . add ( false ) ; SieveOfEratosthenes ( composite ) ; HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) if ( mp . containsKey ( arr [ i ] ) ) { mp . put ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) ; } else { mp . put ( arr [ i ] , 1 ) ; } int sum = 0 ; for ( Map . Entry < Integer , Integer > it : mp . entrySet ( ) ) { if ( composite . get ( it . getValue ( ) ) ) { sum += ( it . getKey ( ) ) ; } } return sum ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 1 , 1 , 1 , 3 , 3 , 2 , 4 } ; int n = arr . length ; System . out . print ( sumOfElements ( arr , n ) ) ; } }


"Sum of elements in an array having prime frequency | Java program to find sum of elements in an array having prime frequency ; Function to create Sieve to check primes ; False here indicates that it is not prime ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p , set them to non - prime ; Function to return the sum of elements in an array having prime frequency ; Map is used to store element frequencies ; Traverse the map ; Count the number of elements having prime frequencies ; Driver code"
Solution in Java:

import java . util . * ; class GFG { static void SieveOfEratosthenes ( boolean prime [ ] , int p_size ) { prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= p_size ; p ++ ) { if ( prime [ p ] ) { for ( int i = p * 2 ; i <= p_size ; i += p ) prime [ i ] = false ; } } } static int sumOfElements ( int arr [ ] , int n ) { boolean prime [ ] = new boolean [ n + 1 ] ; Arrays . fill ( prime , true ) ; SieveOfEratosthenes ( prime , n + 1 ) ; int i , j ; HashMap < Integer , Integer > m = new HashMap < > ( ) ; for ( i = 0 ; i < n ; i ++ ) { if ( m . containsKey ( arr [ i ] ) ) m . put ( arr [ i ] , m . get ( arr [ i ] ) + 1 ) ; else m . put ( arr [ i ] , 1 ) ; } int sum = 0 ; for ( Map . Entry < Integer , Integer > entry : m . entrySet ( ) ) { int key = entry . getKey ( ) ; int value = entry . getValue ( ) ; if ( prime [ value ] ) { sum += ( key ) ; } } return sum ; } public static void main ( String args [ ] ) { int arr [ ] = { 5 , 4 , 6 , 5 , 4 , 6 } ; int n = arr . length ; System . out . println ( sumOfElements ( arr , n ) ) ; } }


"Sum of numbers from 1 to N which are divisible by 3 or 4 | Java program to find sum of numbers from 1 to N which are divisible by 3 or 4 ; Function to calculate the sum of numbers divisible by 3 or 4 ; Driver code"
Solution in Java:


"Sum of products of all combination taken ( 1 to n ) at a time | Java Program to find sum of all combination takne ( 1 to N ) at a time using dynamic programming ; find the postfix sum array ; modify the array such that we don 't  have to compute the products which  are obtained before ; finding sum of all combination taken 1 to N at a time ; sum taken 1 at time is simply sum of 1 - N ; for sum of products for all combination ; finding postfix array ; sum of products taken i + 1 at a time ; modify the array for overlapping problem ; Driver 's Code ; storing numbers from 1 to N ; calling allCombination"
Solution in Java:

import java . util . * ; class GFG { static void postfix ( int a [ ] , int n ) { for ( int i = n - 1 ; i > 0 ; i -- ) { a [ i - 1 ] = a [ i - 1 ] + a [ i ] ; } } static void modify ( int a [ ] , int n ) { for ( int i = 1 ; i < n ; i ++ ) { a [ i - 1 ] = i * a [ i ] ; } } static void allCombination ( int a [ ] , int n ) { int sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { sum += i ; } System . out . println ( " f ( 1 ) ▁ - - > ▁ " + sum ) ; for ( int i = 1 ; i < n ; i ++ ) { postfix ( a , n - i + 1 ) ; sum = 0 ; for ( int j = 1 ; j <= n - i ; j ++ ) { sum += ( j * a [ j ] ) ; } System . out . println ( " f ( " + ( i + 1 ) + " ) ▁ - - > ▁ " + sum ) ; modify ( a , n ) ; } } public static void main ( String [ ] args ) { int n = 5 ; int [ ] a = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { a [ i ] = i + 1 ; } allCombination ( a , n ) ; } }


"Sum of products of all combination taken ( 1 to n ) at a time | Program to find SOP of all combination taken ( 1 to N ) at a time using brute force ; to store sum of every combination ; if we have reached sufficient depth ; find the product of combination ; add the product into sum ; recursion to produce different combination ; function to print sum of products of all combination taken 1 - N at a time ; creating temporary array for storing combination ; call combination with r = i for combination taken i at a time ; displaying sum ; Driver code ; storing numbers from 1 - N in array ; calling allCombination"
Solution in Java:

 import java . io . * ; class GFG { static int sum = 0 ; static void Combination ( int [ ] a , int [ ] combi , int n , int r , int depth , int index ) { if ( index == r ) { int product = 1 ; for ( int i = 0 ; i < r ; i ++ ) product = product * combi [ i ] ; sum += product ; return ; } for ( int i = depth ; i < n ; i ++ ) { combi [ index ] = a [ i ] ; Combination ( a , combi , n , r , i + 1 , index + 1 ) ; } } static void allCombination ( int [ ] a , int n ) { for ( int i = 1 ; i <= n ; i ++ ) { int [ ] combi = new int [ i ] ; Combination ( a , combi , n , i , 0 , 0 ) ; System . out . print ( " f ( " + i + " ) ▁ - - > ▁ " + sum + "
"); sum = 0 ; } } public static void main ( String args [ ] ) { int n = 5 ; int [ ] a = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) a [ i ] = i + 1 ; allCombination ( a , n ) ; } }


"Sum of specially balanced nodes from a given Binary Tree | Java program for the above approach ; Structure of Binary Tree ; Function to create a new node ; Return the created node ; Function to insert a node in the tree ; Left insertion ; Right insertion ; Return the root node ; Function to find sum of specially balanced nodes in the Tree ; Base Case ; Find the left subtree sum ; Find the right subtree sum ; Condition of specially balanced node ; Condition of specially balanced node ; Return the sum ; Function to build the binary tree ; Form root node of the tree ; Insert nodes into tree ; Create a new Node ; Insert the node ; Return the root of the Tree ; Function to find the sum of specially balanced nodes ; Build Tree ; Stores the sum of specially balanced node ; Function Call ; Print required sum ; Driver Code ; Given nodes ; Given root ; Given path info of nodes from root ; Given node values ; Function Call"
Solution in Java:

import java . util . * ; class GFG { static int sum ; static class Node { int data ; Node left , right ; } ; static Node newnode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . left = null ; temp . right = null ; return temp ; } static Node insert ( String s , int i , int N , Node root , Node temp ) { if ( i == N ) return temp ; if ( s . charAt ( i ) == ' L ' ) root . left = insert ( s , i + 1 , N , root . left , temp ) ; else root . right = insert ( s , i + 1 , N , root . right , temp ) ; return root ; } static int SBTUtil ( Node root ) { if ( root == null ) return 0 ; if ( root . left == null && root . right == null ) return root . data ; int left = SBTUtil ( root . left ) ; int right = SBTUtil ( root . right ) ; if ( root . left != null && root . right != null ) { if ( ( left % 2 == 0 && right % 2 != 0 ) || ( left % 2 != 0 && right % 2 == 0 ) ) { sum += root . data ; } } return left + right + root . data ; } static Node build_tree ( int R , int N , String str [ ] , int values [ ] ) { Node root = newnode ( R ) ; int i ; for ( i = 0 ; i < N - 1 ; i ++ ) { String s = str [ i ] ; int x = values [ i ] ; Node temp = newnode ( x ) ; root = insert ( s , 0 , s . length ( ) , root , temp ) ; } return root ; } static void speciallyBalancedNodes ( int R , int N , String str [ ] , int values [ ] ) { Node root = build_tree ( R , N , str , values ) ; sum = 0 ; SBTUtil ( root ) ; System . out . print ( sum + " ▁ " ) ; } public static void main ( String [ ] args ) { int N = 7 ; int R = 12 ; String str [ ] = { " L " , " R " , " RL " , " RR " , " RLL " , " RLR " } ; int values [ ] = { 17 , 16 , 4 , 9 , 2 , 3 } ; speciallyBalancedNodes ( R , N , str , values ) ; } }


"Sum of the multiples of two numbers below N | Java program to find the sum of all the integers below N which are multiples of either A or B ; Function to return the sum of all the integers below N which are multiples of either A or B ; If i is a multiple of a or b ; Driver code"
Solution in Java:

import java . io . * ; class GFG { static int findSum ( int n , int a , int b ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( i % a == 0 i % b == 0 ) sum += i ; return sum ; } public static void main ( String [ ] args ) { int n = 10 , a = 3 , b = 5 ; System . out . println ( findSum ( n , a , b ) ) ; } }


"Sum of two numbers where one number is represented as array of digits | Java implementation of the approach ; Function to return the vector containing the answer ; ArrayList v is to store each digits sum and ArrayList ans is to store the answer ; No carry in the beginning ; Start loop from the end and take element one by one ; Array index and last digit of number ; Maintain carry of summation ; Push the digit value into the array ; K value is greater then 0 ; Push digits of K one by one in the array ; Also maintain carry with summation ; Reverse the elements of vector v and store it in vector ans ; Driver code ; Print the answer"
Solution in Java:

import java . util . * ; class GFG { static ArrayList < Integer > addToArrayForm ( ArrayList < Integer > A , int K ) { ArrayList < Integer > v = new ArrayList < Integer > ( ) ; ArrayList < Integer > ans = new ArrayList < Integer > ( ) ; int rem = 0 ; int i = 0 ; for ( i = A . size ( ) - 1 ; i >= 0 ; i -- ) { int my = A . get ( i ) + K % 10 + rem ; if ( my > 9 ) { rem = 1 ; v . add ( my % 10 ) ; } else { v . add ( my ) ; rem = 0 ; } K = K / 10 ; } while ( K > 0 ) { int my = K % 10 + rem ; v . add ( my % 10 ) ; if ( my / 10 > 0 ) rem = 1 ; else rem = 0 ; K = K / 10 ; } if ( rem > 0 ) v . add ( rem ) ; for ( int j = v . size ( ) - 1 ; j >= 0 ; j -- ) ans . add ( v . get ( j ) ) ; return ans ; } public static void main ( String [ ] args ) { ArrayList < Integer > A = new ArrayList < Integer > ( ) ; A . add ( 2 ) ; A . add ( 7 ) ; A . add ( 4 ) ; int K = 181 ; ArrayList < Integer > ans = addToArrayForm ( A , K ) ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) System . out . print ( ans . get ( i ) ) ; } }


"Ternary Search | Java program to illustrate recursive approach to ternary search ; Function to perform Ternary Search ; Find the mid1 and mid2 ; Check if key is present at any mid ; Since key is not present at mid , check in which region it is present then repeat the Search operation in that region ; The key lies in between l and mid1 ; The key lies in between mid2 and r ; The key lies in between mid1 and mid2 ; Key not found ; Driver code ; Get the array Sort the array if not sorted ; Starting index ; length of array ; Key to be searched in the array ; Search the key using ternarySearch ; Print the result ; Key to be searched in the array ; Search the key using ternarySearch ; Print the result"
Solution in Java:

class GFG { static int ternarySearch ( int l , int r , int key , int ar [ ] ) { if ( r >= l ) { int mid1 = l + ( r - l ) / 3 ; int mid2 = r - ( r - l ) / 3 ; if ( ar [ mid1 ] == key ) { return mid1 ; } if ( ar [ mid2 ] == key ) { return mid2 ; } if ( key < ar [ mid1 ] ) { return ternarySearch ( l , mid1 - 1 , key , ar ) ; } else if ( key > ar [ mid2 ] ) { return ternarySearch ( mid2 + 1 , r , key , ar ) ; } else { return ternarySearch ( mid1 + 1 , mid2 - 1 , key , ar ) ; } } return - 1 ; } public static void main ( String args [ ] ) { int l , r , p , key ; int ar [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 } ; l = 0 ; r = 9 ; key = 5 ; p = ternarySearch ( l , r , key , ar ) ; System . out . println ( " Index ▁ of ▁ " + key + " ▁ is ▁ " + p ) ; key = 50 ; p = ternarySearch ( l , r , key , ar ) ; System . out . println ( " Index ▁ of ▁ " + key + " ▁ is ▁ " + p ) ; } }


"Ternary Search | Java program to illustrate the iterative approach to ternary search ; Function to perform Ternary Search ; Find the mid1 mid2 ; Check if key is present at any mid ; Since key is not present at mid , check in which region it is present then repeat the Search operation in that region ; The key lies in between l and mid1 ; The key lies in between mid2 and r ; The key lies in between mid1 and mid2 ; Key not found ; Driver code ; Get the array Sort the array if not sorted ; Starting index ; length of array ; Key to be searched in the array ; Search the key using ternarySearch ; Print the result ; Key to be searched in the array ; Search the key using ternarySearch ; Print the result"
Solution in Java:

class GFG { static int ternarySearch ( int l , int r , int key , int ar [ ] ) { while ( r >= l ) { int mid1 = l + ( r - l ) / 3 ; int mid2 = r - ( r - l ) / 3 ; if ( ar [ mid1 ] == key ) { return mid1 ; } if ( ar [ mid2 ] == key ) { return mid2 ; } if ( key < ar [ mid1 ] ) { r = mid1 - 1 ; } else if ( key > ar [ mid2 ] ) { l = mid2 + 1 ; } else { l = mid1 + 1 ; r = mid2 - 1 ; } } return - 1 ; } public static void main ( String args [ ] ) { int l , r , p , key ; int ar [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 } ; l = 0 ; r = 9 ; key = 5 ; p = ternarySearch ( l , r , key , ar ) ; System . out . println ( " Index ▁ of ▁ " + key + " ▁ is ▁ " + p ) ; key = 50 ; p = ternarySearch ( l , r , key , ar ) ; System . out . println ( " Index ▁ of ▁ " + key + " ▁ is ▁ " + p ) ; } }


"Tetranacci Numbers | A DP based Java program to print the nth tetranacci number ; Function to print the N - th tetranacci number ; base cases ; Driver code"
Solution in Java:

class GFG { static void printTetra ( int n ) { int [ ] dp = new int [ n + 5 ] ; dp [ 0 ] = 0 ; dp [ 1 ] = dp [ 2 ] = 1 ; dp [ 3 ] = 2 ; for ( int i = 4 ; i <= n ; i ++ ) dp [ i ] = dp [ i - 1 ] + dp [ i - 2 ] + dp [ i - 3 ] + dp [ i - 4 ] ; System . out . print ( dp [ n ] ) ; } public static void main ( String [ ] args ) { int n = 10 ; printTetra ( n ) ; } }


"Tetranacci Numbers | A simple recursive Java program to print the nth tetranacci numbers . ; Function to return the N - th tetranacci number ; base cases ; base cases ; base cases ; function to print the Nth tetranacci number ; Driver code"
Solution in Java:

class GFG { static int printTetraRec ( int n ) { if ( n == 0 ) return 0 ; if ( n == 1 n == 2 ) return 1 ; if ( n == 3 ) return 2 ; else return printTetraRec ( n - 1 ) + printTetraRec ( n - 2 ) + printTetraRec ( n - 3 ) + printTetraRec ( n - 4 ) ; } static void printTetra ( int n ) { System . out . println ( printTetraRec ( n ) + " ▁ " ) ; } public static void main ( String [ ] args ) { int n = 10 ; printTetra ( n ) ; } }


"Tetranacci Numbers | A space optimized based Java program to print the nth tetranacci number ; Function to print the N - th tetranacci number ; Initialize first four numbers to base cases ; declare a current variable ; Loop to add previous four numbers for each number starting from 4 and then assign first , second , third to second , third , fourth and curr to fourth respectively ; Driver code"
Solution in Java:

import java . io . * ; import java . util . * ; import java . lang . * ; class GFG { static void printTetra ( int n ) { if ( n < 0 ) return ; int first = 0 , second = 1 ; int third = 1 , fourth = 2 ; int curr = 0 ; if ( n == 0 ) System . out . print ( first ) ; else if ( n == 1 n == 2 ) System . out . print ( second ) ; else if ( n == 3 ) System . out . print ( fourth ) ; else { for ( int i = 4 ; i <= n ; i ++ ) { curr = first + second + third + fourth ; first = second ; second = third ; third = fourth ; fourth = curr ; } System . out . print ( curr ) ; } } public static void main ( String [ ] args ) { int n = 10 ; printTetra ( n ) ; } }


"Third last digit in 5 ^ N for given N | Java implementation of the above approach ; Function to find the element ; if n < 3 ; If n is even return 6 If n is odd return 1 ; Driver code"
Solution in Java:

class GFG { static int findThirdDigit ( int n ) { if ( n < 3 ) return 0 ; return ( n & 1 ) > 0 ? 1 : 6 ; } public static void main ( String args [ ] ) { int n = 7 ; System . out . println ( findThirdDigit ( n ) ) ; } }


"Threaded Binary Search Tree | Deletion |  ; True if left pointer points to predecessor in Inorder Traversal ; True if right pointer points to predecessor in Inorder Traversal"
Solution in Java:

static class Node { Node left , right ; int info ; boolean lthread ; boolean rthread ; } ;


"Threaded Binary Search Tree | Deletion | Complete Java program to demonstrate deletion in threaded BST ; True if left pointer points to predecessor in Inorder Traversal ; True if right pointer points to predecessor in Inorder Traversal ; Insert a Node in Binary Threaded Tree ; Searching for a Node with given value ; Parent of key to be inserted ; If key already exists , return ; Update parent pointer ; Moving on left subtree . ; Moving on right subtree . ; Create a new Node ; Returns inorder successor using left and right children ( Used in deletion ) ; Returns inorder successor using rthread ( Used in inorder ) ; If rthread is set , we can quickly find ; Else return leftmost child of right subtree ; Printing the threaded tree ; Reach leftmost Node ; One by one print successors ; Here ' par ' is pointer to parent Node and ' ptr ' is pointer to current Node . ; If Node to be deleted is root ; If Node to be deleted is left of its parent ; Here ' par ' is pointer to parent Node and ' ptr ' is pointer to current Node . ; Initialize child Node to be deleted has left child . ; Node to be deleted has right child . ; Node to be deleted is root Node . ; Node is left child of its parent . ; Find successor and predecessor ; If ptr has left subtree . ; If ptr has right subtree . ; Here ' par ' is pointer to parent Node and ' ptr ' is pointer to current Node . ; Find inorder successor and its parent . ; Find leftmost child of successor ; Deletes a key from threaded BST with given root and returns new root of BST . ; Initialize parent as null and ptrent Node as root . ; Set true if key is found ; Search key in BST : find Node and its parent . ; Two Children ; Only Left Child ; Only Right Child ; No child ; Driver Program"
Solution in Java:

 import java . util . * ; class solution { static class Node { Node left , right ; int info ; boolean lthread ; boolean rthread ; } ; static Node insert ( Node root , int ikey ) { Node ptr = root ; Node par = null ; while ( ptr != null ) { if ( ikey == ( ptr . info ) ) { System . out . printf ( "Duplicate Key !
"); return root ; } par = ptr ; if ( ikey < ptr . info ) { if ( ptr . lthread == false ) ptr = ptr . left ; else break ; } else { if ( ptr . rthread == false ) ptr = ptr . right ; else break ; } } Node tmp = new Node ( ) ; tmp . info = ikey ; tmp . lthread = true ; tmp . rthread = true ; if ( par == null ) { root = tmp ; tmp . left = null ; tmp . right = null ; } else if ( ikey < ( par . info ) ) { tmp . left = par . left ; tmp . right = par ; par . lthread = false ; par . left = tmp ; } else { tmp . left = par ; tmp . right = par . right ; par . rthread = false ; par . right = tmp ; } return root ; } static Node inSucc ( Node ptr ) { if ( ptr . rthread == true ) return ptr . right ; ptr = ptr . right ; while ( ptr . lthread == false ) ptr = ptr . left ; return ptr ; } static Node inorderSuccessor ( Node ptr ) { if ( ptr . rthread == true ) return ptr . right ; ptr = ptr . right ; while ( ptr . lthread == false ) ptr = ptr . left ; return ptr ; } static void inorder ( Node root ) { if ( root == null ) System . out . printf ( " Tree ▁ is ▁ empty " ) ; Node ptr = root ; while ( ptr . lthread == false ) ptr = ptr . left ; while ( ptr != null ) { System . out . printf ( " % d ▁ " , ptr . info ) ; ptr = inorderSuccessor ( ptr ) ; } } static Node inPred ( Node ptr ) { if ( ptr . lthread == true ) return ptr . left ; ptr = ptr . left ; while ( ptr . rthread == false ) ptr = ptr . right ; return ptr ; } static Node caseA ( Node root , Node par , Node ptr ) { if ( par == null ) root = null ; else if ( ptr == par . left ) { par . lthread = true ; par . left = ptr . left ; } else { par . rthread = true ; par . right = ptr . right ; } return root ; } static Node caseB ( Node root , Node par , Node ptr ) { Node...


"Threaded Binary Search Tree | Deletion | Here ' par ' is pointer to parent Node and ' ptr ' is pointer to current Node . ; If Node to be deleted is root ; If Node to be deleted is left of its parent"
Solution in Java:

Node caseA ( Node root , Node par , Node ptr ) { if ( par == null ) root = null ; else if ( ptr == par . left ) { par . lthread = true ; par . left = ptr . left ; } else { par . rthread = true ; par . right = ptr . right ; } return root ; }


"Threaded Binary Search Tree | Deletion | Here ' par ' is pointer to parent Node and ' ptr ' is pointer to current Node . ; Initialize child Node to be deleted has left child . ; Node to be deleted has right child . ; Node to be deleted is root Node . ; Node is left child of its parent . ; Find successor and predecessor ; If ptr has left subtree . ; If ptr has right subtree ."
Solution in Java:

static Node caseB ( Node root , Node par , Node ptr ) { Node child ; if ( ptr . lthread == false ) child = ptr . left ; else child = ptr . right ; if ( par == null ) root = child ; else if ( ptr == par . left ) par . left = child ; else par . right = child ; Node s = inSucc ( ptr ) ; Node p = inPred ( ptr ) ; if ( ptr . lthread == false ) p . right = s ; else { if ( ptr . rthread == false ) s . left = p ; } return root ; }


"Threaded Binary Tree | Insertion | Java program Insertion in Threaded Binary Search Tree . ; True if left pointer points to predecessor in Inorder Traversal ; True if right pointer points to successor in Inorder Traversal ; Insert a Node in Binary Threaded Tree ; Searching for a Node with given value ; Parent of key to be inserted ; If key already exists , return ; Update parent pointer ; Moving on left subtree . ; Moving on right subtree . ; Create a new node ; Returns inorder successor using rthread ; If rthread is set , we can quickly find ; Else return leftmost child of right subtree ; Printing the threaded tree ; Reach leftmost node ; One by one print successors ; Driver Program"
Solution in Java:

 import java . util . * ; class solution { static class Node { Node left , right ; int info ; boolean lthread ; boolean rthread ; } ; static Node insert ( Node root , int ikey ) { Node ptr = root ; Node par = null ; while ( ptr != null ) { if ( ikey == ( ptr . info ) ) { System . out . printf ( "Duplicate Key !
"); return root ; } par = ptr ; if ( ikey < ptr . info ) { if ( ptr . lthread == false ) ptr = ptr . left ; else break ; } else { if ( ptr . rthread == false ) ptr = ptr . right ; else break ; } } Node tmp = new Node ( ) ; tmp . info = ikey ; tmp . lthread = true ; tmp . rthread = true ; if ( par == null ) { root = tmp ; tmp . left = null ; tmp . right = null ; } else if ( ikey < ( par . info ) ) { tmp . left = par . left ; tmp . right = par ; par . lthread = false ; par . left = tmp ; } else { tmp . left = par ; tmp . right = par . right ; par . rthread = false ; par . right = tmp ; } return root ; } static Node inorderSuccessor ( Node ptr ) { if ( ptr . rthread == true ) return ptr . right ; ptr = ptr . right ; while ( ptr . lthread == false ) ptr = ptr . left ; return ptr ; } static void inorder ( Node root ) { if ( root == null ) System . out . printf ( " Tree ▁ is ▁ empty " ) ; Node ptr = root ; while ( ptr . lthread == false ) ptr = ptr . left ; while ( ptr != null ) { System . out . printf ( " % d ▁ " , ptr . info ) ; ptr = inorderSuccessor ( ptr ) ; } } public static void main ( String [ ] args ) { Node root = null ; root = insert ( root , 20 ) ; root = insert ( root , 10 ) ; root = insert ( root , 30 ) ; root = insert ( root , 5 ) ; root = insert ( root , 16 ) ; root = insert ( root , 14 ) ; root = insert ( root , 17 ) ; root = insert ( root , 13 ) ; inorder ( root ) ; } }


"Toggling k | Java program to toogle k - th bit of a number ; main function"
Solution in Java:

class Toggle { static int toggleKthBit ( int n , int k ) { return ( n ^ ( 1 << ( k - 1 ) ) ) ; } public static void main ( String [ ] args ) { int n = 5 , k = 1 ; System . out . println ( toggleKthBit ( n , k ) ) ; } }


"Total character pairs from two strings , with equal number of set bits in their ascii value | Java implementation of the approach ; Function to return the count of valid pairs ; Default Initialise both arrays 0 Store frequency of number of set bits for s1 ; Store frequency of number of set bits for s2 ; Calculate total pairs ; Return the count of valid pairs ; Driver code"
Solution in Java:

class GFG { static int totalPairs ( String s1 , String s2 ) { int count = 0 ; int [ ] arr1 = new int [ 7 ] ; int [ ] arr2 = new int [ 7 ] ; for ( int i = 0 ; i < s1 . length ( ) ; i ++ ) { int set_bits = Integer . bitCount ( s1 . charAt ( i ) ) ; arr1 [ set_bits ] ++ ; } for ( int i = 0 ; i < s2 . length ( ) ; i ++ ) { int set_bits = Integer . bitCount ( s2 . charAt ( i ) ) ; arr2 [ set_bits ] ++ ; } for ( int i = 1 ; i <= 6 ; i ++ ) { count += ( arr1 [ i ] * arr2 [ i ] ) ; } return count ; } public static void main ( String [ ] args ) { String s1 = " geeks " ; String s2 = " forgeeks " ; System . out . println ( totalPairs ( s1 , s2 ) ) ; } }


"Total number of odd length palindrome sub | Java implementation of above approach ; Function to find the total palindromic odd length sub - sequences ; dp array to store the number of palindromic subsequences for 0 to i - 1 and j + 1 to n - 1 ; We will start with the largest distance between i and j ; For each len , we fix our i ; For this i we will find our j ; Base cases ; If the characters are equal then look for out of bound index ; We have only 1 way that is to just pick these characters ; If the characters are not equal ; Subtract it as we have counted it twice ; We have just 1 palindrome sequence of length 1 ; Else total ways would be sum of dp [ i - 1 ] [ i + 1 ] , that is number of palindrome sub - sequences from 1 to i - 1 + number of palindrome sub - sequences from i + 1 to n - 1 ; Driver code"
Solution in Java:

import java . util . * ; class GFG { static void solve ( char [ ] s ) { int n = s . length ; int [ ] [ ] dp = new int [ n ] [ n ] ; for ( int len = n - 1 ; len >= 0 ; -- len ) { for ( int i = 0 ; i + len < n ; ++ i ) { int j = i + len ; if ( i == 0 && j == n - 1 ) { if ( s [ i ] == s [ j ] ) dp [ i ] [ j ] = 2 ; else if ( s [ i ] != s [ j ] ) dp [ i ] [ j ] = 1 ; } else { if ( s [ i ] == s [ j ] ) { if ( i - 1 >= 0 ) { dp [ i ] [ j ] += dp [ i - 1 ] [ j ] ; } if ( j + 1 <= n - 1 ) { dp [ i ] [ j ] += dp [ i ] [ j + 1 ] ; } if ( i - 1 < 0 j + 1 >= n ) { dp [ i ] [ j ] += 1 ; } } else if ( s [ i ] != s [ j ] ) { if ( i - 1 >= 0 ) { dp [ i ] [ j ] += dp [ i - 1 ] [ j ] ; } if ( j + 1 <= n - 1 ) { dp [ i ] [ j ] += dp [ i ] [ j + 1 ] ; } if ( i - 1 >= 0 && j + 1 <= n - 1 ) { dp [ i ] [ j ] -= dp [ i - 1 ] [ j + 1 ] ; } } } } } Vector < Integer > ways = new Vector < > ( ) ; for ( int i = 0 ; i < n ; ++ i ) { if ( i == 0 i == n - 1 ) { ways . add ( 1 ) ; } else { int total = dp [ i - 1 ] [ i + 1 ] ; ways . add ( total ) ; } } for ( int i = 0 ; i < ways . size ( ) ; ++ i ) { System . out . print ( ways . get ( i ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { char [ ] s = " xyxyx " . toCharArray ( ) ; solve ( s ) ; } }


"Treasure and Cities | A memoization based program to find maximum treasure that can be collected . ; k is current index and col is previous color . ; if ( k == n ) base case ; check if color of this city is equal to prev visited city ; return max of both options ; Driver code"
Solution in Java:

import java . util . * ; class GFG { static int MAX = 1001 ; static int [ ] [ ] dp = new int [ MAX ] [ MAX ] ; static int MaxProfit ( int treasure [ ] , int color [ ] , int n , int k , int col , int A , int B ) { return dp [ k ] [ col ] = 0 ; if ( dp [ k ] [ col ] != - 1 ) return dp [ k ] [ col ] ; int sum = 0 ; if ( col == color [ k ] ) sum += Math . max ( A * treasure [ k ] + MaxProfit ( treasure , color , n , k + 1 , color [ k ] , A , B ) , MaxProfit ( treasure , color , n , k + 1 , col , A , B ) ) ; else sum += Math . max ( B * treasure [ k ] + MaxProfit ( treasure , color , n , k + 1 , color [ k ] , A , B ) , MaxProfit ( treasure , color , n , k + 1 , col , A , B ) ) ; return dp [ k ] [ col ] = sum ; } public static void main ( String [ ] args ) { int A = - 5 , B = 7 ; int treasure [ ] = { 4 , 8 , 2 , 9 } ; int color [ ] = { 2 , 2 , 6 , 2 } ; int n = color . length ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < MAX ; j ++ ) dp [ i ] [ j ] = - 1 ; System . out . print ( MaxProfit ( treasure , color , n , 0 , 0 , A , B ) ) ; } }


"Treasure and Cities | k is current index and col is previous color . ; base case ; check if color of this city is equal to prev visited city ; return max of both options ; Driver code ; Initially begin with color 0"
Solution in Java:

class GFG { static int MaxProfit ( int treasure [ ] , int color [ ] , int n , int k , int col , int A , int B ) { int sum = 0 ; if ( k == n ) return 0 ; if ( col == color [ k ] ) sum += Math . max ( A * treasure [ k ] + MaxProfit ( treasure , color , n , k + 1 , color [ k ] , A , B ) , MaxProfit ( treasure , color , n , k + 1 , col , A , B ) ) ; else sum += Math . max ( B * treasure [ k ] + MaxProfit ( treasure , color , n , k + 1 , color [ k ] , A , B ) , MaxProfit ( treasure , color , n , k + 1 , col , A , B ) ) ; return sum ; } public static void main ( String [ ] args ) { int A = - 5 , B = 7 ; int treasure [ ] = { 4 , 8 , 2 , 9 } ; int color [ ] = { 2 , 2 , 6 , 2 } ; int n = color . length ; System . out . print ( MaxProfit ( treasure , color , n , 0 , 0 , A , B ) ) ; } }


"Tridecagonal Number | Java program to find N - th tridecagonal number ; Function to find N - th tridecagonal number ; Formula to calculate nth tridecagonal number ; Driver Code"
Solution in Java:

 class GFG { static int Tridecagonal_num ( int n ) { return ( 11 * n * n - 9 * n ) / 2 ; } public static void main ( String [ ] args ) { int n = 3 ; System . out . print ( Tridecagonal_num ( n ) + "
"); n = 10 ; System . out . print ( Tridecagonal_num ( n ) + "
"); } }


"Turn off the rightmost set bit | Set 2 | Java program to unset the rightmost set bit ; Unsets the rightmost set bit of n and returns the result ; Checking whether bit position is set or not ; If bit position is found set , we flip this bit by xoring given number and number with bit position set ; Driver code"
Solution in Java:

import java . util . * ; class GFG { static void FlipBits ( int n ) { for ( int bit = 0 ; bit < 32 ; bit ++ ) { if ( ( n >> bit ) % 2 > 0 ) { n = n ^ ( 1 << bit ) ; break ; } } System . out . print ( " The ▁ number ▁ after ▁ unsetting ▁ the " ) ; System . out . print ( " ▁ rightmost ▁ set ▁ bit ▁ " + n ) ; } public static void main ( String [ ] args ) { int N = 12 ; FlipBits ( N ) ; } }


"Turn off the rightmost set bit | Set 2 | Java program to unset the rightmost set bit ; Unsets the rightmost set bit of n and returns the result ; Driver Code"
Solution in Java:

import java . util . * ; class GFG { static int FlipBits ( int n ) { return n -= ( n & ( - n ) ) ; } public static void main ( String [ ] args ) { int N = 12 ; System . out . print ( " The ▁ number ▁ after ▁ unsetting ▁ the ▁ " ) ; System . out . print ( " rightmost ▁ set ▁ bit : ▁ " + FlipBits ( N ) ) ; } }


"Wasteful Numbers | Java program for the above approach ; Array to store all prime less than and equal to MAX . ; Function for Sieve of Sundaram ; Boolean Array ; Mark all numbers which do not generate prime number by 2 * i + 1 ; Since 2 is a prime number ; Print remaining primes are of the form 2 * i + 1 such that marked [ i ] is false . ; Function that returns true if n is a Wasteful number ; Count digits in original number ; Count all digits in prime factors of N pDigit is going to hold this value . ; Count powers of p in n ; If primes [ i ] is a prime factor , ; Count the power of prime factors ; Add its digits to pDigit ; Add digits of power of prime factors to pDigit . ; If n != 1 then one prime factor still to be summed up ; If digits in prime factors is more than digits in original number then return true . Else return false . ; Function to print Wasteful Number before N ; Iterate till N and check if i is wastefull or not ; Driver code ; Precompute prime numbers upto 10 ^ 6 ; Function Call"
Solution in Java:

import java . util . * ; class GFG { static int MAX = 10000 ; static Vector < Integer > primes = new Vector < Integer > ( ) ; static void sieveSundaram ( ) { boolean marked [ ] = new boolean [ MAX / 2 + 1 ] ; for ( int i = 1 ; i <= ( Math . sqrt ( MAX ) - 1 ) / 2 ; i ++ ) { for ( int j = ( i * ( i + 1 ) ) << 1 ; j <= MAX / 2 ; j = j + 2 * i + 1 ) { marked [ j ] = true ; } } primes . add ( 2 ) ; for ( int i = 1 ; i <= MAX / 2 ; i ++ ) if ( marked [ i ] == false ) primes . add ( 2 * i + 1 ) ; } static boolean isWasteful ( int n ) { if ( n == 1 ) return false ; int original_no = n ; int sumDigits = 0 ; while ( original_no > 0 ) { sumDigits ++ ; original_no = original_no / 10 ; } int pDigit = 0 , count_exp = 0 , p = 0 ; for ( int i = 0 ; primes . get ( i ) <= n / 2 ; i ++ ) { while ( n % primes . get ( i ) == 0 ) { p = primes . get ( i ) ; n = n / p ; count_exp ++ ; } while ( p > 0 ) { pDigit ++ ; p = p / 10 ; } while ( count_exp > 1 ) { pDigit ++ ; count_exp = count_exp / 10 ; } } if ( n != 1 ) { while ( n > 0 ) { pDigit ++ ; n = n / 10 ; } } return ( pDigit > sumDigits ) ; } static void Solve ( int N ) { for ( int i = 1 ; i < N ; i ++ ) { if ( isWasteful ( i ) ) { System . out . print ( i + " ▁ " ) ; } } } public static void main ( String [ ] args ) { sieveSundaram ( ) ; int N = 10 ; Solve ( N ) ; } }


"Ways to split array into two groups of same XOR value | Java Program to count number of ways to split array into two groups such that each group has equal XOR value ; Return the count number of ways to split array into two groups such that each group has equal XOR value . ; We can split only if XOR is 0. Since XOR of all is 0 , we can consider all subsets as one group . ; Driver program"
Solution in Java:

import java . io . * ; import java . util . * ; class GFG { static int countgroup ( int a [ ] , int n ) { int xs = 0 ; for ( int i = 0 ; i < n ; i ++ ) xs = xs ^ a [ i ] ; if ( xs == 0 ) return ( 1 << ( n - 1 ) ) - 1 ; return 0 ; } public static void main ( String args [ ] ) { int a [ ] = { 1 , 2 , 3 } ; int n = a . length ; System . out . println ( countgroup ( a , n ) ) ; } }


"Write a program to calculate pow ( x , n ) |  ; Function to calculate x raised to the power y ; Program to test function power"
Solution in Java:

class GFG { static int power ( int x , int y ) { if ( y == 0 ) return 1 ; else if ( y % 2 == 0 ) return power ( x , y / 2 ) * power ( x , y / 2 ) ; else return x * power ( x , y / 2 ) * power ( x , y / 2 ) ; } public static void main ( String [ ] args ) { int x = 2 ; int y = 3 ; System . out . printf ( " % d " , power ( x , y ) ) ; } }


"Write a program to calculate pow ( x , n ) | Function to calculate x raised to the power y in O ( logn )"
Solution in Java:

static int power ( int x , int y ) { int temp ; if ( y == 0 ) return 1 ; temp = power ( x , y / 2 ) ; if ( y % 2 == 0 ) return temp * temp ; else return x * temp * temp ; }


"Write a program to calculate pow ( x , n ) | Java code for extended version of power function that can work for float x and negative y ; Program to test function power"
Solution in Java:

class GFG { static float power ( float x , int y ) { float temp ; if ( y == 0 ) return 1 ; temp = power ( x , y / 2 ) ; if ( y % 2 == 0 ) return temp * temp ; else { if ( y > 0 ) return x * temp * temp ; else return ( temp * temp ) / x ; } } public static void main ( String [ ] args ) { float x = 2 ; int y = - 3 ; System . out . printf ( " % f " , power ( x , y ) ) ; } }


"Write a program to calculate pow ( x , n ) | Java program for the above approach ; If x ^ 0 return 1 ; If we need to find of 0 ^ y ; For all other cases ; Driver Code"
Solution in Java:

import java . io . * ; class GFG { public static int power ( int x , int y ) { if ( y == 0 ) return 1 ; if ( x == 0 ) return 0 ; return x * power ( x , y - 1 ) ; } public static void main ( String [ ] args ) { int x = 2 ; int y = 3 ; System . out . println ( power ( x , y ) ) ; } }


"Write a program to calculate pow ( x , n ) | Java program for the above approach ; Math . pow ( ) is a function that return floating number ; Driver Code"
Solution in Java:

import java . io . * ; class GFG { public static int power ( int x , int y ) { return ( int ) Math . pow ( x , y ) ; } public static void main ( String [ ] args ) { int x = 2 ; int y = 3 ; System . out . println ( power ( x , y ) ) ; } }


"d | Java program to find the size of the minimum dominating set of the tree ; Definition of a tree node ; Helper function that allocates a new node ; DP array to precompute and store the results ; minDominatingSettion to return the size of the minimum dominating set of the array ; Base case ; Setting the compulsory value if needed ; Check if the answer is already computed ; If it is compulsory to select the node ; Choose the node and set its children as covered ; If it is covered ; If the current node is neither covered nor needs to be selected compulsorily ; Store the result ; Driver code ; Initialising the DP array ; Constructing the tree"
Solution in Java:

import java . util . * ; class GFG { static final int N = 1005 ; static class Node { int data ; Node left , right ; } ; static Node newNode ( int data ) { Node node = new Node ( ) ; node . data = data ; node . left = node . right = null ; return node ; } static int [ ] [ ] [ ] dp = new int [ N ] [ 5 ] [ 5 ] ; static int minDominatingSet ( Node root , int covered , int compulsory ) { if ( root == null ) return 0 ; if ( root . left != null && root . right != null && covered > 0 ) compulsory = 1 ; if ( dp [ root . data ] [ covered ] [ compulsory ] != - 1 ) return dp [ root . data ] [ covered ] [ compulsory ] ; if ( compulsory > 0 ) { return dp [ root . data ] [ covered ] [ compulsory ] = 1 + minDominatingSet ( root . left , 1 , 0 ) + minDominatingSet ( root . right , 1 , 0 ) ; } if ( covered > 0 ) { return dp [ root . data ] [ covered ] [ compulsory ] = Math . min ( 1 + minDominatingSet ( root . left , 1 , 0 ) + minDominatingSet ( root . right , 1 , 0 ) , minDominatingSet ( root . left , 0 , 0 ) + minDominatingSet ( root . right , 0 , 0 ) ) ; } int ans = 1 + minDominatingSet ( root . left , 1 , 0 ) + minDominatingSet ( root . right , 1 , 0 ) ; if ( root . left != null ) { ans = Math . min ( ans , minDominatingSet ( root . left , 0 , 1 ) + minDominatingSet ( root . right , 0 , 0 ) ) ; } if ( root . right != null ) { ans = Math . min ( ans , minDominatingSet ( root . left , 0 , 0 ) + minDominatingSet ( root . right , 0 , 1 ) ) ; } return dp [ root . data ] [ covered ] [ compulsory ] = ans ; } public static void main ( String [ ] args ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < 5 ; j ++ ) { for ( int l = 0 ; l < 5 ; l ++ ) dp [ i ] [ j ] [ l ] = - 1 ; } } Node root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . left . left = newNode ( 3 ) ; root . left . right = newNode ( 4 ) ; root . left . left . left = newNode ( 5 ) ; root . left . left . left . left = newNode ( 6 ) ; root . left . left . left . right = newNode ( 7 ) ; root . left . left . left . right . right = newNode ( 10 ) ; root ....


"k | JAVA Program to print kth prime factor ; A function to generate prime factors of a given number n and return k - th prime factor ; Find the number of 2 's that  divide k ; n must be odd at this point . So we can skip one element ( Note i = i + 2 ) ; While i divides n , store i and divide n ; This condition is to handle the case where n is a prime number greater than 2 ; Driver Program"
Solution in Java:

import java . io . * ; import java . math . * ; class GFG { static int kPrimeFactor ( int n , int k ) { while ( n % 2 == 0 ) { k -- ; n = n / 2 ; if ( k == 0 ) return 2 ; } for ( int i = 3 ; i <= Math . sqrt ( n ) ; i = i + 2 ) { while ( n % i == 0 ) { if ( k == 1 ) return i ; k -- ; n = n / i ; } } if ( n > 2 && k == 1 ) return n ; return - 1 ; } public static void main ( String args [ ] ) { int n = 12 , k = 3 ; System . out . println ( kPrimeFactor ( n , k ) ) ; n = 14 ; k = 3 ; System . out . println ( kPrimeFactor ( n , k ) ) ; } }


"k | Java implementation of the above approach ; Function to find the sum of minimum of all subarrays ; Insert all the elements in a set ; Find the maximum and minimum element ; Traverse from the minimum to maximum element ; Check if " i " is missing ; Check if it is kth missing ; If no kth element is missing ; Driver code"
Solution in Java:

import java . util . * ; class GFG { static int findKth ( int arr [ ] , int n , int k ) { HashSet < Integer > missing = new HashSet < > ( ) ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { missing . add ( arr [ i ] ) ; } int maxm = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; int minm = Arrays . stream ( arr ) . min ( ) . getAsInt ( ) ; for ( int i = minm + 1 ; i < maxm ; i ++ ) { if ( ! missing . contains ( i ) ) { count ++ ; } if ( count == k ) { return i ; } } return - 1 ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 10 , 9 , 4 } ; int n = arr . length ; int k = 5 ; System . out . println ( findKth ( arr , n , k ) ) ; } }


"k | Java program for above approach ; Function to find kth missing number ; If the total missing number count is equal to k we can iterate backwards for the first missing number and that will be the answer . ; To further optimize we check if the previous element ' s ▁ ▁ missing ▁ number ▁ count ▁ is ▁ equal ▁ ▁ to ▁ k . ▁ Eg : ▁ arr ▁ = ▁ [ 4,5,6,7,8 ] ▁ ▁ If ▁ you ▁ observe ▁ in ▁ the ▁ example ▁ array , ▁ ▁ the ▁ total ▁ count ▁ of ▁ missing ▁ numbers ▁ for ▁ all ▁ ▁ the ▁ indices ▁ are ▁ same , ▁ and ▁ we ▁ are ▁ ▁ aiming ▁ to ▁ narrow ▁ down ▁ the ▁ ▁ search ▁ window ▁ and ▁ achieve ▁ O ( logn ) ▁ ▁ time ▁ complexity ▁ which ▁ ▁ otherwise ▁ would ' ve been O ( n ) . ; Else we return arr [ mid ] - 1. ; Here we appropriately narrow down the search window . ; In case the upper limit is - ve it means the missing number set is 1 , 2 , . . , k and hence we directly return k . ; Else we find the residual count of numbers which we 'd then add to  arr[u] and get the missing kth number. ; Return arr [ u ] + k ; Driver code ; Function Call"
Solution in Java:

public class GFG { static int missingK ( int [ ] arr , int k ) { int n = arr . length ; int l = 0 , u = n - 1 , mid ; while ( l <= u ) { mid = ( l + u ) / 2 ; int numbers_less_than_mid = arr [ mid ] - ( mid + 1 ) ; if ( numbers_less_than_mid == k ) { if ( mid > 0 && ( arr [ mid - 1 ] - ( mid ) ) == k ) { u = mid - 1 ; continue ; } return arr [ mid ] - 1 ; } if ( numbers_less_than_mid < k ) { l = mid + 1 ; } else if ( k < numbers_less_than_mid ) { u = mid - 1 ; } } if ( u < 0 ) return k ; int less = arr [ u ] - ( u + 1 ) ; k -= less ; return arr [ u ] + k ; } public static void main ( String [ ] args ) { int [ ] arr = { 2 , 3 , 4 , 7 , 11 } ; int k = 5 ; System . out . println ( " Missing ▁ kth ▁ number ▁ = ▁ " + missingK ( arr , k ) ) ; } }


"k | Java program to check for even or odd ; Function to find k - th missing element ; interating over the array ; check if i - th and ( i + 1 ) - th element are not consecutive ; save their difference ; check for difference and given k ; if found ; Driver code ; Input array ; k - th missing element to be found in the array ; calling function to find missing element"
Solution in Java:

import java . io . * ; import java . util . * ; public class GFG { static int missingK ( int [ ] a , int k , int n ) { int difference = 0 , ans = 0 , count = k ; boolean flag = false ; for ( int i = 0 ; i < n - 1 ; i ++ ) { difference = 0 ; if ( ( a [ i ] + 1 ) != a [ i + 1 ] ) { difference += ( a [ i + 1 ] - a [ i ] ) - 1 ; if ( difference >= count ) { ans = a [ i ] + count ; flag = true ; break ; } else count -= difference ; } } if ( flag ) return ans ; else return - 1 ; } public static void main ( String args [ ] ) { int [ ] a = { 1 , 5 , 11 , 19 } ; int k = 11 ; int n = a . length ; int missing = missingK ( a , k , n ) ; System . out . print ( missing ) ; } }


"k | Java program to find k - th absolute difference between two elements ; returns number of pairs with absolute difference less than or equal to mid ; Upper bound returns pointer to position of next higher number than a [ i ] + mid in a [ i . . n - 1 ] . We subtract ( ub + i + 1 ) from this position to count ; returns the upper bound ; Returns k - th absolute difference ; Sort array ; Minimum absolute difference ; Maximum absolute difference ; Do binary search for k - th absolute difference ; Driver function to check the above functions"
Solution in Java:

import java . util . Scanner ; import java . util . Arrays ; class GFG { static int countPairs ( int [ ] a , int n , int mid ) { int res = 0 , value ; for ( int i = 0 ; i < n ; i ++ ) { int ub = upperbound ( a , n , a [ i ] + mid ) ; res += ( ub - ( i - 1 ) ) ; } return res ; } static int upperbound ( int a [ ] , int n , int value ) { int low = 0 ; int high = n ; while ( low < high ) { final int mid = ( low + high ) / 2 ; if ( value >= a [ mid ] ) low = mid + 1 ; else high = mid ; } return low ; } static int kthDiff ( int a [ ] , int n , int k ) { Arrays . sort ( a ) ; int low = a [ 1 ] - a [ 0 ] ; for ( int i = 1 ; i <= n - 2 ; ++ i ) low = Math . min ( low , a [ i + 1 ] - a [ i ] ) ; int high = a [ n - 1 ] - a [ 0 ] ; while ( low < high ) { int mid = ( low + high ) >> 1 ; if ( countPairs ( a , n , mid ) < k ) low = mid + 1 ; else high = mid ; } return low ; } public static void main ( String args [ ] ) { Scanner s = new Scanner ( System . in ) ; int k = 3 ; int a [ ] = { 1 , 2 , 3 , 4 } ; int n = a . length ; System . out . println ( kthDiff ( a , n , k ) ) ; } }


"k | Java program to find k - th element in the Odd - Even sequence . ; insert all the odd numbers from 1 to n . ; insert all the even numbers from 1 to n . ; Driver code"
Solution in Java:

import java . util . * ; class GFG { static int findK ( int n , int k ) { ArrayList < Integer > a = new ArrayList < Integer > ( n ) ; for ( int i = 1 ; i < n ; i ++ ) if ( i % 2 == 1 ) a . add ( i ) ; for ( int i = 1 ; i < n ; i ++ ) if ( i % 2 == 0 ) a . add ( i ) ; return ( a . get ( k - 1 ) ) ; } public static void main ( String [ ] args ) { int n = 10 , k = 3 ; System . out . println ( findK ( n , k ) ) ; } }


"k | Java program to find k - th prime factor using Sieve Of Eratosthenes . This program is efficient when we have a range of numbers . ; Using SieveOfEratosthenes to find smallest prime factor of all the numbers . For example , if MAX is 10 , s [ 2 ] = s [ 4 ] = s [ 6 ] = s [ 10 ] = 2 s [ 3 ] = s [ 9 ] = 3 s [ 5 ] = 5 s [ 7 ] = 7 ; Create a boolean array " prime [ 0 . . MAX ] " and initialize all entries in it as false . ; Initializing smallest factor equal to 2 for all the even numbers ; For odd numbers less then equal to n ; s ( i ) for a prime is the number itself ; For all multiples of current prime number ; i is the smallest prime factor for number " i * j " . ; Function to generate prime factors and return its k - th prime factor . s [ i ] stores least prime factor of i . ; Keep dividing n by least prime factor while either n is not 1 or count of prime factors is not k . ; To keep track of count of prime factors ; Divide n to find next prime factor ; Driver code ; s [ i ] is going to store prime factor of i ."
Solution in Java:

class GFG { static int MAX = 10001 ; static void sieveOfEratosthenes ( int [ ] s ) { boolean [ ] prime = new boolean [ MAX + 1 ] ; for ( int i = 2 ; i <= MAX ; i += 2 ) s [ i ] = 2 ; for ( int i = 3 ; i <= MAX ; i += 2 ) { if ( prime [ i ] == false ) { s [ i ] = i ; for ( int j = i ; j * i <= MAX ; j += 2 ) { if ( prime [ i * j ] == false ) { prime [ i * j ] = true ; s [ i * j ] = i ; } } } } } static int kPrimeFactor ( int n , int k , int [ ] s ) { while ( n > 1 ) { if ( k == 1 ) return s [ n ] ; k -- ; n /= s [ n ] ; } return - 1 ; } public static void main ( String [ ] args ) { int [ ] s = new int [ MAX + 1 ] ; sieveOfEratosthenes ( s ) ; int n = 12 , k = 3 ; System . out . println ( kPrimeFactor ( n , k , s ) ) ; n = 14 ; k = 3 ; System . out . println ( kPrimeFactor ( n , k , s ) ) ; } }


"k | Java program to find the k - th missing element in a given sequence ; Returns k - th missing element . It returns - 1 if no k is more than number of missing elements . ; Insert all elements of givens sequence b [ ] . ; Traverse through increasing sequence and keep track of count of missing numbers . ; Driver code"
Solution in Java:

import java . util . * ; class GFG { static int find ( int a [ ] , int b [ ] , int k , int n1 , int n2 ) { LinkedHashSet < Integer > s = new LinkedHashSet < > ( ) ; for ( int i = 0 ; i < n2 ; i ++ ) s . add ( b [ i ] ) ; int missing = 0 ; for ( int i = 0 ; i < n1 ; i ++ ) { if ( ! s . contains ( a [ i ] ) ) missing ++ ; if ( missing == k ) return a [ i ] ; } return - 1 ; } public static void main ( String [ ] args ) { int a [ ] = { 0 , 2 , 4 , 6 , 8 , 10 , 12 , 14 , 15 } ; int b [ ] = { 4 , 10 , 6 , 8 , 12 } ; int n1 = a . length ; int n2 = b . length ; int k = 3 ; System . out . println ( find ( a , b , k , n1 , n2 ) ) ; } }


"k | Java program to print k - th distinct element in a given array ; Returns k - th distinct element in arr . ; Check if current element is present somewhere else . ; If element is unique ; Driver code"
Solution in Java:

class GFG { static int printKDistinct ( int arr [ ] , int n , int k ) { int dist_count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int j ; for ( j = 0 ; j < n ; j ++ ) if ( i != j && arr [ j ] == arr [ i ] ) break ; if ( j == n ) dist_count ++ ; if ( dist_count == k ) return arr [ i ] ; } return - 1 ; } public static void main ( String [ ] args ) { int ar [ ] = { 1 , 2 , 1 , 3 , 4 , 2 } ; int n = ar . length ; int k = 2 ; System . out . print ( printKDistinct ( ar , n , k ) ) ; } }