"Find Square Root under Modulo p | Set 2 ( Shanks Tonelli algorithm ) | Java program to implement Shanks Tonelli algorithm for finding Modular Square Roots ; utility function to find pow ( base , exponent ) % modulus ; utility function to find gcd ; Returns k such that b ^ k = 1 ( mod p ) ; Initializing k with first odd prime number ; function return p - 1 ( = x argument ) as x * 2 ^ e , where x will be odd sending e as reference because updation is needed in actual e ; Main function for finding the modular square root ; a and p should be coprime for finding the modular square root ; If below expression return ( p - 1 ) then modular square root is not possible ; expressing p - 1 , in terms of s * 2 ^ e , where s is odd number ; finding smallest q such that q ^ ( ( p - 1 ) / 2 ) ( mod p ) = p - 1 ; q - 1 is in place of ( - 1 % p ) ; Initializing variable x , b and g ; keep looping until b become 1 or m becomes 0 ; finding m such that b ^ ( 2 ^ m ) = 1 ; updating value of x , g and b according to algorithm ; Driver code ; p should be prime"
How can the above be solved in Java?

 class GFG { static int z = 0 ; static int pow1 ( int base1 , int exponent , int modulus ) { int result = 1 ; base1 = base1 % modulus ; while ( exponent > 0 ) { if ( exponent % 2 == 1 ) result = ( result * base1 ) % modulus ; exponent = exponent >> 1 ; base1 = ( base1 * base1 ) % modulus ; } return result ; } static int gcd ( int a , int b ) { if ( b == 0 ) return a ; else return gcd ( b , a % b ) ; } static int order ( int p , int b ) { if ( gcd ( p , b ) != 1 ) { System . out . println ( " p ▁ and ▁ b ▁ are " + " not ▁ co - prime . " ) ; return - 1 ; } int k = 3 ; while ( true ) { if ( pow1 ( b , k , p ) == 1 ) return k ; k ++ ; } } static int convertx2e ( int x ) { z = 0 ; while ( x % 2 == 0 ) { x /= 2 ; z ++ ; } return x ; } static int STonelli ( int n , int p ) { if ( gcd ( n , p ) != 1 ) { System . out . println ( " a ▁ and ▁ p ▁ are ▁ not ▁ coprime " ) ; return - 1 ; } if ( pow1 ( n , ( p - 1 ) / 2 , p ) == ( p - 1 ) ) { System . out . println ( " no ▁ sqrt ▁ possible " ) ; return - 1 ; } int s , e ; s = convertx2e ( p - 1 ) ; e = z ; int q ; for ( q = 2 ; ; q ++ ) { if ( pow1 ( q , ( p - 1 ) / 2 , p ) == ( p - 1 ) ) break ; } int x = pow1 ( n , ( s + 1 ) / 2 , p ) ; int b = pow1 ( n , s , p ) ; int g = pow1 ( q , s , p ) ; int r = e ; while ( true ) { int m ; for ( m = 0 ; m < r ; m ++ ) { if ( order ( p , b ) == - 1 ) return - 1 ; if ( order ( p , b ) == Math . pow ( 2 , m ) ) break ; } if ( m == 0 ) return x ; x = ( x * pow1 ( g , ( int ) Math . pow ( 2 , r - m - 1 ) , p ) ) % p ; g = pow1 ( g , ( int ) Math . pow ( 2 , r - m ) , p ) ; b = ( b * g ) % p ; if ( b == 1 ) return x ; r = m ; } } public static void main ( String [ ] args ) { int n = 2 ; int p = 113 ; int x = STonelli ( n , p ) ; if ( x == - 1 ) System . out . println ( " Modular ▁ square " + "root is not exist
"); else System . out . println ( " Modular ▁ square ▁ root ▁ of ▁ " + n + " ▁ and ▁ " + p + " ▁ is ▁ " + x + "
"); } }


"Find Sum of Series 1 ^ 2 | Java Program to find sum of series 1 ^ 2 - 2 ^ 2 + 3 ^ 3 - 4 ^ 4 + ... ; Function to find sum of series ; If i is even ; If i is odd ; return the result ; Driver Code ; Get n ; Find the sum ; Get n ; Find the sum"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static int sum_of_series ( int n ) { int result = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { if ( i % 2 == 0 ) result = result - ( int ) Math . pow ( i , 2 ) ; else result = result + ( int ) Math . pow ( i , 2 ) ; } return result ; } public static void main ( String args [ ] ) { int n = 3 ; System . out . println ( sum_of_series ( n ) ) ; n = 10 ; System . out . println ( sum_of_series ( n ) ) ; } }


"Find Sum of Series 1 ^ 2 | Java Program to find sum of series 1 ^ 2 - 2 ^ 2 + 3 ^ 3 - 4 ^ 4 + ... ; Function to find sum of series ; If n is even ; If n is odd ; return the result ; Driver Code ; Get n ; Find the sum ; Get n ; Find the sum"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static int sum_of_series ( int n ) { int result = 0 ; if ( n % 2 == 0 ) { result = - ( n * ( n + 1 ) ) / 2 ; } else { result = ( n * ( n + 1 ) ) / 2 ; } return result ; } public static void main ( String args [ ] ) { int n = 3 ; System . out . println ( sum_of_series ( n ) ) ; n = 10 ; System . out . println ( sum_of_series ( n ) ) ; } }


"Find Sum of all unique sub | Java for finding sum of all unique subarray sum ; Function for finding grandSum ; Calculate cumulative sum of array cArray [ 0 ] will store sum of zero elements ; Store all subarray sum in vector ; Sort the vector ; Mark all duplicate sub - array sum to zero ; Calculate total sum ; Return totalSum ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findSubarraySum ( int arr [ ] , int n ) { int i , j ; int cArray [ ] = new int [ n + 1 ] ; for ( i = 0 ; i < n ; i ++ ) cArray [ i + 1 ] = cArray [ i ] + arr [ i ] ; Vector < Integer > subArrSum = new Vector < Integer > ( ) ; for ( i = 1 ; i <= n ; i ++ ) for ( j = i ; j <= n ; j ++ ) subArrSum . add ( cArray [ j ] - cArray [ i - 1 ] ) ; Collections . sort ( subArrSum ) ; int totalSum = 0 ; for ( i = 0 ; i < subArrSum . size ( ) - 1 ; i ++ ) { if ( subArrSum . get ( i ) == subArrSum . get ( i + 1 ) ) { j = i + 1 ; while ( subArrSum . get ( j ) == subArrSum . get ( i ) && j < subArrSum . size ( ) ) { subArrSum . set ( j , 0 ) ; j ++ ; } subArrSum . set ( i , 0 ) ; } } for ( i = 0 ; i < subArrSum . size ( ) ; i ++ ) totalSum += subArrSum . get ( i ) ; return totalSum ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 2 , 3 , 1 , 4 } ; int n = arr . length ; System . out . print ( findSubarraySum ( arr , n ) ) ; } }


"Find Sum of all unique sub | Java for finding sum of all unique subarray sum ; function for finding grandSum ; Go through all subarrays , compute sums and count occurrences of sums . ; Print all those sums that appear once . ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findSubarraySum ( int [ ] arr , int n ) { int res = 0 ; HashMap < Integer , Integer > m = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int sum = 0 ; for ( int j = i ; j < n ; j ++ ) { sum += arr [ j ] ; if ( m . containsKey ( sum ) ) { m . put ( sum , m . get ( sum ) + 1 ) ; } else { m . put ( sum , 1 ) ; } } } for ( Map . Entry < Integer , Integer > x : m . entrySet ( ) ) if ( x . getValue ( ) == 1 ) res += x . getKey ( ) ; return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 2 , 3 , 1 , 4 } ; int n = arr . length ; System . out . println ( findSubarraySum ( arr , n ) ) ; } }


"Find Surpasser Count of each element in array | Naive Java program to find surpasser count of each element in array ; Function to find surpasser count of each element in array ; stores surpasser count for element arr [ i ] ; Function to print an array ; Driver program to test above functions"
How can the above be solved in Java?

import java . io . * ; class GFG { static void findSurpasser ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { int count = 0 ; for ( int j = i + 1 ; j < n ; j ++ ) if ( arr [ j ] > arr [ i ] ) count ++ ; System . out . print ( count + " ▁ " ) ; } } static void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; System . out . println ( ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 7 , 5 , 3 , 0 , 8 , 1 } ; int n = arr . length ; System . out . println ( " Given ▁ array ▁ is ▁ " ) ; printArray ( arr , n ) ; System . out . println ( " Surpasser ▁ Count ▁ of " + " ▁ array ▁ is ▁ " ) ; findSurpasser ( arr , n ) ; } }


"Find Tangent at a given point on the curve | Java program for find Tangent on a curve at given point ; function for find Tangent ; differentiate given equation ; check that point on the curve or not ; if differentiate is negative ; differentiate is positive ; differentiate is zero ; Driver code ; declare variable ; call function findTangent"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static void findTangent ( int A , int x , int y ) { int dif = A - x * 2 ; if ( y == ( 2 * x - x * x ) ) { if ( dif < 0 ) System . out . println ( " y ▁ = ▁ " + dif + " x " + ( x * dif + y ) ) ; else if ( dif > 0 ) System . out . println ( " y ▁ = ▁ " + dif + " x + " + - x * dif + y ) ; else System . out . println ( " Not ▁ possible " ) ; } } public static void main ( String args [ ] ) { int A = 2 , x = 2 , y = 0 ; findTangent ( A , x , y ) ; } }


"Find Two Missing Numbers | Set 2 ( XOR based solution ) | Java Program to find 2 Missing Numbers ; Function to find two missing numbers in range [ 1 , n ] . This function assumes that size of array is n - 2 and all array elements are distinct ; Get the XOR of all elements in arr [ ] and { 1 , 2 . . n } ; Get a set bit of XOR ( We get the rightmost set bit ) ; Now divide elements in two sets by comparing rightmost set bit of XOR with bit at same position in each element . int x = 0 , y = 0 ; Initialize missing numbers ; XOR of first set in arr [ ] ; XOR of second set in arr [ ] ; XOR of first set in arr [ ] and { 1 , 2 , ... n } ; XOR of second set in arr [ ] and { 1 , 2 , ... n } ; Driver program to test above function ; Range of numbers is 2 plus size of array"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findTwoMissingNumbers ( int arr [ ] , int n ) { int XOR = arr [ 0 ] ; for ( int i = 1 ; i < n - 2 ; i ++ ) XOR ^= arr [ i ] ; for ( int i = 1 ; i <= n ; i ++ ) XOR ^= i ; int set_bit_no = XOR & ~ ( XOR - 1 ) ; for ( int i = 0 ; i < n - 2 ; i ++ ) { if ( ( arr [ i ] & set_bit_no ) > 0 ) x = x ^ arr [ i ] ; else y = y ^ arr [ i ] ; } for ( int i = 1 ; i <= n ; i ++ ) { if ( ( i & set_bit_no ) > 0 ) x = x ^ i ; else y = y ^ i ; } System . out . println ( " Two ▁ Missing ▁ Numbers ▁ are ▁ " ) ; System . out . println ( x + " ▁ " + y ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 5 , 6 } ; int n = 2 + arr . length ; findTwoMissingNumbers ( arr , n ) ; } }


"Find Union and Intersection of two unsorted arrays | A Java program to print union and intersection of two unsorted arrays ; Prints union of arr1 [ 0. . m - 1 ] and arr2 [ 0. . n - 1 ] ; Before finding union , make sure arr1 [ 0. . m - 1 ] is smaller ; Now arr1 [ ] is smaller Sort the first array and print its elements ( these two steps can be swapped as order in output is not important ) ; Search every element of bigger array in smaller array and print the element if not found ; Prints intersection of arr1 [ 0. . m - 1 ] and arr2 [ 0. . n - 1 ] ; Before finding intersection , make sure arr1 [ 0. . m - 1 ] is smaller ; Now arr1 [ ] is smaller Sort smaller array arr1 [ 0. . m - 1 ] ; Search every element of bigger array in smaller array and print the element if found ; A recursive binary search function . It returns location of x in given array arr [ l . . r ] is present , otherwise - 1 ; If the element is present at the middle itself ; If element is smaller than mid , then it can only be present in left subarray ; Else the element can only be present in right subarray ; We reach here when element is not present in array ; Driver code ; Function call"
How can the above be solved in Java?

import java . util . Arrays ; class UnionAndIntersection { void printUnion ( int arr1 [ ] , int arr2 [ ] , int m , int n ) { if ( m > n ) { int tempp [ ] = arr1 ; arr1 = arr2 ; arr2 = tempp ; int temp = m ; m = n ; n = temp ; } Arrays . sort ( arr1 ) ; for ( int i = 0 ; i < m ; i ++ ) System . out . print ( arr1 [ i ] + " ▁ " ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( binarySearch ( arr1 , 0 , m - 1 , arr2 [ i ] ) == - 1 ) System . out . print ( arr2 [ i ] + " ▁ " ) ; } } void printIntersection ( int arr1 [ ] , int arr2 [ ] , int m , int n ) { if ( m > n ) { int tempp [ ] = arr1 ; arr1 = arr2 ; arr2 = tempp ; int temp = m ; m = n ; n = temp ; } Arrays . sort ( arr1 ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( binarySearch ( arr1 , 0 , m - 1 , arr2 [ i ] ) != - 1 ) System . out . print ( arr2 [ i ] + " ▁ " ) ; } } int binarySearch ( int arr [ ] , int l , int r , int x ) { if ( r >= l ) { int mid = l + ( r - l ) / 2 ; if ( arr [ mid ] == x ) return mid ; if ( arr [ mid ] > x ) return binarySearch ( arr , l , mid - 1 , x ) ; return binarySearch ( arr , mid + 1 , r , x ) ; } return - 1 ; } public static void main ( String [ ] args ) { UnionAndIntersection u_i = new UnionAndIntersection ( ) ; int arr1 [ ] = { 7 , 1 , 5 , 2 , 3 , 6 } ; int arr2 [ ] = { 3 , 8 , 6 , 20 , 7 } ; int m = arr1 . length ; int n = arr2 . length ; System . out . println ( " Union ▁ of ▁ two ▁ arrays ▁ is ▁ " ) ; u_i . printUnion ( arr1 , arr2 , m , n ) ; System . out . println ( " " ) ; System . out . println ( " Intersection ▁ of ▁ two ▁ arrays ▁ is ▁ " ) ; u_i . printIntersection ( arr1 , arr2 , m , n ) ; } }


"Find Union and Intersection of two unsorted arrays | Java code to find intersection when elements may not be distinct ; Function to find intersection ; when both are equal ; Driver Code ; sort ; Function call"
How can the above be solved in Java?

import java . io . * ; import java . util . Arrays ; class GFG { static void intersection ( int a [ ] , int b [ ] , int n , int m ) { int i = 0 , j = 0 ; while ( i < n && j < m ) { if ( a [ i ] > b [ j ] ) { j ++ ; } else if ( b [ j ] > a [ i ] ) { i ++ ; } else { System . out . print ( a [ i ] + " ▁ " ) ; i ++ ; j ++ ; } } } public static void main ( String [ ] args ) { int a [ ] = { 1 , 3 , 2 , 3 , 4 , 5 , 5 , 6 } ; int b [ ] = { 3 , 3 , 5 } ; int n = a . length ; int m = b . length ; Arrays . sort ( a ) ; Arrays . sort ( b ) ; intersection ( a , b , n , m ) ; } }


"Find Union and Intersection of two unsorted arrays | Java program for the above approach ; Defining map container mp ; Inserting array elements in mp ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void printUnion ( int [ ] a , int n , int [ ] b , int m ) { Map < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { mp . put ( a [ i ] , i ) ; } for ( int i = 0 ; i < m ; i ++ ) { mp . put ( b [ i ] , i ) ; } System . out . println ( " The ▁ union ▁ set ▁ of ▁ both ▁ arrays ▁ is ▁ : " ) ; for ( Map . Entry mapElement : mp . entrySet ( ) ) { System . out . print ( mapElement . getKey ( ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int a [ ] = { 1 , 2 , 5 , 6 , 2 , 3 , 5 } ; int b [ ] = { 2 , 4 , 5 , 6 , 8 , 9 , 4 , 6 , 5 } ; printUnion ( a , 7 , b , 9 ) ; } }


"Find Union and Intersection of two unsorted arrays | Java program to find union and intersection using Hashing ; Prints union of arr1 [ 0. . m - 1 ] and arr2 [ 0. . n - 1 ] ; Prints intersection of arr1 [ 0. . m - 1 ] and arr2 [ 0. . n - 1 ] ; Driver code ; Function call"
How can the above be solved in Java?

import java . util . HashSet ; class Test { static void printUnion ( int arr1 [ ] , int arr2 [ ] ) { HashSet < Integer > hs = new HashSet < > ( ) ; for ( int i = 0 ; i < arr1 . length ; i ++ ) hs . add ( arr1 [ i ] ) ; for ( int i = 0 ; i < arr2 . length ; i ++ ) hs . add ( arr2 [ i ] ) ; System . out . println ( hs ) ; } static void printIntersection ( int arr1 [ ] , int arr2 [ ] ) { HashSet < Integer > hs = new HashSet < > ( ) ; HashSet < Integer > hs1 = new HashSet < > ( ) ; for ( int i = 0 ; i < arr1 . length ; i ++ ) hs . add ( arr1 [ i ] ) ; for ( int i = 0 ; i < arr2 . length ; i ++ ) if ( hs . contains ( arr2 [ i ] ) ) System . out . print ( arr2 [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr1 [ ] = { 7 , 1 , 5 , 2 , 3 , 6 } ; int arr2 [ ] = { 3 , 8 , 6 , 20 , 7 } ; System . out . println ( " Union ▁ of ▁ two ▁ arrays ▁ is ▁ : ▁ " ) ; printUnion ( arr1 , arr2 ) ; System . out . println ( " Intersection ▁ of ▁ two ▁ arrays ▁ is ▁ : ▁ " ) ; printIntersection ( arr1 , arr2 ) ; } }


"Find Union and Intersection of two unsorted arrays | Java program to find union and intersection using similar Hashing Technique without using any predefined Java Collections Time Complexity best case & avg case = O ( m + n ) Worst case = O ( nlogn ) package com . arrays . math ; ; Prints intersection of arr1 [ 0. . n1 - 1 ] and arr2 [ 0. . n2 - 1 ] ; Iterate first array ; Iterate second array ; Prints union of arr1 [ 0. . n1 - 1 ] and arr2 [ 0. . n2 - 1 ] ; placeZeroes function ; Function to itreate array ; placeValue function ; Hashing collision happened increment position and do recursive call ; Driver code"
How can the above be solved in Java?

public class UnsortedIntersectionUnion { public void findPosition ( int a [ ] , int b [ ] ) { int v = ( a . length + b . length ) ; int ans [ ] = new int [ v ] ; int zero1 = 0 ; int zero2 = 0 ; System . out . print ( " Intersection ▁ : ▁ " ) ; for ( int i = 0 ; i < a . length ; i ++ ) zero1 = iterateArray ( a , v , ans , i ) ; for ( int j = 0 ; j < b . length ; j ++ ) zero2 = iterateArray ( b , v , ans , j ) ; int zero = zero1 + zero2 ; placeZeros ( v , ans , zero ) ; printUnion ( v , ans , zero ) ; } private void printUnion ( int v , int [ ] ans , int zero ) { int zero1 = 0 ; System . out . print ( " Union : "); for ( int i = 0 ; i < v ; i ++ ) { if ( ( zero == 0 && ans [ i ] == 0 ) || ( ans [ i ] == 0 && zero1 > 0 ) ) continue ; if ( ans [ i ] == 0 ) zero1 ++ ; System . out . print ( ans [ i ] + " , " ) ; } } private void placeZeros ( int v , int [ ] ans , int zero ) { if ( zero == 2 ) { System . out . println ( "0" ) ; int d [ ] = { 0 } ; placeValue ( d , ans , 0 , 0 , v ) ; } if ( zero == 1 ) { int d [ ] = { 0 } ; placeValue ( d , ans , 0 , 0 , v ) ; } } private int iterateArray ( int [ ] a , int v , int [ ] ans , int i ) { if ( a [ i ] != 0 ) { int p = a [ i ] % v ; placeValue ( a , ans , i , p , v ) ; } else return 1 ; return 0 ; } private void placeValue ( int [ ] a , int [ ] ans , int i , int p , int v ) { p = p % v ; if ( ans [ p ] == 0 ) ans [ p ] = a [ i ] ; else { if ( ans [ p ] == a [ i ] ) System . out . print ( a [ i ] + " , " ) ; else { p = p + 1 ; placeValue ( a , ans , i , p , v ) ; } } } public static void main ( String args [ ] ) { int a [ ] = { 7 , 1 , 5 , 2 , 3 , 6 } ; int b [ ] = { 3 , 8 , 6 , 20 , 7 } ; UnsortedIntersectionUnion uiu = new UnsortedIntersectionUnion ( ) ; uiu . findPosition ( a , b ) ; } }


"Find Unique ID and Domain Name of a Website from a string | Java program for the above approach ; Function to check if a character is alphabet or not ; Function to check if a character is a numeric or not ; Function to find ID and Domain name from a given String ; Stores ID and the domain names ; Stores the words of String S ; Stores the temporary word ; Traverse the String S ; If the current character is space ; Push the curr in words ; Update the curr ; Otherwise ; If curr is not empty ; If length of ss is 10 ; Traverse the String ss ; If j is in the range [ 5 , 9 ) ; If current character is not numeric ; Mark flag 1 ; Otherwise ; If current character is not alphabet ; Mark flag 1 ; If flag is false ; Assign ss to ID ; If subString formed by the first 3 character is " www " and last 3 character is " moc " ; Update the domain name ; Print ID and Domain ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static boolean ischar ( char x ) { if ( ( x >= ' A ' && x <= ' Z ' ) || ( x >= ' a ' && x <= ' z ' ) ) { return true ; } return false ; } static boolean isnum ( char x ) { if ( x >= '0' && x <= '9' ) return true ; return false ; } static void findIdandDomain ( String S , int N ) { String ID = " " , Domain = " " ; Vector < String > words = new Vector < String > ( ) ; String curr = " " ; for ( int i = 0 ; i < N ; i ++ ) { if ( S . charAt ( i ) == ' ▁ ' ) { words . add ( curr ) ; curr = " " ; } else { if ( S . charAt ( i ) == ' . ' ) { if ( i + 1 == N || ( i + 1 < N && S . charAt ( i + 1 ) == ' ▁ ' ) ) continue ; } curr += S . charAt ( i ) ; } } if ( curr . length ( ) > 0 ) words . add ( curr ) ; for ( String ss : words ) { if ( ss . length ( ) == 10 ) { boolean flag = false ; for ( int j = 0 ; j <= 9 ; j ++ ) { if ( j >= 5 && j < 9 ) { if ( isnum ( ss . charAt ( j ) ) == false ) flag = true ; } else { if ( ischar ( ss . charAt ( j ) ) == false ) flag = true ; } } if ( ! flag ) { ID = ss ; } } if ( ss . length ( ) > 2 && ss . substring ( 0 , 3 ) . equals ( " www " ) && ss . substring ( ss . length ( ) - 3 ) . equals ( " com " ) ) { Domain = ss . substring ( 4 , ss . length ( ) ) ; } } System . out . print ( " ID ▁ = ▁ " + ID + "
"); System . out . print ( " Domain ▁ = ▁ " + Domain ) ; } public static void main ( String [ ] args ) { String S = " We ▁ thank ▁ ABCDE1234F ▁ for ▁ visiting ▁ " + " us ▁ and ▁ buying ▁ products ▁ item ▁ AMZrr @ ! k . ▁ " + " For ▁ more ▁ offers , ▁ visit ▁ us ▁ at ▁ www . amazon . com " ; int N = S . length ( ) ; findIdandDomain ( S , N ) ; } }


"Find Unique pair in an array with pairs of numbers | Java program to find a unique pair in an array of pairs . ; XOR each element and get XOR of two unique elements ( ans ) ; Get a set bit of XOR ( We get the rightmost set bit ) ; Now divide elements in two sets by comparing rightmost set bit of XOR with bit at same position in each element . Initialize missing numbers ; XOR of first set in arr [ ] ; XOR of second set in arr [ ] ; Driver code"
How can the above be solved in Java?

class GFG { static void findUniquePair ( int [ ] arr , int n ) { int XOR = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) XOR = XOR ^ arr [ i ] ; int set_bit_no = XOR & ~ ( XOR - 1 ) ; int x = 0 , y = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( arr [ i ] & set_bit_no ) > 0 ) x = x ^ arr [ i ] ; else y = y ^ arr [ i ] ; } System . out . println ( " The ▁ unique ▁ pair ▁ is ▁ ( " + x + " , " + y + " ) " ) ; } public static void main ( String [ ] args ) { int [ ] a = { 6 , 1 , 3 , 5 , 1 , 3 , 7 , 6 } ; int n = a . length ; findUniquePair ( a , n ) ; } }


"Find X and Y intercepts of a line passing through the given points | Java implementation of the approach ; Function to find the X and Y intercepts of the line passing through the given points ; if line is parallel to y axis ; x - intercept will be p [ 0 ] ; y - intercept will be infinity ; if line is parallel to x axis ; x - intercept will be infinity ; y - intercept will be p [ 1 ] ; Slope of the line ; y = mx + c in where c is unknown Use any of the given point to find c ; For finding the x - intercept put y = 0 ; For finding the y - intercept put x = 0 ; Driver code"
How can the above be solved in Java?

class GFG { static void getXandYintercept ( int P [ ] , int Q [ ] ) { int a = P [ 1 ] - Q [ 1 ] ; int b = P [ 0 ] - Q [ 0 ] ; if ( b == 0 ) { System . out . println ( P [ 0 ] ) ; System . out . println ( " infinity " ) ; return ; } if ( a == 0 ) { System . out . println ( " infinity " ) ; System . out . println ( P [ 1 ] ) ; return ; } double m = a / ( b * 1.0 ) ; int x = P [ 0 ] ; int y = P [ 1 ] ; double c = y - m * x ; y = 0 ; double r = ( y - c ) / ( m * 1.0 ) ; System . out . println ( r ) ; x = 0 ; y = ( int ) ( m * x + c ) ; System . out . print ( c ) ; } public static void main ( String [ ] args ) { int p1 [ ] = { 5 , 2 } ; int p2 [ ] = { 2 , 7 } ; getXandYintercept ( p1 , p2 ) ; } }


"Find XOR of all elements in an Array | Java program to find the XOR of all elements in the array ; Function to find the XOR of all elements in the array ; Resultant variable ; Iterating through every element in the array ; Find XOR with the result ; Return the XOR ; Driver Code ; Function call"
How can the above be solved in Java?

class GFG { static int xorOfArray ( int arr [ ] , int n ) { int xor_arr = 0 ; for ( int i = 0 ; i < n ; i ++ ) { xor_arr = xor_arr ^ arr [ i ] ; } return xor_arr ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 9 , 12 , 13 , 15 } ; int n = arr . length ; System . out . println ( xorOfArray ( arr , n ) ) ; } }


"Find XOR of numbers from the range [ L , R ] | Java implementation of the approach ; Function to return the XOR of elements from the range [ 1 , n ] ; If n is a multiple of 4 ; If n % 4 gives remainder 1 ; If n % 4 gives remainder 2 ; If n % 4 gives remainder 3 ; Function to return the XOR of elements from the range [ l , r ] ; Driver code"
How can the above be solved in Java?

class GFG { static int findXOR ( int n ) { int mod = n % 4 ; if ( mod == 0 ) return n ; else if ( mod == 1 ) return 1 ; else if ( mod == 2 ) return n + 1 ; else if ( mod == 3 ) return 0 ; return 0 ; } static int findXOR ( int l , int r ) { return ( findXOR ( l - 1 ) ^ findXOR ( r ) ) ; } public static void main ( String [ ] args ) { int l = 4 , r = 8 ; System . out . println ( findXOR ( l , r ) ) ; } }


"Find XOR of two number without using XOR operator | Java program to find XOR without using ^ ; Returns XOR of x and y ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int myXOR ( int x , int y ) { return ( x y ) & ( ~ x ~ y ) ; } public static void main ( String [ ] args ) { int x = 3 , y = 5 ; System . out . println ( " XOR ▁ is ▁ " + ( myXOR ( x , y ) ) ) ; } }


import java . io . * ; class GFG { static int myXOR ( int x , int y ) { return ( x & ( ~ y ) ) | ( ( ~ x ) & y ) ; } public static void main ( String [ ] args ) { int x = 3 , y = 5 ; System . out . println ( " XOR ▁ is ▁ " + ( myXOR ( x , y ) ) ) ; } }


"Find XOR of two number without using XOR operator | Java program to find XOR without using ^ ; Returns XOR of x and y ; Initialize result ; Assuming 32 - bit Integer ; Find current bits in x and y ; If both are 1 then 0 else xor is same as OR ; Update result ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int myXOR ( int x , int y ) { int res = 0 ; for ( int i = 31 ; i >= 0 ; i -- ) { int b1 = ( ( x & ( 1 << i ) ) == 0 ) ? 0 : 1 ; int b2 = ( ( y & ( 1 << i ) ) == 0 ) ? 0 : 1 ; int xoredBit = ( ( b1 & b2 ) != 0 ) ? 0 : ( b1 b2 ) ; res <<= 1 ; res |= xoredBit ; } return res ; } public static void main ( String [ ] args ) { int x = 3 , y = 5 ; System . out . println ( " XOR ▁ is ▁ " + myXOR ( x , y ) ) ; } }


"Find XOR sum of Bitwise AND of all pairs from given two Arrays | Java algorithm for the above approach ; Function to calculate the XOR sum of all ANDS of all pairs on A [ ] and B [ ] ; Variable to store xor sums of first array and second array respectively . ; Xor sum of first array ; Xor sum of second array ; Required answer ; Driver code ; Input ; Function call"
How can the above be solved in Java?

import java . io . * ; class GFG { static int XorSum ( int A [ ] , int B [ ] , int N , int M ) { int ans1 = 0 , ans2 = 0 ; for ( int i = 0 ; i < N ; i ++ ) ans1 = ans1 ^ A [ i ] ; for ( int i = 0 ; i < M ; i ++ ) ans2 = ans2 ^ B [ i ] ; return ( ans1 & ans2 ) ; } public static void main ( String [ ] args ) { int A [ ] = { 3 , 5 } ; int B [ ] = { 2 , 3 } ; int N = A . length ; int M = B . length ; System . out . print ( XorSum ( A , B , N , M ) ) ; } }


"Find XOR sum of Bitwise AND of all pairs from given two Arrays | Java program for the above approach ; Function to calculate the XOR sum of all ANDS of all pairs on A [ ] and B [ ] ; variable to store anshu ; when there has been no AND of pairs before this ; Driver code ; Input ; Function call"
How can the above be solved in Java?

import java . io . * ; class GFG { public static int XorSum ( int A [ ] , int B [ ] , int N , int M ) { int ans = - 1 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( ans == - 1 ) ans = ( A [ i ] & B [ j ] ) ; else ans ^= ( A [ i ] & B [ j ] ) ; } } return ans ; } public static void main ( String [ ] args ) { int A [ ] = { 3 , 5 } ; int B [ ] = { 2 , 3 } ; int N = A . length ; int M = B . length ; System . out . println ( XorSum ( A , B , N , M ) ) ; } }


"Find a K | Java program to implement the above approach ; Utility function to check if subarray of size K exits whose XOR of elements equal to XOR ofremaning array elements ; Find XOR of whole array ; Find XOR of first K elements ; Adding XOR of next element ; Removing XOR of previous element ; Check if XOR of current subarray matches with the XOR of remaining elements or not ; Function to check if subarray of size K exits whose XOR of elements equal to XOR ofremaning array elements ; Driver Code ; Given array ; Size of the array ; Given K ; Function Call"
How can the above be solved in Java?

 import java . util . * ; class GFG { static boolean isSubarrayExistUtil ( int arr [ ] , int K , int N ) { int totalXOR = 0 ; int SubarrayXOR = 0 ; for ( int i = 0 ; i < N ; i ++ ) totalXOR ^= arr [ i ] ; for ( int i = 0 ; i < K ; i ++ ) SubarrayXOR ^= arr [ i ] ; if ( SubarrayXOR == ( totalXOR ^ SubarrayXOR ) ) return true ; for ( int i = K ; i < N ; i ++ ) { SubarrayXOR ^= arr [ i ] ; SubarrayXOR ^= arr [ i - 1 ] ; if ( SubarrayXOR == ( totalXOR ^ SubarrayXOR ) ) return true ; } return false ; } static void isSubarrayExist ( int arr [ ] , int K , int N ) { if ( isSubarrayExistUtil ( arr , K , N ) ) System . out . print ( "YES
"); else System . out . print ( "NO
"); } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 3 , 5 , 7 , 7 , 3 , 4 } ; int N = arr . length ; int K = 5 ; isSubarrayExist ( arr , K , N ) ; } }


"Find a N | JAVA program to find N digit number such that it is not divisible by any of its digits ; Function that print the answer ; if n == 1 then it is not possible ; loop to n - 1 times ; print 4 as last digit of the number ; Driver code ; Function call"
How can the above be solved in Java?

 class GFG { static void findTheNumber ( int n ) { if ( n == 1 ) { System . out . print ( " Impossible " + "
"); return ; } for ( int i = 0 ; i < n - 1 ; i ++ ) { System . out . print ( "5" ) ; } System . out . print ( "4" ) ; } public static void main ( String [ ] args ) { int n = 12 ; findTheNumber ( n ) ; } }


"Find a Square Matrix such that sum of elements in every row and column is K | Java implementation of the approach ; Function to print the required matrix ; Print k for the left diagonal elements ; Print 0 for the rest ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void printMatrix ( int n , int k ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( i == j ) System . out . print ( k + " ▁ " ) ; else System . out . print ( "0 ▁ " ) ; } System . out . print ( "
"); } } public static void main ( String [ ] args ) { int n = 3 , k = 7 ; printMatrix ( n , k ) ; } }


"Find a Symmetric matrix of order N that contain integers from 0 to N | Java implementation of the approach ; Function to generate the required matrix ; Form cyclic array of elements 1 to n - 1 ; Store initial array into final array ; Fill the last row and column with 0 's ; Swap 0 and the number present at the current indexed row ; Also make changes in the last row with the number we swapped ; Print the final array ; Driver code"
How can the above be solved in Java?

class GFG { static void solve ( long n ) { long initial_array [ ] [ ] = new long [ ( int ) n - 1 ] [ ( int ) n - 1 ] , final_array [ ] [ ] = new long [ ( int ) n ] [ ( int ) n ] ; for ( long i = 0 ; i < n - 1 ; ++ i ) initial_array [ 0 ] [ ( int ) i ] = i + 1 ; for ( long i = 1 ; i < n - 1 ; ++ i ) for ( long j = 0 ; j < n - 1 ; ++ j ) initial_array [ ( int ) i ] [ ( int ) j ] = initial_array [ ( int ) i - 1 ] [ ( int ) ( ( int ) j + 1 ) % ( ( int ) n - 1 ) ] ; for ( long i = 0 ; i < n - 1 ; ++ i ) for ( long j = 0 ; j < n - 1 ; ++ j ) final_array [ ( int ) i ] [ ( int ) j ] = initial_array [ ( int ) i ] [ ( int ) j ] ; for ( long i = 0 ; i < n ; ++ i ) final_array [ ( int ) i ] [ ( int ) n - 1 ] = final_array [ ( int ) n - 1 ] [ ( int ) i ] = 0 ; for ( long i = 0 ; i < n ; ++ i ) { long t0 = final_array [ ( int ) i ] [ ( int ) i ] ; long t1 = final_array [ ( int ) i ] [ ( int ) n - 1 ] ; long s = final_array [ ( int ) i ] [ ( int ) i ] ; final_array [ ( int ) i ] [ ( int ) i ] = final_array [ ( int ) i ] [ ( int ) n - 1 ] ; final_array [ ( int ) i ] [ ( int ) n - 1 ] = s ; final_array [ ( int ) n - 1 ] [ ( int ) i ] = t0 ; } for ( long i = 0 ; i < n ; ++ i ) { for ( long j = 0 ; j < n ; ++ j ) System . out . print ( final_array [ ( int ) i ] [ ( int ) j ] + " ▁ " ) ; System . out . println ( ) ; } } public static void main ( String args [ ] ) { long n = 5 ; solve ( n ) ; } }


"Find a common element in all rows of a given row | A Java program to find a common element in all rows of a row wise sorted array ; Specify number of rows and columns ; Returns common element in all rows of mat [ M ] [ N ] . If there is no common element , then - 1 is returned ; An array to store indexes of current last column ; To store index of row whose current last element is minimum ; Initialize current last element of all rows ; Initialize min_row as first row ; Keep finding min_row in current last column , till either all elements of last column become same or we hit first column . ; Find minimum in current last column ; eq_count is count of elements equal to minimum in current last column . ; Traverse current last column elements again to update it ; Decrease last column index of a row whose value is more than minimum . ; Reduce last column index by 1 ; If equal count becomes M , return the value ; Driver code"
How can the above be solved in Java?

class GFG { static final int M = 4 ; static final int N = 5 ; static int findCommon ( int mat [ ] [ ] ) { int column [ ] = new int [ M ] ; int min_row ; int i ; for ( i = 0 ; i < M ; i ++ ) column [ i ] = N - 1 ; min_row = 0 ; while ( column [ min_row ] >= 0 ) { for ( i = 0 ; i < M ; i ++ ) { if ( mat [ i ] [ column [ i ] ] < mat [ min_row ] [ column [ min_row ] ] ) min_row = i ; } int eq_count = 0 ; for ( i = 0 ; i < M ; i ++ ) { if ( mat [ i ] [ column [ i ] ] > mat [ min_row ] [ column [ min_row ] ] ) { if ( column [ i ] == 0 ) return - 1 ; column [ i ] -= 1 ; } else eq_count ++ ; } if ( eq_count == M ) return mat [ min_row ] [ column [ min_row ] ] ; } return - 1 ; } public static void main ( String [ ] args ) { int mat [ ] [ ] = { { 1 , 2 , 3 , 4 , 5 } , { 2 , 4 , 5 , 8 , 10 } , { 3 , 5 , 7 , 9 , 11 } , { 1 , 3 , 5 , 7 , 9 } } ; int result = findCommon ( mat ) ; if ( result == - 1 ) System . out . print ( " No ▁ common ▁ element " ) ; else System . out . print ( " Common ▁ element ▁ is ▁ " + result ) ; } }


"Find a common element in all rows of a given row | Java implementation of the approach ; Specify number of rows and columns ; Returns common element in all rows of mat [ M ] [ N ] . If there is no common element , then - 1 is returned ; A hash map to store count of elements ; Increment the count of first element of the row ; Starting from the second element of the current row ; If current element is different from the previous element i . e . it is appearing for the first time in the current row ; Find element having count equal to number of rows ; No such element found ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int M = 4 ; static int N = 5 ; static int findCommon ( int mat [ ] [ ] ) { HashMap < Integer , Integer > cnt = new HashMap < Integer , Integer > ( ) ; int i , j ; for ( i = 0 ; i < M ; i ++ ) { if ( cnt . containsKey ( mat [ i ] [ 0 ] ) ) { cnt . put ( mat [ i ] [ 0 ] , cnt . get ( mat [ i ] [ 0 ] ) + 1 ) ; } else { cnt . put ( mat [ i ] [ 0 ] , 1 ) ; } for ( j = 1 ; j < N ; j ++ ) { if ( mat [ i ] [ j ] != mat [ i ] [ j - 1 ] ) if ( cnt . containsKey ( mat [ i ] [ j ] ) ) { cnt . put ( mat [ i ] [ j ] , cnt . get ( mat [ i ] [ j ] ) + 1 ) ; } else { cnt . put ( mat [ i ] [ j ] , 1 ) ; } } } for ( Map . Entry < Integer , Integer > ele : cnt . entrySet ( ) ) { if ( ele . getValue ( ) == M ) return ele . getKey ( ) ; } return - 1 ; } public static void main ( String [ ] args ) { int mat [ ] [ ] = { { 1 , 2 , 3 , 4 , 5 } , { 2 , 4 , 5 , 8 , 10 } , { 3 , 5 , 7 , 9 , 11 } , { 1 , 3 , 5 , 7 , 9 } } ; int result = findCommon ( mat ) ; if ( result == - 1 ) System . out . println ( " No ▁ common ▁ element " ) ; else System . out . println ( " Common ▁ element ▁ is ▁ " + result ) ; } }


"Find a distinct pair ( x , y ) in given range such that x divides y | Java implementation of the approach ; Driver code"
How can the above be solved in Java?

class GFG { static void findpair ( int l , int r ) { int c = 0 ; for ( int i = l ; i <= r ; i ++ ) { for ( int j = i + 1 ; j <= r ; j ++ ) { if ( j % i == 0 && j != i ) { System . out . println ( i + " , ▁ " + j ) ; c = 1 ; break ; } } if ( c == 1 ) break ; } } public static void main ( String args [ ] ) { int l = 1 , r = 10 ; findpair ( l , r ) ; } }


"Find a distinct pair ( x , y ) in given range such that x divides y | Java implementation of the approach ; Function to return the possible pair ; ans1 , ans2 store value of x and y respectively ; Driver Code"
How can the above be solved in Java?

class GFG { static void findpair ( int l , int r ) { int ans1 = l ; int ans2 = 2 * l ; System . out . println ( ans1 + " , ▁ " + ans2 ) ; } public static void main ( String args [ ] ) { int l = 1 , r = 10 ; findpair ( l , r ) ; } }


"Find a number M < N such that difference between their XOR and AND is maximum | Java program for the above approach ; Function to flip all bits of N ; Finding most significant bit of N ; Calculating required number ; Return the answer ; Driver Code ; Given number ; Function call"
How can the above be solved in Java?

class GFG { static int findM ( int N ) { int M = 0 ; int MSB = ( int ) Math . log ( N ) ; for ( int i = 0 ; i < MSB ; i ++ ) { if ( ( N & ( 1 << i ) ) == 0 ) M += ( 1 << i ) ; } return M ; } public static void main ( String [ ] args ) { int N = 6 ; System . out . print ( findM ( N ) ) ; } }


"Find a number M < N such that difference between their XOR and AND is maximum | Java program for the above approach ; Function to return M < N such that N ^ M - N & M is maximum ; Initialize variables ; Iterate for all values < N ; Find the difference between Bitwise XOR and AND ; Check if new difference is greater than previous maximum ; Update variables ; Return the answer ; Driver Code ; Given Number N ; Function Call"
How can the above be solved in Java?

class GFG { static int getMaxDifference ( int N ) { int M = - 1 ; int maxDiff = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int diff = ( N ^ i ) - ( N & i ) ; if ( diff >= maxDiff ) { maxDiff = diff ; M = i ; } } return M ; } public static void main ( String [ ] args ) { int N = 6 ; System . out . print ( getMaxDifference ( N ) ) ; } }


"Find a number containing N | Java implementation of above approach ; Function to return the String generated by appending "10" n - 1 times ; Initialising String as empty ; Function to return the decimal equivalent of the given binary String ; Initializing base value to 1 i . e 2 ^ 0 ; Function that calls the constructString and binarytodecimal and returns the answer ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static String constructString ( int n ) { String s = " " ; for ( int i = 0 ; i < n ; i ++ ) { s += "10" ; } return s ; } static int binaryToDecimal ( String n ) { String num = n ; int dec_value = 0 ; int base = 1 ; int len = num . length ( ) ; for ( int i = len - 1 ; i >= 0 ; i -- ) { if ( num . charAt ( i ) == '1' ) dec_value += base ; base = base * 2 ; } return dec_value ; } static int findNumber ( int n ) { String s = constructString ( n - 1 ) ; int num = binaryToDecimal ( s ) ; return num ; } public static void main ( String [ ] args ) { int n = 4 ; System . out . println ( findNumber ( n ) ) ; } }


"Find a number containing N | Java implementation of the approach ; Function to compute number using our deduced formula ; Initialize num to n - 1 ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int findNumber ( int n ) { int num = n - 1 ; num = 2 * ( int ) Math . pow ( 4 , num ) ; num = ( int ) Math . floor ( num / 3.0 ) ; return num ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . println ( findNumber ( n ) ) ; } }


"Find a number in minimum steps | Java program to Find a number in minimum steps ; Steps sequence ; Current sum ; Sign of the number ; Basic steps required to get sum >= required value . ; If we have reached ahead to destination . ; If the last step was an odd number , then it has following mechanism for negating a particular number and decreasing the sum to required number Also note that it may require 1 more step in order to reach the sum . ; If the current time instance is even and sum is odd than it takes 2 more steps and few negations in previous elements to reach there . ; Driver Program"
How can the above be solved in Java?

import java . util . * ; class GFG { static Vector < Integer > find ( int n ) { Vector < Integer > ans = new Vector < > ( ) ; int sum = 0 ; int i = 1 ; int sign = ( n >= 0 ? 1 : - 1 ) ; n = Math . abs ( n ) ; for ( ; sum < n ; ) { ans . add ( sign * i ) ; sum += i ; i ++ ; } if ( sum > sign * n ) { if ( i % 2 != 0 ) { sum -= n ; if ( sum % 2 != 0 ) { ans . add ( sign * i ) ; sum += i ; i ++ ; } int a = ans . get ( ( sum / 2 ) - 1 ) ; ans . remove ( ( sum / 2 ) - 1 ) ; ans . add ( ( ( sum / 2 ) - 1 ) , a * ( - 1 ) ) ; } else { sum -= n ; if ( sum % 2 != 0 ) { sum -- ; ans . add ( sign * i ) ; ans . add ( sign * - 1 * ( i + 1 ) ) ; } ans . add ( ( sum / 2 ) - 1 , ans . get ( ( sum / 2 ) - 1 ) * - 1 ) ; } } return ans ; } public static void main ( String [ ] args ) { int n = 20 ; if ( n == 0 ) System . out . print ( "Minimum number of Steps: 0 Step sequence : 0 "); else { Vector < Integer > a = find ( n ) ; System . out . print ( " Minimum ▁ number ▁ of ▁ Steps : ▁ " + a . size ( ) + " Step sequence : "); for ( int i : a ) System . out . print ( i + " ▁ " ) ; } } }


"Find a number in minimum steps | Java program to find a number in minimum steps ; To represent data of a node in tree ; Prints level of node n ; Create a queue and insert root ; Do level order traversal ; Remove a node from queue ; To astatic void infinite loop ; Check if dequeued number is same as n ; Insert children of dequeued node to queue ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static final int InF = 99999 ; static class number { int no ; int level ; number ( ) { } number ( int n , int l ) { this . no = n ; this . level = l ; } } ; static void findnthnumber ( int n ) { Queue < number > q = new LinkedList < > ( ) ; number r = new number ( 0 , 1 ) ; q . add ( r ) ; while ( ! q . isEmpty ( ) ) { number temp = q . peek ( ) ; q . remove ( ) ; if ( temp . no >= InF temp . no <= - InF ) break ; if ( temp . no == n ) { System . out . print ( " Found ▁ number ▁ n ▁ at ▁ level ▁ " + ( temp . level - 1 ) ) ; break ; } q . add ( new number ( temp . no + temp . level , temp . level + 1 ) ) ; q . add ( new number ( temp . no - temp . level , temp . level + 1 ) ) ; } } public static void main ( String [ ] args ) { findnthnumber ( 13 ) ; } }


"Find a number that divides maximum array elements | Java program to find a number that divides maximum array elements ; stores smallest prime factor for every number ; Calculating SPF ( Smallest Prime Factor ) for every number till MAXN . Time Complexity : O ( nloglogn ) ; marking smallest prime factor for every number to be itself . ; separately marking spf for every even number as 2 ; checking if i is prime ; marking SPF for all numbers divisible by i ; marking spf [ j ] if it is not previously marked ; A O ( log n ) function returning primefactorization by dividing by smallest prime factor at every step ; Function to find a number that divides maximum array elements ; precalculating Smallest Prime Factor ; Hash to store frequency of each divisors ; Traverse the array and get spf of each element ; calling getFactorization function ; Returns Set view ; Driver program"
How can the above be solved in Java?

import java . util . * ; class Solution { static final int MAXN = 100001 ; static int spf [ ] = new int [ MAXN ] ; static void sieve ( ) { spf [ 1 ] = 1 ; for ( int i = 2 ; i < MAXN ; i ++ ) spf [ i ] = i ; for ( int i = 4 ; i < MAXN ; i += 2 ) spf [ i ] = 2 ; for ( int i = 3 ; i * i < MAXN ; i ++ ) { if ( spf [ i ] == i ) { for ( int j = i * i ; j < MAXN ; j += i ) if ( spf [ j ] == j ) spf [ j ] = i ; } } } static Vector < Integer > getFactorization ( int x ) { Vector < Integer > ret = new Vector < Integer > ( ) ; while ( x != 1 ) { int temp = spf [ x ] ; ret . add ( temp ) ; while ( x % temp == 0 ) x = x / temp ; } return ret ; } static int maxElement ( int A [ ] , int n ) { sieve ( ) ; Map < Integer , Integer > m = new HashMap < Integer , Integer > ( ) ; for ( int j = 0 ; j < n ; ++ j ) { Vector < Integer > p = getFactorization ( A [ j ] ) ; for ( int i = 0 ; i < p . size ( ) ; i ++ ) m . put ( p . get ( i ) , m . get ( p . get ( i ) ) == null ? 0 : m . get ( p . get ( i ) ) + 1 ) ; } int cnt = 0 , ans = 10000000 ; Set < Map . Entry < Integer , Integer > > st = m . entrySet ( ) ; for ( Map . Entry < Integer , Integer > me : st ) { if ( me . getValue ( ) >= cnt ) { cnt = me . getValue ( ) ; if ( ans > me . getKey ( ) ) ans = me . getKey ( ) ; else ans = ans ; } } return ans ; } public static void main ( String args [ ] ) { int A [ ] = { 2 , 5 , 10 } ; int n = A . length ; System . out . print ( maxElement ( A , n ) ) ; } }


"Find a number which give minimum sum when XOR with every number of array of integers | Java implementation of above approach ; Function to find an integer X such that the sum of all the array elements after getting XORed with X is minimum ; Finding Maximum element of array ; Find Maximum number of bits required in the binary representation of maximum number so log2 is calculated ; Running loop from p times which is the number of bits required to represent all the elements of the array ; If the bits in same position are set then count ; If count becomes greater than half of size of array then we need to make that bit '0' by setting X bit to '1' ; Again using shift operation to calculate the required number ; Calculate minimized sum ; Print solution ; Driver Code"
How can the above be solved in Java?

import java . lang . Math ; import java . util . * ; class GFG { public static void findX ( int [ ] a , int n ) { Collections . sort ( Arrays . asList ( a ) , null ) ; int itr = a [ n - 1 ] ; int p = ( int ) ( Math . log ( itr ) / Math . log ( 2 ) ) + 1 ; int x = 0 ; for ( int i = 0 ; i < p ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( a [ j ] & ( 1 << i ) ) != 0 ) count ++ ; } if ( count > ( n / 2 ) ) { x += 1 << i ; } } long sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += ( x ^ a [ i ] ) ; System . out . println ( " X ▁ = ▁ " + x + " , ▁ Sum ▁ = ▁ " + sum ) ; } public static void main ( String [ ] args ) { int [ ] a = { 2 , 3 , 4 , 5 , 6 } ; int n = a . length ; findX ( a , n ) ; } }


"Find a number x such that sum of x and its digits is equal to given n . | Java program to find x such that x + digSum ( x ) is equal to n . ; utility function for digit sum ; function for finding x ; iterate from 1 to n . For every no . check if its digit sum with it is equal to n . ; if no such i found return - 1 ; Driver code"
How can the above be solved in Java?

class GFG { static int digSum ( int n ) { int sum = 0 , rem = 0 ; while ( n > 0 ) { rem = n % 10 ; sum += rem ; n /= 10 ; } return sum ; } static int findX ( int n ) { for ( int i = 0 ; i <= n ; i ++ ) if ( i + digSum ( i ) == n ) return i ; return - 1 ; } public static void main ( String [ ] args ) { int n = 43 ; System . out . println ( " x ▁ = ▁ " + findX ( n ) ) ; } }


"Find a pair ( n , r ) in an integer array such that value of nPr is maximum | Java implementation of the approach ; Function to print the pair ( n , r ) such that nPr is maximum possible ; There should be atleast 2 elements ; Findex the largest 2 elements ; Driver code"
How can the above be solved in Java?

class GFG { static void findPair ( int arr [ ] , int n ) { if ( n < 2 ) { System . out . print ( " - 1" ) ; return ; } int i , first , second ; first = second = - 1 ; for ( i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > first ) { second = first ; first = arr [ i ] ; } else if ( arr [ i ] > second ) { second = arr [ i ] ; } } System . out . println ( " n ▁ = ▁ " + first + " ▁ and ▁ r ▁ = ▁ " + second ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 0 , 2 , 3 , 4 , 1 , 6 , 8 , 9 } ; int n = arr . length ; findPair ( arr , n ) ; } }


"Find a pair from the given array with maximum nCr value | Java implementation of the approach ; Function to print the pair that gives maximum nCr ; This gives the value of N in nCr ; Case 1 : When N is odd ; Case 2 : When N is even ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void printMaxValPair ( Vector < Long > v , int n ) { Collections . sort ( v ) ; long N = v . get ( ( int ) n - 1 ) ; if ( N % 2 == 1 ) { long first_maxima = N / 2 ; long second_maxima = first_maxima + 1 ; long ans1 = ( long ) 3e18 , ans2 = ( long ) 3e18 ; long from_left = - 1 , from_right = - 1 ; long from = - 1 ; for ( long i = 0 ; i < n ; ++ i ) { if ( v . get ( ( int ) i ) > first_maxima ) { from = i ; break ; } else { long diff = first_maxima - v . get ( ( int ) i ) ; if ( diff < ans1 ) { ans1 = diff ; from_left = v . get ( ( int ) i ) ; } } } from_right = v . get ( ( int ) from ) ; long diff1 = first_maxima - from_left ; long diff2 = from_right - second_maxima ; if ( diff1 < diff2 ) System . out . println ( N + " ▁ " + from_left ) ; else System . out . println ( N + " ▁ " + from_right ) ; } else { long maxima = N / 2 ; long ans1 = ( int ) 3e18 ; long R = - 1 ; for ( long i = 0 ; i < n - 1 ; ++ i ) { long diff = Math . abs ( v . get ( ( int ) i ) - maxima ) ; if ( diff < ans1 ) { ans1 = diff ; R = v . get ( ( int ) i ) ; } } System . out . println ( N + " ▁ " + R ) ; } } public static void main ( String args [ ] ) { long arr [ ] = { 1 , 1 , 2 , 3 , 6 , 1 } ; Vector < Long > v = new Vector < Long > ( ) ; for ( int i = 0 ; i < arr . length ; i ++ ) v . add ( arr [ i ] ) ; int n = v . size ( ) ; printMaxValPair ( v , n ) ; } }


"Find a pair in Array with second largest product | Java program for the above approach ; Function to find second largest product pair in arr [ 0. . n - 1 ] ; No pair exits ; Initialize max product pair ; Traverse through every possible pair and keep track of largest product ; If pair is largest ; Second largest ; If pair dose not largest but larger then second largest ; Print the pairs ; Driver Code ; Given array ; Function Call"
How can the above be solved in Java?

class GFG { static void maxProduct ( int arr [ ] , int N ) { if ( N < 3 ) { return ; } int a = arr [ 0 ] , b = arr [ 1 ] ; int c = 0 , d = 0 ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = i + 1 ; j < N - 1 ; j ++ ) { if ( arr [ i ] * arr [ j ] > a * b ) { c = a ; d = b ; a = arr [ i ] ; b = arr [ j ] ; } if ( arr [ i ] * arr [ j ] < a * b && arr [ i ] * arr [ j ] > c * d ) c = arr [ i ] ; d = arr [ j ] ; } System . out . println ( c + " ▁ " + d ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 2 , 67 , 45 , 160 , 78 } ; int N = arr . length ; maxProduct ( arr , N ) ; } }


"Find a pair in Array with second largest product | Java program for the above approach ; Function to find second largest product pair in arr [ 0. . n - 1 ] ; No pair exits ; Sort the array ; Initialize smallest element of the array ; Initialize largest element of the array ; Print second largest product pair ; Driver Code ; Given array ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void maxProduct ( int arr [ ] , int N ) { if ( N < 3 ) { return ; } Arrays . sort ( arr ) ; int smallest1 = arr [ 0 ] ; int smallest3 = arr [ 2 ] ; int largest1 = arr [ N - 1 ] ; int largest3 = arr [ N - 3 ] ; if ( smallest1 * smallest3 >= largest1 * largest3 ) { System . out . print ( smallest1 + " ▁ " + smallest3 ) ; } else { System . out . print ( largest1 + " ▁ " + largest3 ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 2 , 67 , 45 , 160 , 78 } ; int N = arr . length ; maxProduct ( arr , N ) ; } }


"Find a pair of intersecting ranges from a given array | Java program for the above approach ; Store ranges and their corresponding array indices ; Function to find a pair of intersecting ranges ; Stores ending point of every range ; Stores the maximum ending point obtained ; Iterate from 0 to N - 1 ; Starting point of the current range ; End point of the current range ; Push pairs into tup ; Sort the tup vector sort ( tup . begin ( ) , tup . end ( ) ) ; ; Iterate over the ranges ; If starting points are equal ; Print the indices of the intersecting ranges ; If no such pair of segments exist ; Driver Code ; Given N ; Given 2d ranges [ ] [ ] array ; Function call"
How can the above be solved in Java?

import java . util . ArrayList ; import java . util . Collections ; import java . util . Comparator ; class GFG { static ArrayList < int [ ] > tup = new ArrayList < > ( ) ; static void findIntersectingRange ( int N , int ranges [ ] [ ] ) { int curr ; int currPos ; for ( int i = 0 ; i < N ; i ++ ) { int x , y ; x = ranges [ i ] [ 0 ] ; y = ranges [ i ] [ 1 ] ; int [ ] arr = { x , y , i + 1 } ; tup . add ( arr ) ; } Collections . sort ( tup , new Comparator < int [ ] > ( ) { public int compare ( int [ ] a , int [ ] b ) { if ( a [ 0 ] == b [ 0 ] ) { if ( a [ 1 ] == b [ 1 ] ) { return a [ 2 ] - b [ 2 ] ; } else { return a [ 1 ] - b [ 1 ] ; } } return a [ 0 ] - b [ 0 ] ; } } ) ; curr = tup . get ( 0 ) [ 1 ] ; currPos = tup . get ( 0 ) [ 2 ] ; for ( int i = 1 ; i < N ; i ++ ) { int Q = tup . get ( i - 1 ) [ 0 ] ; int R = tup . get ( i ) [ 0 ] ; if ( Q == R ) { if ( tup . get ( i - 1 ) [ 1 ] < tup . get ( i ) [ 1 ] ) System . out . print ( tup . get ( i - 1 ) [ 2 ] + " ▁ " + tup . get ( i ) [ 2 ] ) ; else System . out . print ( tup . get ( i ) [ 2 ] + " ▁ " + tup . get ( i - 1 ) [ 2 ] ) ; return ; } int T = tup . get ( i ) [ 1 ] ; if ( T <= curr ) { System . out . print ( tup . get ( i ) [ 2 ] + " ▁ " + currPos ) ; return ; } else { curr = T ; currPos = tup . get ( i ) [ 2 ] ; } } System . out . print ( " - 1 ▁ - 1" ) ; } public static void main ( String [ ] args ) { int N = 5 ; int ranges [ ] [ ] = { { 1 , 5 } , { 2 , 10 } , { 3 , 10 } , { 2 , 2 } , { 2 , 15 } } ; findIntersectingRange ( N , ranges ) ; } }


"Find a pair of overlapping intervals from a given Set | Java program to implement the above approach ; Function to find a pair ( i , j ) such that i - th interval lies within the j - th interval ; Store interval and index of the interval in the form of { { l , r } , index } ; Traverse the array , arr [ ] [ ] ; Stores l - value of the interval ; Stores r - value of the interval ; Push current interval and index into tup ; Sort the vector based on l - value of the intervals ; Stores r - value of current interval ; Stores index of current interval ; Traverse the vector , tup [ ] ; Stores l - value of previous interval ; Stores l - value of current interval ; If Q and R are equal ; Print the index of interval ; Stores r - value of current interval ; If T is less than or equal to curr ; Update curr ; Update currPos ; If such intervals found ; Driver code ; Given l - value of segments ; Given r - value of segments ; Given size ; Function Call"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class pair { int l , r , index ; pair ( int l , int r , int index ) { this . l = l ; this . r = r ; this . index = index ; } } class GFG { static void findOverlapSegement ( int N , int [ ] a , int [ ] b ) { ArrayList < pair > tup = new ArrayList < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { int x , y ; x = a [ i ] ; y = b [ i ] ; tup . add ( new pair ( x , y , i ) ) ; } Collections . sort ( tup , ( aa , bb ) -> ( aa . l != bb . l ) ? aa . l - bb . l : aa . r - bb . r ) ; int curr = tup . get ( 0 ) . r ; int currPos = tup . get ( 0 ) . index ; for ( int i = 1 ; i < N ; i ++ ) { int Q = tup . get ( i - 1 ) . l ; int R = tup . get ( i ) . l ; if ( Q == R ) { if ( tup . get ( i - 1 ) . r < tup . get ( i ) . r ) System . out . print ( tup . get ( i - 1 ) . index + " ▁ " + tup . get ( i ) . index ) ; else System . out . print ( tup . get ( i ) . index + " ▁ " + tup . get ( i - 1 ) . index ) ; return ; } int T = tup . get ( i ) . r ; if ( T <= curr ) { System . out . print ( tup . get ( i ) . index + " ▁ " + currPos ) ; return ; } else { curr = T ; currPos = tup . get ( i ) . index ; } } System . out . print ( " - 1 ▁ - 1" ) ; } public static void main ( String [ ] args ) { int [ ] a = { 1 , 2 , 3 , 2 , 2 } ; int [ ] b = { 5 , 10 , 10 , 2 , 15 } ; int N = a . length ; findOverlapSegement ( N , a , b ) ; } }


"Find a pair with given sum in BST | JAVA program to find a pair with given sum using hashing ; 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 = null ; temp . right = null ; return temp ; } static Node insert ( Node root , int key ) { if ( root == null ) return NewNode ( key ) ; if ( key < root . data ) root . left = insert ( root . left , key ) ; else root . right = insert ( root . right , key ) ; return root ; } static boolean findpairUtil ( Node root , int sum , HashSet < Integer > set ) { if ( root == null ) return false ; if ( findpairUtil ( root . left , sum , set ) ) return true ; if ( set . contains ( sum - root . data ) ) { System . out . println ( " Pair ▁ is ▁ found ▁ ( " + ( sum - root . data ) + " , ▁ " + root . data + " ) " ) ; return true ; } else set . add ( root . data ) ; return findpairUtil ( root . right , sum , set ) ; } static void findPair ( Node root , int sum ) { HashSet < Integer > set = new HashSet < Integer > ( ) ; if ( ! findpairUtil ( root , sum , set ) ) System . out . print ( " Pairs ▁ do ▁ not ▁ exit " + "
"); } public static void main ( String [ ] args ) { Node root = null ; root = insert ( root , 15 ) ; root = insert ( root , 10 ) ; root = insert ( root , 20 ) ; root = insert ( root , 8 ) ; root = insert ( root , 12 ) ; root = insert ( root , 16 ) ; root = insert ( root , 25 ) ; root = insert ( root , 10 ) ; int sum = 33 ; findPair ( root , sum ) ; } }


"Find a pair with given sum in a Balanced BST | In a balanced binary search tree isPairPresent two element which sums to a given value time O ( n ) space O ( logn ) ; A BST node ; Stack type ; A utility function to create a stack of given size ; BASIC OPERATIONS OF STACK ; Returns true if a pair with target sum exists in BST , otherwise false ; Create two stacks . s1 is used for normal inorder traversal and s2 is used for reverse inorder traversal ; Note the sizes of stacks is MAX_SIZE , we can find the tree size and fix stack size as O ( Logn ) for balanced trees like AVL and Red Black tree . We have used MAX_SIZE to keep the code simple done1 , val1 and curr1 are used for normal inorder traversal using s1 done2 , val2 and curr2 are used for reverse inorder traversal using s2 ; The loop will break when we either find a pair or one of the two traversals is complete ; Find next node in normal Inorder traversal . See following post www . geeksforgeeks . org / inorder - tree - traversal - without - recursion / https : ; Find next node in REVERSE Inorder traversal . The only difference between above and below loop is , in below loop right subtree is traversed before left subtree ; If we find a pair , then print the pair and return . The first condition makes sure that two same values are not added ; If sum of current values is smaller , then move to next node in normal inorder traversal ; If sum of current values is greater , then move to next node in reverse inorder traversal ; If any of the inorder traversals is over , then there is no pair so return false ; A utility function to create BST node ; Driver program to test above functions ; 15 / \ 10 20 / \ / \ 8 12 16 25"
How can the above be solved in Java?

 import java . util . * ; class GFG { static final int MAX_SIZE = 100 ; static class node { int val ; node left , right ; } ; static class Stack { int size ; int top ; node [ ] array ; } ; static Stack createStack ( int size ) { Stack stack = new Stack ( ) ; stack . size = size ; stack . top = - 1 ; stack . array = new node [ stack . size ] ; return stack ; } static int isFull ( Stack stack ) { return ( stack . top - 1 == stack . size ) ? 1 : 0 ; } static int isEmpty ( Stack stack ) { return stack . top == - 1 ? 1 : 0 ; } static void push ( Stack stack , node node ) { if ( isFull ( stack ) == 1 ) return ; stack . array [ ++ stack . top ] = node ; } static node pop ( Stack stack ) { if ( isEmpty ( stack ) == 1 ) return null ; return stack . array [ stack . top -- ] ; } static boolean isPairPresent ( node root , int target ) { Stack s1 = createStack ( MAX_SIZE ) ; Stack s2 = createStack ( MAX_SIZE ) ; boolean done1 = false , done2 = false ; int val1 = 0 , val2 = 0 ; node curr1 = root , curr2 = root ; while ( true ) { while ( done1 == false ) { if ( curr1 != null ) { push ( s1 , curr1 ) ; curr1 = curr1 . left ; } else { if ( isEmpty ( s1 ) == 1 ) done1 = true ; else { curr1 = pop ( s1 ) ; val1 = curr1 . val ; curr1 = curr1 . right ; done1 = true ; } } } while ( done2 == false ) { if ( curr2 != null ) { push ( s2 , curr2 ) ; curr2 = curr2 . right ; } else { if ( isEmpty ( s2 ) == 1 ) done2 = true ; else { curr2 = pop ( s2 ) ; val2 = curr2 . val ; curr2 = curr2 . left ; done2 = true ; } } } if ( ( val1 != val2 ) && ( val1 + val2 ) == target ) { System . out . print ( " Pair ▁ Found : ▁ " + val1 + " + ▁ " + val2 + " ▁ = ▁ " + target + "
"); return true ; } else if ( ( val1 + val2 ) < target ) done1 = false ; else if ( ( val1 + val2 ) > target ) done2 = false ; if ( val1 >= val2 ) return false ; } } static node NewNode ( int val ) { node tmp = new node ( ) ; tmp . val = val ; tmp . right = tmp . left = null ; return tmp ; } public static void main ( String [ ] args ) { node root = NewNode ( 15 ) ; root . left =...


"Find a pair with given sum in a Balanced BST | Java code to find a pair with given sum in a Balanced BST ; A binary tree node ; Root of BST ; Constructor ; Inorder traversal of the tree ; Utility function for inorder traversal of the tree ; This method mainly calls insertRec ( ) ; A recursive function to insert a new key in BST ; If the tree is empty , return a new node ; Otherwise , recur down the tree ; Method that adds values of given BST into ArrayList and hence returns the ArrayList ; Base Case ; method that checks if there is a pair present ; This list a1 is passed as an argument in treeToList method which is later on filled by the values of BST ; a2 list contains all the values of BST returned by treeToList method ; Starting index of a2 ; Ending index of a2 ; Target Found ! ; decrements end ; increments start ; Driver function ; 15 / \ 10 20 / \ / \ 8 12 16 25"
How can the above be solved in Java?

import java . util . ArrayList ; class Node { int data ; Node left , right ; Node ( int d ) { data = d ; left = right = null ; } } class BinarySearchTree { Node root ; BinarySearchTree ( ) { root = null ; } void inorder ( ) { inorderUtil ( this . root ) ; } void inorderUtil ( Node node ) { if ( node == null ) return ; inorderUtil ( node . left ) ; System . out . print ( node . data + " ▁ " ) ; inorderUtil ( node . right ) ; } void insert ( int key ) { root = insertRec ( root , key ) ; } Node insertRec ( Node root , int data ) { if ( root == null ) { root = new Node ( data ) ; return root ; } if ( data < root . data ) root . left = insertRec ( root . left , data ) ; else if ( data > root . data ) root . right = insertRec ( root . right , data ) ; return root ; } ArrayList < Integer > treeToList ( Node node , ArrayList < Integer > list ) { if ( node == null ) return list ; treeToList ( node . left , list ) ; list . add ( node . data ) ; treeToList ( node . right , list ) ; return list ; } boolean isPairPresent ( Node node , int target ) { ArrayList < Integer > a1 = new ArrayList < > ( ) ; ArrayList < Integer > a2 = treeToList ( node , a1 ) ; int start = 0 ; int end = a2 . size ( ) - 1 ; while ( start < end ) { if ( a2 . get ( start ) + a2 . get ( end ) == target ) { System . out . println ( " Pair ▁ Found : ▁ " + a2 . get ( start ) + " ▁ + ▁ " + a2 . get ( end ) + " ▁ " + " = ▁ " + target ) ; return true ; } if ( a2 . get ( start ) + a2 . get ( end ) > target ) { end -- ; } if ( a2 . get ( start ) + a2 . get ( end ) < target ) { start ++ ; } } System . out . println ( " No ▁ such ▁ values ▁ are ▁ found ! " ) ; return false ; } public static void main ( String [ ] args ) { BinarySearchTree tree = new BinarySearchTree ( ) ; tree . insert ( 15 ) ; tree . insert ( 10 ) ; tree . insert ( 20 ) ; tree . insert ( 8 ) ; tree . insert ( 12 ) ; tree . insert ( 16 ) ; tree . insert ( 25 ) ; tree . isPairPresent ( tree . root , 33 ) ; } }


"Find a pair with sum N having minimum absolute difference | Java program to implement the above approach ; Function to find the value of X and Y having minimum value of Math . abs ( X - Y ) ; If N is an odd number ; If N is an even number ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findXandYwithminABSX_Y ( int N ) { if ( N % 2 == 1 ) { System . out . print ( ( N / 2 ) + " ▁ " + ( N / 2 + 1 ) ) ; } else { System . out . print ( ( N / 2 - 1 ) + " ▁ " + ( N / 2 + 1 ) ) ; } } public static void main ( String [ ] args ) { int N = 12 ; findXandYwithminABSX_Y ( N ) ; } }


"Find a palindromic string B such that given String A is a subsequense of B | Java program to find a palindromic string B such that given String A is a subsequense of B ; Function to check if a string is palindrome ; Reversing a string ; check if reversed string is equal to given string ; Function to find a palindromic string B such that given String A is a subsequense of B ; Reversing the string A ; If the string A is already a palindrome return A ; else return B ; Swap values of left and right ; Driver Code"
How can the above be solved in Java?

class GFG { static boolean checkPalindrome ( String s ) { String x = reverse ( s ) ; return x . equals ( s ) ; } static String findStringB ( String A ) { String B = reverse ( A ) ; B = B + A ; if ( checkPalindrome ( A ) ) { return A ; } return B ; } static String reverse ( String input ) { char [ ] temparray = input . toCharArray ( ) ; int left , right = 0 ; right = temparray . length - 1 ; for ( left = 0 ; left < right ; left ++ , right -- ) { char temp = temparray [ left ] ; temparray [ left ] = temparray [ right ] ; temparray [ right ] = temp ; } return String . valueOf ( temparray ) ; } public static void main ( String [ ] args ) { String A = " ab " ; System . out . println ( findStringB ( A ) ) ; } }


"Find a partition point in array to maximize its xor sum | Java program to find partition point in array to maximize xor sum ; Function to calculate Prefix Xor array ; Calculating prefix xor ; Function to find partition point in array to maximize xor sum ; To store prefix xor ; Compute the prefix xor ; To store sum and index ; Calculate the maximum sum that can be obtained splitting the array at some index i ; PrefixXor [ i ] = Xor of all arr elements till i ' th ▁ index ▁ PrefixXor [ n - 1 ] ▁ ▁ ^ ▁ PrefixXor [ i ] ▁ = ▁ Xor ▁ of ▁ all ▁ elements ▁ ▁ from ▁ i + 1' th index to n - 1 'th index ; Return the index ; Driver code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void ComputePrefixXor ( int arr [ ] , int PrefixXor [ ] , int n ) { PrefixXor [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) PrefixXor [ i ] = PrefixXor [ i - 1 ] ^ arr [ i ] ; } static int Xor_Sum ( int arr [ ] , int n ) { int [ ] PrefixXor = new int [ n ] ; ComputePrefixXor ( arr , PrefixXor , n ) ; int sum = 0 , index = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( PrefixXor [ i ] + ( PrefixXor [ n - 1 ] ^ PrefixXor [ i ] ) > sum ) { sum = PrefixXor [ i ] + ( PrefixXor [ n - 1 ] ^ PrefixXor [ i ] ) ; index = i ; } } return index + 1 ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 4 , 6 , 3 , 8 , 13 , 34 , 2 , 21 , 10 } ; int n = arr . length ; System . out . println ( Xor_Sum ( arr , n ) ) ; } }


"Find a partition point in array to maximize its xor sum | Java program to find partition point in array to maximize xor sum ; Function to find partition point in array to maximize xor sum ; Traverse through the array ; Calculate xor of elements left of index i including ith element ; Calculate xor of the elements right of index i ; Keep the maximum possible xor sum ; Return the 1 based index of the array ; Driver code ; Function call"
How can the above be solved in Java?

class GFG { public static int Xor_Sum ( int [ ] arr , int n ) { int sum = 0 , index = - 1 ; int left_xor = 0 , right_xor = 0 ; for ( int i = 0 ; i < n ; i ++ ) { left_xor = left_xor ^ arr [ i ] ; right_xor = 0 ; for ( int j = i + 1 ; j < n ; j ++ ) { right_xor = right_xor ^ arr [ j ] ; } if ( left_xor + right_xor > sum ) { sum = left_xor + right_xor ; index = i ; } } return index + 1 ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 4 , 6 , 3 , 8 , 13 , 34 , 2 , 21 , 10 } ; int n = arr . length ; System . out . println ( Xor_Sum ( arr , n ) ) ; } }


"Find a peak element | A Java program to find a peak element ; Find the peak element in the array ; First or last element is peak element ; Check for every other element ; Check if the neighbors are smaller ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findPeak ( int arr [ ] , int n ) { if ( n == 1 ) return 0 ; if ( arr [ 0 ] >= arr [ 1 ] ) return 0 ; if ( arr [ n - 1 ] >= arr [ n - 2 ] ) return n - 1 ; for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( arr [ i ] >= arr [ i - 1 ] && arr [ i ] >= arr [ i + 1 ] ) return i ; } return 0 ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 20 , 4 , 1 , 0 } ; int n = arr . length ; System . out . print ( " Index ▁ of ▁ a ▁ peak ▁ point ▁ is ▁ " + findPeak ( arr , n ) ) ; } }


"Find a peak element | A Java program to find a peak element using divide and conquer ; A binary search based function that returns index of a peak element ; Find index of middle element ( low + high ) / 2 ; Compare middle element with its neighbours ( if neighbours exist ) ; If middle element is not peak and its left neighbor is greater than it , then left half must have a peak element ; If middle element is not peak and its right neighbor is greater than it , then right half must have a peak element ; A wrapper over recursive function findPeakUtil ( ) ; Driver method"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class PeakElement { static int findPeakUtil ( int arr [ ] , int low , int high , int n ) { int mid = low + ( high - low ) / 2 ; if ( ( mid == 0 arr [ mid - 1 ] <= arr [ mid ] ) && ( mid == n - 1 arr [ mid + 1 ] <= arr [ mid ] ) ) return mid ; else if ( mid > 0 && arr [ mid - 1 ] > arr [ mid ] ) return findPeakUtil ( arr , low , ( mid - 1 ) , n ) ; else return findPeakUtil ( arr , ( mid + 1 ) , high , n ) ; } static int findPeak ( int arr [ ] , int n ) { return findPeakUtil ( arr , 0 , n - 1 , n ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 20 , 4 , 1 , 0 } ; int n = arr . length ; System . out . println ( " Index ▁ of ▁ a ▁ peak ▁ point ▁ is ▁ " + findPeak ( arr , n ) ) ; } }


"Find a permutation of 2 N numbers such that the result of given expression is exactly 2 K | Java program to find the required permutation of first 2 * N natural numbers ; Function to find the required permutation of first 2 * N natural numbers ; Iterate in blocks of 2 ; We need more increments , so print in reverse order ; We have enough increments , so print in same order ; Driver code"
How can the above be solved in Java?

class GFG { static void printPermutation ( int n , int k ) { for ( int i = 1 ; i <= n ; i ++ ) { int x = 2 * i - 1 ; int y = 2 * i ; if ( i <= k ) System . out . print ( y + " ▁ " + x + " ▁ " ) ; else System . out . print ( x + " ▁ " + y + " ▁ " ) ; } } public static void main ( String [ ] args ) { int n = 2 , k = 1 ; printPermutation ( n , k ) ; } }


"Find a point such that sum of the Manhattan distances is minimized | Java implementation of above approach ; Function to print the required points which minimizes the sum of Manhattan distances ; Sorting points in all k dimension ; Output the required k points ; Driver code ; function call to print required points"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static void minDistance ( int n , int k , int point [ ] [ ] ) { for ( int i = 0 ; i < k ; i ++ ) Arrays . sort ( point [ i ] ) ; for ( int i = 0 ; i < k ; i ++ ) System . out . print ( point [ i ] [ ( int ) Math . ceil ( ( double ) ( n / 2 ) - 1 ) ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int n = 4 ; int k = 4 ; int point [ ] [ ] = { { 1 , 5 , 2 , 4 } , { 6 , 2 , 0 , 6 } , { 9 , 5 , 1 , 3 } , { 6 , 7 , 5 , 9 } } ; minDistance ( n , k , point ) ; } }


"Find a point whose sum of distances from all given points on a line is K | Java program for the above approach ; Function to find the sum of distances of all points from a given point ; Stores sum of distances ; Traverse the array ; Return the sum ; Function to find such a point having sum of distances of all other points from this point equal to K ; If N is odd keep left as arr [ n / 2 ] else keep left as arr [ n / 2 - 1 ] + 1 ; ; Keep right as arr [ N - 1 ] ; Perform binary search in the right half ; Calculate the mid index of the range ; If temp is equal to K ; Print the value of mid ; If the value of K < temp ; Update right to mid - 1 ; If the value of K > temp ; Update left to mid + 1 ; Update the value of left ; Update the value of right ; Perform binary search on the left half ; Calculate the mid index of the range ; If temp is equal to K ; Print mid ; if K > temp ; Update right to mid - 1 ; If K < temp ; Update left to mid + 1 ; If no such point found ; Driver Code"
How can the above be solved in Java?

import java . lang . * ; class GFG { public static int findSum ( int arr [ ] , int N , int pt ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += Math . abs ( arr [ i ] - pt ) ; } return sum ; } public static void findPoint ( int arr [ ] , int N , int K ) { int left ; if ( N % 2 != 0 ) { left = arr [ N / 2 ] ; } else { left = arr [ N / 2 - 1 ] + 1 ; } int right = arr [ N - 1 ] ; while ( left <= right ) { int mid = ( left + right ) / 2 ; int temp = findSum ( arr , N , mid ) ; if ( temp == K ) { System . out . println ( mid ) ; return ; } else if ( K < temp ) { right = mid - 1 ; } else { left = mid + 1 ; } } left = arr [ 0 ] ; right = arr [ N / 2 ] - 1 ; while ( left <= right ) { int mid = ( left + right ) / 2 ; int temp = findSum ( arr , N , mid ) ; if ( temp == K ) { System . out . println ( mid ) ; return ; } else if ( K > temp ) { right = mid - 1 ; } else { left = mid + 1 ; } } System . out . println ( " - 1" ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 3 , 6 , 7 , 11 } ; int K = 18 ; int N = arr . length ; findPoint ( arr , N , K ) ; } }


"Find a range of composite numbers of given length | Java program to find a range of composite numbers of given length ; method to find factorial of given number ; to print range of length n having all composite integers ; Driver method"
How can the above be solved in Java?

class Test { static int factorial ( int n ) { if ( n == 0 ) return 1 ; return n * factorial ( n - 1 ) ; } static void printRange ( int n ) { int a = factorial ( n + 2 ) + 2 ; int b = a + n - 1 ; System . out . println ( " [ " + a + " , ▁ " + b + " ] " ) ; } public static void main ( String args [ ] ) throws Exception { int n = 3 ; printRange ( n ) ; } }


"Find a rotation with maximum hamming distance | Java program to Find another array such that the hamming distance from the original array is maximum ; Return the maximum hamming distance of a rotation ; arr [ ] to brr [ ] two times so that we can traverse through all rotations . ; We know hamming distance with 0 rotation would be 0. ; We try other rotations one by one and compute Hamming distance of every rotation ; We can never get more than n . ; driver code"
How can the above be solved in Java?

class GFG { static int maxHamming ( int arr [ ] , int n ) { int brr [ ] = new int [ 2 * n + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) brr [ i ] = arr [ i ] ; for ( int i = 0 ; i < n ; i ++ ) brr [ n + i ] = arr [ i ] ; int maxHam = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int currHam = 0 ; for ( int j = i , k = 0 ; j < ( i + n ) ; j ++ , k ++ ) if ( brr [ j ] != arr [ k ] ) currHam ++ ; if ( currHam == n ) return n ; maxHam = Math . max ( maxHam , currHam ) ; } return maxHam ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 4 , 6 , 8 } ; int n = arr . length ; System . out . print ( maxHamming ( arr , n ) ) ; } }


"Find a sorted subsequence of size 3 in linear time | Java Program for above approach ; Function to find the triplet ; If number of elements < 3 then no triplets are possible ; track best sequence length ( not current sequence length ) ; min number in array ; least max number in best sequence i . e . track arr [ j ] ( e . g . in array { 1 , 5 , 3 } our best sequence would be { 1 , 3 } with arr [ j ] = 3 ) ; save arr [ i ] ; Iterate from 1 to nums . size ( ) ; this condition is only hit when current sequence size is 2 ; update best sequence max number to a smaller value ( i . e . we 've found a smaller value for arr[j]) ; store best sequence start value i . e . arr [ i ] ; Increase best sequence length & save next number in our triplet ; We 've found our arr[k]!  Print the output ; No triplet found ; Driver program ; Function Call"
How can the above be solved in Java?

class Main { public static void find3Numbers ( int [ ] nums ) { if ( nums . length < 3 ) { System . out . print ( " No ▁ such ▁ triplet ▁ found " ) ; return ; } int seq = 1 ; int min_num = nums [ 0 ] ; int max_seq = Integer . MIN_VALUE ; int store_min = min_num ; for ( int i = 1 ; i < nums . length ; i ++ ) { if ( nums [ i ] == min_num ) continue ; else if ( nums [ i ] < min_num ) { min_num = nums [ i ] ; continue ; } else if ( nums [ i ] < max_seq ) { max_seq = nums [ i ] ; store_min = min_num ; } else if ( nums [ i ] > max_seq ) { seq ++ ; if ( seq == 3 ) { System . out . println ( " Triplet : ▁ " + store_min + " , ▁ " + max_seq + " , ▁ " + nums [ i ] ) ; return ; } max_seq = nums [ i ] ; } } System . out . print ( " No ▁ such ▁ triplet ▁ found " ) ; } public static void main ( String [ ] args ) { int [ ] nums = { 1 , 2 , - 1 , 7 , 5 } ; find3Numbers ( nums ) ; } }


"Find a string in lexicographic order which is in between given two strings | Java program to find the string in lexicographic order which is in between given two strings ; Function to find the lexicographically next string ; Iterate from last character ; If not ' z ' , increase by one ; if ' z ' , change it to ' a ' ; Driver Code ; If not equal , print the resultant string"
How can the above be solved in Java?

class GFG { static String lexNext ( String str , int n ) { char [ ] s = str . toCharArray ( ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( s [ i ] != ' z ' ) { s [ i ] ++ ; return String . valueOf ( s ) ; } s [ i ] = ' a ' ; } return null ; } static public void main ( String [ ] args ) { String S = " abcdeg " , T = " abcfgh " ; int n = S . length ( ) ; String res = lexNext ( S , n ) ; if ( res != T ) { System . out . println ( res ) ; } else { System . out . println ( " - 1" ) ; } } }


"Find a string such that every character is lexicographically greater than its immediate next character | Java program to print a String in reverse alphabetical order upto given number ; Function that prints the required String ; Find modulus with 26 ; Print extra characters required ; Print the given reverse String countOfStr times ; Driver Code ; Initialize a String in reverse order"
How can the above be solved in Java?

class GFG { static String printString ( int n , String str ) { String str2 = " " ; int extraChar = n % 26 ; if ( extraChar >= 1 ) { for ( int i = 26 - ( extraChar + 1 ) ; i <= 25 ; i ++ ) { str2 += str . charAt ( i ) ; } } int countOfStr = n / 26 ; for ( int i = 1 ; i <= countOfStr ; i ++ ) { for ( int j = 0 ; j < 26 ; j ++ ) { str2 += str . charAt ( j ) ; } } return str2 ; } public static void main ( String [ ] args ) { int n = 30 ; String str = " zyxwvutsrqponmlkjihgfedcba " ; System . out . println ( printString ( n , str ) ) ; } }


"Find a sub matrix with maximum XOR | Java program to implement the above approach ; Compute the xor of elements from ( 1 , 1 ) to ( i , j ) and store it in prefix_xor [ i ] [ j ] ; xor of submatrix from 1 , 1 to i , j is ( xor of submatrix from 1 , 1 to i - 1 , j ) ^ ( xor of submatrix from 1 , 1 to i , j - 1 ) ^ ( xor of submatrix from 1 , 1 to i - 1 , j - 1 ) ^ arr [ i ] [ j ] ; find the submatrix with maximum xor value ; we need four loops to find all the submatrix of a matrix ; xor of submatrix from i , j to i1 , j1 is ( xor of submatrix from 1 , 1 to i1 , j1 ) ^ ( xor of submatrix from 1 , 1 to i - 1 , j - 1 ) ^ ( xor of submatrix from 1 , 1 to i1 , j - 1 ) ^ ( xor of submatrix from 1 , 1 to i - 1 , j1 ) ; if the xor is greater than maximum value substitute it ; Driver code ; Find the prefix_xor ; Find submatrix with maximum bitwise xor"
How can the above be solved in Java?

public class GFG { static int N = 101 ; static void prefix ( int arr [ ] [ ] , int prefix_xor [ ] [ ] , int n ) { for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 1 ; j < n ; j ++ ) { prefix_xor [ i ] [ j ] = arr [ i ] [ j ] ^ prefix_xor [ i - 1 ] [ j ] ^ prefix_xor [ i ] [ j - 1 ] ^ prefix_xor [ i - 1 ] [ j - 1 ] ; } } } static void Max_xor ( int prefix_xor [ ] [ ] , int n ) { int max_value = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { for ( int i1 = i ; i1 <= n ; i1 ++ ) { for ( int j1 = j ; j1 <= n ; j1 ++ ) { int x = 0 ; x ^= prefix_xor [ i1 ] [ j1 ] ; x ^= prefix_xor [ i - 1 ] [ j - 1 ] ; x ^= prefix_xor [ i1 ] [ j - 1 ] ; x ^= prefix_xor [ i - 1 ] [ j1 ] ; max_value = Math . max ( max_value , x ) ; } } } } System . out . println ( max_value ) ; } public static void main ( String [ ] args ) { int arr [ ] [ ] = { { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 16 } } ; int n = 4 ; int prefix_xor [ ] [ ] = new int [ N ] [ N ] ; prefix ( arr , prefix_xor , n ) ; Max_xor ( prefix_xor , n ) ; } }


"Find a subarray of size K whose sum is a perfect square | Java program for the above approach ; Function to check if a given number is a perfect square or not ; Find square root of n ; Check if the square root is an integer or not ; Function to print the subarray whose sum is a perfect square ; Sum of first K elements ; If the first k elements have a sum as perfect square ; Iterate through the array ; If sum is perfect square ; If subarray not found ; Driver Code ; Given array ; Given subarray size K ; Function Call"
How can the above be solved in Java?

class GFG { static class pair { int first , second ; } static boolean isPerfectSquare ( int n ) { double sr = Math . sqrt ( n ) ; return ( ( sr - Math . floor ( sr ) ) == 0 ) ; } static void SubarrayHavingPerfectSquare ( int [ ] arr , int k ) { pair ans = new pair ( ) ; int sum = 0 , i ; for ( i = 0 ; i < k ; i ++ ) { sum += arr [ i ] ; } boolean found = false ; if ( isPerfectSquare ( sum ) ) { ans . first = 0 ; ans . second = i - 1 ; } else { for ( int j = i ; j < arr . length ; j ++ ) { sum = sum + arr [ j ] - arr [ j - k ] ; if ( isPerfectSquare ( sum ) ) { found = true ; ans . first = j - k + 1 ; ans . second = j ; } } for ( int k1 = ans . first ; k1 <= ans . second ; k1 ++ ) { System . out . print ( arr [ k1 ] + " ▁ " ) ; } } if ( found == false ) { System . out . print ( " - 1" ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 20 , 34 , 51 , 10 , 99 , 87 , 23 , 45 } ; int K = 3 ; SubarrayHavingPerfectSquare ( arr , K ) ; } }


"Find a subarray whose sum is divisible by size of the array | Java implementation of above approach ; Function to check is there exists a subarray whose sum is a multiple of N ; Prefix sum array to store cumulative sum ; Single state dynamic programming relation for prefix sum array ; Modulo class vector ; Storing the index value in the modulo class vector ; If there exists a sub - array with starting index equal to zero ; In this class , there are more than two presums % N . Hence difference of any two subarrays would be a multiple of N ; 0 based indexing ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void CheckSubarray ( int arr [ ] , int N ) { int [ ] presum = new int [ N + 1 ] ; for ( int i = 1 ; i <= N ; i += 1 ) { presum [ i ] = presum [ i - 1 ] + arr [ i - 1 ] ; } Vector < Integer > [ ] moduloclass = new Vector [ N ] ; for ( int i = 0 ; i < N ; i += 1 ) { moduloclass [ i ] = new Vector < > ( ) ; } for ( int i = 1 ; i <= N ; i += 1 ) { moduloclass [ presum [ i ] % N ] . add ( i - 1 ) ; } if ( moduloclass [ 0 ] . size ( ) > 0 ) { System . out . print ( 0 + " ▁ " + moduloclass [ 0 ] . get ( 0 ) ) ; return ; } for ( int i = 1 ; i < N ; i += 1 ) { if ( moduloclass [ i ] . size ( ) >= 2 ) { System . out . print ( moduloclass [ i ] . get ( 0 ) + 1 + " ▁ " + moduloclass [ i ] . get ( 1 ) ) ; return ; } } } public static void main ( String args [ ] ) { int arr [ ] = { 7 , 3 , 5 , 2 } ; int N = arr . length ; CheckSubarray ( arr , N ) ; } }


"Find a subarray whose sum is divisible by size of the array | Java implementation of above approach ; Function to find a subarray whose sum is a multiple of N ; Prefix sum array to store cumulative sum ; Single state dynamic programming relation for prefix sum array ; Generating all sub - arrays ; If the sum of the sub - array [ i : j ] is a multiple of N ; If the function reaches here it means there are no subarrays with sum as a multiple of N ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void CheckSubarray ( int arr [ ] , int N ) { int presum [ ] = new int [ N + 1 ] ; for ( int i = 1 ; i <= N ; i += 1 ) { presum [ i ] = presum [ i - 1 ] + arr [ i - 1 ] ; } for ( int i = 1 ; i <= N ; i += 1 ) { for ( int j = i ; j <= N ; j += 1 ) { if ( ( presum [ j ] - presum [ i - 1 ] ) % N == 0 ) { System . out . print ( ( i - 1 ) + " ▁ " + ( j - 1 ) ) ; return ; } } } System . out . print ( - 1 ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 7 , 5 , 3 , 7 } ; int N = arr . length ; CheckSubarray ( arr , N ) ; } }


"Find a triplet ( i , j , k ) from an array such that i < j < k and arr [ i ] < arr [ j ] > arr [ k ] | Java program for the above approach ; Function to find a triplet such that i < j < k and arr [ i ] < arr [ j ] and arr [ j ] > arr [ k ] ; Traverse the array ; Condition to satisfy for the resultant triplet ; Otherwise , triplet doesn 't exist ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void print_triplet ( int arr [ ] , int n ) { for ( int i = 1 ; i <= n - 2 ; i ++ ) { if ( arr [ i - 1 ] < arr [ i ] && arr [ i ] > arr [ i + 1 ] ) { System . out . print ( i - 1 + " ▁ " + i + " ▁ " + ( i + 1 ) ) ; return ; } } System . out . print ( - 1 ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 3 , 5 , 2 , 1 , 6 } ; int N = arr . length ; print_triplet ( arr , N ) ; } }


"Find a triplet in an array such that arr [ i ] arr [ k ] and i < j < k | Java program to implement the above approach ; Function to find a triplet that satisfy the conditions ; Traverse the given array ; Stores current element ; Stores element just before the current element ; Stores element just after the current element ; Check the given conditions ; Print a triplet ; If no triplet found ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void FindTrip ( int arr [ ] , int N ) { for ( int i = 1 ; i < N - 1 ; i ++ ) { int p = arr [ i - 1 ] ; int q = arr [ i ] ; int r = arr [ i + 1 ] ; if ( p < q && q > r ) { System . out . println ( ( i - 1 ) + " ▁ " + ( i ) + " ▁ " + ( i + 1 ) ) ; return ; } } System . out . println ( - 1 ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 2 , 1 , 4 , 3 } ; int N = arr . length ; FindTrip ( arr , N ) ; } }


"Find a triplet in an array whose sum is closest to a given number | Java implementation of the above approach ; Function to return the sum of a triplet which is closest to x ; Sort the array ; To store the closest sum Assigning long to avoid overflow condition when array has negative integers ; Fix the smallest number among the three integers ; Two pointers initially pointing at the last and the element next to the fixed element ; While there could be more pairs to check ; Calculate the sum of the current triplet ; If the sum is more closer than the current closest sum ; If sum is greater then x then decrement the second pointer to get a smaller sum ; Else increment the first pointer to get a larger sum ; Return the closest sum found ; Driver code"
How can the above be solved in Java?

import static java . lang . Math . abs ; import java . util . * ; class GFG { static int solution ( Vector < Integer > arr , int x ) { Collections . sort ( arr ) ; long closestSum = Integer . MAX_VALUE ; for ( int i = 0 ; i < arr . size ( ) - 2 ; i ++ ) { int ptr1 = i + 1 , ptr2 = arr . size ( ) - 1 ; while ( ptr1 < ptr2 ) { int sum = arr . get ( i ) + arr . get ( ptr1 ) + arr . get ( ptr2 ) ; if ( abs ( x - sum ) < abs ( x - closestSum ) ) { closestSum = sum ; } if ( sum > x ) { ptr2 -- ; } else { ptr1 ++ ; } } } return ( int ) closestSum ; } public static void main ( String [ ] args ) { Vector arr = new Vector ( Arrays . asList ( - 1 , 2 , 1 , - 4 ) ) ; int x = 1 ; System . out . println ( solution ( arr , x ) ) ; } }


"Find a triplet in an array whose sum is closest to a given number | Java implementation of the above approach ; Function to return the sum of a triplet which is closest to x ; To store the closest sum ; Run three nested loops each loop for each element of triplet ; Update the closestSum ; Return the closest sum found ; Driver code"
How can the above be solved in Java?

class GFG { public static int solution ( int arr [ ] , int x ) { int closestSum = Integer . MAX_VALUE ; for ( int i = 0 ; i < arr . length ; i ++ ) { for ( int j = i + 1 ; j < arr . length ; j ++ ) { for ( int k = j + 1 ; k < arr . length ; k ++ ) { if ( Math . abs ( x - closestSum ) > Math . abs ( x - ( arr [ i ] + arr [ j ] + arr [ k ] ) ) ) closestSum = ( arr [ i ] + arr [ j ] + arr [ k ] ) ; } } } return closestSum ; } public static void main ( String [ ] args ) { int arr [ ] = { - 1 , 2 , 1 , - 4 } ; int x = 1 ; System . out . print ( solution ( arr , x ) ) ; } }


"Find a triplet that sum to a given value | Java program to find a triplet ; returns true if there is triplet with sum equal to ' sum ' present in A [ ] . Also , prints the triplet ; Fix the first element as A [ i ] ; Fix the second element as A [ j ] ; Now look for the third number ; If we reach here , then no triplet was found ; Driver program to test above functions"
How can the above be solved in Java?

class FindTriplet { boolean find3Numbers ( int A [ ] , int arr_size , int sum ) { int l , r ; for ( int i = 0 ; i < arr_size - 2 ; i ++ ) { for ( int j = i + 1 ; j < arr_size - 1 ; j ++ ) { for ( int k = j + 1 ; k < arr_size ; k ++ ) { if ( A [ i ] + A [ j ] + A [ k ] == sum ) { System . out . print ( " Triplet ▁ is ▁ " + A [ i ] + " , ▁ " + A [ j ] + " , ▁ " + A [ k ] ) ; return true ; } } } } return false ; } public static void main ( String [ ] args ) { FindTriplet triplet = new FindTriplet ( ) ; int A [ ] = { 1 , 4 , 45 , 6 , 10 , 8 } ; int sum = 22 ; int arr_size = A . length ; triplet . find3Numbers ( A , arr_size , sum ) ; } }


"Find a triplet that sum to a given value | Java program to find a triplet ; returns true if there is triplet with sum equal to ' sum ' present in A [ ] . Also , prints the triplet ; Sort the elements ; Now fix the first element one by one and find the other two elements ; To find the other two elements , start two index variables from two corners of the array and move them toward each other index of the first element in the remaining elements ; index of the last element ; A [ i ] + A [ l ] + A [ r ] > sum ; If we reach here , then no triplet was found ; partition function ; Implementation of Quick Sort A [ ] -- > Array to be sorted si -- > Starting index ei -- > Ending index ; Partitioning index ; Driver program to test above functions"
How can the above be solved in Java?

class FindTriplet { boolean find3Numbers ( int A [ ] , int arr_size , int sum ) { int l , r ; quickSort ( A , 0 , arr_size - 1 ) ; for ( int i = 0 ; i < arr_size - 2 ; i ++ ) { l = i + 1 ; r = arr_size - 1 ; while ( l < r ) { if ( A [ i ] + A [ l ] + A [ r ] == sum ) { System . out . print ( " Triplet ▁ is ▁ " + A [ i ] + " , ▁ " + A [ l ] + " , ▁ " + A [ r ] ) ; return true ; } else if ( A [ i ] + A [ l ] + A [ r ] < sum ) l ++ ; else r -- ; } } return false ; } int partition ( int A [ ] , int si , int ei ) { int x = A [ ei ] ; int i = ( si - 1 ) ; int j ; for ( j = si ; j <= ei - 1 ; j ++ ) { if ( A [ j ] <= x ) { i ++ ; int temp = A [ i ] ; A [ i ] = A [ j ] ; A [ j ] = temp ; } } int temp = A [ i + 1 ] ; A [ i + 1 ] = A [ ei ] ; A [ ei ] = temp ; return ( i + 1 ) ; } void quickSort ( int A [ ] , int si , int ei ) { int pi ; if ( si < ei ) { pi = partition ( A , si , ei ) ; quickSort ( A , si , pi - 1 ) ; quickSort ( A , pi + 1 , ei ) ; } } public static void main ( String [ ] args ) { FindTriplet triplet = new FindTriplet ( ) ; int A [ ] = { 1 , 4 , 45 , 6 , 10 , 8 } ; int sum = 22 ; int arr_size = A . length ; triplet . find3Numbers ( A , arr_size , sum ) ; } }


"Find a triplet that sum to a given value | Java program to find a triplet using Hashing ; returns true if there is triplet with sum equal to ' sum ' present in A [ ] . Also , prints the triplet ; Fix the first element as A [ i ] ; Find pair in subarray A [ i + 1. . n - 1 ] with sum equal to sum - A [ i ] ; If we reach here , then no triplet was found ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean find3Numbers ( int A [ ] , int arr_size , int sum ) { for ( int i = 0 ; i < arr_size - 2 ; i ++ ) { HashSet < Integer > s = new HashSet < Integer > ( ) ; int curr_sum = sum - A [ i ] ; for ( int j = i + 1 ; j < arr_size ; j ++ ) { if ( s . contains ( curr_sum - A [ j ] ) ) { System . out . printf ( " Triplet ▁ is ▁ % d , ▁ % d , ▁ % d " , A [ i ] , A [ j ] , curr_sum - A [ j ] ) ; return true ; } s . add ( A [ j ] ) ; } } return false ; } public static void main ( String [ ] args ) { int A [ ] = { 1 , 4 , 45 , 6 , 10 , 8 } ; int sum = 22 ; int arr_size = A . length ; find3Numbers ( A , arr_size , sum ) ; } }


"Find a valid parenthesis sequence of length K from a given valid parenthesis sequence | Java program for the above approach ; Function to find the subsequence of length K forming valid sequence ; Stores the resultant String ; Check whether character at index i is visited or not ; Traverse the String ; Push index of open bracket ; Pop and mark visited ; Increment count by 2 ; Append the characters and create the resultant String ; Return the resultant String ; Driver Code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static String findString ( String s , int k ) { int n = s . length ( ) ; String ans = " ▁ " ; Stack < Integer > st = new Stack < > ( ) ; boolean [ ] vis = new boolean [ n ] ; Vector < boolean > vis ( n , false ) ; int count = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( s . charAt ( i ) == ' ( ' ) { st . add ( i ) ; } if ( count < k && s . charAt ( i ) == ' ) ' ) { vis [ st . peek ( ) ] = true ; st . pop ( ) ; vis [ i ] = true ; count += 2 ; } } for ( int i = 0 ; i < n ; ++ i ) { if ( vis [ i ] == true ) { ans += s . charAt ( i ) ; } } return ans ; } public static void main ( String [ ] args ) { String s = " ( ) ( ) ( ) " ; int K = 2 ; System . out . print ( findString ( s , K ) ) ; } }


"Find a value whose XOR with given number is maximum | Java implementation of the above approach ; Function To Calculate Answer ; Find number of bits in the given integer ; XOR the given integer with poe ( 2 , number_of_bits - 1 and print the result ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int calculate ( int X ) { int number_of_bits = 8 ; return ( ( 1 << number_of_bits ) - 1 ) ^ X ; } public static void main ( String [ ] args ) { int X = 4 ; System . out . println ( " Required ▁ Number ▁ is ▁ : ▁ " + calculate ( X ) ) ; } }


"Find a way to fill matrix with 1 ' s ▁ and ▁ 0' s in blank positions | Java implementation of the approach ; Function to generate and print the required matrix ; Replace the ' . ' ; Toggle number ; For each row , change the starting number ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int N = 2 ; static int M = 2 ; static void Matrix ( char a [ ] [ ] ) { char ch = '1' ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( a [ i ] [ j ] == ' . ' ) a [ i ] [ j ] = ch ; ch = ( ch == '1' ) ? '0' : '1' ; System . out . print ( a [ i ] [ j ] + " ▁ " ) ; } System . out . println ( ) ; if ( i % 2 == 0 ) ch = '0' ; else ch = '1' ; } } public static void main ( String [ ] args ) { char a [ ] [ ] = { { ' . ' , ' _ ' } , { ' _ ' , ' . ' } } ; Matrix ( a ) ; } }