"First and Last Three Bits | Java implementation of the approach ; Function to print the first and last 3 bits equivalent decimal number ; Converting n to binary ; Length of the array has to be at least 3 ; Convert first three bits to decimal ; Print the decimal ; Convert last three bits to decimal ; Print the decimal ; Driver code"
How can the above be solved in Java?

import java . math . * ; public class GFG { static void binToDecimal3 ( int n ) { int a [ ] = new int [ 64 ] ; int x = 0 , i ; for ( i = 0 ; n > 0 ; i ++ ) { a [ i ] = n % 2 ; n /= 2 ; } x = ( i < 3 ) ? 3 : i ; int d = 0 , p = 0 ; for ( int j = x - 3 ; j < x ; j ++ ) d += a [ j ] * Math . pow ( 2 , p ++ ) ; System . out . print ( d + " ▁ " ) ; d = 0 ; p = 0 ; for ( int k = 0 ; k < 3 ; k ++ ) d += a [ k ] * Math . pow ( 2 , p ++ ) ; System . out . print ( d ) ; } public static void main ( String [ ] args ) { int n = 86 ; binToDecimal3 ( n ) ; } }


"First and Last Three Bits | Java implementation of the approach ; Function to print the first and last 3 bits equivalent decimal number ; Number formed from last three bits ; Let us get first three bits in n ; Number formed from first three bits ; Printing result ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void binToDecimal3 ( int n ) { int last_3 = ( ( n & 4 ) + ( n & 2 ) + ( n & 1 ) ) ; n = n >> 3 ; while ( n > 7 ) n = n >> 1 ; int first_3 = ( ( n & 4 ) + ( n & 2 ) + ( n & 1 ) ) ; System . out . println ( first_3 + " ▁ " + last_3 ) ; } public static void main ( String args [ ] ) { int n = 86 ; binToDecimal3 ( n ) ; } }


"First collision point of two series | Java program to calculate the colliding point of two series ; Iterating through n terms of the first series ; x is i - th term of first series ; d is first element of second series and c is common difference for second series . ; If no term of first series is found ; Driver function"
How can the above be solved in Java?

import java . io . * ; class GFG { static void point ( int a , int b , int c , int d , int n ) { int x , flag = 0 ; for ( int i = 0 ; i < n ; i ++ ) { x = b + i * a ; if ( ( x - d ) % c == 0 && x - d >= 0 ) { System . out . println ( x ) ; flag = 1 ; break ; } } if ( flag == 0 ) { System . out . println ( " No ▁ collision ▁ point " ) ; } } public static void main ( String [ ] args ) { int a = 20 ; int b = 2 ; int c = 9 ; int d = 19 ; int n = 20 ; point ( a , b , c , d , n ) ; } }


"First common element in two linked lists | Java program to find first common element in two unsorted linked list ; Link list node ; A utility function to insert a node at the beginning of a linked list ; Returns the first repeating element in linked list ; Traverse through every node of first list ; If current node is present in second list ; If no common node ; Driver code"
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 firstCommon ( Node head1 , Node head2 ) { for ( ; head1 != null ; head1 = head1 . next ) for ( Node p = head2 ; p != null ; p = p . next ) if ( p . data == head1 . data ) return head1 . data ; return 0 ; } public static void main ( String [ ] args ) { Node head1 = null ; head1 = push ( head1 , 20 ) ; head1 = push ( head1 , 5 ) ; head1 = push ( head1 , 15 ) ; head1 = push ( head1 , 10 ) ; Node head2 = null ; head2 = push ( head2 , 10 ) ; head2 = push ( head2 , 2 ) ; head2 = push ( head2 , 15 ) ; head2 = push ( head2 , 8 ) ; System . out . println ( firstCommon ( head1 , head2 ) ) ; } }


"First digit in factorial of a number | A Java program for finding the First digit of the large factorial number ; Removing trailing 0 s as this does not change first digit . ; loop for divide the fact until it become the single digit and return the fact ; derive main"
How can the above be solved in Java?

class GFG { static int firstDigit ( int n ) { int fact = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { fact = fact * i ; while ( fact % 10 == 0 ) fact = fact / 10 ; } while ( fact >= 10 ) fact = fact / 10 ; return fact ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . println ( firstDigit ( n ) ) ; } }


"First digit in product of an array of numbers | Java implementation of finding first digit of product of n numbers ; returns the first digit of product of elements of arr [ ] ; stores the logarithm of product of elements of arr [ ] ; fractional ( s ) = s - floor ( s ) ; ans = 10 ^ fract_s ; Driver method"
How can the above be solved in Java?

class Test { static int FirstDigit ( int arr [ ] , int n ) { double S = 0 ; for ( int i = 0 ; i < n ; i ++ ) S = S + Math . log10 ( arr [ i ] * 1.0 ) ; double fract_S = S - Math . floor ( S ) ; int ans = ( int ) Math . pow ( 10 , fract_S ) ; return ans ; } public static void main ( String args [ ] ) { int arr [ ] = { 5 , 8 , 3 , 7 } ; System . out . println ( FirstDigit ( arr , arr . length ) ) ; } }


"First digit in product of an array of numbers | Java implementation to find first digit of a single number ; Keep dividing by 10 until it is greater than equal to 10 ; Driver method"
How can the above be solved in Java?

class Test { static int firstDigit ( int x ) { while ( x >= 10 ) x = x / 10 ; return x ; } public static void main ( String args [ ] ) { System . out . println ( firstDigit ( 12345 ) ) ; System . out . println ( firstDigit ( 5432 ) ) ; } }


"First element greater than or equal to X in prefix sum of N numbers using Binary Lifting | Java program to find lower_bound of x in prefix sums array using binary lifting . ; function to make prefix sums array ; function to find lower_bound of x in prefix sums array using binary lifting . ; initialize position ; find log to the base 2 value of n . ; if x less than first number . ; starting from most significant bit . ; if value at this position less than x then updateposition Here ( 1 << i ) is similar to 2 ^ i . ; + 1 because ' pos ' will have position of largest value less than ' x ' ; Driver code ; given array ; value to find ; size of array ; to store prefix sum ; call for prefix sum ; function call"
How can the above be solved in Java?

import java . util . * ; class solution { static void MakePreSum ( int [ ] arr , int [ ] presum , int n ) { presum [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) presum [ i ] = presum [ i - 1 ] + arr [ i ] ; } static int BinaryLifting ( int [ ] presum , int n , int x ) { int pos = 0 ; int LOGN = ( int ) Math . log ( n ) ; if ( x <= presum [ 0 ] ) return 0 ; for ( int i = LOGN ; i >= 0 ; i -- ) { if ( pos + ( 1 << i ) < n && presum [ pos + ( 1 << i ) ] < x ) { pos += ( 1 << i ) ; } } return pos + 1 ; } public static void main ( String args [ ] ) { int [ ] arr = { 2 , 5 , 7 , 1 , 6 , 9 , 12 , 4 , 6 } ; int x = 8 ; int n = arr . length ; int [ ] presum = new int [ n ] ; Arrays . fill ( presum , 0 ) ; MakePreSum ( arr , presum , n ) ; System . out . println ( BinaryLifting ( presum , n , x ) ) ; } }


"First negative integer in every window of size k | Java code for First negative integer in every window of size k ; Skip out of window and positive elements ; Check if a negative element is found , otherwise use 0 ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void printFirstNegativeInteger ( int arr [ ] , int k , int n ) { int firstNegativeIndex = 0 ; int firstNegativeElement ; for ( int i = k - 1 ; i < n ; i ++ ) { while ( ( firstNegativeIndex < i ) && ( firstNegativeIndex <= i - k arr [ firstNegativeIndex ] > 0 ) ) { firstNegativeIndex ++ ; } if ( arr [ firstNegativeIndex ] < 0 ) { firstNegativeElement = arr [ firstNegativeIndex ] ; } else { firstNegativeElement = 0 ; } System . out . print ( firstNegativeElement + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 12 , - 1 , - 7 , 8 , - 15 , 30 , 16 , 28 } ; int n = arr . length ; int k = 3 ; printFirstNegativeInteger ( arr , k , n ) ; } }


"First negative integer in every window of size k | Java implementation to find the first negative integer in every window of size k ; function to find the first negative integer in every window of size k ; A Double Ended Queue , Di that will store indexes of useful array elements for the current window of size k . The useful elements are all negative integers . ; Process first k ( or first window ) elements of array ; Add current element at the rear of Di if it is a negative integer ; Process rest of the elements , i . e . , from arr [ k ] to arr [ n - 1 ] ; if Di is not empty then the element at the front of the queue is the first negative integer of the previous window ; else the window does not have a negative integer ; Remove the elements which are out of this window ; Remove from front of queue ; Add current element at the rear of Di if it is a negative integer ; Print the first negative integer of last window ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void printFirstNegativeInteger ( int arr [ ] , int n , int k ) { LinkedList < Integer > Di = new LinkedList < > ( ) ; int i ; for ( i = 0 ; i < k ; i ++ ) if ( arr [ i ] < 0 ) Di . add ( i ) ; for ( ; i < n ; i ++ ) { if ( ! Di . isEmpty ( ) ) System . out . print ( arr [ Di . peek ( ) ] + " ▁ " ) ; else System . out . print ( "0" + " ▁ " ) ; while ( ( ! Di . isEmpty ( ) ) && Di . peek ( ) < ( i - k + 1 ) ) Di . remove ( ) ; if ( arr [ i ] < 0 ) Di . add ( i ) ; } if ( ! Di . isEmpty ( ) ) System . out . print ( arr [ Di . peek ( ) ] + " ▁ " ) ; else System . out . print ( "0" + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 12 , - 1 , - 7 , 8 , - 15 , 30 , 16 , 28 } ; int n = arr . length ; int k = 3 ; printFirstNegativeInteger ( arr , n , k ) ; } }


"First negative integer in every window of size k | Java implementation to find the first negative integer in every window of size k ; function to find the first negative integer in every window of size k ; flag to check whether window contains a negative integer or not ; Loop for each subarray ( window ) of size k ; traverse through the current window ; if a negative integer is found , then it is the first negative integer for current window . Print it , set the flag and break ; if the current window does not contain a negative integer ; Driver program to test above functions"
How can the above be solved in Java?

import java . util . * ; class solution { static void printFirstNegativeInteger ( int arr [ ] , int n , int k ) { boolean flag ; for ( int i = 0 ; i < ( n - k + 1 ) ; i ++ ) { flag = false ; for ( int j = 0 ; j < k ; j ++ ) { if ( arr [ i + j ] < 0 ) { System . out . print ( ( arr [ i + j ] ) + " ▁ " ) ; flag = true ; break ; } } if ( ! flag ) System . out . print ( "0" + " ▁ " ) ; } } public static void main ( String args [ ] ) { int arr [ ] = { 12 , - 1 , - 7 , 8 , - 15 , 30 , 16 , 28 } ; int n = arr . length ; int k = 3 ; printFirstNegativeInteger ( arr , n , k ) ; } }


"First non | Java program to find first non - repeating character using 1D array and one traversal . ; The function returns index of the first non - repeating character in a string . If all characters are repeating then returns INT_MAX ; Initialize all characters as absent . ; After below loop , the value of arr [ x ] is going to be index of x if x appears only once . Else the value is going to be either - 1 or - 2. ; If this character occurs only once and appears before the current result , then update the result ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; import java . lang . * ; class GFG { static int firstNonRepeating ( String str ) { int NO_OF_CHARS = 256 ; int arr [ ] = new int [ NO_OF_CHARS ] ; for ( int i = 0 ; i < NO_OF_CHARS ; i ++ ) arr [ i ] = - 1 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( arr [ str . charAt ( i ) ] == - 1 ) arr [ str . charAt ( i ) ] = i ; else arr [ str . charAt ( i ) ] = - 2 ; } int res = Integer . MAX_VALUE ; for ( int i = 0 ; i < NO_OF_CHARS ; i ++ ) if ( arr [ i ] >= 0 ) res = Math . min ( res , arr [ i ] ) ; return res ; } public static void main ( String args [ ] ) { String str = " geeksforgeeks " ; int index = firstNonRepeating ( str ) ; if ( index == Integer . MAX_VALUE ) System . out . print ( " Either ▁ all ▁ characters ▁ are ▁ " + " repeating ▁ or ▁ string ▁ is ▁ empty " ) ; else System . out . print ( " First ▁ non - repeating ▁ character " + " ▁ is ▁ " + str . charAt ( index ) ) ; } }


"First number to leave an odd remainder after repetitive division by 2 | Java program implementation of the approach ; Function to return the position least significant set bit ; Function return the first number to be converted to an odd integer ; Stores the positions of the first set bit ; If both are same ; If A has the least significant set bit ; Otherwise ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . lang . Math ; import java . io . * ; class GFG { static int getFirstSetBitPos ( int n ) { return ( int ) ( Math . log ( n & - n ) / Math . log ( 2 ) ) ; } static int oddFirst ( int a , int b ) { int steps_a = getFirstSetBitPos ( a ) ; int steps_b = getFirstSetBitPos ( b ) ; if ( steps_a == steps_b ) { return - 1 ; } else if ( steps_a > steps_b ) { return b ; } else { return a ; } } public static void main ( String [ ] args ) { int a = 10 ; int b = 8 ; System . out . print ( oddFirst ( a , b ) ) ; } }


"First occurrence of a digit in a given fraction | Java program to find first occurrence of c in a / b ; Function to print the first digit ; Reduce the number to its mod ; Traverse for every decimal places ; Get every fraction places when ( a * 10 / b ) / c ; Check if it is equal to the required integer ; Mod the number ; Driver function"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; public class GfG { public static int first ( int a , int b , int c ) { a %= b ; for ( int i = 1 ; i <= b ; i ++ ) { a = a * 10 ; if ( a / b == c ) return i ; a %= b ; } return - 1 ; } public static void main ( String argc [ ] ) { int a = 1 , b = 4 , c = 5 ; System . out . println ( first ( a , b , c ) ) ; } }


"First strictly greater element in a sorted array in Java | Java program to find first element that is strictly greater than given target . ; Move to right side if target is greater . ; Move left side . ; Driver code"
How can the above be solved in Java?

class GfG { private static int next ( int [ ] arr , int target ) { int start = 0 , end = arr . length - 1 ; int ans = - 1 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; if ( arr [ mid ] <= target ) { start = mid + 1 ; } else { ans = mid ; end = mid - 1 ; } } return ans ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 5 , 8 , 12 } ; System . out . println ( next ( arr , 8 ) ) ; } }


"First strictly smaller element in a sorted array in Java | Java program to find first element that is strictly smaller than given target . ; Minimum size of the array should be 1 ; If target lies beyond the max element , than the index of strictly smaller value than target should be ( end - 1 ) ; Move to the left side if the target is smaller ; Move right side ; Driver code"
How can the above be solved in Java?

class GfG { private static int next ( int [ ] arr , int target ) { int start = 0 , end = arr . length - 1 ; if ( end == 0 ) return - 1 ; if ( target > arr [ end ] ) return end ; int ans = - 1 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; if ( arr [ mid ] >= target ) { end = mid - 1 ; } else { ans = mid ; start = mid + 1 ; } } return ans ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 5 , 8 , 12 } ; System . out . println ( next ( arr , 5 ) ) ; } }


"First string from the given array whose reverse is also present in the same array | Java implementation of the approach ; Function that returns true if s1 is equal to reverse of s2 ; If both the strings differ in length ; In case of any character mismatch ; Function to return the first word whose reverse is also present in the array ; Check every string ; Pair with every other string appearing after the current string ; If first string is equal to the reverse of the second string ; No such string exists ; Driver code"
How can the above be solved in Java?

class GFG { static boolean isReverseEqual ( String s1 , String s2 ) { if ( s1 . length ( ) != s2 . length ( ) ) return false ; int len = s1 . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) if ( s1 . charAt ( i ) != s2 . charAt ( len - i - 1 ) ) return false ; return true ; } static String getWord ( String str [ ] , int n ) { for ( int i = 0 ; i < n - 1 ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( isReverseEqual ( str [ i ] , str [ j ] ) ) return str [ i ] ; return " - 1" ; } public static void main ( String [ ] args ) { String str [ ] = { " geeks " , " for " , " skeeg " } ; int n = str . length ; System . out . print ( getWord ( str , n ) ) ; } }


"First term from given Nth term of the equation F ( N ) = ( 2 * F ( N | Java program to implement the above approach ; Function to find the value of power ( X , N ) % M ; Stores the value of ( X ^ N ) % M ; Calculate the value of power ( x , N ) % M ; If N is odd ; Update res ; Update x ; Update N ; Function to find modulo multiplicative inverse of X under modulo M ; Function to find the value of F ( 1 ) ; Stores power ( 2 , N - 1 ) ; Stores modulo multiplicative inverse of P_2 under modulo M ; Stores the value of F ( 1 ) ; Update res ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static final int M = 1000000007 ; static long power ( long x , long N ) { long res = 1 ; while ( N > 0 ) { if ( N % 2 == 1 ) { res = ( res * x ) % M ; } x = ( x * x ) % M ; N = N >> 1 ; } return res ; } static long moduloInverse ( long X ) { return power ( X , M - 2 ) ; } static long F_1 ( long N , long F_N ) { long P_2 = power ( 2 , N - 1 ) ; long modInv = moduloInverse ( P_2 ) ; long res ; res = ( ( modInv % M ) * ( F_N % M ) ) % M ; return res ; } public static void main ( String [ ] args ) { long N = 3 ; long F_N = 6 ; System . out . print ( F_1 ( N , F_N ) ) ; } }


"First uppercase letter in a string ( Iterative and Recursive ) | Java program to find the first uppercase letter using linear search ; Function to find string which has first character of each word . ; Driver program"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static char first ( String str ) { for ( int i = 0 ; i < str . length ( ) ; i ++ ) if ( Character . isUpperCase ( str . charAt ( i ) ) ) return str . charAt ( i ) ; return 0 ; } public static void main ( String args [ ] ) { String str = " geeksforGeeKS " ; char res = first ( str ) ; if ( res == 0 ) System . out . println ( " No ▁ uppercase ▁ letter " ) ; else System . out . println ( res ) ; } }


"Fizz Buzz Implementation | Set 2 | Java program for the above approach ; Function to generate FizzBuzz sequence ; Stores count of multiples of 3 and 5 respectively ; Iterate from 1 to N ; Increment count3 by 1 ; Increment count5 by 1 ; Initialize a boolean variable to check if none of the condition matches ; Check if the value of count3 is equal to 3 ; Reset count3 to 0 , and set flag as True ; Check if the value of count5 is equal to 5 ; Reset count5 to 0 , and set flag as True ; If none of the condition matches ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void fizzBuzz ( int N ) { int count3 = 0 ; int count5 = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { count3 ++ ; count5 ++ ; boolean flag = false ; if ( count3 == 3 ) { System . out . print ( " Fizz " ) ; count3 = 0 ; flag = true ; } if ( count5 == 5 ) { System . out . print ( " Buzz " ) ; count5 = 0 ; flag = true ; } if ( ! flag ) { System . out . print ( i ) ; } System . out . print ( " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 15 ; fizzBuzz ( N ) ; } }


"Flatten a multi |"
How can the above be solved in Java?

Node flattenList2 ( Node head ) { Node headcop = head ; Stack < Node > save = new Stack < > ( ) ; save . push ( head ) ; Node prev = null ; while ( ! save . isEmpty ( ) ) { Node temp = save . peek ( ) ; save . pop ( ) ; if ( temp . next ) save . push ( temp . next ) ; if ( temp . down ) save . push ( temp . down ) ; if ( prev != null ) prev . next = temp ; prev = temp ; } return headcop ; }


"Flatten a multilevel linked list |"
How can the above be solved in Java?

static class List { public int data ; public List next ; public List child ; } ;


"Flattening a Linked List | Java program for flattening a Linked List ; head of list ; Linked list Node ; An utility function to merge two sorted linked lists ; if first linked list is empty then second is the answer ; if second linked list is empty then first is the result ; compare the data members of the two linked lists and put the larger one in the result ; Base Cases ; recur for list on right ; now merge ; return the root it will be in turn merged with its left ; Utility function to insert a node at beginning of the linked list ; 1 & 2 : Allocate the Node & Put in the data ; 3. Make next of new Node as head ; 4. Move the head to point to new Node ; 5. return to link it back ; Driver program to test above functions ; Let us create the following linked list 5 -> 10 -> 19 -> 28 | | | | V V V V 7 20 22 35 | | | V V V 8 50 40 | | V V 30 45 ; flatten the list"
How can the above be solved in Java?

class LinkedList { Node head ; class Node { int data ; Node right , down ; Node ( int data ) { this . data = data ; right = null ; down = null ; } } Node merge ( Node a , Node b ) { if ( a == null ) return b ; if ( b == null ) return a ; Node result ; if ( a . data < b . data ) { result = a ; result . down = merge ( a . down , b ) ; } else { result = b ; result . down = merge ( a , b . down ) ; } result . right = null ; return result ; } Node flatten ( Node root ) { if ( root == null root . right == null ) return root ; root . right = flatten ( root . right ) ; root = merge ( root , root . right ) ; return root ; } Node push ( Node head_ref , int data ) { Node new_node = new Node ( data ) ; new_node . down = head_ref ; head_ref = new_node ; return head_ref ; } void printList ( ) { Node temp = head ; while ( temp != null ) { System . out . print ( temp . data + " ▁ " ) ; temp = temp . down ; } System . out . println ( ) ; } public static void main ( String args [ ] ) { LinkedList L = new LinkedList ( ) ; L . head = L . push ( L . head , 30 ) ; L . head = L . push ( L . head , 8 ) ; L . head = L . push ( L . head , 7 ) ; L . head = L . push ( L . head , 5 ) ; L . head . right = L . push ( L . head . right , 20 ) ; L . head . right = L . push ( L . head . right , 10 ) ; L . head . right . right = L . push ( L . head . right . right , 50 ) ; L . head . right . right = L . push ( L . head . right . right , 22 ) ; L . head . right . right = L . push ( L . head . right . right , 19 ) ; L . head . right . right . right = L . push ( L . head . right . right . right , 45 ) ; L . head . right . right . right = L . push ( L . head . right . right . right , 40 ) ; L . head . right . right . right = L . push ( L . head . right . right . right , 35 ) ; L . head . right . right . right = L . push ( L . head . right . right . right , 20 ) ; L . head = L . flatten ( L . head ) ; L . printList ( ) ; } }


"Flattening a linked list | Set 2 | Java program for Flattening a linked list using Heaps ; Linked list Node ; Function to print the linked list ; Class that compares the value pointed by node and make LinkedList sorted ; Function which returns the root of the flattened linked list ; Min Heap which will return smallest element currently present in heap ; Push the head nodes of each downward linked list ; This loop will execute till the pq becomes empty ; Pop out the node that contains element currently in heap ; Push the next node pointed by the current node into heap if it is not null ; Create new linked list that is to be returned ; Pointer to head node in the linked list ; Create and push new nodes ; Driver code ; Flatten the list ; Print the flattened linked list"
How can the above be solved in Java?

import java . util . * ; class Node { int data ; Node right , down ; Node ( int data ) { this . data = data ; right = null ; down = null ; } } class pair { int val ; Node head ; pair ( Node head , int val ) { this . val = val ; this . head = head ; } } public static void printList ( Node h ) { while ( h != null ) { System . out . print ( h . data + " ▁ " ) ; h = h . down ; } } class pairComp implements Comparator < pair > { public int compare ( pair p1 , pair p2 ) { return p1 . val - p2 . val ; } } class GFG { public static Node flatten ( Node root ) { Node ptr = root ; Node h = null ; PriorityQueue < pair > pq = new PriorityQueue < pair > ( new pairComp ( ) ) ; while ( ptr != null ) { pq . add ( new pair ( ptr , ptr . data ) ) ; ptr = ptr . right ; } while ( ! pq . isEmpty ( ) ) { Node temp = pq . poll ( ) . head ; if ( temp . down != null ) { pq . add ( new pair ( temp . down , temp . down . data ) ) ; } if ( h == null ) { h = temp ; ptr = temp ; ptr . right = null ; } else { ptr . down = temp ; ptr = temp ; ptr . right = null ; } } return h ; } public static Node push ( Node head_ref , int data ) { Node new_node = new Node ( data ) ; new_node . down = head_ref ; head_ref = new_node ; return head_ref ; } public static void main ( String args [ ] ) { Node head = null ; head = push ( head , 30 ) ; head = push ( head , 8 ) ; head = push ( head , 7 ) ; head = push ( head , 5 ) ; head . right = push ( head . right , 20 ) ; head . right = push ( head . right , 10 ) ; head . right . right = push ( head . right . right , 50 ) ; head . right . right = push ( head . right . right , 22 ) ; head . right . right = push ( head . right . right , 19 ) ; head . right . right . right = push ( head . right . right . right , 45 ) ; head . right . right . right = push ( head . right . right . right , 40 ) ; head . right . right . right = push ( head . right . right . right , 35 ) ; head . right . right . right = push ( head . right . right . right , 20 ) ; head = flatten ( head ) ; printList ( head ) ; } }


"Flip Binary Tree | Java program to flip a binary tree ; A binary tree node ; Utility function to create a new Binary Tree Node ; method to flip the binary tree ; Initialization of pointers ; Iterate through all left nodes ; Swapping nodes now , need temp to keep the previous right child Making prev ' s ▁ right ▁ ▁ as ▁ curr ' s left child ; Storing curr 's right child ; Making prev as curr 's  right child ; Iterative method to do level order traversal line by line ; Base Case ; Create an empty queue for level order traversal ; Enqueue Root and initialize height ; nodeCount ( queue size ) indicates number of nodes at current lelvel . ; Dequeue all nodes of current level and Enqueue all nodes of next level ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static class Node { int data ; Node left , right ; } ; static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . left = temp . right = null ; return temp ; } static Node flipBinaryTree ( Node root ) { Node curr = root ; Node next = null ; Node temp = null ; Node prev = null ; while ( curr != null ) { next = curr . left ; curr . left = temp ; temp = curr . right ; curr . right = prev ; prev = curr ; curr = next ; } return prev ; } static void printLevelOrder ( Node root ) { if ( root == null ) return ; Queue < Node > q = new LinkedList < Node > ( ) ; q . add ( root ) ; while ( true ) { int nodeCount = q . size ( ) ; if ( nodeCount == 0 ) break ; while ( nodeCount > 0 ) { Node node = q . peek ( ) ; System . out . print ( node . data + " ▁ " ) ; q . remove ( ) ; if ( node . left != null ) q . add ( node . left ) ; if ( node . right != null ) q . add ( node . right ) ; nodeCount -- ; } System . out . println ( ) ; } } public static void main ( String args [ ] ) { Node root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 3 ) ; root . right . left = newNode ( 4 ) ; root . right . right = newNode ( 5 ) ; System . out . print ( " Level ▁ order ▁ traversal ▁ " + "of given tree
"); printLevelOrder ( root ) ; root = flipBinaryTree ( root ) ; System . out . print ( " Level order traversal " ▁ + ▁ " of the flipped tree "); printLevelOrder ( root ) ; } }


"Flip Binary Tree | Java program to flip a binary tree ; A binary tree node structure ; method to flip the binary tree ; recursively call the same method ; rearranging main root Node after returning from recursive call ; Iterative method to do level order traversal line by line ; Base Case ; Create an empty queue for level order traversal ; Enqueue Root and initialize height ; nodeCount ( queue size ) indicates number of nodes at current lelvel . ; Dequeue all nodes of current level and Enqueue all nodes of next level ; Driver code"
How can the above be solved in Java?

import java . util . Queue ; import java . util . LinkedList ; public class FlipTree { class Node { int data ; Node left , right ; Node ( int data ) { this . data = data ; } } ; public static Node flipBinaryTree ( Node root ) { if ( root == null ) return root ; if ( root . left == null && root . right == null ) return root ; Node flippedRoot = flipBinaryTree ( root . left ) ; root . left . left = root . right ; root . left . right = root ; root . left = root . right = null ; return flippedRoot ; } public static void printLevelOrder ( Node root ) { if ( root == null ) return ; Queue < Node > q = new LinkedList < > ( ) ; q . add ( root ) ; while ( true ) { int nodeCount = q . size ( ) ; if ( nodeCount == 0 ) break ; while ( nodeCount > 0 ) { Node node = q . remove ( ) ; System . out . print ( node . data + " ▁ " ) ; if ( node . left != null ) q . add ( node . left ) ; if ( node . right != null ) q . add ( node . right ) ; nodeCount -- ; } System . out . println ( ) ; } } public static void main ( String args [ ] ) { Node root = new Node ( 1 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 1 ) ; root . right . left = new Node ( 4 ) ; root . right . right = new Node ( 5 ) ; System . out . println ( " Level ▁ order ▁ traversal ▁ of ▁ given ▁ tree " ) ; printLevelOrder ( root ) ; root = flipBinaryTree ( root ) ; System . out . println ( " Level ▁ order ▁ traversal ▁ of ▁ flipped ▁ tree " ) ; printLevelOrder ( root ) ; } }


"Flip all K | Java program for the above approach ; Function to flip all K - bits of an unsigned number N ; Stores ( 2 ^ K ) - 1 ; Update N ; Print the answer ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void flippingBits ( long N , long K ) { long X = ( 1 << ( K - 1 ) ) - 1 ; N = X - N ; System . out . print ( N ) ; } public static void main ( String [ ] args ) { long N = 1 , K = 8 ; flippingBits ( N , K ) ; } }


"Flip bits of the sum of count of set bits of two given numbers | Java program for the above approach ; Function to count number of set bits in integer ; Variable for counting set bits ; Function to invert bits of a number ; Calculate number of bits of N - 1 ; ; Function to invert the sum of set bits in A and B ; Stores sum of set bits ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int countSetBits ( int n ) { int count = 0 ; while ( n != 0 ) { n &= ( n - 1 ) ; count ++ ; } return count ; } static int invertBits ( int n ) { int x = ( int ) ( Math . log ( n ) / Math . log ( 2 ) ) ; int m = 1 << x ; m = m | m - 1 ; n = n ^ m ; return n ; } static void invertSum ( int A , int B ) { int temp = countSetBits ( A ) + countSetBits ( B ) ; System . out . print ( invertBits ( temp ) ) ; } static public void main ( String args [ ] ) { int A = 5 ; int B = 7 ; invertSum ( A , B ) ; } }


"Flip consecutive set bits starting from LSB of a given number | Java program for the above approach ; Function to find the number after converting 1 s from end to 0 s ; Count of 1 s ; AND operation of N and 1 ; Left shift N by count ; Driver Code ; Function Call"
How can the above be solved in Java?

class GFG { static int findNumber ( int N ) { int count = 0 ; while ( ( N & 1 ) == 1 ) { N = N >> 1 ; count ++ ; } return N << count ; } public static void main ( String [ ] args ) { int N = 39 ; System . out . println ( findNumber ( N ) ) ; } }


"Flip consecutive set bits starting from LSB of a given number | Java program for the above approach ; Function to find the number after converting 1 s from end to 0 s ; Return the logical AND of N and ( N + 1 ) ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findNumber ( int N ) { return N & ( N + 1 ) ; } public static void main ( String [ ] args ) { int N = 39 ; System . out . print ( findNumber ( N ) ) ; } }


"Flip minimum signs of array elements to get minimum sum of positive elements possible | Java implementation of the above approach : ; Function to return the minimum number of elements whose sign must be flipped to get the positive sum of array elements as close to 0 as possible ; boolean variable used for toggling between maps ; Calculate the sum of all elements of the array ; Initializing first map ( dp [ 0 ] ) with INT_MAX because for i = 0 , there are no elements in the array to flip ; Base Case ; For toggling ; Required sum is minimum non - negative So , we iterate from i = 0 to sum and find the first i where dp [ flag ^ 1 ] [ i ] != INT_MAX ; In worst case we will flip max n - 1 elements ; Driver code"
How can the above be solved in Java?

class GFG { public static int solve ( int [ ] A , int n ) { int [ ] [ ] dp = new int [ 2000 ] [ 2000 ] ; int flag = 1 ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += A [ i ] ; for ( int i = - sum ; i <= sum ; i ++ ) { try { dp [ 0 ] [ i ] = Integer . MAX_VALUE ; } catch ( Exception e ) { } } dp [ 0 ] [ 0 ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 0 ; j <= sum ; j ++ ) { try { dp [ flag ] [ j ] = Integer . MAX_VALUE ; if ( j - A [ i - 1 ] <= sum && j - A [ i - 1 ] >= - sum ) dp [ flag ] [ j ] = dp [ flag ^ 1 ] [ j - A [ i - 1 ] ] ; if ( j + A [ i - 1 ] <= sum && j + A [ i - 1 ] >= - sum && dp [ flag ^ 1 ] [ j + A [ i - 1 ] ] != Integer . MAX_VALUE ) dp [ flag ] [ j ] = Math . min ( dp [ flag ] [ j ] , dp [ flag ^ 1 ] [ j + A [ i - 1 ] ] + 1 ) ; } catch ( Exception e ) { } } flag = flag ^ 1 ; } for ( int i = 0 ; i <= sum ; i ++ ) { if ( dp [ flag ^ 1 ] [ i ] != Integer . MAX_VALUE ) return dp [ flag ^ 1 ] [ i ] ; } return n - 1 ; } public static void main ( String [ ] args ) { int [ ] arr = { 10 , 22 , 9 , 33 , 21 , 50 , 41 , 60 } ; int n = arr . length ; System . out . println ( solve ( arr , n ) ) ; } }


"Flood fill Algorithm | Java program to implement flood fill algorithm ; Dimentions of paint screen ; A recursive function to replace previous color ' prevC ' at ' ( x , ▁ y ) ' and all surrounding pixels of ( x , y ) with new color ' newC ' and ; Base cases ; Replace the color at ( x , y ) ; Recur for north , east , south and west ; It mainly finds the previous color on ( x , y ) and calls floodFillUtil ( ) ; Driver code"
How can the above be solved in Java?

class GFG { static int M = 8 ; static int N = 8 ; static void floodFillUtil ( int screen [ ] [ ] , int x , int y , int prevC , int newC ) { if ( x < 0 x >= M y < 0 y >= N ) return ; if ( screen [ x ] [ y ] != prevC ) return ; screen [ x ] [ y ] = newC ; floodFillUtil ( screen , x + 1 , y , prevC , newC ) ; floodFillUtil ( screen , x - 1 , y , prevC , newC ) ; floodFillUtil ( screen , x , y + 1 , prevC , newC ) ; floodFillUtil ( screen , x , y - 1 , prevC , newC ) ; } static void floodFill ( int screen [ ] [ ] , int x , int y , int newC ) { int prevC = screen [ x ] [ y ] ; floodFillUtil ( screen , x , y , prevC , newC ) ; } public static void main ( String [ ] args ) { int screen [ ] [ ] = { { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 } , { 1 , 1 , 1 , 1 , 1 , 1 , 0 , 0 } , { 1 , 0 , 0 , 1 , 1 , 0 , 1 , 1 } , { 1 , 2 , 2 , 2 , 2 , 0 , 1 , 0 } , { 1 , 1 , 1 , 2 , 2 , 0 , 1 , 0 } , { 1 , 1 , 1 , 2 , 2 , 2 , 2 , 0 } , { 1 , 1 , 1 , 1 , 1 , 2 , 1 , 1 } , { 1 , 1 , 1 , 1 , 1 , 2 , 2 , 1 } , } ; int x = 4 , y = 4 , newC = 3 ; floodFill ( screen , x , y , newC ) ; System . out . println ( " Updated ▁ screen ▁ after ▁ call ▁ to ▁ floodFill : ▁ " ) ; for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) System . out . print ( screen [ i ] [ j ] + " ▁ " ) ; System . out . println ( ) ; } } }


"Flood fill Algorithm | Pair class ; Function to check valid coordinate ; Function to run bfs ; Visiing array ; Initialing all as zero ; Creating queue for bfs ; Pushing pair of { x , y } ; Marking { x , y } as visited ; Untill queue is emppty ; Extrating front pair ; Poping front pair of queue ; For Upside Pixel or Cell ; For Downside Pixel or Cell ; For Right side Pixel or Cell ; For Left side Pixel or Cell ; Printing The Changed Matrix Of Pixels ; Driver Code ; Function Call"
How can the above be solved in Java?

class Pair implements Comparable < Pair > { int first ; int second ; public Pair ( int first , int second ) { this . first = first ; this . second = second ; } @ Override public int compareTo ( Pair o ) { return second - o . second ; } } class GFG { public static int validCoord ( int x , int y , int n , int m ) { if ( x < 0 y < 0 ) { return 0 ; } if ( x >= n y >= m ) { return 0 ; } return 1 ; } public static void bfs ( int n , int m , int data [ ] [ ] , int x , int y , int color ) { int vis [ ] [ ] = new int [ 101 ] [ 101 ] ; for ( int i = 0 ; i <= 100 ; i ++ ) { for ( int j = 0 ; j <= 100 ; j ++ ) { vis [ i ] [ j ] = 0 ; } } Queue < Pair > obj = new LinkedList < > ( ) ; Pair pq = new Pair ( x , y ) ; obj . add ( pq ) ; vis [ x ] [ y ] = 1 ; while ( ! obj . isEmpty ( ) ) { Pair coord = obj . peek ( ) ; int x1 = coord . first ; int y1 = coord . second ; int preColor = data [ x1 ] [ y1 ] ; data [ x1 ] [ y1 ] = color ; obj . remove ( ) ; if ( ( validCoord ( x1 + 1 , y1 , n , m ) == 1 ) && vis [ x1 + 1 ] [ y1 ] == 0 && data [ x1 + 1 ] [ y1 ] == preColor ) { Pair p = new Pair ( x1 + 1 , y1 ) ; obj . add ( p ) ; vis [ x1 + 1 ] [ y1 ] = 1 ; } if ( ( validCoord ( x1 - 1 , y1 , n , m ) == 1 ) && vis [ x1 - 1 ] [ y1 ] == 0 && data [ x1 - 1 ] [ y1 ] == preColor ) { Pair p = new Pair ( x1 - 1 , y1 ) ; obj . add ( p ) ; vis [ x1 - 1 ] [ y1 ] = 1 ; } if ( ( validCoord ( x1 , y1 + 1 , n , m ) == 1 ) && vis [ x1 ] [ y1 + 1 ] == 0 && data [ x1 ] [ y1 + 1 ] == preColor ) { Pair p = new Pair ( x1 , y1 + 1 ) ; obj . add ( p ) ; vis [ x1 ] [ y1 + 1 ] = 1 ; } if ( ( validCoord ( x1 , y1 - 1 , n , m ) == 1 ) && vis [ x1 ] [ y1 - 1 ] == 0 && data [ x1 ] [ y1 - 1 ] == preColor ) { Pair p = new Pair ( x1 , y1 - 1 ) ; obj . add ( p ) ; vis [ x1 ] [ y1 - 1 ] = 1 ; } } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { System . out . print ( data [ i ] [ j ] + " ▁ " ) ; } System . out . println ( ) ; } System . out . println ( ) ; } public static void main ( String [ ] args ) { int nn , mm , xx , yy , colorr ; nn = 8 ;...


"Floor and Ceil from a BST | A binary tree node has key , left child and right child ; Function to find ceil of a given input in BST . If input is more than the max key in BST , return - 1 ; Base case ; We found equal key ; If root 's key is smaller,  ceil must be in right subtree ; Else , either left subtree or root has the ceil value ; Driver Code"
How can the above be solved in Java?

class Node { int data ; Node left , right ; Node ( int d ) { data = d ; left = right = null ; } } class BinaryTree { Node root ; int Ceil ( Node node , int input ) { if ( node == null ) { return - 1 ; } if ( node . data == input ) { return node . data ; } if ( node . data < input ) { return Ceil ( node . right , input ) ; } int ceil = Ceil ( node . left , input ) ; return ( ceil >= input ) ? ceil : node . data ; } public static void main ( String [ ] args ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 8 ) ; tree . root . left = new Node ( 4 ) ; tree . root . right = new Node ( 12 ) ; tree . root . left . left = new Node ( 2 ) ; tree . root . left . right = new Node ( 6 ) ; tree . root . right . left = new Node ( 10 ) ; tree . root . right . right = new Node ( 14 ) ; for ( int i = 0 ; i < 16 ; i ++ ) { System . out . println ( i + " ▁ " + tree . Ceil ( tree . root , i ) ) ; } } }


"Floor and Ceil from a BST | Java program to find floor and ceil of a given key in BST ; A binary tree node has key , left child and right child ; Helper function to find floor and ceil of a given key in BST ; Display the floor and ceil of a given key in BST . If key is less than the min key in BST , floor will be - 1 ; If key is more than the max key in BST , ceil will be - 1 ; ; Variables ' floor ' and ' ceil ' are passed by reference ; Driver code"
How can the above be solved in Java?

import java . io . * ; class Node { int data ; Node left , right ; Node ( int d ) { data = d ; left = right = null ; } } class BinaryTree { Node root ; int floor ; int ceil ; public void floorCeilBSTHelper ( Node root , int key ) { while ( root != null ) { if ( root . data == key ) { ceil = root . data ; floor = root . data ; return ; } if ( key > root . data ) { floor = root . data ; root = root . right ; } else { ceil = root . data ; root = root . left ; } } return ; } public void floorCeilBST ( Node root , int key ) { floor = - 1 ; ceil = - 1 ; floorCeilBSTHelper ( root , key ) ; System . out . println ( key + " ▁ " + floor + " ▁ " + ceil ) ; } public static void main ( String [ ] args ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 8 ) ; tree . root . left = new Node ( 4 ) ; tree . root . right = new Node ( 12 ) ; tree . root . left . left = new Node ( 2 ) ; tree . root . left . right = new Node ( 6 ) ; tree . root . right . left = new Node ( 10 ) ; tree . root . right . right = new Node ( 14 ) ; for ( int i = 0 ; i < 16 ; i ++ ) { tree . floorCeilBST ( tree . root , i ) ; } } }


"Floor square root without using sqrt ( ) function : Recursive | Java implementation to find the square root of the number N without using sqrt ( ) function ; Function to find the square root of the number N using BS ; If the range is still valid ; Find the mid - value of the range ; Base Case ; Condition to check if the left search space is useless ; Driver Code"
How can the above be solved in Java?

class GFG { static int sqrtSearch ( int low , int high , int N ) { if ( low <= high ) { int mid = ( int ) ( low + high ) / 2 ; if ( ( mid * mid <= N ) && ( ( mid + 1 ) * ( mid + 1 ) > N ) ) { return mid ; } else if ( mid * mid < N ) { return sqrtSearch ( mid + 1 , high , N ) ; } else { return sqrtSearch ( low , mid - 1 , N ) ; } } return low ; } public static void main ( String [ ] args ) { int N = 25 ; System . out . println ( sqrtSearch ( 0 , N , N ) ) ; } }


"Foldable Binary Trees | A binary tree node has data , pointer to left child and a pointer to right child ; Returns true if the given tree can be folded ; A utility function that checks if trees with roots as n1 and n2 are mirror of each other ; If both left and right subtrees are NULL , then return true ; If one of the trees is NULL and other is not , then return false ; Otherwise check if left and right subtrees are mirrors of their counterparts ; Driver program to test above functions ; The constructed binary tree is 1 / \ 2 3 \ / 4 5"
How can the above be solved in Java?

class Node { int data ; Node left , right ; Node ( int item ) { data = item ; left = right = null ; } } class BinaryTree { Node root ; boolean IsFoldable ( Node node ) { if ( node == null ) return true ; return IsFoldableUtil ( node . left , node . right ) ; } boolean IsFoldableUtil ( Node n1 , Node n2 ) { if ( n1 == null && n2 == null ) return true ; if ( n1 == null n2 == null ) return false ; return IsFoldableUtil ( n1 . left , n2 . right ) && IsFoldableUtil ( n1 . right , n2 . left ) ; } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 1 ) ; tree . root . left = new Node ( 2 ) ; tree . root . right = new Node ( 3 ) ; tree . root . right . left = new Node ( 4 ) ; tree . root . left . right = new Node ( 5 ) ; if ( tree . IsFoldable ( tree . root ) ) System . out . println ( " tree ▁ is ▁ foldable " ) ; else System . out . println ( " Tree ▁ is ▁ not ▁ foldable " ) ; } }


"For each lowercase English alphabet find the count of strings having these alphabets | Java program to find count of Strings for each letter [ a - z ] in english alphabet ; Function to find the countStrings for each letter [ a - z ] ; Initialize result as zero ; Mark all letter as not visited ; Loop through each Strings ; Increment the global counter for current character of String ; Instead of re - initialising boolean vector every time we just reset all visited letter to false ; Print count for each letter ; Driver program ; Given array of Strings ; Call the countStrings function"
How can the above be solved in Java?

class GFG { static void CountStrings ( String [ ] str ) { int size = str . length ; int [ ] count = new int [ 26 ] ; boolean [ ] visited = new boolean [ 26 ] ; for ( int i = 0 ; i < size ; ++ i ) { for ( int j = 0 ; j < str [ i ] . length ( ) ; ++ j ) { if ( visited [ str [ i ] . charAt ( j ) - ' a ' ] == false ) count [ str [ i ] . charAt ( j ) - ' a ' ] ++ ; visited [ str [ i ] . charAt ( j ) - ' a ' ] = true ; } for ( int j = 0 ; j < str [ i ] . length ( ) ; ++ j ) { visited [ str [ i ] . charAt ( j ) - ' a ' ] = false ; } } for ( int i = 0 ; i < 26 ; ++ i ) { System . out . print ( count [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { String [ ] str = { " i " , " will " , " practice " , " everyday " } ; CountStrings ( str ) ; } }


"For every set bit of a number toggle bits of other | A Java program toggle bits of n2 that are at same position as set bits of n1 . ; function for the Nega_bit ; Driver program"
How can the above be solved in Java?

import java . io . * ; class GFG { static int toggleBits ( int n1 , int n2 ) { return ( n1 ^ n2 ) ; } public static void main ( String args [ ] ) { int n1 = 2 , n2 = 5 ; System . out . println ( toggleBits ( n1 , n2 ) ) ; } }


"Ford | Java program for implementation of Ford Fulkerson algorithm ; Number of vertices in graph ; Returns true if there is a path from source ' s ' to sink ' t ' in residual graph . Also fills parent [ ] to store the path ; Create a visited array and mark all vertices as not visited ; Create a queue , enqueue source vertex and mark source vertex as visited ; Standard BFS Loop ; If we find a connection to the sink node , then there is no point in BFS anymore We just have to set its parent and can return true ; We didn 't reach sink in BFS starting from source,  so return false ; Returns tne maximum flow from s to t in the given graph ; Create a residual graph and fill the residual graph with given capacities in the original graph as residual capacities in residual graph Residual graph where rGraph [ i ] [ j ] indicates residual capacity of edge from i to j ( if there is an edge . If rGraph [ i ] [ j ] is 0 , then there is not ) ; This array is filled by BFS and to store path ; There is no flow initially ; Augment the flow while tere is path from source to sink ; Find minimum residual capacity of the edhes along the path filled by BFS . Or we can say find the maximum flow through the path found . ; update residual capacities of the edges and reverse edges along the path ; Add path flow to overall flow ; Return the overall flow ; Driver program to test above functions ; Let us create a graph shown in the above example"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; import java . util . LinkedList ; class MaxFlow { static final int V = 6 ; boolean bfs ( int rGraph [ ] [ ] , int s , int t , int parent [ ] ) { boolean visited [ ] = new boolean [ V ] ; for ( int i = 0 ; i < V ; ++ i ) visited [ i ] = false ; LinkedList < Integer > queue = new LinkedList < Integer > ( ) ; queue . add ( s ) ; visited [ s ] = true ; parent [ s ] = - 1 ; while ( queue . size ( ) != 0 ) { int u = queue . poll ( ) ; for ( int v = 0 ; v < V ; v ++ ) { if ( visited [ v ] == false && rGraph [ u ] [ v ] > 0 ) { if ( v == t ) { parent [ v ] = u ; return true ; } queue . add ( v ) ; parent [ v ] = u ; visited [ v ] = true ; } } } return false ; } int fordFulkerson ( int graph [ ] [ ] , int s , int t ) { int u , v ; int rGraph [ ] [ ] = new int [ V ] [ V ] ; for ( u = 0 ; u < V ; u ++ ) for ( v = 0 ; v < V ; v ++ ) rGraph [ u ] [ v ] = graph [ u ] [ v ] ; int parent [ ] = new int [ V ] ; int max_flow = 0 ; while ( bfs ( rGraph , s , t , parent ) ) { int path_flow = Integer . MAX_VALUE ; for ( v = t ; v != s ; v = parent [ v ] ) { u = parent [ v ] ; path_flow = Math . min ( path_flow , rGraph [ u ] [ v ] ) ; } for ( v = t ; v != s ; v = parent [ v ] ) { u = parent [ v ] ; rGraph [ u ] [ v ] -= path_flow ; rGraph [ v ] [ u ] += path_flow ; } max_flow += path_flow ; } return max_flow ; } public static void main ( String [ ] args ) throws java . lang . Exception { int graph [ ] [ ] = new int [ ] [ ] { { 0 , 16 , 13 , 0 , 0 , 0 } , { 0 , 0 , 10 , 12 , 0 , 0 } , { 0 , 4 , 0 , 0 , 14 , 0 } , { 0 , 0 , 9 , 0 , 0 , 20 } , { 0 , 0 , 0 , 7 , 0 , 4 } , { 0 , 0 , 0 , 0 , 0 , 0 } } ; MaxFlow m = new MaxFlow ( ) ; System . out . println ( " The ▁ maximum ▁ possible ▁ flow ▁ is ▁ " + m . fordFulkerson ( graph , 0 , 5 ) ) ; } }


"Form N by adding 1 or 2 in minimum number of operations X where X is divisible by M | Java program to find minimum number of steps to cover distance x ; Function to calculate the minimum number of steps required total steps taken is divisible by m and only 1 or 2 steps can be taken at a time ; If m > n ans is - 1 ; else discussed above approach ; Driver code"
How can the above be solved in Java?

class GFG { static int minsteps ( int n , int m ) { if ( m > n ) { return - 1 ; } else { return ( ( n + 1 ) / 2 + m - 1 ) / m * m ; } } public static void main ( String [ ] args ) { int n = 17 , m = 4 ; int ans = minsteps ( n , m ) ; System . out . println ( ans ) ; } }


"Form N | Java code to find minimum cost to form a N - copy string ; Returns the minimum cost to form a n - copy string Here , x -> Cost to add / remove a single character ' G ' and y -> cost to append the string to itself ; Base Case : to form a 1 - copy string we need to perform an operation of type 1 ( i . e Add ) ; Case1 . Perform a Add operation on ( i - 1 ) - copy string , Case2 . Perform a type 2 operation on ( ( i + 1 ) / 2 ) - copy string ; Case1 . Perform a Add operation on ( i - 1 ) - copy string , Case2 . Perform a type 3 operation on ( i / 2 ) - copy string ; Driver Code"
How can the above be solved in Java?

class Solution { static int findMinimumCost ( int n , int x , int y ) { int dp [ ] = new int [ n + 1 ] ; dp [ 1 ] = x ; for ( int i = 2 ; i <= n ; i ++ ) { if ( ( i & 1 ) != 0 ) { dp [ i ] = Math . min ( dp [ i - 1 ] + x , dp [ ( i + 1 ) / 2 ] + y + x ) ; } else { dp [ i ] = Math . min ( dp [ i - 1 ] + x , dp [ i / 2 ] + y ) ; } } return dp [ n ] ; } public static void main ( String args [ ] ) { int n = 4 , x = 2 , y = 1 ; System . out . println ( findMinimumCost ( n , x , y ) ) ; } }


"Form a number using corner digits of powers | Java program to find number formed by corner digits of powers . ; Find next power by multiplying N with current power ; Store digits of Power one by one . ; Calculate carry . ; Store carry in Power array . ; Prints number formed by corner digits of powers of N . ; Storing N raised to power 0 ; Initializing empty result ; One by one compute next powers and add their corner digits . ; Call Function that store power in Power array . ; Store unit and last digits of power in res . ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; public class GFG { static List < Integer > power = new ArrayList < Integer > ( ) ; static void nextPower ( Integer N ) { Integer carry = 0 ; for ( int i = 0 ; i < power . size ( ) ; i ++ ) { Integer prod = ( power . get ( i ) * N ) + carry ; power . set ( i , prod % 10 ) ; carry = prod / 10 ; } while ( carry >= 1 ) { power . add ( carry % 10 ) ; carry = carry / 10 ; } } static void printPowerNumber ( int X , int N ) { power . add ( 1 ) ; List < Integer > res = new ArrayList < Integer > ( ) ; for ( int i = 1 ; i <= X ; i ++ ) { nextPower ( N ) ; res . add ( power . get ( power . size ( ) - 1 ) ) ; res . add ( power . get ( 0 ) ) ; } for ( int i = 0 ; i < res . size ( ) ; i ++ ) System . out . print ( res . get ( i ) ) ; } public static void main ( String args [ ] ) { Integer N = 19 , X = 4 ; printPowerNumber ( X , N ) ; } }


"Form coils in a matrix | Java program to print 2 coils of a 4 n x 4 n matrix . ; Print coils in a matrix of size 4 n x 4 n ; Number of elements in each coil ; Let us fill elements in coil 1. ; First element of coil1 4 * n * 2 * n + 2 * n ; ; Fill remaining m - 1 elements in coil1 [ ] ; Fill elements of current step from down to up ; Next element from current element ; Fill elements of current step from up to down . ; get coil2 from coil1 ; Print both coils ; Driver code"
How can the above be solved in Java?

class GFG { static void printCoils ( int n ) { int m = 8 * n * n ; int coil1 [ ] = new int [ m ] ; coil1 [ 0 ] = 8 * n * n + 2 * n ; int curr = coil1 [ 0 ] ; int nflg = 1 , step = 2 ; int index = 1 ; while ( index < m ) { for ( int i = 0 ; i < step ; i ++ ) { curr = coil1 [ index ++ ] = ( curr - 4 * n * nflg ) ; if ( index >= m ) break ; } if ( index >= m ) break ; for ( int i = 0 ; i < step ; i ++ ) { curr = coil1 [ index ++ ] = curr + nflg ; if ( index >= m ) break ; } nflg = nflg * ( - 1 ) ; step += 2 ; } int coil2 [ ] = new int [ m ] ; for ( int i = 0 ; i < 8 * n * n ; i ++ ) coil2 [ i ] = 16 * n * n + 1 - coil1 [ i ] ; System . out . print ( " Coil ▁ 1 ▁ : ▁ " ) ; for ( int i = 0 ; i < 8 * n * n ; i ++ ) System . out . print ( coil1 [ i ] + " ▁ " ) ; System . out . print ( " Coil 2 : "); for ( int i = 0 ; i < 8 * n * n ; i ++ ) System . out . print ( coil2 [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int n = 1 ; printCoils ( n ) ; } }


"Form minimum number of Palindromic Strings from a given string | Java Program to implement the above approach ; Function to return minimum palindromic Strings formed ; Store the length of String ; Iterate over the String and store the frequency of all charactrs A vector to store the frequency ; Store the odd frequency characters ; Iterate through all possible characters and check the parity of frequency ; store answer in a vector ; if there are no odd Frequency characters then print the String with even characters ; store the left part of the palindromic String ; reverse the right part of the String ; store the String in ans vector ; take any character from off frequency element ; repeat the above step to form left and right Strings ; reverse the right part of the String ; store the String in ans vector ; store all other odd frequency Strings ; Print the answer ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int minimumPalindromicStrings ( String S ) { int N = S . length ( ) ; int [ ] freq = new int [ 26 ] ; for ( int i = 0 ; i < N ; i ++ ) { freq [ S . charAt ( i ) - ' a ' ] ++ ; } Vector < Integer > oddFreqCharacters = new Vector < Integer > ( ) ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( freq [ i ] % 2 == 1 ) { oddFreqCharacters . add ( i ) ; freq [ i ] -- ; } freq [ i ] /= 2 ; } Vector < String > ans = new Vector < String > ( ) ; if ( oddFreqCharacters . isEmpty ( ) ) { String left = " " ; for ( int i = 0 ; i < 26 ; i ++ ) { for ( int j = 0 ; j < freq [ i ] ; j ++ ) { left += ( char ) ( i + ' a ' ) ; } } String right = left ; right = reverse ( right ) ; ans . add ( left + right ) ; } else { String middle = " " ; int c = oddFreqCharacters . lastElement ( ) ; oddFreqCharacters . remove ( oddFreqCharacters . size ( ) - 1 ) ; middle += ( char ) ( c + ' a ' ) ; String left = " " ; for ( int i = 0 ; i < 26 ; i ++ ) { for ( int j = 0 ; j < freq [ i ] ; j ++ ) { left += ( char ) ( i + ' a ' ) ; } } String right = left ; right = reverse ( right ) ; ans . add ( left + middle + right ) ; while ( ! oddFreqCharacters . isEmpty ( ) ) { c = oddFreqCharacters . lastElement ( ) ; oddFreqCharacters . remove ( oddFreqCharacters . size ( ) - 1 ) ; middle = " " ; middle += ( char ) ( c + ' a ' ) ; ans . add ( middle ) ; } } System . out . print ( " [ " ) ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) { System . out . print ( ans . get ( i ) ) ; if ( i != ans . size ( ) - 1 ) { System . out . print ( " , ▁ " ) ; } } System . out . print ( " ] " ) ; return 0 ; } static String reverse ( String input ) { char [ ] a = input . toCharArray ( ) ; int l , r = a . length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { char temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return String . valueOf ( a ) ; } public static void main ( String [ ] args ) { String S = " geeksforgeeks " ; minimumPalindromicStrings ( S ) ; } }


"Form smallest number using indices of numbers chosen from Array with sum less than S | Java implementation to find minimum number which have a maximum length ; Function to find the minimum number which have maximum length ; Find Maximum length of number ; Find minimum number WHich have maximum length ; Driver Code"
How can the above be solved in Java?

class GFG { static String max_number ( int arr [ ] , int sum ) { int frac [ ] = new int [ 9 ] ; int maxi = Integer . MIN_VALUE ; StringBuilder ans = new StringBuilder ( ) ; int pos = 0 ; for ( int i = 0 ; i < 9 ; i ++ ) { frac [ i ] = sum / arr [ i ] ; if ( frac [ i ] > maxi ) { pos = i ; maxi = frac [ i ] ; } } for ( int i = 0 ; i < maxi ; i ++ ) { ans . append ( ( char ) ( ( pos + 1 ) + '0' ) ) ; } sum -= maxi * arr [ pos ] ; for ( int i = 0 ; i < maxi ; i ++ ) { for ( int j = 1 ; j <= 9 ; j ++ ) { if ( sum + arr [ pos ] - arr [ j - 1 ] >= 0 ) { ans . setCharAt ( i , ( char ) ( j + '0' ) ) ; sum += arr [ pos ] - arr [ j - 1 ] ; break ; } } } if ( maxi == 0 ) { return "0" ; } else { return ans . toString ( ) ; } } public static void main ( String str [ ] ) { int arr [ ] = { 3 , 4 , 2 , 4 , 6 , 5 , 4 , 2 , 3 } ; int s = 13 ; System . out . println ( max_number ( arr , s ) ) ; } }


"Form the Cubic equation from the given roots | Java program for the approach ; Function to find the cubic equation whose roots are a , b and c ; Find the value of coefficient ; Print the equation as per the above coefficients ; Driver Code ; Function Call"
How can the above be solved in Java?

class GFG { static void findEquation ( int a , int b , int c ) { int X = ( a + b + c ) ; int Y = ( a * b ) + ( b * c ) + ( c * a ) ; int Z = a * b * c ; System . out . print ( " x ^ 3 ▁ - ▁ " + X + " x ^ 2 ▁ + ▁ " + Y + " x ▁ - ▁ " + Z + " ▁ = ▁ 0" ) ; } public static void main ( String [ ] args ) { int a = 5 , b = 2 , c = 3 ; findEquation ( a , b , c ) ; } }


"Form the largest number using at most one swap operation | Java implementation to form the largest number by applying atmost one swap operation ; function to form the largest number by applying atmost one swap operation ; for the rightmost digit , there will be no greater right digit ; index of the greatest right digit till the current index from the right direction ; traverse the array from second right element up to the left element ; if ' num . charAt ( i ) ' is less than the greatest digit encountered so far ; there is no greater right digit for ' num . charAt ( i ) ' ; update ' right ' index ; traverse the ' rightMax [ ] ' array from left to right ; if for the current digit , greater right digit exists then swap it with its greater right digit and break ; performing the required swap operation ; required largest number ; Utility method to swap two characters in a String ; Driver Function to test above Function"
How can the above be solved in Java?

public class GFG { static String largestNumber ( String num ) { int n = num . length ( ) ; int right ; int rightMax [ ] = new int [ n ] ; rightMax [ n - 1 ] = - 1 ; right = n - 1 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( num . charAt ( i ) < num . charAt ( right ) ) rightMax [ i ] = right ; else { rightMax [ i ] = - 1 ; right = i ; } } for ( int i = 0 ; i < n ; i ++ ) { if ( rightMax [ i ] != - 1 ) { num = swap ( num , i , rightMax [ i ] ) ; break ; } } return num ; } static String swap ( String num , int i , int j ) { StringBuilder sb = new StringBuilder ( num ) ; sb . setCharAt ( i , num . charAt ( j ) ) ; sb . setCharAt ( j , num . charAt ( i ) ) ; return sb . toString ( ) ; } public static void main ( String [ ] args ) { String num = "8725634" ; System . out . println ( " Largest ▁ Number ▁ : ▁ " + largestNumber ( num ) ) ; } }


"Form the largest palindromic number using atmost two swaps | Java implementation to form the largest palindromic number using atmost two swaps ; function to form the largest palindromic number using atmost two swaps ; if length of number is less than '3' then no higher palindromic number can be formed ; find the index of last digit in the 1 st half of ' num ' ; as only the first half of ' num [ ] ' is being considered , therefore for the rightmost digit in the first half of ' num [ ] ' , there will be no greater right digit ; index of the greatest right digit till the current index from the right direction ; traverse the array from second right element in the first half of ' num [ ] ' up to the left element ; if ' num [ i ] ' is less than the greatest digit encountered so far ; there is no greater right digit for ' num [ i ] ' ; update ' right ' index ; traverse the ' rightMax [ ] ' array from left to right ; if for the current digit , greater right digit exists then swap it with its greater right digit and also perform the required swap operation in the right halft of ' num [ ] ' to maintain palindromic property , then break ; performing the required swap operations ;  ; Driver code ; required largest palindromic number"
How can the above be solved in Java?

class GFG { static void largestPalin ( char num [ ] , int n ) { if ( n <= 3 ) return ; int mid = n / 2 - 1 ; int [ ] rightMax = new int [ mid + 1 ] ; int right ; rightMax [ mid ] = - 1 ; right = mid ; for ( int i = mid - 1 ; i >= 0 ; i -- ) { if ( num [ i ] < num [ right ] ) rightMax [ i ] = right ; else { rightMax [ i ] = - 1 ; right = i ; } } for ( int i = 0 ; i <= mid ; i ++ ) { if ( rightMax [ i ] != - 1 ) { swap ( num , i , rightMax [ i ] ) ; swap ( num , n - i - 1 , n - rightMax [ i ] - 1 ) ; break ; } } } static char [ ] swap ( char [ ] arr , int i , int j ) { char temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; return arr ; } public static void main ( String [ ] args ) { char num [ ] = "4697557964" . toCharArray ( ) ; int n = num . length ; largestPalin ( num , n ) ; System . out . println ( " Largest ▁ Palindrome : ▁ " + String . valueOf ( num ) ) ; } }


"Forming smallest array with given constraints | Java program to find the length of smallest array begin with x , having y , ends with z and having absolute difference between adjacent elements <= 1. ; Return the size of smallest array with given constraint . ; Drivers code"
How can the above be solved in Java?

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


"Forming triangles using points on a square | Java implementation of the above approach ; Function to return the count of possible triangles ; Driver code"
How can the above be solved in Java?

class GFG { static int noOfTriangles ( int n ) { int y = 4 * n ; return ( ( y * ( y - 2 ) * ( y - 1 ) ) - ( 4 * n * ( n - 2 ) * ( n - 1 ) ) ) / 6 ; } public static void main ( String [ ] args ) { int n = 1 ; System . out . println ( noOfTriangles ( n ) ) ; } }


"Fraction | Java program to add 2 fractions ; Function to return gcd of a and b ; Function to convert the obtained fraction into it 's simplest form ; Finding gcd of both terms ; Converting both terms into simpler terms by dividing them by common factor ; Function to add two fractions ; Finding gcd of den1 and den2 ; Denominator of final fraction obtained finding LCM of den1 and den2 LCM * GCD = a * b ; Changing the fractions to have same denominator . Numerator of the final fraction obtained ; Calling function to convert final fraction into it 's simplest form ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int den3 , num3 ; static int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } static void lowest ( ) { int common_factor = gcd ( num3 , den3 ) ; den3 = den3 / common_factor ; num3 = num3 / common_factor ; } static void addFraction ( int num1 , int den1 , int num2 , int den2 ) { den3 = gcd ( den1 , den2 ) ; den3 = ( den1 * den2 ) / den3 ; num3 = ( num1 ) * ( den3 / den1 ) + ( num2 ) * ( den3 / den2 ) ; lowest ( ) ; } public static void main ( String [ ] args ) { int num1 = 1 , den1 = 500 , num2 = 2 , den2 = 1500 ; addFraction ( num1 , den1 , num2 , den2 ) ; System . out . printf ( "%d/%d + %d/%d is equal to %d/%d
", num1, den1, num2, den2, num3, den3); } }


"Freivaldâ €™ s Algorithm to check if a matrix is product of two | Java code to implement Freivald 's Algorithm ; Function to check if ABx = Cx ; Generate a random vector ; Now comput B * r for evaluating expression A * ( B * r ) - ( C * r ) ; Now comput C * r for evaluating expression A * ( B * r ) - ( C * r ) ; Now comput A * ( B * r ) for evaluating expression A * ( B * r ) - ( C * r ) ; Finally check if value of expression A * ( B * r ) - ( C * r ) is 0 or not ; Runs k iterations Freivald . The value of k determines accuracy . Higher value means higher accuracy . ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; import java . math . * ; class GFG { static int N = 2 ; static boolean freivald ( int a [ ] [ ] , int b [ ] [ ] , int c [ ] [ ] ) { int r [ ] = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) r [ i ] = ( int ) ( Math . random ( ) ) % 2 ; int br [ ] = new int [ N ] ; Arrays . fill ( br , 0 ) ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) br [ i ] = br [ i ] + b [ i ] [ j ] * r [ j ] ; int cr [ ] = new int [ N ] ; Arrays . fill ( cr , 0 ) ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) cr [ i ] = cr [ i ] + c [ i ] [ j ] * r [ j ] ; int axbr [ ] = new int [ N ] ; Arrays . fill ( axbr , 0 ) ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) axbr [ i ] = axbr [ i ] + a [ i ] [ j ] * br [ j ] ; for ( int i = 0 ; i < N ; i ++ ) if ( axbr [ i ] - cr [ i ] != 0 ) return false ; return true ; } static boolean isProduct ( int a [ ] [ ] , int b [ ] [ ] , int c [ ] [ ] , int k ) { for ( int i = 0 ; i < k ; i ++ ) if ( freivald ( a , b , c ) == false ) return false ; return true ; } public static void main ( String args [ ] ) { int a [ ] [ ] = { { 1 , 1 } , { 1 , 1 } } ; int b [ ] [ ] = { { 1 , 1 } , { 1 , 1 } } ; int c [ ] [ ] = { { 2 , 2 } , { 2 , 2 } } ; int k = 2 ; if ( isProduct ( a , b , c , k ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Frequencies of even and odd numbers in a matrix | Java Program to Find the frequency of even and odd numbers in a matrix ; function for calculating frequency ; modulo by 2 to check even and odd ; print Frequency of numbers ; Driver code"
How can the above be solved in Java?

 class GFG { static final int MAX = 100 ; static void freq ( int ar [ ] [ ] , int m , int n ) { int even = 0 , odd = 0 ; for ( int i = 0 ; i < m ; ++ i ) { for ( int j = 0 ; j < n ; ++ j ) { if ( ( ar [ i ] [ j ] % 2 ) == 0 ) ++ even ; else ++ odd ; } } System . out . print ( " ▁ Frequency ▁ of ▁ odd ▁ number ▁ = " + odd + "
"); System . out . print ( " ▁ Frequency ▁ of ▁ even ▁ number ▁ = ▁ " + even + "
"); } public static void main ( String [ ] args ) { int m = 3 , n = 3 ; int array [ ] [ ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; freq ( array , m , n ) ; } }


"Frequency of a substring in a string | Simple Java program to count occurrences of pat in txt . ; A loop to slide pat [ ] one by one ; For current index i , check for pattern match ; if pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; Driver program to test above function"
How can the above be solved in Java?

class GFG { static int countFreq ( String pat , String txt ) { int M = pat . length ( ) ; int N = txt . length ( ) ; int res = 0 ; for ( int i = 0 ; i <= N - M ; i ++ ) { int j ; for ( j = 0 ; j < M ; j ++ ) { if ( txt . charAt ( i + j ) != pat . charAt ( j ) ) { break ; } } if ( j == M ) { res ++ ; j = 0 ; } } return res ; } static public void main ( String [ ] args ) { String txt = " dhimanman " ; String pat = " man " ; System . out . println ( countFreq ( pat , txt ) ) ; } }


"Frequency of an integer in the given array using Divide and Conquer | Java implrmrntation of the approach ; Function to return the frequency of x in the subarray arr [ low ... high ] ; If the subarray is invalid or the element is not found ; If there 's only a single element  which is equal to x ; Divide the array into two parts and then find the count of occurrences of x in both the parts ; Driver code"
How can the above be solved in Java?

class GFG { static int count ( int arr [ ] , int low , int high , int x ) { if ( ( low > high ) || ( low == high && arr [ low ] != x ) ) return 0 ; if ( low == high && arr [ low ] == x ) return 1 ; return count ( arr , low , ( low + high ) / 2 , x ) + count ( arr , 1 + ( low + high ) / 2 , high , x ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 30 , 1 , 42 , 5 , 56 , 3 , 56 , 9 } ; int n = arr . length ; int x = 56 ; System . out . print ( count ( arr , 0 , n - 1 , x ) ) ; } }


"Frequency of lexicographically Kth smallest character in the a string | Java program for the above approach ; Function to find the frequency of the lexicographically Kth smallest character ; Convert the string to array of characters ; Sort the array in ascending order ; Store the Kth character ; Store the frequency of the K - th character ; Count the frequency of the K - th character ; Print the count ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { public static void KthCharacter ( String S , int N , int K ) { char strarray [ ] = S . toCharArray ( ) ; Arrays . sort ( strarray ) ; char ch = strarray [ K - 1 ] ; int count = 0 ; for ( char c : strarray ) { if ( c == ch ) count ++ ; } System . out . println ( count ) ; } public static void main ( String [ ] args ) { String S = " geeksforgeeks " ; int N = S . length ( ) ; int K = 3 ; KthCharacter ( S , N , K ) ; } }


"Frequency of maximum occurring subsequence in given string | Java program for the above approach ; Function to find the frequency ; freq stores frequency of each english lowercase character ; dp [ i ] [ j ] stores the count of subsequence with ' a ' + i and ' a ' + j character ; Increment the count of subsequence j and s [ i ] ; Update the frequency array ; For 1 length subsequence ; For 2 length subsequence ; Return the final result ; Driver Code ; Given String str ; Function call"
How can the above be solved in Java?

class GFG { static int findCount ( String s ) { int [ ] freq = new int [ 26 ] ; int [ ] [ ] dp = new int [ 26 ] [ 26 ] ; for ( int i = 0 ; i < s . length ( ) ; ++ i ) { for ( int j = 0 ; j < 26 ; j ++ ) { dp [ j ] [ s . charAt ( i ) - ' a ' ] += freq [ j ] ; } freq [ s . charAt ( i ) - ' a ' ] ++ ; } int ans = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) ans = Math . max ( freq [ i ] , ans ) ; for ( int i = 0 ; i < 26 ; i ++ ) { for ( int j = 0 ; j < 26 ; j ++ ) { ans = Math . max ( dp [ i ] [ j ] , ans ) ; } } return ans ; } public static void main ( String [ ] args ) { String str = " acbab " ; System . out . print ( findCount ( str ) ) ; } }


"Frequency of smallest character in first sentence less than that of second sentence | Java program for the above approach ; Function to count the frequency of minimum character ; Sort the string s ; Return the count with smallest character ; Function to count number of frequency of smallest character of string arr1 [ ] is less than the string in arr2 [ ] ; To store the frequency of smallest character in each string of arr2 ; Traverse the arr2 [ ] ; Count the frequency of smallest character in string s ; Append the frequency to freq [ ] ; Sort the frequency array ; Traverse the array arr1 [ ] ; Count the frequency of smallest character in string s ; find the element greater than f ; Find the count such that arr1 [ i ] < arr2 [ j ] ; Print the count ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int countMinFreq ( String s ) { char [ ] tempArray = s . toCharArray ( ) ; Arrays . sort ( tempArray ) ; s = new String ( tempArray ) ; int x = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) if ( s . charAt ( i ) == s . charAt ( 0 ) ) x ++ ; return x ; } static void countLessThan ( List < String > arr1 , List < String > arr2 ) { List < Integer > freq = new ArrayList < Integer > ( ) ; for ( String s : arr2 ) { int f = countMinFreq ( s ) ; freq . add ( f ) ; } Collections . sort ( freq ) ; for ( String s : arr1 ) { int f = countMinFreq ( s ) ; int it = upper_bound ( freq , f ) ; int cnt = freq . size ( ) - it ; System . out . print ( cnt + " ▁ " ) ; } } static int upper_bound ( List < Integer > freq , int f ) { int low = 0 , high = freq . size ( ) - 1 ; while ( low < high ) { int mid = ( low + high ) / 2 ; if ( freq . get ( mid ) > f ) high = mid ; else low = mid + 1 ; } return ( freq . get ( low ) < f ) ? low ++ : low ; } public static void main ( String [ ] args ) { List < String > arr1 , arr2 ; arr1 = Arrays . asList ( new String [ ] { " yyy " , " zz " } ) ; arr2 = Arrays . asList ( new String [ ] { " x " , " xx " , " xxx " , " xxxx " } ) ; countLessThan ( arr1 , arr2 ) ; } }


"Friends Pairing Problem | Java program for solution of friends pairing problem ; Returns count of ways n people can remain single or paired up . ; Filling dp [ ] in bottom - up manner using recursive formula explained above . ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countFriendsPairings ( int n ) { int dp [ ] = new int [ n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) { if ( i <= 2 ) dp [ i ] = i ; else dp [ i ] = dp [ i - 1 ] + ( i - 1 ) * dp [ i - 2 ] ; } return dp [ n ] ; } public static void main ( String [ ] args ) { int n = 4 ; System . out . println ( countFriendsPairings ( n ) ) ; } }


"Friends Pairing Problem | Java program for solution of friends pairing problem Using Recursion ; Returns count of ways n people can remain single or paired up . ; Driver code"
How can the above be solved in Java?

class GFG { static int [ ] dp = new int [ 1000 ] ; static int countFriendsPairings ( int n ) { if ( dp [ n ] != - 1 ) return dp [ n ] ; if ( n > 2 ) return dp [ n ] = countFriendsPairings ( n - 1 ) + ( n - 1 ) * countFriendsPairings ( n - 2 ) ; else return dp [ n ] = n ; } public static void main ( String [ ] args ) { for ( int i = 0 ; i < 1000 ; i ++ ) dp [ i ] = - 1 ; int n = 4 ; System . out . println ( countFriendsPairings ( n ) ) ; } }


"Friends Pairing Problem | Java soln using mathematical approach ; Returns count of ways n people can remain single or paired up . ; pow of 1 will always be one ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static Vector < Integer > fact ; static void preComputeFact ( int n ) { for ( int i = 1 ; i <= n ; i ++ ) fact . add ( fact . elementAt ( i - 1 ) * i ) ; } static int countFriendsPairings ( int n ) { int ones = n , twos = 1 , ans = 0 ; while ( ones >= 0 ) { ans += fact . elementAt ( n ) / ( twos * fact . elementAt ( ones ) * fact . elementAt ( ( n - ones ) / 2 ) ) ; ones -= 2 ; twos *= 2 ; } return ans ; } public static void main ( String [ ] args ) { fact = new Vector < > ( ) ; fact . add ( 1 ) ; preComputeFact ( 100 ) ; int n = 4 ; System . out . print ( countFriendsPairings ( n ) + "
"); } }


"Friends Pairing Problem | Returns count of ways n people can remain single or paired up . ; Driver code"
How can the above be solved in Java?

class GFG { static int countFriendsPairings ( int n ) { int a = 1 , b = 2 , c = 0 ; if ( n <= 2 ) { return n ; } for ( int i = 3 ; i <= n ; i ++ ) { c = b + ( i - 1 ) * a ; a = b ; b = c ; } return c ; } public static void main ( String [ ] args ) { int n = 4 ; System . out . println ( countFriendsPairings ( n ) ) ; } }


"Frobenius coin problem | Java program to find the largest number that cannot be formed from given two coins ; Utility function to find gcd ; Function to print the desired output ; Solution doesn 't exist   if GCD is not 1 ; Else apply the formula ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int gcd ( int a , int b ) { int c ; while ( a != 0 ) { c = a ; a = b % a ; b = c ; } return b ; } static void forbenius ( int X , int Y ) { if ( gcd ( X , Y ) != 1 ) { System . out . println ( " NA " ) ; return ; } int A = ( X * Y ) - ( X + Y ) ; int N = ( X - 1 ) * ( Y - 1 ) / 2 ; System . out . println ( " Largest ▁ Amount ▁ = ▁ " + A ) ; System . out . println ( " Total ▁ Count ▁ = ▁ " + N ) ; } public static void main ( String [ ] args ) { int X = 2 , Y = 5 ; forbenius ( X , Y ) ; X = 5 ; Y = 10 ; System . out . println ( ) ; forbenius ( X , Y ) ; } }


"Front and Back Search in unsorted array | Java program to implement front and back search ; Start searching from both ends ; Keep searching while two indexes do not cross . ; driver code"
How can the above be solved in Java?

class GFG { static boolean search ( int arr [ ] , int n , int x ) { int front = 0 , back = n - 1 ; while ( front <= back ) { if ( arr [ front ] == x arr [ back ] == x ) return true ; front ++ ; back -- ; } return false ; } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 20 , 80 , 30 , 60 , 50 , 110 , 100 , 130 , 170 } ; int x = 130 ; int n = arr . length ; if ( search ( arr , n , x ) ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } }


"Frugal Number | Program to check for Frugal number ; Finding primes upto entered number ; Finding primes by Sieve of Eratosthenes method ; If prime [ i ] is not changed , then it is prime ; Update all multiples of p ; Forming array of the prime numbers found ; Returns number of digits in n ; Checking whether a number is Frugal or not ; Finding number of digits in prime factorization of the number ; Exponent for current factor ; Counting number of times this prime factor divides ( Finding exponent ) ; Finding number of digits in the exponent Avoiding exponents of value 1 ; Checking condition for frugal number ; Driver Code"
How can the above be solved in Java?

 import java . io . * ; import java . util . * ; class GFG { static ArrayList < Long > primes ( long n ) { boolean [ ] prime = new boolean [ ( int ) n + 1 ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) prime [ i ] = true ; for ( int i = 2 ; i * i <= n ; i ++ ) { if ( prime [ i ] == true ) { for ( int j = i * 2 ; j <= n ; j += i ) prime [ j ] = false ; } } ArrayList < Long > arr = new ArrayList < Long > ( ) ; for ( int i = 2 ; i < n ; i ++ ) if ( prime [ i ] ) arr . add ( ( long ) i ) ; return arr ; } static int countDigits ( long n ) { long temp = n ; int c = 0 ; while ( temp != 0 ) { temp = temp / 10 ; c ++ ; } return c ; } static boolean frugal ( long n ) { ArrayList < Long > r = primes ( n ) ; long t = n ; long s = 0 ; for ( int i = 0 ; i < r . size ( ) ; i ++ ) { if ( t % r . get ( i ) == 0 ) { long k = 0 ; while ( t % r . get ( i ) == 0 ) { t = t / r . get ( i ) ; k ++ ; } if ( k == 1 ) s = s + countDigits ( r . get ( i ) ) ; else if ( k != 1 ) s = s + countDigits ( r . get ( i ) ) + countDigits ( k ) ; } } return ( countDigits ( n ) > s && s != 0 ) ; } public static void main ( String [ ] args ) { long n = 343 ; if ( frugal ( n ) ) System . out . print ( "A Frugal number
"); else System . out . print ( "Not a frugal number
"); } }


"Function to check if a singly linked list is palindrome | Java program to check if linked list is palindrome ; Linked list Node ; head of list ; Function to check if given linked list is palindrome or not ; To handle odd size list ; initialize result ; Get the middle of the list . Move slow_ptr by 1 and fast_ptrr by 2 , slow_ptr will have the middle node ; We need previous of the slow_ptr for linked lists with odd elements ; fast_ptr would become NULL when there are even elements in the list and not NULL for odd elements . We need to skip the middle node for odd case and store it somewhere so that we can restore the original list ; Now reverse the second half and compare it with first half ; NULL terminate first half ; Reverse the second half ; compare ; Reverse the second half again ; If there was a mid node ( odd size case ) which was not part of either first half or second half . ; Function to reverse the linked list Note that this function may change the head ; Function to check if two input lists have same data ; Both are empty reurn 1 ; Will reach here when one is NULL and other is not ; Push a node to linked list . Note that this function changes the head ; Allocate the Node & Put in the data ; link the old list off the new one ; Move the head to point to new Node ; A utility function to print a given linked list ; Driver program to test the above functions ; Start with the empty list"
How can the above be solved in Java?

class LinkedList { class Node { char data ; Node next ; Node ( char d ) { data = d ; next = null ; } } Node head ; Node slow_ptr , fast_ptr , second_half ; boolean isPalindrome ( Node head ) { slow_ptr = head ; fast_ptr = head ; Node prev_of_slow_ptr = head ; Node midnode = null ; boolean res = true ; if ( head != null && head . next != null ) { while ( fast_ptr != null && fast_ptr . next != null ) { fast_ptr = fast_ptr . next . next ; prev_of_slow_ptr = slow_ptr ; slow_ptr = slow_ptr . next ; } if ( fast_ptr != null ) { midnode = slow_ptr ; slow_ptr = slow_ptr . next ; } second_half = slow_ptr ; prev_of_slow_ptr . next = null ; reverse ( ) ; res = compareLists ( head , second_half ) ; reverse ( ) ; if ( midnode != null ) { prev_of_slow_ptr . next = midnode ; midnode . next = second_half ; } else prev_of_slow_ptr . next = second_half ; } return res ; } void reverse ( ) { Node prev = null ; Node current = second_half ; Node next ; while ( current != null ) { next = current . next ; current . next = prev ; prev = current ; current = next ; } second_half = prev ; } boolean compareLists ( Node head1 , Node head2 ) { Node temp1 = head1 ; Node temp2 = head2 ; while ( temp1 != null && temp2 != null ) { if ( temp1 . data == temp2 . data ) { temp1 = temp1 . next ; temp2 = temp2 . next ; } else return false ; } if ( temp1 == null && temp2 == null ) return true ; return false ; } public void push ( char new_data ) { Node new_node = new Node ( new_data ) ; new_node . next = head ; head = new_node ; } void printList ( Node ptr ) { while ( ptr != null ) { System . out . print ( ptr . data + " - > " ) ; ptr = ptr . next ; } System . out . println ( " NULL " ) ; } public static void main ( String [ ] args ) { LinkedList llist = new LinkedList ( ) ; char str [ ] = { ' a ' , ' b ' , ' a ' , ' c ' , ' a ' , ' b ' , ' a ' } ; String string = new String ( str ) ; for ( int i = 0 ; i < 7 ; i ++ ) { llist . push ( str [ i ] ) ; llist . printList ( llist . head ) ; if ( llist . isPalindrome ( llist . head ) != false ) { System . out...


"Function to copy string ( Iterative and Recursive ) | Iterative Java Program to copy one String to another . ; Function to copy one string to other assuming that other string has enough space . ; Driver code"
How can the above be solved in Java?

class GFG { static void myCopy ( char s1 [ ] , char s2 [ ] ) { int i = 0 ; for ( i = 0 ; i < s1 . length ; i ++ ) s2 [ i ] = s1 [ i ] ; } public static void main ( String [ ] args ) { char s1 [ ] = " GEEKSFORGEEKS " . toCharArray ( ) ; char s2 [ ] = new char [ s1 . length ] ; myCopy ( s1 , s2 ) ; System . out . println ( String . valueOf ( s2 ) ) ; } }


"Function to find Number of customers who could not get a computer | JAVA program to find number of customers who couldn 't get a resource. ; n is number of computers in cafe . ' seq ' is given sequence of customer entry , exit events ; seen [ i ] = 0 , indicates that customer ' i ' is not in cafe seen [ 1 ] = 1 , indicates that customer ' i ' is in cafe but computer is not assigned yet . seen [ 2 ] = 2 , indicates that customer ' i ' is in cafe and has occupied a computer . ; Initialize result which is number of customers who could not get any computer . ; To keep track of occupied computers ; Traverse the input sequence ; Find index of current character in seen [ 0. . .25 ] ; If First occurrence of ' seq [ i ] ' ; set the current character as seen ; If number of occupied computers is less than n , then assign a computer to new customer ; Set the current character as occupying a computer ; Else this customer cannot get a computer , increment result ; If this is second occurrence of ' seq [ i ] ' ; Decrement occupied only if this customer was using a computer ; Driver program"
How can the above be solved in Java?

class GFG { static int MAX_CHAR = 26 ; static int runCustomerSimulation ( int n , char [ ] seq ) { char [ ] seen = new char [ MAX_CHAR ] ; int res = 0 ; int occupied = 0 ; for ( int i = 0 ; i < seq . length ; i ++ ) { int ind = seq [ i ] - ' A ' ; if ( seen [ ind ] == 0 ) { seen [ ind ] = 1 ; if ( occupied < n ) { occupied ++ ; seen [ ind ] = 2 ; } else res ++ ; } else { if ( seen [ ind ] == 2 ) occupied -- ; seen [ ind ] = 0 ; } } return res ; } public static void main ( String [ ] args ) { System . out . println ( runCustomerSimulation ( 2 , " ABBAJJKZKZ " . toCharArray ( ) ) ) ; System . out . println ( runCustomerSimulation ( 3 , " GACCBDDBAGEE " . toCharArray ( ) ) ) ; System . out . println ( runCustomerSimulation ( 3 , " GACCBGDDBAEE " . toCharArray ( ) ) ) ; System . out . println ( runCustomerSimulation ( 1 , " ABCBCA " . toCharArray ( ) ) ) ; System . out . println ( runCustomerSimulation ( 1 , " ABCBCADEED " . toCharArray ( ) ) ) ; } }


"GCD of a number raised to some power and another number | Java program of the above approach ; Calculates modular exponentiation , i . e . , ( x ^ y ) % p in O ( log y ) ; x = x % p ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 ; y = y / 2 ; Returns GCD of a ^ n and b ; Driver code"
How can the above be solved in Java?

import java . util . * ; class Solution { static long power ( long x , long y , long p ) { while ( y > 0 ) { if ( ( y & 1 ) != 0 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return res ; } static long gcd ( long a , long b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } static long powerGCD ( long a , long b , long n ) { long e = power ( a , n , b ) ; return gcd ( e , b ) ; } public static void main ( String args [ ] ) { long a = 5 , b = 4 , n = 2 ; System . out . print ( powerGCD ( a , b , n ) ) ; } }


"GCD of a number raised to some power and another number | Java program to find GCD of a ^ n and b . ; Returns GCD of a ^ n and b . ; Driver code"
How can the above be solved in Java?

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


"GCD of elements occurring Fibonacci number of times in an Array | Java program to find the GCD of elements which occur Fibonacci number of times ; Function to create hash table to check Fibonacci numbers ; Inserting the first two numbers into the hash ; Adding the remaining Fibonacci numbers using the previously added elements ; Function to return the GCD of elements in an array having fibonacci frequency ; Creating the hash ; Map is used to store the frequencies of the elements ; Iterating through the array ; Traverse the map using iterators ; Calculate the gcd of elements having fibonacci frequencies ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { 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 int gcdFibonacciFreq ( int arr [ ] , int n ) { HashSet < Integer > hash = new HashSet < Integer > ( ) ; createHash ( hash , Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ) ; int i ; HashMap < Integer , Integer > m = new HashMap < Integer , Integer > ( ) ; for ( i = 0 ; i < n ; i ++ ) { if ( m . containsKey ( arr [ i ] ) ) { m . put ( arr [ i ] , m . get ( arr [ i ] ) + 1 ) ; } else { m . put ( arr [ i ] , 1 ) ; } } int gcd = 0 ; for ( Map . Entry < Integer , Integer > it : m . entrySet ( ) ) { if ( hash . contains ( it . getValue ( ) ) ) { gcd = __gcd ( gcd , it . getKey ( ) ) ; } } return gcd ; } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 3 , 6 , 5 , 6 , 6 , 5 , 5 } ; int n = arr . length ; System . out . print ( gcdFibonacciFreq ( arr , n ) ) ; } }


"GCD of factorials of two numbers | Java program to find GCD of factorial of two numbers . ; Driver program to test above functions"
How can the above be solved in Java?

public class FactorialGCD { static int factorial ( int x ) { if ( x <= 1 ) return 1 ; int res = 2 ; for ( int i = 3 ; i <= x ; i ++ ) res = res * i ; return res ; } static int gcdOfFactorial ( int m , int n ) { int min = m < n ? m : n ; return factorial ( min ) ; } public static void main ( String [ ] args ) { int m = 5 , n = 9 ; System . out . println ( gcdOfFactorial ( m , n ) ) ; } }


"GCD of more than two ( or array ) numbers |  ; Recursive function to return gcd of a and b ; recursive implementation ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } static int GcdOfArray ( int [ ] arr , int idx ) { if ( idx == arr . length - 1 ) { return arr [ idx ] ; } int a = arr [ idx ] ; int b = GcdOfArray ( arr , idx + 1 ) ; return __gcd ( a , b ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 } ; System . out . print ( GcdOfArray ( arr , 0 ) + "
"); int [ ] arr1 = { 2 , 4 , 6 , 8 } ; System . out . print ( GcdOfArray ( arr1 , 0 ) + "
"); } }


"GCD of more than two ( or array ) numbers | Java program to find GCD of two or more numbers ; Function to return gcd of a and b ; Function to find gcd of array of numbers ; Driver code"
How can the above be solved in Java?

public class GCD { static int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } static int findGCD ( int arr [ ] , int n ) { int result = 0 ; for ( int element : arr ) { result = gcd ( result , element ) ; if ( result == 1 ) { return 1 ; } } return result ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 4 , 6 , 8 , 16 } ; int n = arr . length ; System . out . println ( findGCD ( arr , n ) ) ; } }


"GCD of two numbers formed by n repeating x and y times | Java program to print Greatest Common Divisor of number formed by N repeating x times and y times ; Return the Greatest common Divisor of two numbers . ; Prints Greatest Common Divisor of number formed by n repeating x times and y times . ; Finding GCD of x and y . ; Print n , g times . ; Driver code"
How can the above be solved in Java?

class GFG { static int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } static void findgcd ( int n , int x , int y ) { int g = gcd ( x , y ) ; for ( int i = 0 ; i < g ; i ++ ) System . out . print ( n ) ; } public static void main ( String [ ] args ) { int n = 123 , x = 5 , y = 2 ; findgcd ( n , x , y ) ; } }


"GCDs of given index ranges in an array | Java Program to find GCD of a number in a given Range using segment Trees ; Array to store segment tree ; A recursive function that constructs Segment Tree for array [ ss . . se ] . si is index of current node in segment tree st ; Function to construct segment tree from given array . This function allocates memory for segment tree and calls constructSTUtil ( ) to fill the allocated memory ; Function to find gcd of 2 numbers . ; If b greater than a swap a and b ; A recursive function to get gcd of given range of array indexes . The following are parameters for this function . st -- > Pointer to segment tree si -- > Index of current node in the segment tree . Initially 0 is passed as root is always at index 0 ss & se -- > Starting and ending indexes of the segment represented by current node , i . e . , st [ si ] qs & qe -- > Starting and ending indexes of query range ; Finding The gcd of given Range ; Driver Code ; Starting index of range . ; Last index of range ."
How can the above be solved in Java?

import java . io . * ; public class Main { private static int [ ] st ; public static int constructST ( int [ ] arr , int ss , int se , int si ) { if ( ss == se ) { st [ si ] = arr [ ss ] ; return st [ si ] ; } int mid = ss + ( se - ss ) / 2 ; st [ si ] = gcd ( constructST ( arr , ss , mid , si * 2 + 1 ) , constructST ( arr , mid + 1 , se , si * 2 + 2 ) ) ; return st [ si ] ; } public static int [ ] constructSegmentTree ( int [ ] arr ) { int height = ( int ) Math . ceil ( Math . log ( arr . length ) / Math . log ( 2 ) ) ; int size = 2 * ( int ) Math . pow ( 2 , height ) - 1 ; st = new int [ size ] ; constructST ( arr , 0 , arr . length - 1 , 0 ) ; return st ; } private static int gcd ( int a , int b ) { if ( a < b ) { int temp = b ; b = a ; a = temp ; } if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } public static int findGcd ( int ss , int se , int qs , int qe , int si ) { if ( ss > qe se < qs ) return 0 ; if ( qs <= ss && qe >= se ) return st [ si ] ; int mid = ss + ( se - ss ) / 2 ; return gcd ( findGcd ( ss , mid , qs , qe , si * 2 + 1 ) , findGcd ( mid + 1 , se , qs , qe , si * 2 + 2 ) ) ; } public static int findRangeGcd ( int ss , int se , int [ ] arr ) { int n = arr . length ; if ( ss < 0 se > n - 1 ss > se ) throw new IllegalArgumentException ( " Invalid ▁ arguments " ) ; return findGcd ( 0 , n - 1 , ss , se , 0 ) ; } public static void main ( String [ ] args ) throws IOException { int [ ] a = { 2 , 3 , 6 , 9 , 5 } ; constructSegmentTree ( a ) ; int l = 1 ; int r = 3 ; System . out . print ( " GCD ▁ of ▁ the ▁ given ▁ range ▁ is : ▁ " ) ; System . out . print ( findRangeGcd ( l , r , a ) ) ; } }


"Game Theory in Balanced Ternary Numeral System | ( Moving 3 k steps at a time ) | Java implementation of the approach ; Function that returns true if the game cannot be won ; Driver code ; Common length"
How can the above be solved in Java?

class GfG { static boolean isDefeat ( String s1 , String s2 , int n ) { for ( int i = 0 ; i < n ; i ++ ) { if ( ( s1 . charAt ( i ) == '0' && s2 . charAt ( i ) == '1' ) || ( s1 . charAt ( i ) == '1' && s2 . charAt ( i ) == '0' ) ) continue ; else if ( ( s1 . charAt ( i ) == '0' && s2 . charAt ( i ) == ' Z ' ) || ( s1 . charAt ( i ) == ' Z ' && s2 . charAt ( i ) == '0' ) ) continue ; else { return true ; } } return false ; } public static void main ( String [ ] args ) { String s1 = ( "01001101ZZ " ) ; String s2 = ( "10Z1001000" ) ; int n = 10 ; if ( isDefeat ( s1 , s2 , n ) ) System . out . println ( " Defeat " ) ; else System . out . println ( " Victory " ) ; } }


"Game Theory in Balanced Ternary Numeral System | ( Moving 3 k steps at a time ) | Java implementation of the approach ; Numbers are in range of pow ( 3 , 32 ) ; Conversion of ternary into balanced ternary as start iterating from Least Significant Bit ( i . e 0 th ) , if encountered 0 or 1 , safely skip and pass carry 0 further 2 , replace it to - 1 and pass carry 1 further 3 , replace it to 0 and pass carry 1 further ; Similar to binary conversion ; Driver code ; Moving on to first occupied bit ; Printing ; Print ' Z ' in place of - 1"
How can the above be solved in Java?

import java . util . * ; class GFG { static int [ ] arr = new int [ 33 ] ; static void balTernary ( int ter ) { int carry = 0 , base = 10 ; int i = 32 ; while ( ter > 0 ) { int rem = ter % base ; rem = rem + carry ; if ( rem == 0 ) { arr [ i -- ] = 0 ; carry = 0 ; } else if ( rem == 1 ) { arr [ i -- ] = 1 ; carry = 0 ; } else if ( rem == 2 ) { arr [ i -- ] = - 1 ; carry = 1 ; } else if ( rem == 3 ) { arr [ i -- ] = 0 ; carry = 1 ; } ter = ( int ) ( ter / base ) ; } if ( carry == 1 ) arr [ i ] = 1 ; } static int ternary ( int number ) { int ans = 0 , rem = 1 , base = 1 ; while ( number > 0 ) { rem = number % 3 ; ans = ans + rem * base ; number = ( int ) ( number / 3 ) ; base = base * 10 ; } return ans ; } public static void main ( String args [ ] ) { int number = 3056 ; int ter = ternary ( number ) ; Arrays . fill ( arr , 0 ) ; balTernary ( ter ) ; int i = 0 ; while ( arr [ i ] == 0 ) { i ++ ; } for ( int j = i ; j <= 32 ; j ++ ) { if ( arr [ j ] == - 1 ) System . out . print ( ' Z ' ) ; else System . out . print ( arr [ j ] ) ; } } }


"Game of Nim with removal of one stone allowed | JAVA Code For Game of Nim with removal of one stone allowed ; Return true if player A wins , return false if player B wins . ; Checking the last bit of N . ; Driver program to test above function"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findWinner ( int N ) { return N & 1 ; } public static void main ( String [ ] args ) { int N = 15 ; if ( findWinner ( N ) == 1 ) System . out . println ( " Player ▁ A " ) ; else System . out . println ( " Player ▁ B " ) ; } }


"Game of replacing array elements | Java program for Game of Replacement ; Function return which player win the game ; Create hash that will stores all distinct element ; Traverse an array element ; Driver Function"
How can the above be solved in Java?

import java . util . HashSet ; public class GameOfReplacingArrayElements { public static int playGame ( int arr [ ] ) { HashSet < Integer > set = new HashSet < > ( ) ; for ( int i : arr ) set . add ( i ) ; return ( set . size ( ) % 2 == 0 ) ? 1 : 2 ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 1 , 2 , 2 , 2 , 2 } ; System . out . print ( " Player ▁ " + playGame ( arr ) + " ▁ wins " ) ; } }