"Subset with sum closest to zero | Java Program for above approach ; Variable to store states of dp ; Function to return the number closer to integer s ; To find the sum closest to zero Since sum can be negative , we will add MAX to it to make it positive ; Base cases ; Checks if a state is already solved ; Recurrence relation ; Returning the value ; Function to calculate the closest sum value ; Calculate the Closest value for every subarray arr [ i - 1 : n ] ; Driver Code ; Input array"
How can the above be solved in Java?

import java . io . * ; class GFG { static int arrSize = 51 ; static int maxSum = 201 ; static int MAX = 100 ; static int inf = 999999 ; static int dp [ ] [ ] = new int [ arrSize ] [ maxSum ] ; static int visit [ ] [ ] = new int [ arrSize ] [ maxSum ] ; static int RetClose ( int a , int b , int s ) { if ( Math . abs ( a - s ) < Math . abs ( b - s ) ) return a ; else return b ; } static int MinDiff ( int i , int sum , int arr [ ] , int n ) { if ( i == n ) return 0 ; if ( visit [ i ] [ sum + MAX ] > 0 ) return dp [ i ] [ sum + MAX ] ; visit [ i ] [ sum + MAX ] = 1 ; dp [ i ] [ sum + MAX ] = RetClose ( arr [ i ] + MinDiff ( i + 1 , sum + arr [ i ] , arr , n ) , MinDiff ( i + 1 , sum , arr , n ) , - 1 * sum ) ; return dp [ i ] [ sum + MAX ] ; } static void FindClose ( int arr [ ] , int n ) { int ans = inf ; for ( int i = 1 ; i <= n ; i ++ ) ans = RetClose ( arr [ i - 1 ] + MinDiff ( i , arr [ i - 1 ] , arr , n ) , ans , 0 ) ; System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 25 , - 9 , - 10 , - 4 , - 7 , - 33 } ; int n = arr . length ; FindClose ( arr , n ) ; } }


"Subset with sum divisible by m | Java program to check if there is a subset with sum divisible by m . ; Returns true if there is a subset of arr [ ] with sum divisible by m ; This array will keep track of all the possible sum ( after modulo m ) which can be made using subsets of arr [ ] initialising boolean array with all false ; we 'll loop through all the elements  of arr[] ; anytime we encounter a sum divisible by m , we are done ; To store all the new encountered sum ( after modulo ) . It is used to make sure that arr [ i ] is added only to those entries for which DP [ j ] was true before current iteration . ; For each element of arr [ ] , we loop through all elements of DP table from 1 to m and we add current element i . e . , arr [ i ] to all those elements which are true in DP table ; if an element is true in DP table ; We update it in temp and update to DP once loop of j is over ; Updating all the elements of temp to DP table since iteration over j is over ; Also since arr [ i ] is a single element subset , arr [ i ] % m is one of the possible sum ; driver code"
How can the above be solved in Java?

 import java . util . Arrays ; class GFG { static boolean modularSum ( int arr [ ] , int n , int m ) { if ( n > m ) return true ; boolean DP [ ] = new boolean [ m ] ; Arrays . fill ( DP , false ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( DP [ 0 ] ) return true ; boolean temp [ ] = new boolean [ m ] ; Arrays . fill ( temp , false ) ; for ( int j = 0 ; j < m ; j ++ ) { if ( DP [ j ] == true ) { if ( DP [ ( j + arr [ i ] ) % m ] == false ) temp [ ( j + arr [ i ] ) % m ] = true ; } } for ( int j = 0 ; j < m ; j ++ ) if ( temp [ j ] ) DP [ j ] = true ; DP [ arr [ i ] % m ] = true ; } return DP [ 0 ] ; } public static void main ( String arg [ ] ) { int arr [ ] = { 1 , 7 } ; int n = arr . length ; int m = 5 ; if ( modularSum ( arr , n , m ) ) System . out . print ( "YES
"); else System . out . print ( "NO
"); } }


"Substring Reverse Pattern | Java program to print the required pattern ; Function to print the required pattern ; Print the unmodified string ; Reverse the string ; Replace the first and last character by ' * ' then second and second last character and so on until the string has characters remaining ; Driver Code"
How can the above be solved in Java?

class GFG { static void printPattern ( char [ ] s , int n ) { System . out . println ( s ) ; int i = 0 , j = n - 1 ; while ( i < j ) { char c = s [ i ] ; s [ i ] = s [ j ] ; s [ j ] = c ; i ++ ; j -- ; } i = 0 ; j = n - 1 ; while ( j - i > 1 ) { s [ i ] = s [ j ] = ' * ' ; System . out . println ( s ) ; i ++ ; j -- ; } } public static void main ( String [ ] args ) { char [ ] s = " geeks " . toCharArray ( ) ; int n = s . length ; printPattern ( s , n ) ; } }


"Substring Sort | Alternative code to sort substrings ; sort the input array ; repeated length should be the same string ; two different strings with the same length input array cannot be sorted ; validate that each string is a substring of the following one ; get first element ; The array is valid and sorted print the strings in order ; Test 1 ; Test 2"
How can the above be solved in Java?

import java . util . Arrays ; public class Demo { public static void substringSort ( String [ ] arr , int n , int maxLen ) { int count [ ] = new int [ maxLen ] ; String [ ] sortedArr = new String [ maxLen ] ; Arrays . fill ( count , 0 ) ; Arrays . fill ( sortedArr , " " ) ; for ( int i = 0 ; i < n ; i ++ ) { String s = arr [ i ] ; int len = s . length ( ) ; if ( count [ len - 1 ] == 0 ) { sortedArr [ len - 1 ] = s ; count [ len - 1 ] = 1 ; } else if ( sortedArr [ len - 1 ] . equals ( s ) ) { count [ len - 1 ] ++ ; } else { System . out . println ( " Cannot ▁ be ▁ sorted " ) ; return ; } } int index = 0 ; while ( count [ index ] == 0 ) index ++ ; int prev = index ; String prevString = sortedArr [ prev ] ; index ++ ; for ( ; index < maxLen ; index ++ ) { if ( count [ index ] != 0 ) { String current = sortedArr [ index ] ; if ( current . contains ( prevString ) ) { prev = index ; prevString = current ; } else { System . out . println ( " Cannot ▁ be ▁ sorted " ) ; return ; } } } for ( int i = 0 ; i < maxLen ; i ++ ) { String s = sortedArr [ i ] ; for ( int j = 0 ; j < count [ i ] ; j ++ ) { System . out . println ( s ) ; } } } public static void main ( String [ ] args ) { int maxLen = 100 ; String [ ] arr1 = { " d " , " zddsaaz " , " ds " , " ddsaa " , " dds " , " dds " } ; substringSort ( arr1 , arr1 . length , maxLen ) ; String [ ] arr2 = { " for " , " rof " } ; substringSort ( arr2 , arr2 . length , maxLen ) ; } }


"Substrings starting with vowel and ending with consonants and vice versa | Java program to count special strings ; Returns true if ch is vowel ; function to check consonant ; in case of empty string , we can 't fullfill the  required condition, hence we return ans as 0. ; co [ i ] is going to store counts of consonants from str [ len - 1 ] to str [ i ] . vo [ i ] is going to store counts of vowels from str [ len - 1 ] to str [ i ] . ; Counting consonants and vowels from end of string . ; Now we traverse string from beginning ; If vowel , then count of substrings starting with str [ i ] is equal to count of consonants after it . ; If consonant , then count of substrings starting with str [ i ] is equal to count of vowels after it . ; Driver program"
How can the above be solved in Java?

class GfG { static boolean isVowel ( char ch ) { return ( ch == ' a ' ch == ' e ' ch == ' i ' ch == ' o ' ch == ' u ' ) ; } static boolean isCons ( char ch ) { return ( ch != ' a ' && ch != ' e ' && ch != ' i ' && ch != ' o ' && ch != ' u ' ) ; } static int countSpecial ( char [ ] str ) { int len = str . length ; if ( len == 0 ) return 0 ; int co [ ] = new int [ len + 1 ] ; int vo [ ] = new int [ len + 1 ] ; if ( isCons ( str [ len - 1 ] ) == true ) co [ len - 1 ] = 1 ; else vo [ len - 1 ] = 1 ; for ( int i = len - 2 ; i >= 0 ; i -- ) { if ( isCons ( str [ i ] ) == true ) { co [ i ] = co [ i + 1 ] + 1 ; vo [ i ] = vo [ i + 1 ] ; } else { co [ i ] = co [ i + 1 ] ; vo [ i ] = vo [ i + 1 ] + 1 ; } } long ans = 0 ; for ( int i = 0 ; i < len ; i ++ ) { if ( isVowel ( str [ i ] ) ) ans = ans + co [ i + 1 ] ; else ans = ans + vo [ i + 1 ] ; } return ( int ) ans ; } public static void main ( String [ ] args ) { String str = " adceba " ; System . out . println ( countSpecial ( str . toCharArray ( ) ) ) ; } }


"Subtraction in the Array | Java implementation of the approach ; Function to perform the given operation on arr [ ] ; Skip elements which are 0 ; Pick smallest non - zero element ; If all the elements of arr [ ] are 0 ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void operations ( int arr [ ] , int n , int k ) { Arrays . sort ( arr ) ; int i = 0 , sum = 0 ; while ( k -- > 0 ) { while ( i < n && arr [ i ] - sum == 0 ) i ++ ; if ( i < n && arr [ i ] - sum > 0 ) { System . out . print ( arr [ i ] - sum + " ▁ " ) ; sum = arr [ i ] ; } else System . out . println ( "0" ) ; } } public static void main ( String args [ ] ) { int k = 5 ; int arr [ ] = { 3 , 6 , 4 , 2 } ; int n = arr . length ; operations ( arr , n , k ) ; } }


"Succinct Encoding of Binary Tree | Java program to demonstrate Succinct Tree Encoding and decoding ; A Binary Tree Node ; Utility function to create new Node ; This function fills lists ' struc ' and ' data ' . ' struc ' list stores structure information . ' data ' list stores tree data ; If root is null , put 0 in structure array and return ; Else place 1 in structure array , key in ' data ' array and recur for left and right children ; Constructs tree from ' struc ' and ' data ' ; Remove one item from structure list ; If removed bit is 1 , ; Remove an item from data list ; Create a tree node with the removed data ; And recur to create left and right subtrees ; A utility function to print tree ; Driver code ; Let us conthe Tree shown in the above figure ; Structure iterator ; Data iterator"
How can the above be solved in Java?

 import java . util . * ; class GFG { static class Node { int key ; Node left , right ; } ; static Node newNode ( int key ) { Node temp = new Node ( ) ; temp . key = key ; temp . left = temp . right = null ; return ( temp ) ; } static Vector < Boolean > struc ; static Vector < Integer > data ; static Node root ; static void EncodeSuccinct ( Node root ) { if ( root == null ) { struc . add ( false ) ; return ; } struc . add ( true ) ; data . add ( root . key ) ; EncodeSuccinct ( root . left ) ; EncodeSuccinct ( root . right ) ; } static Node DecodeSuccinct ( ) { if ( struc . size ( ) <= 0 ) return null ; boolean b = struc . get ( 0 ) ; struc . remove ( 0 ) ; if ( b == true ) { int key = data . get ( 0 ) ; data . remove ( 0 ) ; Node root = newNode ( key ) ; root . left = DecodeSuccinct ( ) ; root . right = DecodeSuccinct ( ) ; return root ; } return null ; } static void preorder ( Node root ) { if ( root != null ) { System . out . print ( " key : ▁ " + root . key ) ; if ( root . left != null ) System . out . print ( " ▁ left ▁ child : ▁ " + root . left . key ) ; if ( root . right != null ) System . out . print ( " ▁ right ▁ child : ▁ " + root . right . key ) ; System . out . println ( ) ; preorder ( root . left ) ; preorder ( root . right ) ; } } public static void main ( String [ ] args ) { Node root = newNode ( 10 ) ; root . left = newNode ( 20 ) ; root . right = newNode ( 30 ) ; root . left . left = newNode ( 40 ) ; root . left . right = newNode ( 50 ) ; root . right . right = newNode ( 70 ) ; System . out . print ( "Given Tree
"); preorder ( root ) ; struc = new Vector < > ( ) ; data = new Vector < > ( ) ; EncodeSuccinct ( root ) ; System . out . print ( " Encoded Tree "); System . out . print ( "Structure List
"); for ( boolean si : struc ) { if ( si == true ) System . out . print ( 1 + " ▁ " ) ; else System . out . print ( 0 + " ▁ " ) ; } System . out . print ( " Data List "); for ( int di : data ) System . out . print ( di + " ▁ " ) ; Node newroot = DecodeSuccinct ( ) ; System . out . print ( " Preorder...


"Sudo Placement [ 1.5 ] | Wolfish | Java program for SP - Wolfish ; Function to find the maxCost of path from ( n - 1 , n - 1 ) to ( 0 , 0 ) ; base condition ; reaches the point ; if the state has been visited previously ; i + j ; check if it is a power of 2 , then only move diagonally ; if not a power of 2 then move side - wise ; Function to return the maximum cost ; calling dp function to get the answer ; Driver Code ; Function calling to get the answer"
How can the above be solved in Java?

class GFG { static int size = 1000 ; static int maxCost ( int a [ ] [ ] , int m , int n , int dp [ ] [ ] ) { if ( n < 0 m < 0 ) return ( int ) - 1e9 ; else if ( m == 0 && n == 0 ) return 0 ; else if ( dp [ m ] [ n ] != - 1 ) return dp [ m ] [ n ] ; else { int num = m + n ; if ( ( num & ( num - 1 ) ) == 0 ) return dp [ m ] [ n ] = a [ m ] [ n ] + maxCost ( a , m - 1 , n - 1 , dp ) ; else return dp [ m ] [ n ] = ( a [ m ] [ n ] + Math . max ( maxCost ( a , m - 1 , n , dp ) , maxCost ( a , m , n - 1 , dp ) ) ) ; } } static int answer ( int a [ ] [ ] , int n ) { int dp [ ] [ ] = new int [ size ] [ size ] ; for ( int i = 0 ; i < size ; i ++ ) { for ( int j = 0 ; j < size ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } return maxCost ( a , n - 1 , n - 1 , dp ) ; } public static void main ( String [ ] args ) { int a [ ] [ ] = { { 1 , 2 , 3 , 1 } , { 4 , 5 , 6 , 1 } , { 7 , 8 , 9 , 1 } , { 1 , 1 , 1 , 1 } } ; int n = 4 ; System . out . println ( answer ( a , n ) ) ; } }


"Sudo Placement [ 1.5 ] | Wolfish | Java program for SP - Wolfish ; Function to find the maxCost of path from ( n - 1 , n - 1 ) to ( 0 , 0 ) | recursive approach ; base condition ; reaches the point ; i + j ; check if it is a power of 2 , then only move diagonally ; if not a power of 2 then move side - wise ; Function to return the maximum cost ; calling dp function to get the answer ; Driver Code ; Function calling to get the answer"
How can the above be solved in Java?

class GFG { static int size = 1000 ; public static int maxCost ( int [ ] [ ] a , int m , int n ) { if ( n < 0 m < 0 ) { return - 1 ; } else if ( m == 0 && n == 0 ) { return 0 ; } else { int num = m + n ; if ( ( num & ( num - 1 ) ) == 0 ) { return a [ m ] [ n ] + maxCost ( a , m - 1 , n - 1 ) ; } else { return a [ m ] [ n ] + Math . max ( maxCost ( a , m - 1 , n ) , maxCost ( a , m , n - 1 ) ) ; } } } public static int answer ( int [ ] [ ] a , int n ) { return maxCost ( a , n - 1 , n - 1 ) ; } public static void main ( String [ ] args ) { int [ ] [ ] a = new int [ ] [ ] { { 1 , 2 , 3 , 1 } , { 4 , 5 , 6 , 1 } , { 7 , 8 , 9 , 1 } , { 1 , 1 , 1 , 1 } } ; int n = 4 ; System . out . println ( answer ( a , n ) ) ; } }


"Sudo Placement [ 1.7 ] | Greatest Digital Root | Java program to print the digital roots of a number ; Function to return dig - sum ; Function to print the Digital Roots ; store the largest digital roots ; Iterate till sqrt ( n ) ; if i is a factor ; get the digit sum of both factors i and n / i ; if digit sum is greater then previous maximum ; if digit sum is greater then previous maximum ; if digit sum is same as then previous maximum , then check for larger divisor ; if digit sum is same as then previous maximum , then check for larger divisor ; Print the digital roots ; Driver Code ; Function call to print digital roots"
How can the above be solved in Java?

class GFG { static int summ ( int n ) { if ( n == 0 ) return 0 ; return ( n % 9 == 0 ) ? 9 : ( n % 9 ) ; } static void printDigitalRoot ( int n ) { int maxi = 1 ; int dig = 1 ; for ( int i = 1 ; i <= Math . sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { int d1 = summ ( n / i ) ; int d2 = summ ( i ) ; if ( d1 > maxi ) { dig = n / i ; maxi = d1 ; } if ( d2 > maxi ) { dig = i ; maxi = d2 ; } if ( d1 == maxi ) { if ( dig < ( n / i ) ) { dig = n / i ; maxi = d1 ; } } if ( d2 == maxi ) { if ( dig < i ) { dig = i ; maxi = d2 ; } } } } System . out . println ( dig + " ▁ " + maxi ) ; } public static void main ( String [ ] args ) { int n = 10 ; printDigitalRoot ( n ) ; } }


"Sudo Placement | Beautiful Pairs | Java code for finding required pairs ; The function to check if beautiful pair exists ; Set for hashing ; Traversing the first array ; Traversing the second array to check for every j corresponding to single i ; x + y = z = > x = y - z ; if such x exists then we return true ; hash to make use of it next time ; no pair exists ; Driver Code ; If pair exists then 1 else 0 2 nd argument as size of first array fourth argument as sizeof 2 nd array"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean pairExists ( int [ ] arr1 , int m , int [ ] arr2 , int n ) { Set < Integer > s = new HashSet < Integer > ( ) ; for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( s . contains ( arr2 [ j ] - arr1 [ i ] ) ) return true ; } s . add ( arr1 [ i ] ) ; } return false ; } public static void main ( String [ ] args ) { int [ ] arr1 = { 1 , 5 , 10 , 8 } ; int [ ] arr2 = { 2 , 20 , 13 } ; if ( pairExists ( arr1 , 4 , arr2 , 3 ) ) System . out . println ( 1 ) ; else System . out . println ( 0 ) ; } }


"Sudo Placement | Placement Tour | Java Program to find the optimal number of elements such that the cumulative value should be less than given number ; This function returns true if the value cumulative according to received integer K is less than budget B , otherwise returns false ; Initialize a temporary array which stores the cumulative value of the original array ; Sort the array to find the smallest K values ; Check if the value is less than budget ; This function prints the optimal number of elements and respective cumulative value which is less than the given number ; Initialize answer as zero as optimal value may not exists ; If the current Mid Value is an optimal value , then try to maximize it ; Call Again to set the corresponding cumulative value for the optimal ans ; Driver Code ; Budget"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int value ; static boolean canBeOptimalValue ( int K , int arr [ ] , int N , int B ) { int [ ] tmp = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) tmp [ i ] = ( arr [ i ] + K * ( i + 1 ) ) ; Arrays . sort ( tmp ) ; value = 0 ; for ( int i = 0 ; i < K ; i ++ ) value += tmp [ i ] ; return value <= B ; } static void findNoOfElementsandValue ( int arr [ ] , int N , int B ) { int ans = 0 ; value = 0 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; if ( canBeOptimalValue ( mid , arr , N , B ) ) { ans = mid ; start = mid + 1 ; } else end = mid - 1 ; } canBeOptimalValue ( ans , arr , N , B ) ; System . out . print ( ans + " ▁ " + value + "
"); } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 5 , 6 , 3 } ; int N = arr . length ; int B = 90 ; findNoOfElementsandValue ( arr , N , B ) ; } }


"Sudo Placement | Range Queries | Java program to find the numbers having atmost 3 set bits within a given range ; Class to store the L and R range of a query ; It returns index of first element which is greater than searched value If searched element is bigger than any array element function returns first index after last element . ; Set of Numbers having at most 3 set bits arranged in non - descending order ; 0 Set bits ; Iterate over all possible combinations of i , j , k for 60 bits . And add all the numbers with 0 , 1 or 2 set bits into the set allNum . ; For one set bit , check if i , j , k are equal if yes , then set that bit and add it to the set ; For two set bits , two of the three variable i , j , k will be equal and the third will not be . Set both the bits where two variabls are equal and the bit which is not equal , and add it to the set ; Setting all the 3 bits ; Adding all the numbers to an array list so that it can be sorted ; Answer queries by applying binary search ; Swap L and R if R is smaller than L"
How can the above be solved in Java?

import java . util . * ; import java . io . * ; public class RangeQueries { static class Query { long L ; long R ; } public static int upperBound ( ArrayList < Long > validNumbers , Long value ) { int low = 0 ; int high = validNumbers . size ( ) - 1 ; while ( low < high ) { int mid = ( low + high ) / 2 ; if ( value >= validNumbers . get ( mid ) ) { low = mid + 1 ; } else { high = mid ; } } return low ; } public static void answerQueries ( ArrayList < Query > queries ) { Set < Long > allNum = new HashSet < > ( ) ; allNum . add ( 0L ) ; for ( int i = 0 ; i <= 60 ; i ++ ) { for ( int j = 0 ; j <= 60 ; j ++ ) { for ( int k = 0 ; k <= 60 ; k ++ ) { if ( i == j && j == k ) { allNum . add ( 1L << i ) ; } else if ( i == j && j != k ) { long toAdd = ( 1L << i ) + ( 1L << k ) ; allNum . add ( toAdd ) ; } else if ( i == k && k != j ) { long toAdd = ( 1L << i ) + ( 1L << j ) ; allNum . add ( toAdd ) ; } else if ( j == k && k != i ) { long toAdd = ( 1L << j ) + ( 1L << i ) ; allNum . add ( toAdd ) ; } else { long toAdd = ( 1L << i ) + ( 1L << j ) + ( 1L << k ) ; allNum . add ( toAdd ) ; } } } } ArrayList < Long > validNumbers = new ArrayList < > ( ) ; for ( Long num : allNum ) { validNumbers . add ( num ) ; } Collections . sort ( validNumbers ) ; for ( int i = 0 ; i < queries . size ( ) ; i ++ ) { long L = queries . get ( i ) . L ; long R = queries . get ( i ) . R ; if ( R < L ) { long temp = L ; L = R ; R = temp ; } if ( L == 0 ) { int indxOfLastNum = upperBound ( validNumbers , R ) ; System . out . println ( indxOfLastNum + 1 ) ; } else { int indxOfFirstNum = upperBound ( validNumbers , L ) ; int indxOfLastNum = upperBound ( validNumbers , R ) ; System . out . println ( ( indxOfLastNum - indxOfFirstNum + 1 ) ) ; } } } public static void main ( String [ ] args ) { int Q = 2 ; ArrayList < Query > queries = new ArrayList < > ( ) ; Query q1 = new Query ( ) ; q1 . L = 3 ; q1 . R = 7 ; Query q2 = new Query ( ) ; q2 . L = 10 ; q2 . R = 16 ; queries . add ( q1 ) ; queries . add ( q2 ) ; answerQueries ( queries ) ; } }


"Sudo Placement | Special Subsequences | Java Program to find all special subsequences of the given type ; Function to generate the required subsequences ; If the index pointer has reached the end of input string ; Skip empty ( " ▁ " ) subsequence ; Exclude the character in the output string ; Include the current character as it is ; Include the current character in its upper case form To remove the last character , we generate a substring till the second last character ; Function to print the required subsequences ; Output String to store every subsequence ; Set of strings that will store all special subsequences in lexicographical sorted order ; Sort the strings to print in the sorted order ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . io . * ; public class SpecialSubsequences { public static void generateSubsequences ( String input , String output , int index , ArrayList < String > ans ) { if ( index == input . length ( ) ) { if ( output . length ( ) != 0 ) { ans . add ( output ) ; } return ; } generateSubsequences ( input , output , index + 1 , ans ) ; output += String . valueOf ( input . charAt ( index ) ) ; generateSubsequences ( input , output , index + 1 , ans ) ; output = output . substring ( 0 , output . length ( ) - 1 ) ; output += String . valueOf ( Character . toUpperCase ( input . charAt ( index ) ) ) ; generateSubsequences ( input , output , index + 1 , ans ) ; } public static void printSubsequences ( String s ) { String output = " " ; ArrayList < String > ans = new ArrayList < > ( ) ; generateSubsequences ( s , output , 0 , ans ) ; Collections . sort ( ans ) ; for ( String str : ans ) { System . out . print ( str + " ▁ " ) ; } System . out . println ( ) ; } public static void main ( String [ ] args ) { String s = " ab " ; printSubsequences ( s ) ; } }


"Sudoku | Backtracking | Java program for above approach ; N is the size of the 2D matrix N * N ; A utility function to print grid ; Check whether it will be legal to assign num to the given row , col ; Check if we find the same num in the similar row , we return false ; Check if we find the same num in the similar column , we return false ; Check if we find the same num in the particular 3 * 3 matrix , we return false ; Takes a partially filled - in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution ( non - duplication across rows , columns , and boxes ) ; if we have reached the 8 th row and 9 th column ( 0 indexed matrix ) , we are returning true to avoid further backtracking ; Check if column value becomes 9 , we move to next row and column start from 0 ; Check if the current position of the grid already contains value > 0 , we iterate for next column ; Check if it is safe to place the num ( 1 - 9 ) in the given row , col -> we move to next column ; assigning the num in the current ( row , col ) position of the grid and assuming our assigned num in the position is correct ; Checking for next possibility with next column ; removing the assigned num , since our assumption was wrong , and we go for next assumption with diff num value ; Driver Code ; 0 means unassigned cells"
How can the above be solved in Java?

public class Suduko { static int N = 9 ; static void print ( int [ ] [ ] grid ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) System . out . print ( grid [ i ] [ j ] + " ▁ " ) ; System . out . println ( ) ; } } static boolean isSafe ( int [ ] [ ] grid , int row , int col , int num ) { for ( int x = 0 ; x <= 8 ; x ++ ) if ( grid [ row ] [ x ] == num ) return false ; for ( int x = 0 ; x <= 8 ; x ++ ) if ( grid [ x ] [ col ] == num ) return false ; int startRow = row - row % 3 , startCol = col - col % 3 ; for ( int i = 0 ; i < 3 ; i ++ ) for ( int j = 0 ; j < 3 ; j ++ ) if ( grid [ i + startRow ] [ j + startCol ] == num ) return false ; return true ; } static boolean solveSuduko ( int grid [ ] [ ] , int row , int col ) { if ( row == N - 1 && col == N ) return true ; if ( col == N ) { row ++ ; col = 0 ; } if ( grid [ row ] [ col ] != 0 ) return solveSuduko ( grid , row , col + 1 ) ; for ( int num = 1 ; num < 10 ; num ++ ) { if ( isSafe ( grid , row , col , num ) ) { grid [ row ] [ col ] = num ; if ( solveSuduko ( grid , row , col + 1 ) ) return true ; } grid [ row ] [ col ] = 0 ; } return false ; } public static void main ( String [ ] args ) { int grid [ ] [ ] = { { 3 , 0 , 6 , 5 , 0 , 8 , 4 , 0 , 0 } , { 5 , 2 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 8 , 7 , 0 , 0 , 0 , 0 , 3 , 1 } , { 0 , 0 , 3 , 0 , 1 , 0 , 0 , 8 , 0 } , { 9 , 0 , 0 , 8 , 6 , 3 , 0 , 0 , 5 } , { 0 , 5 , 0 , 0 , 9 , 0 , 6 , 0 , 0 } , { 1 , 3 , 0 , 0 , 0 , 0 , 2 , 5 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 7 , 4 } , { 0 , 0 , 5 , 2 , 0 , 6 , 3 , 0 , 0 } } ; if ( solveSuduko ( grid , 0 , 0 ) ) print ( grid ) ; else System . out . println ( " No ▁ Solution ▁ exists " ) ; } }


"Sudoku | Backtracking | Java program for above approach ; N is the size of the 2D matrix N * N ; A utility function to print grid ; Check whether it will be legal to assign num to the given row , col ; Check if we find the same num in the similar row , we return false ; Check if we find the same num in the similar column , we return false ; Check if we find the same num in the particular 3 * 3 matrix , we return false ; Takes a partially filled - in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution ( non - duplication across rows , columns , and boxes ) ; if we have reached the 8 th row and 9 th column ( 0 indexed matrix ) , we are returning true to avoid further backtracking ; Check if column value becomes 9 , we move to next row and column start from 0 ; Check if the current position of the grid already contains value > 0 , we iterate for next column ; Check if it is safe to place the num ( 1 - 9 ) in the given row , col -> we move to next column ; assigning the num in the current ( row , col ) position of the grid and assuming our assined num in the position is correct ; Checking for next possibility with next column ; removing the assigned num , since our assumption was wrong , and we go for next assumption with diff num value ; Driver Code"
How can the above be solved in Java?


"Sum and Product of all Fibonacci Nodes of a Singly Linked List | Java implementation to find the sum and product of all of the Fibonacci nodes in a singly linked list ; Node of the singly linked list ; Function to insert a node at the beginning of the singly Linked List ; Allocate new node ; Insert the data ; Link the old list to the new node ; Move the head to point the new node ; Function that returns the largest element from the linked list . ; Declare a max variable and initialize with Integer . MIN_VALUE ; Check loop while head not equal to null ; If max is less then head . data then assign value of head . data to max otherwise node points to next node . ; Function to create a hash table to check Fibonacci numbers ; Inserting the first two numbers in the hash ; Loop to add Fibonacci numbers upto the maximum element present in the linked list ; Function to find the required sum and product ; Find the largest node value in Singly Linked List ; Creating a set containing all the fibonacci numbers upto the maximum data value in the Singly Linked List ; Traverse the linked list ; If current node is fibonacci ; Find the sum and the product ; Driver code ; Create the linked list 15.16 . 8.6 .13"
How can the above be solved in Java?

 import java . util . * ; class GFG { static class Node { int data ; Node next ; } ; static Node push ( Node head_ref , int new_data ) { Node new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = head_ref ; head_ref = new_node ; return head_ref ; } static int largestElement ( Node head_ref ) { int max = Integer . MIN_VALUE ; Node head = head_ref ; while ( head != null ) { if ( max < head . data ) max = head . data ; head = head . next ; } return max ; } static void createHash ( HashSet < Integer > hash , int maxElement ) { int prev = 0 , curr = 1 ; hash . add ( prev ) ; hash . add ( curr ) ; while ( curr <= maxElement ) { int temp = curr + prev ; hash . add ( temp ) ; prev = curr ; curr = temp ; } } static void sumAndProduct ( Node head_ref ) { int maxEle = largestElement ( head_ref ) ; HashSet < Integer > hash = new HashSet < Integer > ( ) ; createHash ( hash , maxEle ) ; int prod = 1 ; int sum = 0 ; Node ptr = head_ref ; while ( ptr != null ) { if ( hash . contains ( ptr . data ) ) { prod *= ptr . data ; sum += ptr . data ; } ptr = ptr . next ; } System . out . print ( " Sum ▁ = ▁ " + sum + "
"); System . out . print ( " Product ▁ = ▁ " + prod ) ; } public static void main ( String [ ] args ) { Node head = null ; head = push ( head , 13 ) ; head = push ( head , 6 ) ; head = push ( head , 8 ) ; head = push ( head , 16 ) ; head = push ( head , 15 ) ; sumAndProduct ( head ) ; } }


"Sum and Product of all even digit sum Nodes of a Singly Linked List | Java program for the above approach ; Node of Linked List ; Function to insert a node at the beginning of the singly Linked List ; Allocate new node ; Insert the data ; Link old list to the new node ; Move head to point the new node ; Function to find the digit sum for a number ; Return the sum ; Function to find the required sum and product ; Initialise the sum and product to 0 and 1 respectively ; Traverse the given linked list ; If current node has even digit sum then include it in resultant sum and product ; Find the sum and the product ; Print the final Sum and Product ; Driver Code ; Head of the linked list ; Create the linked list 15.16 . 8.6 .13 ; Function call"
How can the above be solved in Java?

 class GFG { static class Node { int data ; Node next ; } ; static Node push ( Node head_ref , int new_data ) { Node new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = head_ref ; head_ref = new_node ; return head_ref ; } static int digitSum ( int num ) { int sum = 0 ; while ( num > 0 ) { sum += ( num % 10 ) ; num /= 10 ; } return sum ; } static void sumAndProduct ( Node head_ref ) { int prod = 1 ; int sum = 0 ; Node ptr = head_ref ; while ( ptr != null ) { if ( ( digitSum ( ptr . data ) % 2 != 1 ) ) { prod *= ptr . data ; sum += ptr . data ; } ptr = ptr . next ; } System . out . print ( " Sum ▁ = ▁ " + sum + "
"); System . out . print ( " Product ▁ = ▁ " + prod ) ; } public static void main ( String [ ] args ) { Node head = null ; head = push ( head , 13 ) ; head = push ( head , 6 ) ; head = push ( head , 8 ) ; head = push ( head , 16 ) ; head = push ( head , 15 ) ; sumAndProduct ( head ) ; } }


"Sum and Product of digits in a number that divide the number | Java implementation of the above approach ; Print the sum and product of digits that divides the number . ; Fetching each digit of the number ; Checking if digit is greater than 0 and can divides n . ; Driver code"
How can the above be solved in Java?

import java . lang . * ; import java . util . * ; class GFG { static void countDigit ( int n ) { int temp = n , sum = 0 , product = 1 ; while ( temp != 0 ) { int d = temp % 10 ; temp /= 10 ; if ( d > 0 && n % d == 0 ) { sum += d ; product *= d ; } } System . out . print ( " Sum ▁ = ▁ " + sum ) ; System . out . print ( " Product = " + product); } public static void main ( String args [ ] ) { int n = 1012 ; countDigit ( n ) ; } }


"Sum and Product of minimum and maximum element of an Array | Java program for the above approach ; Function to get sum ; Function to get product ; Driver code ; sorting the array ; min element would be the element at 0 th index of array after sorting ; max element would be the element at ( n - 1 ) th index of array after sorting"
How can the above be solved in Java?

import java . io . * ; import java . util . Arrays ; class GFG { static int findSum ( int minEle , int maxEle ) { return minEle + maxEle ; } static int findProduct ( int minEle , int maxEle ) { return minEle * maxEle ; } public static void main ( String [ ] args ) { int [ ] arr = { 12 , 1234 , 45 , 67 , 1 } ; int n = arr . length ; Arrays . sort ( arr ) ; int minEle = arr [ 0 ] ; int maxEle = arr [ n - 1 ] ; System . out . println ( " Sum ▁ = ▁ " + findSum ( minEle , maxEle ) ) ; System . out . println ( " Product ▁ = ▁ " + findProduct ( minEle , maxEle ) ) ; } }


"Sum and Product of minimum and maximum element of an Array | Java program to find the sum and product of minimum and maximum element in an array ; Function to find minimum element ; Function to find maximum element ; Function to get Sum ; Function to get product ; Driver Code ; Sum of min and max element ; Product of min and max element"
How can the above be solved in Java?

import java . io . * ; class GFG { static int getMin ( int arr [ ] , int n ) { int res = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) res = Math . min ( res , arr [ i ] ) ; return res ; } static int getMax ( int arr [ ] , int n ) { int res = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) res = Math . max ( res , arr [ i ] ) ; return res ; } static int findSum ( int arr [ ] , int n ) { int min = getMin ( arr , n ) ; int max = getMax ( arr , n ) ; return min + max ; } static int findProduct ( int arr [ ] , int n ) { int min = getMin ( arr , n ) ; int max = getMax ( arr , n ) ; return min * max ; } public static void main ( String [ ] args ) { int arr [ ] = { 12 , 1234 , 45 , 67 , 1 } ; int n = arr . length ; System . out . println ( " Sum ▁ = ▁ " + findSum ( arr , n ) ) ; System . out . println ( " Product ▁ = ▁ " + findProduct ( arr , n ) ) ; } }


"Sum and product of k smallest and k largest composite numbers in the array | Java program to find the sum and product of k smallest and k largest composite numbers in an array ; Create a boolean vector " prime [ 0 . . n ] " . 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 ; Function that calculates the sum and product of k smallest and k largest composite numbers in an array ; Find maximum value in the array ; Use sieve to find all prime numbers less than or equal to max_val ; Set 0 and 1 as primes so that they don 't get counted as  composite numbers ; Max Heap to store all the composite numbers ; Min Heap to store all the composite numbers ; Push all the composite numbers from the array to the heaps ; Calculate the products ; Calculate the sum ; Pop the current minimum element ; Pop the current maximum element ; when maxHeap or minHeap is exhausted then this consition will run ;  ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean [ ] SieveOfEratosThenes ( int max_val ) { boolean [ ] prime = new boolean [ max_val + 1 ] ; Arrays . fill ( prime , true ) ; for ( int p = 2 ; p * p <= max_val ; p ++ ) { if ( prime [ p ] ) { for ( int i = p * 2 ; i <= max_val ; i += p ) prime [ i ] = false ; } } return prime ; } static void compositeSumAndProduct ( Integer [ ] arr , int n , int k ) { int max_val = Collections . max ( Arrays . asList ( arr ) ) ; boolean [ ] prime = SieveOfEratosThenes ( max_val ) ; prime [ 0 ] = true ; prime [ 1 ] = true ; PriorityQueue < Integer > maxHeap = new PriorityQueue < Integer > ( ( x , y ) -> y - x ) ; PriorityQueue < Integer > minHeap = new PriorityQueue < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! prime [ arr [ i ] ] ) { minHeap . add ( arr [ i ] ) ; maxHeap . add ( arr [ i ] ) ; } } long minProduct = 1 , maxProduct = 1 , minSum = 0 , maxSum = 0 ; Integer lastMin = 0 , lastMax = 0 ; while ( k -- > 0 ) { if ( minHeap . peek ( ) != null || maxHeap . peek ( ) != null ) { minProduct *= minHeap . peek ( ) ; maxProduct *= maxHeap . peek ( ) ; minSum += minHeap . peek ( ) ; maxSum += maxHeap . peek ( ) ; lastMin = minHeap . poll ( ) ; lastMax = maxHeap . poll ( ) ; } else { minProduct *= lastMin ; maxProduct *= lastMax ; minSum += lastMin ; maxSum += lastMax ; } } '' ' ▁ Print ▁ results ▁ ' '' System . out . println ( " Sum ▁ of ▁ k - minimum ▁ composite " + " ▁ numbers ▁ is ▁ " + minSum ) ; System . out . println ( " Sum ▁ of ▁ k - maximum ▁ composite " + " ▁ numbers ▁ is ▁ " + maxSum ) ; System . out . println ( " Product ▁ of ▁ k - minimum ▁ composite " + " ▁ numbers ▁ is ▁ " + minProduct ) ; System . out . println ( " Product ▁ of ▁ k - maximum ▁ composite " + " ▁ numbers ▁ is ▁ " + maxProduct ) ; } public static void main ( String [ ] args ) { Integer [ ] arr = { 4 , 2 , 12 , 13 , 5 , 19 } ; int n = arr . length ; int k = 3 ; compositeSumAndProduct ( arr , n , k ) ; } }


"Sum of ( maximum element | Java implementation of the above approach ; Function to return a ^ n % mod ; Compute sum of max ( A ) - min ( A ) for all subsets ; Sort the array . ; Maxs = 2 ^ i - 1 ; Mins = 2 ^ ( n - 1 - i ) - 1 ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int mod = 1000000007 ; static long power ( long a , long n ) { if ( n == 0 ) { return 1 ; } long p = power ( a , n / 2 ) % mod ; p = ( p * p ) % mod ; if ( n == 1 ) { p = ( p * a ) % mod ; } return p ; } static long computeSum ( int [ ] arr , int n ) { Arrays . sort ( arr ) ; long sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { long maxs = ( power ( 2 , i ) - 1 + mod ) % mod ; maxs = ( maxs * arr [ i ] ) % mod ; long mins = ( power ( 2 , n - 1 - i ) - 1 + mod ) % mod ; mins = ( mins * arr [ i ] ) % mod ; long V = ( maxs - mins + mod ) % mod ; sum = ( sum + V ) % mod ; } return sum ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 3 , 1 } ; int n = arr . length ; System . out . println ( computeSum ( arr , n ) ) ; } }


"Sum of Areas of Rectangles possible for an array | Java code to find sum of all area rectangle possible ; Function to find area of rectangles ; sorting the array in descending order ; store the final sum of all the rectangles area possible ; temporary variable to store the length of rectangle ; Selecting the length of rectangle so that difference between any two number is 1 only . Here length is selected so flag is set ; flag is set means we have got length of rectangle ; length is set to a [ i + 1 ] so that if a [ i ] a [ i + 1 ] is less than by 1 then also we have the correct choice for length ; incrementing the counter one time more as we have considered a [ i + 1 ] element also so . ; Selecting the width of rectangle so that difference between any two number is 1 only . Here width is selected so now flag is again unset for next rectangle ; area is calculated for rectangle ; flag is set false for another rectangle which we can get from elements in array ; incrementing the counter one time more as we have considered a [ i + 1 ] element also so . ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . Arrays ; import java . util . * ; class GFG { static int MaxTotalRectangleArea ( Integer [ ] a , int n ) { Arrays . sort ( a , Collections . reverseOrder ( ) ) ; int sum = 0 ; boolean flag = false ; int len = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( a [ i ] == a [ i + 1 ] a [ i ] - a [ i + 1 ] == 1 ) && ! flag ) { flag = true ; len = a [ i + 1 ] ; i ++ ; } else if ( ( a [ i ] == a [ i + 1 ] a [ i ] - a [ i + 1 ] == 1 ) && ( flag ) ) { sum = sum + a [ i + 1 ] * len ; flag = false ; i ++ ; } } return sum ; } public static void main ( String args [ ] ) { Integer [ ] a = { 10 , 10 , 10 , 10 , 11 , 10 , 11 , 10 , 9 , 9 , 8 , 8 } ; int n = a . length ; System . out . print ( MaxTotalRectangleArea ( a , n ) ) ; } }


"Sum of Arithmetic Geometric Sequence | Java Program to find the sum of first n terms . ; Return the sum of first n term of AGP ; finding the each term of AGP and adding it to sum . ; Driven Program"
How can the above be solved in Java?

import java . io . * ; class GFG { static int sumofNterm ( int a , int d , int b , int r , int n ) { int sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) sum += ( ( a + ( i - 1 ) * d ) * ( b * Math . pow ( r , i - 1 ) ) ) ; return sum ; } public static void main ( String args [ ] ) { int a = 1 , d = 1 , b = 2 , r = 2 , n = 3 ; System . out . println ( sumofNterm ( a , d , b , r , n ) ) ; } }


"Sum of Binomial coefficients | Java Program to find sum of Binomial Coefficient . ; Returns value of Binomial Coefficient Sum which is 2 raised to power n . ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int binomialCoeffSum ( int n ) { return ( 1 << n ) ; } public static void main ( String [ ] args ) { int n = 4 ; System . out . println ( binomialCoeffSum ( n ) ) ; } }


"Sum of Bitwise AND of all unordered triplets of an array | Java program for the above approach ; Function to calculate sum of Bitwise AND of all unordered triplets from a given array such that ( i < j < k ) ; Stores the resultant sum of Bitwise AND of all triplets ; Generate all triplets of ( arr [ i ] , arr [ j ] , arr [ k ] ) ; Add Bitwise AND to ans ; Print the result ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { public static void tripletAndSum ( int arr [ ] , int n ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { for ( int k = j + 1 ; k < n ; k ++ ) { ans += arr [ i ] & arr [ j ] & arr [ k ] ; } } } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 5 , 4 , 7 } ; int N = arr . length ; tripletAndSum ( arr , N ) ; } }


"Sum of Bitwise AND of all unordered triplets of an array | Java program for the above approach ; Function to calculate sum of Bitwise AND of all unordered triplets from a given array such that ( i < j < k ) ; Stores the resultant sum of Bitwise AND of all triplets ; Traverse over all the bits ; Count number of elements with the current bit set ; There are ( cnt ) C ( 3 ) numbers with the current bit set and each triplet contributes 2 ^ bit to the result ; Return the resultant sum ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int tripletAndSum ( int [ ] arr , int n ) { int ans = 0 ; for ( int bit = 0 ; bit < 32 ; bit ++ ) { int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( arr [ i ] & ( 1 << bit ) ) != 0 ) cnt ++ ; } ans += ( 1 << bit ) * cnt * ( cnt - 1 ) * ( cnt - 2 ) / 6 ; } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 5 , 4 , 7 } ; int N = arr . length ; System . out . print ( tripletAndSum ( arr , N ) ) ; } }


"Sum of Bitwise AND of the sum of all leaf and non | Java program for given approach ; Structure of a Binary tree node ; Helper function to allocate a new node with the given data and left and right pointers as None ; Function to calculate the sum of bitwise AND of the sum of all leaf nodes and non - leaf nodes for each level ; Initialize a queue and append root to it ; Store the required answer ; Stores the sum of leaf nodes at the current level ; Stores the sum of non - leaf nodes at the current level ; Get the size of the queue ; Iterate for all the nodes in the queue currently ; Dequeue a node from queue ; Check if the node is a leaf node ; If true , update the leaf node sum ; Otherwise , update the non - leaf node sum ; Enqueue left and right children of removed node ; Update the answer ; Return the answer ; Driver Code ; Given Tree ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static class TreeNode { int val ; TreeNode left , right ; TreeNode ( int x ) { val = x ; left = null ; right = null ; } } ; static int findSum ( TreeNode root ) { Queue < TreeNode > que = new LinkedList < > ( ) ; que . add ( root ) ; int ans = 0 ; while ( que . size ( ) > 0 ) { int leaf = 0 ; int nonleaf = 0 ; int length = que . size ( ) ; while ( length > 0 ) { TreeNode temp = que . peek ( ) ; que . remove ( ) ; if ( temp . left == null && temp . right == null ) leaf += temp . val ; else nonleaf += temp . val ; if ( temp . left != null ) que . add ( temp . left ) ; if ( temp . right != null ) que . add ( temp . right ) ; length -= 1 ; } ans += leaf & nonleaf ; } return ans ; } public static void main ( String [ ] args ) { TreeNode root = new TreeNode ( 5 ) ; root . left = new TreeNode ( 3 ) ; root . right = new TreeNode ( 9 ) ; root . left . left = new TreeNode ( 6 ) ; root . left . right = new TreeNode ( 4 ) ; root . left . left . right = new TreeNode ( 7 ) ; System . out . print ( findSum ( root ) ) ; } }


"Sum of Bitwise And of all pairs in a given array | A Simple Java program to compute sum of bitwise AND of all pairs ; Returns value of " arr [ 0 ] ▁ & ▁ arr [ 1 ] ▁ + ▁ ▁ arr [ 0 ] ▁ & ▁ arr [ 2 ] ▁ + ▁ . . . ▁ arr [ i ] ▁ & ▁ arr [ j ] ▁ + ▁ ▁ . . . . . ▁ arr [ n - 2 ] ▁ & ▁ arr [ n - 1 ] " ; Consider all pairs ( arr [ i ] , arr [ j ) such that i < j ; Driver program to test above function"
How can the above be solved in Java?

import java . io . * ; class GFG { static int pairAndSum ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) ans += arr [ i ] & arr [ j ] ; return ans ; } public static void main ( String args [ ] ) { int arr [ ] = { 5 , 10 , 15 } ; int n = arr . length ; System . out . println ( pairAndSum ( arr , n ) ) ; } }


"Sum of Bitwise And of all pairs in a given array | An efficient Java program to compute sum of bitwise AND of all pairs ; Returns value of " arr [ 0 ] ▁ & ▁ arr [ 1 ] ▁ + ▁ ▁ arr [ 0 ] ▁ & ▁ arr [ 2 ] ▁ + ▁ . . . ▁ arr [ i ] ▁ & ▁ arr [ j ] ▁ + ▁ ▁ . . . . . ▁ arr [ n - 2 ] ▁ & ▁ arr [ n - 1 ] " ; Traverse over all bits ; Count number of elements with i 'th bit set  Initialize the count ; There are k set bits , means k ( k - 1 ) / 2 pairs . Every pair adds 2 ^ i to the answer . Therefore , we add "2 ^ i ▁ * ▁ [ k * ( k - 1 ) / 2 ] " to the answer . ; Driver program to test above function"
How can the above be solved in Java?

import java . io . * ; class GFG { static int pairAndSum ( int arr [ ] , int n ) { for ( int i = 0 ; i < 32 ; i ++ ) { int k = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( arr [ j ] & ( 1 << i ) ) != 0 ) k ++ ; } ans += ( 1 << i ) * ( k * ( k - 1 ) / 2 ) ; } return ans ; } public static void main ( String args [ ] ) { int arr [ ] = { 5 , 10 , 15 } ; int n = arr . length ; System . out . println ( pairAndSum ( arr , n ) ) ; } }


"Sum of Bitwise OR of all pairs in a given array | A Simple Java program to compute sum of bitwise OR of all pairs ; Returns value of " arr [ 0 ] ▁ | ▁ arr [ 1 ] ▁ + ▁ ▁ arr [ 0 ] ▁ | ▁ arr [ 2 ] ▁ + ▁ . . . ▁ arr [ i ] ▁ | ▁ arr [ j ] ▁ + ▁ ▁ . . . . . ▁ arr [ n - 2 ] ▁ | ▁ arr [ n - 1 ] " ; Consider all pairs ( arr [ i ] , arr [ j ) such that i < j ; Driver program to test above function"
How can the above be solved in Java?

import java . io . * ; class GFG { static int pairORSum ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) ans += arr [ i ] | arr [ j ] ; return ans ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int n = arr . length ; System . out . println ( pairORSum ( arr , n ) ) ; } }


"Sum of Bitwise OR of each array element of an array with all elements of another array | Java program for the above approach ; Function to compute sum of Bitwise OR of each element in arr1 [ ] with all elements of the array arr2 [ ] ; Declaring an array of size 32 to store the count of each bit ; Traverse the array arr1 [ ] ; Current bit position ; While num exceeds 0 ; Checks if i - th bit is set or not ; Increment the count at bit_position by one ; Increment bit_position ; Right shift the num by one ; Traverse in the arr2 [ ] ; Store the ith bit value ; Total required sum ; Traverse in the range [ 0 , 31 ] ; Check if current bit is set ; Increment the Bitwise sum by N * ( 2 ^ i ) ; Right shift num by one ; Left shift valee_at_that_bit by one ; Print the sum obtained for ith number in arr1 [ ] ; Driver code ; Given arr1 [ ] ; Given arr2 [ ] ; Size of arr1 [ ] ; Size of arr2 [ ] ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void Bitwise_OR_sum_i ( int arr1 [ ] , int arr2 [ ] , int M , int N ) { int frequency [ ] = new int [ 32 ] ; Arrays . fill ( frequency , 0 ) ; 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_OR_sum = 0 ; for ( int bit_position = 0 ; bit_position < 32 ; bit_position ++ ) { if ( ( num & 1 ) != 0 ) { bitwise_OR_sum += N * value_at_that_bit ; } else { bitwise_OR_sum += frequency [ bit_position ] * value_at_that_bit ; } num >>= 1 ; value_at_that_bit <<= 1 ; } System . out . print ( bitwise_OR_sum + " ▁ " ) ; } return ; } 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_OR_sum_i ( arr1 , arr2 , M , N ) ; } }


"Sum of Bitwise OR of every array element paired with all other array elements | Java program for the above approach ; Function to print required sum for every valid index i ; Store the required sum for current array element ; Generate all possible pairs ( arr [ i ] , arr [ j ] ) ; Update the value of req_sum ; Print the required sum ; Driver Code ; Given array ; Size of the array ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void printORSumforEachElement ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { int req_sum = 0 ; for ( int j = 0 ; j < N ; j ++ ) { req_sum += ( arr [ i ] arr [ j ] ) ; } System . out . print ( req_sum + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = arr . length ; printORSumforEachElement ( arr , N ) ; } }


"Sum of Bitwise XOR of each array element with all other array elements | Java program for the above approach ; Function to calculate for each array element , sum of its Bitwise XOR with all other array elements ; Declare an array of size 64 to store count of each bit ; Traversing the array ; Check if bit is present of not ; Increase the bit position ; Reduce the number to half ; Traverse the array ; Stores the bit position ; Stores the sum of Bitwise XOR ; Check if bit is present of not ; Reduce the number to its half ; Print the sum for A [ i ] ; Driver code ; Given array ; Given N ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void XOR_for_every_i ( int A [ ] , int N ) { int frequency_of_bits [ ] = new int [ 32 ] ; for ( int i = 0 ; i < N ; i ++ ) { int bit_position = 0 ; int M = A [ i ] ; while ( M != 0 ) { if ( ( M & 1 ) != 0 ) { frequency_of_bits [ bit_position ] += 1 ; } bit_position += 1 ; M >>= 1 ; } } for ( int i = 0 ; i < N ; i ++ ) { int M = A [ i ] ; int value_at_that_bit = 1 ; int XOR_sum = 0 ; for ( int bit_position = 0 ; bit_position < 32 ; bit_position ++ ) { if ( ( M & 1 ) != 0 ) { XOR_sum += ( N - frequency_of_bits [ bit_position ] ) * value_at_that_bit ; } else { XOR_sum += ( frequency_of_bits [ bit_position ] ) * value_at_that_bit ; } M >>= 1 ; value_at_that_bit <<= 1 ; } System . out . print ( XOR_sum + " ▁ " ) ; } return ; } public static void main ( String [ ] args ) { int A [ ] = { 1 , 2 , 3 } ; int N = A . length ; XOR_for_every_i ( A , N ) ; } }


"Sum of Bitwise XOR of elements of an array with all elements of another array | Java Program for the above approach ; Function to calculate sum of Bitwise XOR of elements of arr [ ] with k ; Initialize sum to be zero ; Iterate over each set bit ; Stores contribution of i - th bet to the sum ; If the i - th bit is set ; Stores count of elements whose i - th bit is not set ; Update value ; Update value ; Add value to sum ; Move to the next power of two ; Stores the count of elements whose i - th bit is set ; Initialize count to 0 for all positions ; Traverse the array ; Iterate over each bit ; If the i - th bit is set ; Increase count ; Driver Code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static int xorSumOfArray ( int arr [ ] , int n , int k , int count [ ] ) { int sum = 0 ; int p = 1 ; for ( int i = 0 ; i < 31 ; i ++ ) { int val = 0 ; if ( ( k & ( 1 << i ) ) != 0 ) { int not_set = n - count [ i ] ; val = ( ( not_set ) * p ) ; } else { val = ( count [ i ] * p ) ; } sum += val ; p = ( p * 2 ) ; } return sum ; } static void sumOfXors ( int arr [ ] , int n , int queries [ ] , int q ) { int [ ] count = new int [ 32 ] ; Arrays . fill ( count , 0 ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < 31 ; j ++ ) { if ( ( arr [ i ] & ( 1 << j ) ) != 0 ) count [ j ] ++ ; } } for ( int i = 0 ; i < q ; i ++ ) { int k = queries [ i ] ; System . out . print ( xorSumOfArray ( arr , n , k , count ) + " ▁ " ) ; } } public static void main ( String args [ ] ) { int arr [ ] = { 5 , 2 , 3 } ; int queries [ ] = { 3 , 8 , 7 } ; int n = arr . length ; int q = queries . length ; sumOfXors ( arr , n , queries , q ) ; } }


"Sum of Bitwise | Java program to find sum of Bitwise - OR of all submatrices ; Function to find prefix - count for each row from right to left ; Function to create a booleanean matrix set_bit which stores '1' at an index ( R , C ) if ith bit of arr [ R ] [ C ] is set . ; array to store prefix count of zeros from right to left for booleanean array ; variable to store the count of submatrices with OR value 0 ; For each index of a column we will try to determine the number of sub - matrices starting from that index and has all 1 s ; stack to store elements and the count of the numbers they popped First part of pair will be the value of inserted element . Second part will be the count of the number of elements pushed before with a greater value ; variable to store the number of submatrices with all 0 s ; Function to find sum of Bitwise - OR of all submatrices ; matrix to store the status of ith bit of each element of matrix arr ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int n = 3 ; static void findPrefixCount ( int p_arr [ ] [ ] , boolean set_bit [ ] [ ] ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = n - 1 ; j >= 0 ; j -- ) { if ( set_bit [ i ] [ j ] ) continue ; if ( j != n - 1 ) p_arr [ i ] [ j ] += p_arr [ i ] [ j + 1 ] ; p_arr [ i ] [ j ] += ( ! set_bit [ i ] [ j ] ) ? 1 : 0 ; } } } static class pair { int first , second ; pair ( ) { } pair ( int a , int b ) { first = a ; second = b ; } } static int matrixOrValueOne ( boolean set_bit [ ] [ ] ) { int p_arr [ ] [ ] = new int [ n ] [ n ] ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) p_arr [ i ] [ j ] = 0 ; findPrefixCount ( p_arr , set_bit ) ; int count_zero_submatrices = 0 ; for ( int j = 0 ; j < n ; j ++ ) { int i = n - 1 ; Stack < pair > q = new Stack < pair > ( ) ; int to_sum = 0 ; while ( i >= 0 ) { int c = 0 ; while ( q . size ( ) != 0 && q . peek ( ) . first > p_arr [ i ] [ j ] ) { to_sum -= ( q . peek ( ) . second + 1 ) * ( q . peek ( ) . first - p_arr [ i ] [ j ] ) ; c += q . peek ( ) . second + 1 ; q . pop ( ) ; } to_sum += p_arr [ i ] [ j ] ; count_zero_submatrices += to_sum ; q . push ( new pair ( p_arr [ i ] [ j ] , c ) ) ; i -- ; } } return ( n * ( n + 1 ) * n * ( n + 1 ) ) / 4 - count_zero_submatrices ; } static int sumOrMatrix ( int arr [ ] [ ] ) { int sum = 0 ; int mul = 1 ; for ( int i = 0 ; i < 30 ; i ++ ) { boolean set_bit [ ] [ ] = new boolean [ n ] [ n ] ; for ( int R = 0 ; R < n ; R ++ ) for ( int C = 0 ; C < n ; C ++ ) set_bit [ R ] [ C ] = ( ( arr [ R ] [ C ] & ( 1 << i ) ) != 0 ) ; sum += ( mul * matrixOrValueOne ( set_bit ) ) ; mul *= 2 ; } return sum ; } public static void main ( String args [ ] ) { int arr [ ] [ ] = { { 9 , 7 , 4 } , { 8 , 9 , 2 } , { 11 , 11 , 5 } } ; System . out . println ( sumOrMatrix ( arr ) ) ; } }


"Sum of Digits in a ^ n till a single digit | Java program to find single digit sum of a ^ n . ; This function finds single digit sum of n . ; Returns single digit sum of a ^ n . We use modular exponentiation technique . ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static int digSum ( int n ) { if ( n == 0 ) return 0 ; return ( n % 9 == 0 ) ? 9 : ( n % 9 ) ; } static int powerDigitSum ( int a , int n ) { int res = 1 ; while ( n > 0 ) { if ( n % 2 == 1 ) { res = res * digSum ( a ) ; res = digSum ( res ) ; } a = digSum ( digSum ( a ) * digSum ( a ) ) ; n /= 2 ; } return res ; } public static void main ( String args [ ] ) { int a = 9 , n = 4 ; System . out . print ( powerDigitSum ( a , n ) ) ; } }


"Sum of Digits of the Good Strings | Java implementation of the approach ; To store the states of the dp ; Function to fill the dp table ; Sum of digits of the string of length 1 is i as i is only number in that string and count of good strings of length 1 that end with i is also 1 ; Adjacent digits are different ; Increment the count as digit at ( i - 1 ) 'th index is k and count  of good strings is equal to this  because at the end of the strings of  length (i - 1) we are just  putting digit j as the last digit ; Driver code"
How can the above be solved in Java?

class GFG { final static int DIGITS = 10 ; final static int MAX = 10000 ; final static int MOD = 1000000007 ; static int dp [ ] [ ] = new int [ MAX ] [ DIGITS ] ; static int cnt [ ] [ ] = new int [ MAX ] [ DIGITS ] ; static void precompute ( ) { for ( int i = 0 ; i < DIGITS ; i ++ ) { dp [ 1 ] [ i ] = i ; cnt [ 1 ] [ i ] = 1 ; } for ( int i = 2 ; i < MAX ; i ++ ) { for ( int j = 0 ; j < DIGITS ; j ++ ) { for ( int k = 0 ; k < DIGITS ; k ++ ) { if ( j != k ) { dp [ i ] [ j ] = dp [ i ] [ j ] + ( dp [ i - 1 ] [ k ] + ( cnt [ i - 1 ] [ k ] * j ) % MOD ) % MOD ; dp [ i ] [ j ] %= MOD ; cnt [ i ] [ j ] += cnt [ i - 1 ] [ k ] ; cnt [ i ] [ j ] %= MOD ; } } } } } public static void main ( String [ ] args ) { int x = 6 , y = 4 ; precompute ( ) ; System . out . println ( dp [ x ] [ y ] ) ; } }


"Sum of Euler Totient Functions obtained for each divisor of N | Java program for the above approach ; Function to find the sum of Euler Totient Function of divisors of N ; Return the value of N ; Driver code"
How can the above be solved in Java?

public class GFG { static int sumOfDivisors ( int N ) { return N ; } public static void main ( String [ ] args ) { int N = 5 ; System . out . println ( sumOfDivisors ( N ) ) ; } }


"Sum of Factors of a Number using Prime Factorization | Java Program to find sum of all factors of a given number ; Using SieveOfEratosthenes to find smallest prime factor of all the numbers . For example , if N 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 . . n ] " 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 find sum of all prime factors ; Declaring array to store smallest prime factor of i at i - th index ; Filling values in s [ ] using sieve ; Current prime factor of N ; Power of current prime factor ; N is now N / s [ N ] . If new N als has smallest prime factor as currFactor , increment power ; Update current prime factor as s [ N ] and initializing power of factor as 1. ; Driver code"
How can the above be solved in Java?

public class GFG { static void sieveOfEratosthenes ( int N , int s [ ] ) { boolean [ ] prime = new boolean [ N + 1 ] ; for ( int i = 0 ; i < N + 1 ; i ++ ) prime [ i ] = false ; for ( int i = 2 ; i <= N ; i += 2 ) s [ i ] = 2 ; for ( int i = 3 ; i <= N ; i += 2 ) { if ( prime [ i ] == false ) { s [ i ] = i ; for ( int j = i ; j * i <= N ; j += 2 ) { if ( prime [ i * j ] == false ) { prime [ i * j ] = true ; s [ i * j ] = i ; } } } } } static int findSum ( int N ) { int [ ] s = new int [ N + 1 ] ; int ans = 1 ; sieveOfEratosthenes ( N , s ) ; int currFactor = s [ N ] ; int power = 1 ; while ( N > 1 ) { N /= s [ N ] ; if ( currFactor == s [ N ] ) { power ++ ; continue ; } int sum = 0 ; for ( int i = 0 ; i <= power ; i ++ ) sum += Math . pow ( currFactor , i ) ; ans *= sum ; currFactor = s [ N ] ; power = 1 ; } return ans ; } public static void main ( String [ ] args ) { int n = 12 ; System . out . print ( " Sum ▁ of ▁ the ▁ factors ▁ is ▁ : ▁ " ) ; System . out . print ( findSum ( n ) ) ; } }


"Sum of Fibonacci Numbers in a range | Java implementation of the approach ; Function to return the nth Fibonacci number ; Function to return the required sum ; To store the sum ; Calculate the sum ; Driver code"
How can the above be solved in Java?

import java . lang . Math ; class GFG { static int fib ( int n ) { double phi = ( 1 + Math . sqrt ( 5 ) ) / 2 ; return ( int ) Math . round ( Math . pow ( phi , n ) / Math . sqrt ( 5 ) ) ; } static int calculateSum ( int l , int r ) { int sum = 0 ; for ( int i = l ; i <= r ; i ++ ) sum += fib ( i ) ; return sum ; } public static void main ( String [ ] args ) { int l = 4 , r = 8 ; System . out . println ( calculateSum ( l , r ) ) ; } }


"Sum of Fibonacci Numbers in a range | Java implementation of the approach ; Function to return the nth Fibonacci number ; Function to return the required sum ; Using our deduced result ; Driver code"
How can the above be solved in Java?

class GFG { static int fib ( int n ) { double phi = ( 1 + Math . sqrt ( 5 ) ) / 2 ; return ( int ) Math . round ( Math . pow ( phi , n ) / Math . sqrt ( 5 ) ) ; } static int calculateSum ( int l , int r ) { int sum = fib ( r + 2 ) - fib ( l + 1 ) ; return sum ; } public static void main ( String [ ] args ) { int l = 4 , r = 8 ; System . out . println ( calculateSum ( l , r ) ) ; } }


"Sum of Fibonacci Numbers | Java Program to find sum of Fibonacci numbers ; Computes value of first fibonacci numbers ; Initialize result ; Add remaining terms ; Driver program to test above function"
How can the above be solved in Java?

import java . io . * ; class GFG { static int calculateSum ( int n ) { if ( n <= 0 ) return 0 ; int fibo [ ] = new int [ n + 1 ] ; fibo [ 0 ] = 0 ; fibo [ 1 ] = 1 ; int sum = fibo [ 0 ] + fibo [ 1 ] ; for ( int i = 2 ; i <= n ; i ++ ) { fibo [ i ] = fibo [ i - 1 ] + fibo [ i - 2 ] ; sum += fibo [ i ] ; } return sum ; } public static void main ( String args [ ] ) { int n = 4 ; System . out . println ( " Sum ▁ of ▁ Fibonacci " + " ▁ numbers ▁ is ▁ : ▁ " + calculateSum ( n ) ) ; } }


"Sum of Fibonacci Numbers | Set 2 | Java program for the above approach ; Function to find the sum of first N + 1 fibonacci numbers ; Apply the formula ; Print the result ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { public static void sumFib ( int N ) { double num = ( 1 - Math . sqrt ( 5 ) ) / 2 ; long val = Math . round ( Math . abs ( 1 / ( Math . pow ( num , N + 2 ) + Math . pow ( num , N + 1 ) + Math . pow ( num , N ) + Math . pow ( num , N - 1 ) ) ) - 1 ) ; System . out . println ( val ) ; } public static void main ( String [ ] args ) { int N = 3 ; sumFib ( N ) ; } }


"Sum of Fibonacci Numbers | Set 2 | Java program for the above approach ; Function to find the sum of first N + 1 fibonacci numbers ; Apply the formula ; Print the result ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { public static void sumFib ( int N ) { long num = ( long ) Math . round ( Math . pow ( ( Math . sqrt ( 5 ) + 1 ) / 2.0 , N + 2 ) / Math . sqrt ( 5 ) ) ; System . out . println ( num - 1 ) ; } public static void main ( String [ ] args ) { int N = 3 ; sumFib ( N ) ; } }


"Sum of Fibonacci numbers at even indexes upto N terms | Java Program to find even indexed Fibonacci Sum in O ( Log n ) time . ; Create an array for memoization ; Returns n 'th Fibonacci number using table f[] ; Base cases ; If fib ( n ) is already computed ; Applying above formula [ Note value n & 1 is 1 if n is odd , else 0 ] . ; Computes value of even - indexed Fibonacci Sum ; Driver program to test above function ; Get n ; Find the alternating sum"
How can the above be solved in Java?

class GFG { static int MAX = 1000 ; static int f [ ] = new int [ MAX ] ; static int fib ( int n ) { if ( n == 0 ) { return 0 ; } if ( n == 1 n == 2 ) { return ( f [ n ] = 1 ) ; } if ( f [ n ] == 1 ) { return f [ n ] ; } int k = ( n % 2 == 1 ) ? ( n + 1 ) / 2 : n / 2 ; f [ n ] = ( n % 2 == 1 ) ? ( fib ( k ) * fib ( k ) + fib ( k - 1 ) * fib ( k - 1 ) ) : ( 2 * fib ( k - 1 ) + fib ( k ) ) * fib ( k ) ; return f [ n ] ; } static int calculateEvenSum ( int n ) { return ( fib ( 2 * n + 1 ) - 1 ) ; } public static void main ( String [ ] args ) { int n = 8 ; System . out . println ( " Even ▁ indexed ▁ Fibonacci ▁ Sum ▁ upto ▁ " + n + " ▁ terms : ▁ " + calculateEvenSum ( n ) ) ; } }


"Sum of Fibonacci numbers at even indexes upto N terms | Java Program to find sum of even - indiced Fibonacci numbers ; Computes value of first fibonacci numbers and stores the even - indexed sum ; Initialize result ; Add remaining terms ; For even indices ; Return the alternting sum ; Driver program ; Get n ; Find the even - indiced sum"
How can the above be solved in Java?

import java . io . * ; class GFG { static int calculateEvenSum ( int n ) { if ( n <= 0 ) return 0 ; int fibo [ ] = new int [ 2 * n + 1 ] ; fibo [ 0 ] = 0 ; fibo [ 1 ] = 1 ; int sum = 0 ; for ( int i = 2 ; i <= 2 * n ; i ++ ) { fibo [ i ] = fibo [ i - 1 ] + fibo [ i - 2 ] ; if ( i % 2 == 0 ) sum += fibo [ i ] ; } return sum ; } public static void main ( String [ ] args ) { int n = 8 ; System . out . println ( " Even ▁ indexed ▁ Fibonacci ▁ Sum ▁ upto ▁ " + n + " ▁ terms : ▁ " + + calculateEvenSum ( n ) ) ; } }


"Sum of GCD of all numbers upto N with N itself | Java program to find the Sum of GCD of all integers up to N with N itself ; Function to Find Sum of GCD of each numbers ; Consider all prime factors of no . and subtract their multiples from result ; Check if p is a prime factor ; If yes , then update no and result ; If no has a prime factor greater than Math . sqrt ( n ) then at - most one such prime factor exists ; Return the result ; Finding GCD of pairs ; Calculate the divisors ; Return count of numbers from 1 to N with GCD d with N ; Check if d1 and d2 are equal then skip this ; Driver code"
How can the above be solved in Java?

class GFG { static int getCount ( int d , int n ) { int no = n / d ; int result = no ; for ( int p = 2 ; p * p <= no ; ++ p ) { if ( no % p == 0 ) { while ( no % p == 0 ) no /= p ; result -= result / p ; } } if ( no > 1 ) result -= result / no ; return result ; } static int sumOfGCDofPairs ( int n ) { int res = 0 ; for ( int i = 1 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { int d1 = i ; int d2 = n / i ; res += d1 * getCount ( d1 , n ) ; if ( d1 != d2 ) res += d2 * getCount ( d2 , n ) ; } } return res ; } public static void main ( String [ ] args ) { int n = 12 ; System . out . print ( sumOfGCDofPairs ( n ) ) ; } }


"Sum of GCD of all possible sequences | Java implementation of the above approach ; A recursive function that generates all the sequence and find GCD ; If we reach the sequence of length N g is the GCD of the sequence ; Initialise answer to 0 ; Placing all possible values at this position and recursively find the GCD of the sequence ; Take GCD of GCD calculated uptill now i . e . g with current element ; Take modulo to astatic void overflow ; Return the final answer ; Function that finds the sum of GCD of all the subsequence of N length ; Recursive function that generates the sequence and return the GCD ; Driver Code ; Function Call"
How can the above be solved in Java?

class GFG { static int MOD = ( int ) 1e9 + 7 ; static int calculate ( int pos , int g , int n , int k ) { if ( pos == n ) { return g ; } int answer = 0 ; for ( int i = 1 ; i <= k ; i ++ ) { answer = ( answer % MOD + calculate ( pos + 1 , __gcd ( g , i ) , n , k ) % MOD ) ; answer %= MOD ; } return answer ; } static int sumofGCD ( int n , int k ) { return calculate ( 0 , 0 , n , k ) ; } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } public static void main ( String [ ] args ) { int N = 3 , K = 2 ; System . out . print ( sumofGCD ( N , K ) ) ; } }


"Sum of GCD of all possible sequences | Java implementation of the above approach ; Function to find a ^ b in log ( b ) ; Function that finds the sum of GCD of all the subsequence of N length ; To stores the number of sequences with gcd i ; Find contribution of each gcd to happen ; To count multiples ; possible sequences with overcounting ; to astatic void overflow ; Find extra element which will not form gcd = i ; Find overcounting ; Remove the overcounting ; To store the final answer ; Return Final answer ; Driver Code ; Function call"
How can the above be solved in Java?

class GFG { static int MOD = ( int ) 1e9 + 7 ; static int fastexpo ( int a , int b ) { int res = 1 ; a %= MOD ; while ( b > 0 ) { if ( b % 2 == 1 ) res = ( res * a ) % MOD ; a *= a ; a %= MOD ; b >>= 1 ; } return res ; } static int sumofGCD ( int n , int k ) { int [ ] count = new int [ k + 1 ] ; for ( int g = k ; g >= 1 ; g -- ) { int count_multiples = k / g ; int temp ; temp = fastexpo ( count_multiples , n ) ; temp %= MOD ; int extra = 0 ; for ( int j = g * 2 ; j <= k ; j += g ) { extra = ( extra + count [ j ] ) ; extra %= MOD ; } count [ g ] = ( temp - extra + MOD ) ; count [ g ] %= MOD ; } int sum = 0 ; int add ; for ( int i = 1 ; i <= k ; ++ i ) { add = ( count [ i ] % MOD * i % MOD ) ; add %= MOD ; sum += add ; sum %= MOD ; } return sum ; } public static void main ( String [ ] args ) { int N = 3 , K = 2 ; System . out . print ( sumofGCD ( N , K ) ) ; } }


"Sum of LCM ( 1 , n ) , LCM ( 2 , n ) , LCM ( 3 , n ) , ... , LCM ( n , n ) | Java implementation of the approach ; Euler totient Function ; Function to return the required LCM sum ; Summation of d * ETF ( d ) where d belongs to set of divisors of n ; Driver code"
How can the above be solved in Java?

class GFG { static int n = 1000002 ; static int [ ] phi = new int [ n + 2 ] ; static int [ ] ans = new int [ n + 2 ] ; static void ETF ( ) { for ( int i = 1 ; i <= n ; i ++ ) { phi [ i ] = i ; } for ( int i = 2 ; i <= n ; i ++ ) { if ( phi [ i ] == i ) { phi [ i ] = i - 1 ; for ( int j = 2 * i ; j <= n ; j += i ) { phi [ j ] = ( phi [ j ] * ( i - 1 ) ) / i ; } } } } static int LcmSum ( int m ) { ETF ( ) ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = i ; j <= n ; j += i ) { ans [ j ] += ( i * phi [ i ] ) ; } } int answer = ans [ m ] ; answer = ( answer + 1 ) * m ; answer = answer / 2 ; return answer ; } public static void main ( String [ ] args ) { int m = 5 ; System . out . println ( LcmSum ( m ) ) ; } }


"Sum of M maximum distinct digit sum from 1 to N that are factors of K | Java implementation to find the sum of maximum distinct digit sum of at most M numbers from 1 to N that are factors of K ; Function to find the factors of K in N ; Initialise a vector ; Find out the factors of K less than N ; Find the digit sum of each factor ; Sum of digits for each element in vector ; Find the largest M distinct digit sum from the digitSum vector ; Find the sum of last M numbers . ; Find the at most M numbers from N natural numbers whose digit sum is distinct and those M numbers are factors of K . ; Find out the factors of K less than N ; Sum of digits for each element in vector ; Sorting the digitSum vector ; Removing the duplicate elements ; " HashSet " is stores only unique elements ; Finding the sum and returning it ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { public static Vector < Integer > findFactors ( int n , int k ) { Vector < Integer > factors = new Vector < Integer > ( ) ; for ( int i = 1 ; i <= Math . sqrt ( k ) ; i ++ ) { if ( k % i == 0 ) { if ( k / i == i && i <= n ) factors . add ( i ) ; else { if ( i <= n ) factors . add ( i ) ; if ( k / i <= n ) factors . add ( k / i ) ; } } } return factors ; } public static Vector < Integer > findDigitSum ( Vector < Integer > a ) { for ( int i = 0 ; i < a . size ( ) ; i ++ ) { int c = 0 ; while ( a . get ( i ) > 0 ) { c += ( a . get ( i ) % 10 ) ; a . set ( i , ( a . get ( i ) / 10 ) ) ; } a . set ( i , c ) ; } return a ; } public static int findMMaxDistinctDigitSum ( Vector < Integer > distinctDigitSum , int m ) { int sum = 0 ; for ( int i = distinctDigitSum . size ( ) - 1 ; i >= 0 && m > 0 ; i -- , m -- ) sum += distinctDigitSum . get ( i ) ; return sum ; } public static int findDistinctMnumbers ( int n , int k , int m ) { Vector < Integer > factors = findFactors ( n , k ) ; Vector < Integer > digitSum = findDigitSum ( factors ) ; Collections . sort ( digitSum ) ; HashSet < Integer > hs1 = new HashSet < Integer > ( digitSum ) ; Vector < Integer > vect2 = new Vector < Integer > ( hs1 ) ; return findMMaxDistinctDigitSum ( vect2 , m ) ; } public static void main ( String args [ ] ) { int n = 100 , k = 80 , m = 4 ; System . out . println ( findDistinctMnumbers ( n , k , m ) ) ; } }


"Sum of Manhattan distances between all pairs of points | Java Program to find sum of Manhattan distance between all the pairs of given points ; Return the sum of distance between all the pair of points . ; for each point , finding distance to rest of the point ; Driven Program"
How can the above be solved in Java?

import java . io . * ; class GFG { static int distancesum ( int x [ ] , int y [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) sum += ( Math . abs ( x [ i ] - x [ j ] ) + Math . abs ( y [ i ] - y [ j ] ) ) ; return sum ; } public static void main ( String [ ] args ) { int x [ ] = { - 1 , 1 , 3 , 2 } ; int y [ ] = { 5 , 6 , 5 , 3 } ; int n = x . length ; System . out . println ( distancesum ( x , y , n ) ) ; } }


"Sum of Manhattan distances between all pairs of points | Java Program to find sum of Manhattan distances between all the pairs of given points ; Return the sum of distance of one axis . ; sorting the array . ; for each point , finding the distance . ; Driven Program"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int distancesum ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int res = 0 , sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { res += ( arr [ i ] * i - sum ) ; sum += arr [ i ] ; } return res ; } static int totaldistancesum ( int x [ ] , int y [ ] , int n ) { return distancesum ( x , n ) + distancesum ( y , n ) ; } public static void main ( String [ ] args ) { int x [ ] = { - 1 , 1 , 3 , 2 } ; int y [ ] = { 5 , 6 , 5 , 3 } ; int n = x . length ; System . out . println ( totaldistancesum ( x , y , n ) ) ; } }


"Sum of Manhattan distances between repetitions in a String | Java program for the above approach ; Function to find the sum of the manhattan distances between same characters in string ; Vector to store indices for each unique character of the string ; Append the position of each character in their respective vectors ; Store the required result ; Iterate over all the characters ; Calculate sum of all elements present in the vector ; Traverse the current vector ; Find suffix [ i + 1 ] ; Adding distance of all pairs whose first element is i and second element belongs to [ i + 1 , n ] ; Print the result ; Driver code ; Given Input ; Function Call"
How can the above be solved in Java?

import java . lang . * ; import java . util . * ; class GFG { static void SumofDistances ( String s ) { ArrayList < ArrayList < Integer > > v = new ArrayList < > ( ) ; for ( int i = 0 ; i < 26 ; i ++ ) v . add ( new ArrayList < > ( ) ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { v . get ( s . charAt ( i ) - ' a ' ) . add ( i ) ; } int ans = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) { int sum = 0 ; for ( int j = 0 ; j < v . get ( i ) . size ( ) ; j ++ ) { sum += v . get ( i ) . get ( j ) ; } for ( int j = 0 ; j < v . get ( i ) . size ( ) ; j ++ ) { sum -= v . get ( i ) . get ( j ) ; ans += ( sum - ( v . get ( i ) . size ( ) - 1 - j ) * ( v . get ( i ) . get ( j ) ) ) ; } } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { String s = " ababa " ; SumofDistances ( s ) ; } }


"Sum of Maximum and Minimum prime factor of every number in the Array | Java implementation of the approach ; max_prime [ i ] represent maximum prime number that divides the number i ; min_prime [ i ] represent minimum prime number that divides the number i ; Function to store the minimum prime factor and the maximum prime factor in two arrays ; Check for prime number if min_prime [ i ] > 0 , then it is not a prime number ; if i is a prime number min_prime number that divide prime number and max_prime number that divide prime number is the number itself . ; If this number is being visited for first time then this divisor must be the smallest prime number that divides this number ; The last prime number that divides this number will be maximum . ; Function to find the sum of the minimum and the maximum prime factors of every number from the given array ; Pre - calculation ; For every element of the given array ; The sum of its smallest and largest prime factor ; Driver code"
How can the above be solved in Java?

class GFG { static int MAX = 100000 ; static int max_prime [ ] = new int [ MAX + 1 ] ; static int min_prime [ ] = new int [ MAX + 1 ] ; static void sieve ( int n ) { for ( int i = 2 ; i <= n ; ++ i ) { if ( min_prime [ i ] > 0 ) { continue ; } min_prime [ i ] = i ; max_prime [ i ] = i ; int j = i + i ; while ( j <= n ) { if ( min_prime [ j ] == 0 ) { min_prime [ j ] = i ; } max_prime [ j ] = i ; j += i ; } } } static void findSum ( int arr [ ] , int n ) { sieve ( MAX ) ; for ( int i = 0 ; i < n ; i ++ ) { int sum = min_prime [ arr [ i ] ] + max_prime [ arr [ i ] ] ; System . out . print ( sum + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 10 , 15 , 20 , 25 , 30 } ; int n = arr . length ; findSum ( arr , n ) ; } }


"Sum of N terms in the expansion of Arcsin ( x ) | Java implementation of the approach ; Function to find the arcsin ( x ) ; The power to which ' x ' is raised ; Numerator value ; Denominator value ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void find_Solution ( double x , int n ) { double sum = x , e = 2 , o = 1 , p = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { p += 2 ; sum += ( double ) ( o / e ) * ( double ) ( Math . pow ( x , p ) / p ) ; o = o * ( o + 2 ) ; e = e * ( e + 2 ) ; } System . out . println ( sum ) ; } public static void main ( String [ ] args ) { double x = - 0.5 ; if ( Math . abs ( x ) >= 1 ) { System . out . println ( " Invalid ▁ Input " ) ; } int n = 8 ; find_Solution ( x , n ) ; } }


"Sum of N | Java implementation to illustrate the program ; Function to calculate the sum recursively ; Base cases ; If n is odd ; If n is even ; Function to prlong the value of Sum ; Driver Code ; First element ; Common difference ; Number of elements ; Mod value"
How can the above be solved in Java?

import java . io . * ; class GFG { static long SumGPUtil ( long r , long n , long m ) { if ( n == 0 ) return 1 ; if ( n == 1 ) return ( 1 + r ) % m ; long ans ; if ( n % 2 == 1 ) { ans = ( 1 + r ) * SumGPUtil ( ( r * r ) % m , ( n - 1 ) / 2 , m ) ; } else { ans = 1 + ( r * ( 1 + r ) * SumGPUtil ( ( r * r ) % m , ( n / 2 ) - 1 , m ) ) ; } return ( ans % m ) ; } static void SumGP ( long a , long r , long N , long M ) { long answer ; answer = a * SumGPUtil ( r , N , M ) ; answer = answer % M ; System . out . println ( answer ) ; } public static void main ( String [ ] args ) { long a = 1 ; long r = 4 ; long N = 10000 ; long M = 100000 ; SumGP ( a , r , N , M ) ; } }


"Sum of Nodes and respective Neighbors on the path from root to a vertex V | Java Program to implement the above approach ; Creating Adjacency list ; Function to perform DFS traversal ; Initializing parent of each node to p ; Iterate over the children ; Function to add values of children to respective parent nodes ; Root node ; Function to return sum of values of each node in path from V to the root ; Path from node V to root node ; Driver Code ; Insert edges into the graph ; Values assigned to each vertex ; Constructing the tree using adjacency list ; Parent array ; store values in the parent array ; Add values of children to the parent ; Find sum of nodes lying in the path ; Add root node since its value is not included yet"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { private static List < List < Integer > > constructTree ( int n , int [ ] [ ] edges ) { List < List < Integer > > adjl = new ArrayList < List < Integer > > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { adjl . add ( new ArrayList < Integer > ( ) ) ; } for ( int [ ] e : edges ) { int u = e [ 0 ] ; int v = e [ 1 ] ; adjl . get ( u ) . add ( v ) ; adjl . get ( v ) . add ( u ) ; } return adjl ; } private static void DFS ( List < List < Integer > > adjl , int [ ] parent , int u , int p ) { parent [ u ] = p ; for ( int v : adjl . get ( u ) ) { if ( v != p ) { DFS ( adjl , parent , v , u ) ; } } } private static int [ ] valuesFromChildren ( int [ ] parent , int [ ] values ) { int [ ] valuesChildren = new int [ parent . length ] ; for ( int i = 0 ; i < parent . length ; i ++ ) { if ( parent [ i ] == - 1 ) continue ; else { int p = parent [ i ] ; valuesChildren [ p ] += values [ i ] ; } } return valuesChildren ; } private static int findSumOfValues ( int v , int [ ] parent , int [ ] valuesChildren ) { int cur_node = v ; int sum = 0 ; while ( cur_node != - 1 ) { sum += valuesChildren [ cur_node ] ; cur_node = parent [ cur_node ] ; } return sum ; } public static void main ( String [ ] args ) { int n = 8 ; int [ ] [ ] edges = { { 0 , 1 } , { 0 , 2 } , { 0 , 3 } , { 1 , 4 } , { 1 , 5 } , { 4 , 7 } , { 3 , 6 } } ; int v = 7 ; int [ ] values = new int [ ] { 1 , 2 , 3 , 0 , 0 , 4 , 3 , 6 } ; List < List < Integer > > adjl = constructTree ( n , edges ) ; int [ ] parent = new int [ n ] ; DFS ( adjl , parent , 0 , - 1 ) ; int [ ] valuesChildren = valuesFromChildren ( parent , values ) ; int sum = findSumOfValues ( v , parent , valuesChildren ) ; sum += values [ 0 ] ; System . out . println ( sum ) ; } }


"Sum of P terms of an AP if Mth and Nth terms are given | Java implementation of the above approach ; Function to calculate the value of the ; Calculate value of d using formula ; Calculate value of a using formula ; Return pair ; Function to calculate value sum of first p numbers of the series ; First calculate value of a and d ; Calculate the sum by using formula ; Return the sum ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static ArrayList < Integer > findingValues ( int m , int n , int mth , int nth ) { int d = ( Math . abs ( mth - nth ) ) / Math . abs ( ( m - 1 ) - ( n - 1 ) ) ; int a = mth - ( ( m - 1 ) * d ) ; ArrayList < Integer > res = new ArrayList < Integer > ( ) ; res . add ( a ) ; res . add ( d ) ; return res ; } static int findSum ( int m , int n , int mth , int nth , int p ) { ArrayList < Integer > ad = findingValues ( m , n , mth , nth ) ; int a = ad . get ( 0 ) ; int d = ad . get ( 1 ) ; int sum = ( p * ( 2 * a + ( p - 1 ) * d ) ) / 2 ; return sum ; } public static void main ( String [ ] args ) { int m = 6 , n = 10 , mTerm = 12 , nTerm = 20 , p = 5 ; System . out . println ( findSum ( m , n , mTerm , nTerm , p ) ) ; } }


"Sum of Perrin Numbers | Java program to calculate sum of Perrin Numbers ; function for sum of first n Perrin number . ; if ( n == 0 ) n = 0 ; if ( n == 1 ) n = 1 ; if ( n == 2 ) n = 2 ; calculate k = 5 sum of three previous step . ; Sum remaining numbers ; calculate next term ; Driver code"
How can the above be solved in Java?

import java . lang . * ; class GFG { static int calSum ( int n ) { int a = 3 , b = 0 , c = 2 ; return 3 ; return 3 ; return 5 ; int sum = 5 ; while ( n > 2 ) { int d = a + b ; sum += d ; a = b ; b = c ; c = d ; n -- ; } return sum ; } public static void main ( String [ ] args ) { int n = 9 ; System . out . print ( calSum ( n ) ) ; } }


"Sum of Semi | Java implementation of the above approach ; Vector to store the primes ; Create a boolean array " prime [ 0 . . n ] " ; Initialize along prime values to be true ; If prime [ p ] is not changed then it is a prime ; Update along 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 return the semi - prime sum ; Variable to store the sum of semi - primes ; Iterate over the prime values ; Break the loop once the product exceeds N ; Add valid products which are less than or equal to N each product is a semi - prime number ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static Vector < Long > pr = new Vector < > ( ) ; static boolean prime [ ] = new boolean [ 10000000 + 1 ] ; static void sieve ( long n ) { for ( int i = 2 ; i <= n ; i += 1 ) { prime [ i ] = true ; } for ( int p = 2 ; ( int ) p * ( int ) p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = ( int ) p * ( int ) p ; i <= n ; i += p ) prime [ i ] = false ; } } for ( int p = 2 ; p <= n ; p ++ ) if ( prime [ p ] ) pr . add ( ( long ) p ) ; } static long SemiPrimeSum ( long N ) { long ans = 0 ; for ( int i = 0 ; i < pr . size ( ) ; i += 1 ) { for ( int j = i ; j < pr . size ( ) ; j += 1 ) { if ( ( long ) pr . get ( i ) * ( long ) pr . get ( j ) > N ) break ; ans += ( long ) pr . get ( i ) * ( long ) pr . get ( j ) ; } } return ans ; } public static void main ( String [ ] args ) { long N = 6 ; sieve ( N ) ; System . out . println ( SemiPrimeSum ( N ) ) ; } }


"Sum of Series ( n ^ 2 | javaProgram to finding the sum of the nth series ; function that calculate the sum of the nth series ; using formula of the nth term ; Driver function"
How can the above be solved in Java?

import java . io . * ; class GFG { static int sum_series ( int n ) { int nSquare = n * n ; return nSquare * ( nSquare - 1 ) / 4 ; } public static void main ( String [ ] args ) { int n = 2 ; System . out . println ( sum_series ( n ) ) ; } }


"Sum of XOR of all sub | Java implementation of the approach ; Sum of XOR of all K length sub - array of an array ; If the length of the array is less than k ; Array that will store xor values of subarray from 1 to i ; Traverse through the array ; If i is greater than zero , store xor of all the elements from 0 to i ; If it is the first element ; If i is greater than k ; Xor of values from 0 to i ; Now to find subarray of length k that ends at i , xor sum with x [ i - k ] ; Add the xor of elements from i - k + 1 to i ; Return the resultant sum ; ; Driver code"
How can the above be solved in Java?

class GFG { static int FindXorSum ( int arr [ ] , int k , int n ) { if ( n < k ) return 0 ; int [ ] x = new int [ n ] ; int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i > 0 ) x [ i ] = x [ i - 1 ] ^ arr [ i ] ; else x [ i ] = arr [ i ] ; if ( i >= k - 1 ) { int sum = 0 ; sum = x [ i ] ; if ( i - k > - 1 ) sum ^= x [ i - k ] ; result += sum ; } } return result ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int n = 4 , k = 2 ; System . out . println ( FindXorSum ( arr , k , n ) ) ; } }


"Sum of XOR of all subarrays | Java program to find the sum of XOR of all subarray of the array ; Function to calculate the sum of XOR of all subarrays ; variable to store the final sum ; multiplier ; variable to store number of sub - arrays with odd number of elements with ith bits starting from the first element to the end of the array ; variable to check the status of the odd - even count while calculating c_odd ; loop to calculate initial value of c_odd ; loop to iterate through all the elements of the array and update sum ; updating the multiplier ; returning the sum ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findXorSum ( int arr [ ] , int n ) { int sum = 0 ; int mul = 1 ; for ( int i = 0 ; i < 30 ; i ++ ) { int c_odd = 0 ; boolean odd = false ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( arr [ j ] & ( 1 << i ) ) > 0 ) odd = ( ! odd ) ; if ( odd ) c_odd ++ ; } for ( int j = 0 ; j < n ; j ++ ) { sum += ( mul * c_odd ) ; if ( ( arr [ j ] & ( 1 << i ) ) > 0 ) c_odd = ( n - j - c_odd ) ; } mul *= 2 ; } return sum ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 8 , 13 } ; int n = arr . length ; System . out . println ( findXorSum ( arr , n ) ) ; } }


"Sum of XOR of sum of all pairs in an array | Java program to find XOR of pair sums . ; Driver code"
How can the above be solved in Java?

class GFG { static int xorPairSum ( int ar [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum = sum ^ ar [ i ] ; return 2 * sum ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 2 , 3 } ; int n = arr . length ; System . out . println ( xorPairSum ( arr , n ) ) ; } }


"Sum of absolute differences of indices of occurrences of each array element | Set 2 | Java program for the above approach ; Stores the count of occurrences and previous index of every element ; Constructor ; Function to calculate the sum of absolute differences of indices of occurrences of array element ; Stores the count of elements and their previous indices ; Initialize 2 arrays left [ ] and right [ ] of size N ; Traverse the given array ; If arr [ i ] is present in the Map ; Update left [ i ] to 0 and update the value of arr [ i ] in map ; Otherwise , get the value from the map and update left [ i ] ; Clear the map to calculate right [ ] array ; Traverse the array arr [ ] in reverse ; If arr [ i ] is present in theMap ; Update right [ i ] to 0 and update the value of arr [ i ] in the Map ; Otherwise get the value from the map and update right [ i ] ; Iterate in the range [ 0 , N - 1 ] and print the sum of left [ i ] and right [ i ] as the result ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static class pair { int count , prevIndex ; pair ( int count , int prevIndex ) { this . count = count ; this . prevIndex = prevIndex ; } } static void findSum ( int [ ] arr , int n ) { Map < Integer , pair > map = new HashMap < > ( ) ; int [ ] left = new int [ n ] ; int [ ] right = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! map . containsKey ( arr [ i ] ) ) { left [ i ] = 0 ; map . put ( arr [ i ] , new pair ( 1 , i ) ) ; } else { pair tmp = map . get ( arr [ i ] ) ; left [ i ] = ( tmp . count ) * ( i - tmp . prevIndex ) + left [ tmp . prevIndex ] ; map . put ( arr [ i ] , new pair ( tmp . count + 1 , i ) ) ; } } map . clear ( ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( ! map . containsKey ( arr [ i ] ) ) { right [ i ] = 0 ; map . put ( arr [ i ] , new pair ( 1 , i ) ) ; } else { pair tmp = map . get ( arr [ i ] ) ; right [ i ] = ( tmp . count ) * ( Math . abs ( i - tmp . prevIndex ) ) + right [ tmp . prevIndex ] ; map . put ( arr [ i ] , new pair ( tmp . count + 1 , i ) ) ; } } for ( int i = 0 ; i < n ; i ++ ) System . out . print ( left [ i ] + right [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 3 , 1 , 1 , 2 } ; int N = arr . length ; findSum ( arr , N ) ; } }


"Sum of all LCP of maximum length by selecting any two Strings at a time | Java program to find Sum of all LCP of maximum length by selecting any two Strings at a time ; Using map to store the pointers of children nodes for dynamic implementation , for making the program space efiicient ; Counts the number of times the node is visited while making the trie ; Initially visited value for all nodes is zero ; Head node of the trie is initialize as ' \0' , after this all Strings add ; Function to insert the Strings in the trie ; Inserting character - by - character ; If the node of ch is not present in map make a new node and add in map ; Recursive function to calculate the answer argument is passed by reference ; To store changed visited values from children of this node i . e . number of nodes visited by its children ; Updating the visited variable , telling number of nodes that have already been visited by its children ; If node . visited > 1 , means more than one String has prefix up till this node common in them ; Number of String pair with current node common in them ; Updating visited variable of current node ; Returning the total number of nodes already visited that needs to be updated to previous node ; Function to run the dfs function for the first time and give the answer variable ; Stores the final answer as sum of all depths ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static class TrieNode { char val ; HashMap < Character , TrieNode > children ; int visited ; TrieNode ( char x ) { val = x ; visited = 0 ; children = new HashMap < > ( ) ; } } static class Trie { TrieNode head ; int ans ; Trie ( ) { head = new TrieNode ( ' \0' ) ; ans = 0 ; } void addWord ( String s ) { TrieNode temp = head ; int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { char ch = s . charAt ( i ) ; if ( temp . children . get ( ch ) == null ) { temp . children . put ( ch , new TrieNode ( ch ) ) ; } temp = temp . children . get ( ch ) ; temp . visited ++ ; } } int dfs ( TrieNode node , int depth ) { int vis = 0 ; Iterator hmIterator = node . children . entrySet ( ) . iterator ( ) ; while ( hmIterator . hasNext ( ) ) { Map . Entry child = ( Map . Entry ) hmIterator . next ( ) ; vis += dfs ( ( TrieNode ) child . getValue ( ) , depth + 1 ) ; } node . visited -= vis ; int String_pair = 0 ; if ( node . visited > 1 ) { String_pair = ( node . visited / 2 ) ; ans += ( depth * String_pair ) ; node . visited -= ( 2 * String_pair ) ; } return ( 2 * String_pair + vis ) ; } int dfshelper ( ) { ans = 0 ; dfs ( head , 0 ) ; return ans ; } } public static void main ( String args [ ] ) { Trie T = new Trie ( ) ; String str [ ] = { " babab " , " ababb " , " abbab " , " aaaaa " , " babaa " , " babbb " } ; int n = 6 ; for ( int i = 0 ; i < n ; i ++ ) { T . addWord ( str [ i ] ) ; } int ans = T . dfshelper ( ) ; System . out . println ( ans ) ; } }


"Sum of all N digit palindrome numbers | Java program for the above approach ; Function to calculate sum of n digit number ; Corner case ; Using above approach ; Driver code"
How can the above be solved in Java?

class GFG { static double getSum ( int n ) { double sum = 0 ; if ( n == 1 ) { sum = 45.0 ; } else { sum = ( 99.0 / 2.0 ) * Math . pow ( 10 , n - 1 ) * Math . pow ( 10 , ( n - 1 ) / 2 ) ; } return sum ; } public static void main ( String [ ] args ) { int n = 3 ; double ans = getSum ( n ) ; System . out . print ( ans ) ; } }


"Sum of all N digit palindrome numbers | Java program for the above approach ; Function to check palindrome ; Function to calculate the sum of n - digit palindrome ; Run a loop to check all possible palindrome ; If palindrome append sum ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean isPalindrome ( String s ) { int left = 0 , right = s . length ( ) - 1 ; while ( left <= right ) { if ( s . charAt ( left ) != s . charAt ( right ) ) { return false ; } left ++ ; right -- ; } return true ; } static long getSum ( int n ) { int start = ( int ) Math . pow ( 10 , n - 1 ) ; int end = ( int ) ( Math . pow ( 10 , n ) - 1 ) ; long sum = 0 ; for ( int i = start ; i <= end ; i ++ ) { String s = String . valueOf ( i ) ; if ( isPalindrome ( s ) ) { sum += i ; } } return sum ; } public static void main ( String [ ] args ) { int n = 1 ; long ans = getSum ( n ) ; System . out . print ( ans ) ; } }


"Sum of all N digit palindromic numbers divisible by 9 formed using digits 1 to 9 | Java implementation to find the sum of all the N digit palindromic numbers divisible by 9 ; Function for finding count of N digits palindrome which are divisible by 9 ; If N is odd ; If N is even ; Function for finding sum of N digits palindrome which are divisible by 9 ; Count the possible number of palindrome ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int countPalindrome ( int n ) { int count ; if ( n % 2 == 1 ) { count = ( int ) Math . pow ( 9 , ( n - 1 ) / 2 ) ; } else { count = ( int ) Math . pow ( 9 , ( n - 2 ) / 2 ) ; } return count ; } static int sumPalindrome ( int n ) { int count = countPalindrome ( n ) ; int res = 0 ; if ( n == 1 ) return 9 ; if ( n == 2 ) return 99 ; for ( int i = 0 ; i < n ; i ++ ) { res = res * 10 + count * 5 ; } return res ; } public static void main ( String [ ] args ) { int n = 3 ; System . out . println ( sumPalindrome ( n ) ) ; } }