"Split the array and add the first part to the end | Set 2 | Java program to Split the array and add the first part to the end ; Function to reverse arr [ ] from index start to end ; Function to print an array ; Function to left rotate arr [ ] of size n by k ; Driver program to test above functions ; Function calling"
How can the above be solved in Java?

class Geeks { static void rvereseArray ( int arr [ ] , int start , int end ) { while ( start < end ) { int temp = arr [ start ] ; arr [ start ] = arr [ end ] ; arr [ end ] = temp ; start ++ ; end -- ; } } static void printArray ( int arr [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } static void splitArr ( int arr [ ] , int k , int n ) { rvereseArray ( arr , 0 , n - 1 ) ; rvereseArray ( arr , 0 , n - k - 1 ) ; rvereseArray ( arr , n - k , n - 1 ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 12 , 10 , 5 , 6 , 52 , 36 } ; int n = arr . length ; int k = 2 ; splitArr ( arr , k , n ) ; printArray ( arr , n ) ; } }


"Split the array elements into strictly increasing and decreasing sequence | Java program to implement the above approach ; Function to print both the arrays ; Store both arrays ; Used for hashing ; Iterate for every element ; Increase the count ; If first occurrence ; If second occurrence ; If occurs more than 2 times ; Sort in increasing order ; Print the increasing array ; Sort ; Print the decreasing array ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void PrintBothArrays ( int a [ ] , int n ) { Vector < Integer > v1 = new Vector < Integer > ( ) , v2 = new Vector < Integer > ( ) ; HashMap < Integer , Integer > mpp = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { mpp . put ( a [ i ] , ( mpp . get ( a [ i ] ) == null ? 0 : mpp . get ( a [ i ] ) ) + 1 ) ; if ( mpp . get ( a [ i ] ) == 1 ) v1 . add ( a [ i ] ) ; else if ( mpp . get ( a [ i ] ) == 2 ) v2 . add ( a [ i ] ) ; else { System . out . println ( " Not ▁ possible " ) ; return ; } } Collections . sort ( v1 ) ; System . out . println ( " Strictly ▁ increasing ▁ array ▁ is : " ) ; for ( int i = 0 ; i < v1 . size ( ) ; i ++ ) System . out . print ( v1 . get ( i ) + " ▁ " ) ; Collections . sort ( v2 ) ; Collections . reverse ( v2 ) ; System . out . println ( " Strictly decreasing array is : "); for ( int i = 0 ; i < v2 . size ( ) ; i ++ ) System . out . print ( v2 . get ( i ) + " ▁ " ) ; } public static void main ( String args [ ] ) { int a [ ] = { 7 , 2 , 7 , 3 , 3 , 1 , 4 } ; int n = a . length ; PrintBothArrays ( a , n ) ; } }


"Split the array into odd number of segments of odd lengths | Java to check whether given array is breakable or not ; Function to check ; Check the result by processing the first & last element and size ; Driver code"
How can the above be solved in Java?

class GFG { static int checkArray ( int [ ] arr , int n ) { return ( ( arr [ 0 ] % 2 ) > 0 && ( arr [ n - 1 ] % 2 ) > 0 && ( n % 2 ) > 0 ) ? 1 : 0 ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 } ; int n = arr . length ; System . out . println ( checkArray ( arr , n ) ) ; } }


"Split the binary string into substrings with equal number of 0 s and 1 s | Java implementation of the above approach ; Function to return the count of maximum substrings str can be divided into ; To store the count of 0 s and 1 s ; To store the count of maximum substrings str can be divided into ; It is not possible to split the string ; Driver code"
How can the above be solved in Java?

class GFG { static int maxSubStr ( String str , int n ) { int count0 = 0 , count1 = 0 ; int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str . charAt ( i ) == '0' ) { count0 ++ ; } else { count1 ++ ; } if ( count0 == count1 ) { cnt ++ ; } } if ( cnt == 0 ) { return - 1 ; } return cnt ; } public static void main ( String [ ] args ) { String str = "0100110101" ; int n = str . length ( ) ; System . out . println ( maxSubStr ( str , n ) ) ; } }


"Split the fraction into sum of multiple fractions having numerator as 1 | Java program for the above approach ; Function to split the fraction into distinct unit fraction ; To store answer ; While numerator is positive ; Finding x = ceil ( d / n ) ; Add 1 / x to list of ans ; Update fraction ; Driver code ; Given Input ; Function Call ; Print Answer"
How can the above be solved in Java?

import java . util . Vector ; public class GFG { static Vector < String > FractionSplit ( long n , long d ) { Vector < String > UnitFactions = new Vector < > ( ) ; while ( n > 0 ) { long x = ( d + n - 1 ) / n ; String s = "1 / " + String . valueOf ( x ) ; UnitFactions . add ( s ) ; n = n * x - d ; d = d * x ; } return UnitFactions ; } public static void main ( String [ ] args ) { long n = 13 , d = 18 ; Vector < String > res = FractionSplit ( n , d ) ; for ( String s : res ) System . out . print ( s + " , ▁ " ) ; } }


"Split the given array into K sub | Java implementation of the above approach ; Function to check if mid can be maximum sub - arrays sum ; If individual element is greater maximum possible sum ; Increase sum of current sub - array ; If the sum is greater than mid increase count ; Check condition ; Function to find maximum subarray sum which is minimum ; start = array [ i ] ; Max subarray sum , considering subarray of length 1 ; end += array [ i ] ; Max subarray sum , considering subarray of length n ; Answer stores possible maximum sub array sum ; If mid is possible solution Put answer = mid ; ; Driver Code"
How can the above be solved in Java?

class GFG { static boolean check ( int mid , int array [ ] , int n , int K ) { int count = 0 ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( array [ i ] > mid ) return false ; sum += array [ i ] ; if ( sum > mid ) { count ++ ; sum = array [ i ] ; } } count ++ ; if ( count <= K ) return true ; return false ; } static int solve ( int array [ ] , int n , int K ) { int start = 1 ; for ( int i = 0 ; i < n ; ++ i ) { if ( array [ i ] > start ) } int end = 0 ; for ( int i = 0 ; i < n ; i ++ ) { } int answer = 0 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; if ( check ( mid , array , n , K ) ) { answer = mid ; end = mid - 1 ; } else { start = mid + 1 ; } } return answer ; } public static void main ( String [ ] args ) { int array [ ] = { 1 , 2 , 3 , 4 } ; int n = array . length ; int K = 3 ; System . out . println ( solve ( array , n , K ) ) ; } }


"Split the given string into Odds : Digit DP | Java program to split the given string into odds ; Function to check whether a string is an odd number or not ; A function to find the minimum number of segments the given string can be divided such that every segment is a odd number ; Declare a splitdp [ ] array and initialize to - 1 ; Build the DP table in a bottom - up manner ; Initially Check if the entire prefix is odd ; If the Given Prefix can be split into Odds then for the remaining string from i to j Check if Odd . If yes calculate the minimum split till j ; To check if the substring from i to j is a odd number or not ; If it is an odd number , then update the dp array ; Return the minimum number of splits for the entire string ; Driver code"
How can the above be solved in Java?

class GFG { static int checkOdd ( String number ) { int n = number . length ( ) ; int num = number . charAt ( n - 1 ) - '0' ; return ( num & 1 ) ; } static int splitIntoOdds ( String number ) { int numLen = number . length ( ) ; int splitDP [ ] = new int [ numLen + 1 ] ; for ( int i = 0 ; i < numLen + 1 ; i ++ ) splitDP [ i ] = - 1 ; for ( int i = 1 ; i <= numLen ; i ++ ) { if ( i <= 9 && ( checkOdd ( number . substring ( 0 , i ) ) == 1 ) ) splitDP [ i ] = 1 ; if ( splitDP [ i ] != - 1 ) { for ( int j = 1 ; j <= 9 && i + j <= numLen ; j ++ ) { if ( checkOdd ( number . substring ( i , i + j ) ) == 1 ) { if ( splitDP [ i + j ] == - 1 ) splitDP [ i + j ] = 1 + splitDP [ i ] ; else splitDP [ i + j ] = Math . min ( splitDP [ i + j ] , 1 + splitDP [ i ] ) ; } } } } return splitDP [ numLen ] ; } public static void main ( String [ ] args ) { System . out . println ( splitIntoOdds ( "123456789123456789123" ) ) ; } }


"Split the given string into Primes : Digit DP | Java implementation of the above approach ; Function to check whether a String is a prime number or not ; A recursive function to find the minimum number of segments the given String can be divided such that every segment is a prime ; If the number is null ; checkPrime function is called to check if the number is a prime or not . ; A very large number denoting maximum ; Consider a minimum of 6 and length since the primes are less than 10 ^ 6 ; Recursively call the function to check for the remaining String ; Evaluating minimum splits into Primes for the suffix ; Checks if no combination found ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static boolean checkPrime ( String number ) { int num = Integer . valueOf ( number ) ; for ( int i = 2 ; i * i <= num ; i ++ ) if ( ( num % i ) == 0 ) return false ; return true ; } static int splitIntoPrimes ( String number ) { if ( number . length ( ) == 0 ) return 0 ; if ( number . length ( ) <= 6 && checkPrime ( number ) ) return 1 ; else { int numLen = number . length ( ) ; int ans = 1000000 ; for ( int i = 1 ; i <= 6 && i <= numLen ; i ++ ) { if ( checkPrime ( number . substring ( 0 , i ) ) ) { int val = splitIntoPrimes ( number . substring ( i ) ) ; if ( val != - 1 ) { ans = Math . min ( ans , 1 + val ) ; } } } if ( ans == 1000000 ) return - 1 ; return ans ; } } public static void main ( String [ ] args ) { System . out . print ( splitIntoPrimes ( "13499315" ) + "
"); System . out . print ( splitIntoPrimes ( "43" ) + "
"); } }


"Split the given string into Primes : Digit DP | Java implementation of the above approach ; Function to precompute all the primes upto 1000000 and store it in a set using Sieve of Eratosthenes ; Here to_String ( ) is used for converting int to String ; A function to find the minimum number of segments the given String can be divided such that every segment is a prime ; Declare a splitdp [ ] array and initialize to - 1 ; Call sieve function to store primes in primes array ; Build the DP table in a bottom - up manner ; If the prefix is prime then the prefix will be found in the prime set ; If the Given Prefix can be split into Primes then for the remaining String from i to j Check if Prime . If yes calculate the minimum split till j ; To check if the subString from i to j is a prime number or not ; If it is a prime , then update the dp array ; Return the minimum number of splits for the entire String ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void getPrimesFromSeive ( HashSet < String > primes ) { boolean [ ] prime = new boolean [ 1000001 ] ; Arrays . fill ( prime , true ) ; prime [ 0 ] = prime [ 1 ] = false ; for ( int i = 2 ; i * i <= 1000000 ; i ++ ) { if ( prime [ i ] == true ) { for ( int j = i * i ; j <= 1000000 ; j += i ) prime [ j ] = false ; } } for ( int i = 2 ; i <= 1000000 ; i ++ ) { if ( prime [ i ] == true ) primes . add ( String . valueOf ( i ) ) ; } } static int splitIntoPrimes ( String number ) { int numLen = number . length ( ) ; int [ ] splitDP = new int [ numLen + 1 ] ; Arrays . fill ( splitDP , - 1 ) ; HashSet < String > primes = new HashSet < String > ( ) ; getPrimesFromSeive ( primes ) ; for ( int i = 1 ; i <= numLen ; i ++ ) { if ( i <= 6 && ( primes . contains ( number . substring ( 0 , i ) ) ) ) splitDP [ i ] = 1 ; if ( splitDP [ i ] != - 1 ) { for ( int j = 1 ; j <= 6 && i + j <= numLen ; j ++ ) { if ( primes . contains ( number . substring ( i , i + j ) ) ) { if ( splitDP [ i + j ] == - 1 ) splitDP [ i + j ] = 1 + splitDP [ i ] ; else splitDP [ i + j ] = Math . min ( splitDP [ i + j ] , 1 + splitDP [ i ] ) ; } } } } return splitDP [ numLen ] ; } public static void main ( String [ ] args ) { System . out . print ( splitIntoPrimes ( "13499315" ) + "
"); System . out . print ( splitIntoPrimes ( "43" ) + "
"); } }


"Split the number N by maximizing the count of subparts divisible by K | Java program to split the number N by maximizing the count of subparts divisible by K ; Function to count the subparts ; Total subStr till now ; If it can be divided , then this subString is one of the possible answer ; Convert String to long and check if its divisible with X ; Consider there is no vertical cut between this index and the next one , hence take total carrying total substr a . ; If there is vertical cut between this index and next one , then we start again with subStr as " " and add b for the count of subStr upto now ; Return max of both the cases ; Driver code"
How can the above be solved in Java?

 class GFG { static int count ( String N , int X , String subStr , int index , int n ) { if ( index == n ) return 0 ; String a = subStr + N . charAt ( index ) ; int b = 0 ; if ( Long . valueOf ( a ) % X == 0 ) b = 1 ; int m1 = count ( N , X , a , index + 1 , n ) ; int m2 = b + count ( N , X , " " , index + 1 , n ) ; return Math . max ( m1 , m2 ) ; } public static void main ( String [ ] args ) { String N = "00001242" ; int K = 3 ; int l = N . length ( ) ; System . out . print ( count ( N , K , " " , 0 , l ) + "
"); } }


"Split the number into N parts such that difference between the smallest and the largest part is minimum | Java implementation of the approach ; Function that prints the required sequence ; If we cannot split the number into exactly ' N ' parts ; If x % n == 0 then the minimum difference is 0 and all numbers are x / n ; upto n - ( x % n ) the values will be x / n after that the values will be x / n + 1 ; Driver code"
How can the above be solved in Java?

class GFG { static void split ( int x , int n ) { if ( x < n ) System . out . print ( " - 1 ▁ " ) ; else if ( x % n == 0 ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( ( x / n ) + " ▁ " ) ; } else { int zp = n - ( x % n ) ; int pp = x / n ; for ( int i = 0 ; i < n ; i ++ ) { if ( i >= zp ) System . out . print ( ( pp + 1 ) + " ▁ " ) ; else System . out . print ( pp + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int x = 5 ; int n = 3 ; split ( x , n ) ; } }


"Split the string into substrings using delimiter | Java implementation to split String into substrings on the basis of delimiter ; function to split String into subStrings on the basis of delimiter and return the subStrings after split ; to count the number of split Strings ; adding delimiter character at the end of ' str ' ; length of ' str ' ; traversing ' str ' from left to right ; if str [ i ] is not equal to the delimiter character then accumulate it to ' word ' ; if ' word ' is not an empty String , then add this ' word ' to the array ' substr _ list [ ] ' ; reset ' word ' ; return the splitted Strings ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static Vector < String > splitStrings ( String str , char dl ) { String word = " " ; int num = 0 ; str = str + dl ; int l = str . length ( ) ; Vector < String > substr_list = new Vector < String > ( ) ; for ( int i = 0 ; i < l ; i ++ ) { if ( str . charAt ( i ) != dl ) { word = word + str . charAt ( i ) ; } else { if ( ( int ) word . length ( ) != 0 ) { substr_list . add ( word ) ; } word = " " ; } } return substr_list ; } public static void main ( String [ ] args ) { String str = " geeks ; for ; geeks " ; char dl = ' ; ' ; Vector < String > res = splitStrings ( str , dl ) ; for ( String x : res ) { System . out . println ( x ) ; } } }


"Splitting a Numeric String | Java program to split a numeric string in an Increasing sequence if possible ; Function accepts a string and checks if string can be split . ; if there is only 1 number in the string then it is not possible to split it ; storing the substring from 0 to i + 1 to form initial number of the increasing sequence ; convert string to integer and add 1 and again convert back to string s2 ; if s2 is not a substring of number than not possible ; if s2 is the next substring of the numeric string ; Incearse num2 by 1 i . e the next number to be looked for ; check if string is fully traversed then break ; If next string doesnot occurs in a given numeric string then it is not possible ; if the string was fully traversed and conditions were satisfied ; if conditions failed to hold ; Driver Code ; Call the split function for splitting the string"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { public static void split ( String str ) { int len = str . length ( ) ; if ( len == 1 ) { System . out . println ( " Not ▁ Possible " ) ; return ; } String s1 = " " , s2 = " " ; long num1 , num2 ; for ( int i = 0 ; i <= len / 2 ; i ++ ) { int flag = 0 ; s1 = str . substring ( 0 , i + 1 ) ; num1 = Long . parseLong ( ( s1 ) ) ; num2 = num1 + 1 ; s2 = Long . toString ( num2 ) ; int k = i + 1 ; while ( flag == 0 ) { int l = s2 . length ( ) ; if ( k + l > len ) { flag = 1 ; break ; } if ( ( str . substring ( k , k + l ) . equals ( s2 ) ) ) { flag = 0 ; num2 ++ ; k = k + l ; if ( k == len ) break ; s2 = Long . toString ( num2 ) ; l = s2 . length ( ) ; if ( k + 1 > len ) { flag = 1 ; break ; } } else flag = 1 ; } if ( flag == 0 ) { System . out . println ( " Possible " + " ▁ " + s1 ) ; break ; } else if ( flag == 1 && i > len / 2 - 1 ) { System . out . println ( " Not ▁ Possible " ) ; break ; } } } public static void main ( String args [ ] ) { Scanner in = new Scanner ( System . in ) ; String str = "99100" ; split ( str ) ; } }


"Splitting starting N nodes into new Circular Linked List while preserving the old nodes | Java implementation of the approach ; Function to add a node to the empty list ; If not empty ; Creating a node dynamically ; Assigning the data ; Creating the link ; Function to add a node to the beginning of the list ; If list is empty ; Create node ; Assign data ; Function to traverse and print the list ; If list is empty ; Pointing to the first Node of the list ; Traversing the list ; Function to find the length of the CircularLinkedList ; Stores the length ; List is empty ; Iterator Node to traverse the List ; Return the length of the list ; Function to split the first k nodes into a new CircularLinkedList and the remaining nodes stay in the original CircularLinkedList ; Empty Node for reference ; Check if the list is empty If yes , then return null ; NewLast will contain the last node of the new split list itr to iterate the node till the required node ; Update NewLast to the required node and link the last to the start of rest of the list ; Return the last node of the required list ; Driver code ; Create a new list for the starting k nodes ; Append the new last node into the new list ; Print the new lists"
How can the above be solved in Java?

public class CircularLinkedList { Node last ; static class Node { int data ; Node next ; } ; public Node addToEmpty ( int data ) { if ( this . last != null ) return this . last ; Node temp = new Node ( ) ; temp . data = data ; this . last = temp ; this . last . next = this . last ; return last ; } public Node addBegin ( int data ) { if ( last == null ) return addToEmpty ( data ) ; Node temp = new Node ( ) ; temp . data = data ; temp . next = this . last . next ; this . last . next = temp ; return this . last ; } public void traverse ( ) { Node p ; if ( this . last == null ) { System . out . println ( " List ▁ is ▁ empty . " ) ; return ; } p = this . last . next ; do { System . out . print ( p . data + " ▁ " ) ; p = p . next ; } while ( p != this . last . next ) ; System . out . println ( " " ) ; } public int length ( ) { int x = 0 ; if ( this . last == null ) return x ; Node itr = this . last . next ; while ( itr . next != this . last . next ) { x ++ ; itr = itr . next ; } return ( x + 1 ) ; } public Node split ( int k ) { Node pass = new Node ( ) ; if ( this . last == null ) return this . last ; Node newLast , itr = this . last ; for ( int i = 0 ; i < k ; i ++ ) { itr = itr . next ; } newLast = itr ; pass . next = itr . next ; newLast . next = this . last . next ; this . last . next = pass . next ; return newLast ; } public static void main ( String [ ] args ) { CircularLinkedList clist = new CircularLinkedList ( ) ; clist . last = null ; clist . addToEmpty ( 12 ) ; clist . addBegin ( 10 ) ; clist . addBegin ( 8 ) ; clist . addBegin ( 6 ) ; clist . addBegin ( 4 ) ; clist . addBegin ( 2 ) ; System . out . println ( " Original ▁ list : " ) ; clist . traverse ( ) ; int k = 4 ; CircularLinkedList clist2 = new CircularLinkedList ( ) ; clist2 . last = clist . split ( k ) ; System . out . println ( " The ▁ new ▁ lists ▁ are : " ) ; clist2 . traverse ( ) ; clist . traverse ( ) ; } }


"Spt function or Smallest Parts Function of a given number | Java implementation to find the Spt Function to given number ; Variable to store spt function of a number ; Find the value of frequency of minimum element ; Function to add value of frequency of minimum element among all representations of n ; Find the value of frequency of minimum element ; Calculate spt ; Recursive function to find different ways in which n can be written as a sum of at one or more positive integers ; If sum becomes n , consider this representation ; Start from previous element in the representation till n ; Include current element from representation ; Call function again with reduced sum ; backtrack - remove current element from representation ; Function to find the spt function ; Using recurrence find different ways in which n can be written as a sum of at 1 or more positive integers ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int spt = 0 ; static int count ( Vector < Integer > arr , int min_i ) { int count = 0 ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) if ( min_i == arr . get ( i ) ) count ++ ; return count ; } static void printVector ( Vector < Integer > arr ) { int min_i = Integer . MAX_VALUE ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) min_i = Math . min ( min_i , arr . elementAt ( i ) ) ; int freq = count ( arr , min_i ) ; spt += freq ; } static void findWays ( Vector < Integer > arr , int i , int n ) { if ( n == 0 ) printVector ( arr ) ; for ( int j = i ; j <= n ; j ++ ) { arr . add ( j ) ; findWays ( arr , j , n - j ) ; arr . remove ( arr . size ( ) - 1 ) ; } } static void spt_function ( int n ) { Vector < Integer > arr = new Vector < > ( ) ; findWays ( arr , 1 , n ) ; System . out . print ( spt ) ; } public static void main ( String [ ] args ) { int N = 4 ; spt_function ( N ) ; } }


"Sqrt ( or Square Root ) Decomposition Technique | Set 1 ( Introduction ) | Java program to demonstrate working of Square Root Decomposition . ; original array ; decomposed array ; block size ; Time Complexity : O ( 1 ) ; Time Complexity : O ( sqrt ( n ) ) ; traversing first block in range ; traversing completely overlapped blocks in range ; traversing last block in range ; Fills values in input [ ] ; initiating block pointer ; calculating size of block ; building the decomposed array ; entering next block incementing block pointer ; Driver code ; We have used separate array for input because the purpose of this code is to explain SQRT decomposition in competitive programming where we have multiple inputs ."
How can the above be solved in Java?

import java . util . * ; class GFG { static int MAXN = 10000 ; static int SQRSIZE = 100 ; static int [ ] arr = new int [ MAXN ] ; static int [ ] block = new int [ SQRSIZE ] ; static int blk_sz ; static void update ( int idx , int val ) { int blockNumber = idx / blk_sz ; block [ blockNumber ] += val - arr [ idx ] ; arr [ idx ] = val ; } static int query ( int l , int r ) { int sum = 0 ; while ( l < r && l % blk_sz != 0 && l != 0 ) { sum += arr [ l ] ; l ++ ; } while ( l + blk_sz <= r ) { sum += block [ l / blk_sz ] ; l += blk_sz ; } while ( l <= r ) { sum += arr [ l ] ; l ++ ; } return sum ; } static void preprocess ( int input [ ] , int n ) { int blk_idx = - 1 ; blk_sz = ( int ) Math . sqrt ( n ) ; for ( int i = 0 ; i < n ; i ++ ) { arr [ i ] = input [ i ] ; if ( i % blk_sz == 0 ) { blk_idx ++ ; } block [ blk_idx ] += arr [ i ] ; } } public static void main ( String [ ] args ) { int input [ ] = { 1 , 5 , 2 , 4 , 6 , 1 , 3 , 5 , 7 , 10 } ; int n = input . length ; preprocess ( input , n ) ; System . out . println ( " query ( 3 , ▁ 8 ) ▁ : ▁ " + query ( 3 , 8 ) ) ; System . out . println ( " query ( 1 , ▁ 6 ) ▁ : ▁ " + query ( 1 , 6 ) ) ; update ( 8 , 0 ) ; System . out . println ( " query ( 8 , ▁ 8 ) ▁ : ▁ " + query ( 8 , 8 ) ) ; } }


"Square Free Number | Java Program to print all prime factors ; Returns true if n is a square free number , else returns false . ; If 2 again divides n , then n is not a square free number . ; n must be odd at this point . So we can skip one element ( Note i = i + 2 ) ; Check if i is a prime factor ; If i again divides , then n is not square free ; Driver program to test above function"
How can the above be solved in Java?

class GFG { static boolean isSquareFree ( int n ) { if ( n % 2 == 0 ) n = n / 2 ; if ( n % 2 == 0 ) return false ; for ( int i = 3 ; i <= Math . sqrt ( n ) ; i = i + 2 ) { if ( n % i == 0 ) { n = n / i ; if ( n % i == 0 ) return false ; } } return true ; } public static void main ( String [ ] args ) { int n = 10 ; if ( isSquareFree ( n ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Square of large number represented as String | Java program to multiply two numbers represented as strings . ; Multiplies str1 and str2 , and prints result . ; will keep the result number in vector in reverse order ; Below two indexes are used to find positions in result . ; Go from right to left in num1 ; To shift position to left after every multiplication of a digit in num2 ; Go from right to left in num2 ; Take current digit of second number ; Multiply with current digit of first number and add result to previously stored result at current position . ; Carry for next iteration ; Store result ; store carry in next cell ; To shift position to left after every multiplication of a digit in num1 . ; ignore '0' s from the right ; If all were '0' s - means either both or one of num1 or num2 were '0' ; generate the result string ; Driver code"
How can the above be solved in Java?

class GFG { public static String multiply ( String num1 , String num2 ) { int n1 = num1 . length ( ) ; int n2 = num2 . length ( ) ; if ( n1 == 0 n2 == 0 ) return "0" ; int [ ] result = new int [ n1 + n2 ] ; int i_n1 = 0 ; int i_n2 = 0 ; for ( int i = n1 - 1 ; i >= 0 ; i -- ) { int carry = 0 ; int n_1 = num1 . charAt ( i ) - '0' ; i_n2 = 0 ; for ( int j = n2 - 1 ; j >= 0 ; j -- ) { int n_2 = num2 . charAt ( j ) - '0' ; int sum = n_1 * n_2 + result [ i_n1 + i_n2 ] + carry ; carry = sum / 10 ; result [ i_n1 + i_n2 ] = sum % 10 ; i_n2 ++ ; } if ( carry > 0 ) result [ i_n1 + i_n2 ] += carry ; i_n1 ++ ; } int i = result . length - 1 ; while ( i >= 0 && result [ i ] == 0 ) i -- ; if ( i == - 1 ) return "0" ; String s = " " ; while ( i >= 0 ) s += Integer . toString ( result [ i -- ] ) ; return s ; } public static void main ( String [ ] args ) { String str1 = "454545454545454545" ; System . out . println ( multiply ( str1 , str1 ) ) ; } }


"Square root of a number by Repeated Subtraction method | Java implementation of the above approach ; Function to return the square root of the given number ; Subtract n - th odd number ; Return the result ; Driver code"
How can the above be solved in Java?

class GFG { public static int SquareRoot ( int num ) { int count = 0 ; for ( int n = 1 ; n <= num ; n += 2 ) { num = num - n ; count += 1 ; if ( num == 0 ) break ; } return count ; } public static void main ( String [ ] args ) { int N = 81 ; System . out . println ( SquareRoot ( N ) ) ; } }


"Square root of a number using log | Java program to demonstrate finding square root of a number using sqrt ( )"
How can the above be solved in Java?

import java . io . * ; class GFG { public static void main ( String [ ] args ) { double n = 12 ; System . out . println ( Math . sqrt ( n ) ) ; } }


"Square root of a number without using sqrt ( ) function | Java implementation of the approach ; Recursive function that returns square root of a number with precision upto 5 decimal places ; If mid itself is the square root , return mid ; If mul is less than n , recur second half ; Else recur first half ; Function to find the square root of n ; While the square root is not found ; If n is a perfect square ; Square root will lie in the interval i - 1 and i ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static double Square ( double n , double i , double j ) { double mid = ( i + j ) / 2 ; double mul = mid * mid ; if ( ( mul == n ) || ( Math . abs ( mul - n ) < 0.00001 ) ) return mid ; else if ( mul < n ) return Square ( n , mid , j ) ; else return Square ( n , i , mid ) ; } static void findSqrt ( double n ) { double i = 1 ; boolean found = false ; while ( ! found ) { if ( i * i == n ) { System . out . println ( i ) ; found = true ; } else if ( i * i > n ) { double res = Square ( n , i - 1 , i ) ; System . out . printf ( " % .5f " , res ) ; found = true ; } i ++ ; } } public static void main ( String [ ] args ) { double n = 3 ; findSqrt ( n ) ; } }


"Square root of an integer | A Java program to find floor ( sqrt ( x ) ) ; Returns floor of square root of x ; Base cases ; Starting from 1 , try all numbers until i * i is greater than or equal to x . ; Driver program"
How can the above be solved in Java?

class GFG { static int floorSqrt ( int x ) { if ( x == 0 x == 1 ) return x ; int i = 1 , result = 1 ; while ( result <= x ) { i ++ ; result = i * i ; } return i - 1 ; } public static void main ( String [ ] args ) { int x = 11 ; System . out . print ( floorSqrt ( x ) ) ; } }


"Square root of an integer | A Java program to find floor ( sqrt ( x ) ; Base Cases ; Do Binary Search for floor ( sqrt ( x ) ) ; If x is a perfect square ; Since we need floor , we update answer when mid * mid is smaller than x , and move closer to sqrt ( x ) ; else If mid * mid is greater than x ; Driver Method"
How can the above be solved in Java?

public class Test { public static int floorSqrt ( int x ) { if ( x == 0 x == 1 ) return x ; long start = 1 , end = x , ans = 0 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; if ( mid * mid == x ) return ( int ) mid ; if ( mid * mid < x ) { start = mid + 1 ; ans = mid ; } end = mid - 1 ; } return ( int ) ans ; } public static void main ( String args [ ] ) { int x = 11 ; System . out . println ( floorSqrt ( x ) ) ; } }


"Square root of two Complex Numbers | Java program for the above approach ; Function to find the square root of a complex number ; Stores all the square roots ; Stores the first square root ; Push the square root in the ans ; Stores the second square root ; If X2 is not 0 ; Push the square root in the array ans [ ] ; Stores the third square root ; If X3 is greater than 0 ; Push the square root in the array ans [ ] ; Stores the fourth square root ; Push the square root in the array ans [ ] ; Prints the square roots ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static class pair { double first , second ; public pair ( double first , double second ) { this . first = first ; this . second = second ; } } static void complexRoot ( int A , int B ) { Vector < pair > ans = new Vector < pair > ( ) ; double X1 = Math . abs ( Math . sqrt ( ( A + Math . sqrt ( A * A + B * B ) ) / 2 ) ) ; double Y1 = B / ( 2 * X1 ) ; ans . add ( new pair ( X1 , Y1 ) ) ; double X2 = - 1 * X1 ; double Y2 = B / ( 2 * X2 ) ; if ( X2 != 0 ) { ans . add ( new pair ( X2 , Y2 ) ) ; } double X3 = ( A - Math . sqrt ( A * A + B * B ) ) / 2 ; if ( X3 > 0 ) { X3 = Math . abs ( Math . sqrt ( X3 ) ) ; double Y3 = B / ( 2 * X3 ) ; ans . add ( new pair ( X3 , Y3 ) ) ; double X4 = - 1 * X3 ; double Y4 = B / ( 2 * X4 ) ; if ( X4 != 0 ) { ans . add ( new pair ( X4 , Y4 ) ) ; } } System . out . print ( " The ▁ Square ▁ roots ▁ are : ▁ " + "
"); for ( pair p : ans ) { System . out . printf ( " % .4f " , p . first ) ; if ( p . second > 0 ) System . out . print ( " + " ) ; if ( p . second != 0 ) System . out . printf ( "%.4f*i
", p.second); else System . out . println ( ) ; } } public static void main ( String [ ] args ) { int A = 0 , B = 1 ; complexRoot ( A , B ) ; } }


"Squared triangular number ( Sum of cubes ) | Java program to check if a given number is sum of cubes of natural numbers . ; Function to find if the given number is sum of the cubes of first n natural numbers ; Start adding cubes of the numbers from 1 ; If sum becomes equal to s return n ; Drivers code"
How can the above be solved in Java?

class GFG { static int findS ( int s ) { int sum = 0 ; for ( int n = 1 ; sum < s ; n ++ ) { sum += n * n * n ; if ( sum == s ) return n ; } return - 1 ; } public static void main ( String [ ] args ) { int s = 9 ; int n = findS ( s ) ; if ( n == - 1 ) System . out . println ( " - 1" ) ; else System . out . println ( n ) ; } }


"Squared triangular number ( Sum of cubes ) | Java program to check if a given number is sum of cubes of natural numbers . import java . Math . * ; ; Returns root of n ( n + 1 ) / 2 = num if num is triangular ( orinteger root exists ) . Else returns - 1. ; Considering the equation n * ( n + 1 ) / 2 = num . The equation is : a ( n ^ 2 ) + bn + c = 0 "; ; Find roots of equation ; checking if root1 is natural ; checking if root2 is natural ; Returns square root of x if it is perfect square . Else returns - 1. ; Find floating point value of square root of x . ; If square root is an integer ; Function to find if the given number is sum of the cubes of first n natural numbers ; Driver code"
How can the above be solved in Java?

class GFG { public static int isTriangular ( int num ) { if ( num < 0 ) return 0 ; int c = ( - 2 * num ) ; int b = 1 , a = 1 ; int d = ( b * b ) - ( 4 * a * c ) ; if ( d < 0 ) return - 1 ; double root1 = ( - b + Math . sqrt ( d ) ) / ( 2 * a ) ; double root2 = ( - b - Math . sqrt ( d ) ) / ( 2 * a ) ; if ( ( int ) ( root1 ) > 0 && ( int ) ( Math . floor ( root1 ) ) == ( int ) ( root1 ) ) return ( int ) ( root1 ) ; if ( ( int ) ( root2 ) > 0 && ( int ) ( Math . floor ( root2 ) ) == ( int ) ( root2 ) ) return ( int ) ( root2 ) ; return - 1 ; } static int isPerfectSquare ( double x ) { double sr = Math . sqrt ( x ) ; if ( ( sr - Math . floor ( sr ) ) == 0 ) return ( int ) ( Math . floor ( sr ) ) ; else return - 1 ; } static int findS ( int s ) { int sr = isPerfectSquare ( s ) ; if ( sr == - 1 ) return - 1 ; return isTriangular ( sr ) ; } public static void main ( String [ ] args ) { int s = 9 ; int n = findS ( s ) ; if ( n == - 1 ) System . out . println ( " - 1" ) ; else System . out . println ( n ) ; } }


"Squareroot ( n ) | Java program to find sqrt ( n ) 'th node  of a linked list  ; Linked list node ; Function to get the sqrt ( n ) th node of a linked list ; Traverse the list ; check if j = sqrt ( i ) ; for first node ; increment j if j = sqrt ( i ) ; return node 's data  ; function to add a new node at the beginning of the list ; allocate node ; put in the data ; link the old list off the new node ; move the head to point to the new node ; Driver code ; Start with the empty list"
How can the above be solved in Java?

class GfG { static class Node { int data ; Node next ; } static Node head = null ; static int printsqrtn ( Node head ) { Node sqrtn = null ; int i = 1 , j = 1 ; while ( head != null ) { if ( i == j * j ) { if ( sqrtn == null ) sqrtn = head ; else sqrtn = sqrtn . next ; j ++ ; } i ++ ; head = head . next ; } return sqrtn . data ; } static void print ( Node head ) { while ( head != null ) { System . out . print ( head . data + " ▁ " ) ; head = head . next ; } System . out . println ( ) ; } static void push ( int new_data ) { Node new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = head ; head = new_node ; } public static void main ( String [ ] args ) { push ( 40 ) ; push ( 30 ) ; push ( 20 ) ; push ( 10 ) ; System . out . print ( " Given ▁ linked ▁ list ▁ is : " ) ; print ( head ) ; System . out . print ( " sqrt ( n ) th ▁ node ▁ is ▁ " + printsqrtn ( head ) ) ; } }


"Stable sort for descending order | Bubble sort implementation to sort elements in descending order . ; Sorts a [ ] in descending order using bubble sort . ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void print ( ArrayList < Integer > a , int n ) { for ( int i = 0 ; i <= n ; i ++ ) System . out . print ( a . get ( i ) + " ▁ " ) ; System . out . println ( ) ; } static void sort ( ArrayList < Integer > a , int n ) { for ( int i = n ; i >= 0 ; i -- ) for ( int j = n ; j > n - i ; j -- ) if ( a . get ( j ) > a . get ( j - 1 ) ) { int tempswap = a . get ( j ) ; a . remove ( j ) ; a . add ( j , a . get ( j - 1 ) ) ; a . remove ( j - 1 ) ; a . add ( j - 1 , tempswap ) ; } print ( a , n ) ; } public static void main ( String [ ] args ) { int n = 6 ; ArrayList < Integer > a = new ArrayList < Integer > ( ) ; a . add ( 2 ) ; a . add ( 4 ) ; a . add ( 3 ) ; a . add ( 2 ) ; a . add ( 4 ) ; a . add ( 5 ) ; a . add ( 3 ) ; sort ( a , n ) ; } }


"Stable sort for descending order | Java program to demonstrate descending order stable sort using greater < > ( ) . ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void reverse ( int a [ ] ) { int i , k , n = a . length ; int t ; for ( i = 0 ; i < n / 2 ; i ++ ) { t = a [ i ] ; a [ i ] = a [ n - i - 1 ] ; a [ n - i - 1 ] = t ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 5 , 8 , 9 , 6 , 7 , 3 , 4 , 2 , 0 } ; int n = arr . length ; Arrays . sort ( arr ) ; reverse ( arr ) ; System . out . println ( "Array after sorting :
"); for ( int i = 0 ; i < n ; ++ i ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } }


"Stein 's Algorithm for finding GCD | Iterative Java program to implement Stein 's Algorithm ; Function to implement Stein 's  Algorithm ; GCD ( 0 , b ) == b ; GCD ( a , 0 ) == a , GCD ( 0 , 0 ) == 0 ; Finding K , where K is the greatest power of 2 that divides both a and b ; Dividing a by 2 until a becomes odd ; From here on , ' a ' is always odd . ; If b is even , remove all factor of 2 in b ; Now a and b are both odd . Swap if necessary so a <= b , then set b = b - a ( which is even ) ; restore common factors of 2 ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int gcd ( int a , int b ) { if ( a == 0 ) return b ; if ( b == 0 ) return a ; int k ; for ( k = 0 ; ( ( a b ) & 1 ) == 0 ; ++ k ) { a >>= 1 ; b >>= 1 ; } while ( ( a & 1 ) == 0 ) a >>= 1 ; do { while ( ( b & 1 ) == 0 ) b >>= 1 ; if ( a > b ) { int temp = a ; a = b ; b = temp ; } b = ( b - a ) ; } while ( b != 0 ) ; return a << k ; } public static void main ( String args [ ] ) { int a = 34 , b = 17 ; System . out . println ( " Gcd ▁ of ▁ given ▁ " + " numbers ▁ is ▁ " + gcd ( a , b ) ) ; } }


"Stein 's Algorithm for finding GCD | Recursive Java program to implement Stein 's Algorithm ; Function to implement Stein 's Algorithm ; GCD ( 0 , b ) == b ; GCD ( a , 0 ) == a , GCD ( 0 , 0 ) == 0 ; look for factors of 2 if ( ( ~ a & 1 ) == 1 ) a is even ; if ( ( b & 1 ) == 1 ) b is odd ; else both a and b are even ; a is odd , b is even ; reduce larger number ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int gcd ( int a , int b ) { if ( a == b ) return a ; if ( a == 0 ) return b ; if ( b == 0 ) return a ; { return gcd ( a >> 1 , b ) ; return gcd ( a >> 1 , b >> 1 ) << 1 ; } if ( ( ~ b & 1 ) == 1 ) return gcd ( a , b >> 1 ) ; if ( a > b ) return gcd ( ( a - b ) >> 1 , b ) ; return gcd ( ( b - a ) >> 1 , a ) ; } public static void main ( String args [ ] ) { int a = 34 , b = 17 ; System . out . println ( " Gcd ▁ of ▁ given " + " numbers ▁ is ▁ " + gcd ( a , b ) ) ; } }


"Stella Octangula Number | Program to check if a number is Stella Octangula Number ; Returns value of n * ( 2 * n * n - 1 ) ; Finds if a value of f ( n ) is equal to x where n is in interval [ low . . high ] ; Returns true if x is Stella Octangula Number . Else returns false . ; Find ' high ' for binary search by repeated doubling ; If condition is satisfied for a power of 2. ; Call binary search ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int f ( int n ) { return n * ( 2 * n * n - 1 ) ; } static boolean binarySearch ( int low , int high , int x ) { while ( low <= high ) { int mid = ( low + high ) / 2 ; if ( f ( mid ) < x ) low = mid + 1 ; else if ( f ( mid ) > x ) high = mid - 1 ; else return true ; } return false ; } static boolean isStellaOctangula ( int x ) { if ( x == 0 ) return true ; int i = 1 ; while ( f ( i ) < x ) i = i * 2 ; if ( f ( i ) == x ) return true ; return binarySearch ( i / 2 , i , x ) ; } public static void main ( String [ ] args ) { int n = 51 ; if ( isStellaOctangula ( n ) ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } }


"Stepping Numbers | A Java program to find all the Stepping Number in [ n , m ] ; This Method checks if an integer n is a Stepping Number ; Initalize prevDigit with - 1 ; Iterate through all digits of n and compare difference between value of previous and current digits ; Get Current digit ; Single digit is consider as a Stepping Number ; Check if absolute difference between prev digit and current digit is 1 ; A brute force approach based function to find all stepping numbers . ; Iterate through all the numbers from [ N , M ] and check if it is a stepping number . ; Driver code ; Display Stepping Numbers in the range [ n , m ]"
How can the above be solved in Java?

class Main { public static boolean isStepNum ( int n ) { int prevDigit = - 1 ; while ( n > 0 ) { int curDigit = n % 10 ; if ( prevDigit != - 1 ) { if ( Math . abs ( curDigit - prevDigit ) != 1 ) return false ; } n /= 10 ; prevDigit = curDigit ; } return true ; } public static void displaySteppingNumbers ( int n , int m ) { for ( int i = n ; i <= m ; i ++ ) if ( isStepNum ( i ) ) System . out . print ( i + " ▁ " ) ; } public static void main ( String args [ ] ) { int n = 0 , m = 21 ; displaySteppingNumbers ( n , m ) ; } }


"Stepping Numbers | A Java program to find all the Stepping Number in range [ n , m ] ; Prints all stepping numbers reachable from num and in range [ n , m ] ; Queue will contain all the stepping Numbers ; Get the front element and pop from the queue ; If the Stepping Number is in the range [ n , m ] then display ; If Stepping Number is 0 or greater then m , no need to explore the neighbors ; Get the last digit of the currently visited Stepping Number ; There can be 2 cases either digit to be appended is lastDigit + 1 or lastDigit - 1 ; If lastDigit is 0 then only possible digit after 0 can be 1 for a Stepping Number ; If lastDigit is 9 then only possible digit after 9 can be 8 for a Stepping Number ; Prints all stepping numbers in range [ n , m ] using BFS . ; For every single digit Number ' i ' find all the Stepping Numbers starting with i ; Driver code ; Display Stepping Numbers in the range [ n , m ]"
How can the above be solved in Java?

import java . util . * ; class Main { public static void bfs ( int n , int m , int num ) { Queue < Integer > q = new LinkedList < Integer > ( ) ; q . add ( num ) ; while ( ! q . isEmpty ( ) ) { int stepNum = q . poll ( ) ; if ( stepNum <= m && stepNum >= n ) { System . out . print ( stepNum + " ▁ " ) ; } if ( stepNum == 0 stepNum > m ) continue ; int lastDigit = stepNum % 10 ; int stepNumA = stepNum * 10 + ( lastDigit - 1 ) ; int stepNumB = stepNum * 10 + ( lastDigit + 1 ) ; if ( lastDigit == 0 ) q . add ( stepNumB ) ; else if ( lastDigit == 9 ) q . add ( stepNumA ) ; else { q . add ( stepNumA ) ; q . add ( stepNumB ) ; } } } public static void displaySteppingNumbers ( int n , int m ) { for ( int i = 0 ; i <= 9 ; i ++ ) bfs ( n , m , i ) ; } public static void main ( String args [ ] ) { int n = 0 , m = 21 ; displaySteppingNumbers ( n , m ) ; } }


"Stepping Numbers | A Java program to find all the Stepping Numbers in range [ n , m ] using DFS Approach ; Method display 's all the stepping numbers  in range [n, m] ; If Stepping Number is in the range [ n , m ] then display ; If Stepping Number is 0 or greater than m then return ; Get the last digit of the currently visited Stepping Number ; There can be 2 cases either digit to be appended is lastDigit + 1 or lastDigit - 1 ; If lastDigit is 0 then only possible digit after 0 can be 1 for a Stepping Number ; If lastDigit is 9 then only possible digit after 9 can be 8 for a Stepping Number ; Prints all stepping numbers in range [ n , m ] using DFS . ; For every single digit Number ' i ' find all the Stepping Numbers starting with i ; Driver code ; Display Stepping Numbers in the range [ n , m ]"
How can the above be solved in Java?

import java . util . * ; class Main { public static void dfs ( int n , int m , int stepNum ) { if ( stepNum <= m && stepNum >= n ) System . out . print ( stepNum + " ▁ " ) ; if ( stepNum == 0 stepNum > m ) return ; int lastDigit = stepNum % 10 ; int stepNumA = stepNum * 10 + ( lastDigit - 1 ) ; int stepNumB = stepNum * 10 + ( lastDigit + 1 ) ; if ( lastDigit == 0 ) dfs ( n , m , stepNumB ) ; else if ( lastDigit == 9 ) dfs ( n , m , stepNumA ) ; else { dfs ( n , m , stepNumA ) ; dfs ( n , m , stepNumB ) ; } } public static void displaySteppingNumbers ( int n , int m ) { for ( int i = 0 ; i <= 9 ; i ++ ) dfs ( n , m , i ) ; } public static void main ( String args [ ] ) { int n = 0 , m = 21 ; displaySteppingNumbers ( n , m ) ; } }


"Steps required to visit M points in order on a circular ring of N points | Java implementation of the approach ; Function to count the steps required ; Start at 1 ; Initialize steps ; If nxt is greater than cur ; Now we are at a [ i ] ; Driver code"
How can the above be solved in Java?

class GFG { static int findSteps ( int n , int m , int a [ ] ) { int cur = 1 ; int steps = 0 ; for ( int i = 0 ; i < m ; i ++ ) { if ( a [ i ] >= cur ) steps += ( a [ i ] - cur ) ; else steps += ( n - cur + a [ i ] ) ; cur = a [ i ] ; } return steps ; } public static void main ( String [ ] args ) { int n = 3 , m = 3 ; int a [ ] = { 2 , 1 , 2 } ; System . out . println ( findSteps ( n , m , a ) ) ; } }


"Steps to reduce N to zero by subtracting its most significant digit at every step | Java program to find the count of Steps to reduce N to zero by subtracting its most significant digit at every step ; Function to count the number of digits in a number m ; Function to count the number of steps to reach 0 ; count the total number of stesp ; iterate till we reach 0 ; count the digits in last ; decrease it by 1 ; find the number on whose division , we get the first digit ; first digit in last ; find the first number less than last where the first digit changes ; find the number of numbers with same first digit that are jumped ; count the steps ; the next number with a different first digit ; Driver code"
How can the above be solved in Java?

class GFG { static int countdig ( int m ) { if ( m == 0 ) return 0 ; else return 1 + countdig ( m / 10 ) ; } static int countSteps ( int x ) { int c = 0 ; int last = x ; while ( last > 0 ) { int digits = countdig ( last ) ; digits -= 1 ; int divisor = ( int ) Math . pow ( 10 , digits ) ; int first = last / divisor ; int lastnumber = first * divisor ; int skipped = ( last - lastnumber ) / first ; skipped += 1 ; c += skipped ; last = last - ( first * skipped ) ; } return c ; } public static void main ( String [ ] args ) { int n = 14 ; System . out . println ( countSteps ( n ) ) ; } }


"Stern | Java program to print Brocot Sequence ; loop to create sequence ; adding sum of considered element and it 's precedent ; adding next considered element ; printing sequence . . ; Driver code ; adding first two element in the sequence"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void SternSequenceFunc ( Vector < Integer > BrocotSequence , int n ) { for ( int i = 1 ; BrocotSequence . size ( ) < n ; i ++ ) { int considered_element = BrocotSequence . get ( i ) ; int precedent = BrocotSequence . get ( i - 1 ) ; BrocotSequence . add ( considered_element + precedent ) ; BrocotSequence . add ( considered_element ) ; } for ( int i = 0 ; i < 15 ; ++ i ) System . out . print ( BrocotSequence . get ( i ) + " ▁ " ) ; } public static void main ( String [ ] args ) { int n = 15 ; Vector < Integer > BrocotSequence = new Vector < Integer > ( ) ; BrocotSequence . add ( 1 ) ; BrocotSequence . add ( 1 ) ; SternSequenceFunc ( BrocotSequence , n ) ; } }


"Stooge Sort | Java program to implement stooge sort ; Function to implement stooge sort ; If first element is smaller than last , swap them ; If there are more than 2 elements in the array ; Recursively sort first 2 / 3 elements ; Recursively sort last 2 / 3 elements ; Recursively sort first 2 / 3 elements again to confirm ; Driver Code ; Calling Stooge Sort function to sort the array ; Display the sorted array"
How can the above be solved in Java?

import java . io . * ; public class stooge { static void stoogesort ( int arr [ ] , int l , int h ) { if ( l >= h ) return ; if ( arr [ l ] > arr [ h ] ) { int t = arr [ l ] ; arr [ l ] = arr [ h ] ; arr [ h ] = t ; } if ( h - l + 1 > 2 ) { int t = ( h - l + 1 ) / 3 ; stoogesort ( arr , l , h - t ) ; stoogesort ( arr , l + t , h ) ; stoogesort ( arr , l , h - t ) ; } } public static void main ( String args [ ] ) { int arr [ ] = { 2 , 4 , 5 , 3 , 1 } ; int n = arr . length ; stoogesort ( arr , 0 , n - 1 ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } }


"Straight | Java program for the above approach ; Function to check if N is a Straight Line number or not ; N must be > 99 ; Difference between consecutive digits must be same ; Driver code ; Given Number N ; Function Call"
How can the above be solved in Java?

class GFG { static boolean isStraighLineNum ( int N ) { if ( N <= 99 ) return false ; String s = Integer . toString ( N ) ; int d = s . charAt ( 1 ) - s . charAt ( 0 ) ; for ( int i = 2 ; i < s . length ( ) ; i ++ ) if ( s . charAt ( i ) - s . charAt ( i - 1 ) != d ) return false ; return true ; } public static void main ( String [ ] args ) { int n = 135 ; if ( isStraighLineNum ( n ) ) { System . out . println ( " Yes " ) ; } else { System . out . println ( " No " ) ; } } }


"String formed with middle character of every right substring followed by left sequentially | Java implementation of the above approach ; Function to decrypt and print the new String ; If the whole String has been traversed ; To calculate middle index of the String ; Print the character at middle index ; Recursively call for right - subString ; Recursive call for left - subString ; Driver Code"
How can the above be solved in Java?

 class GFG { static void decrypt ( String Str , int Start , int End ) { if ( Start > End ) { return ; } int mid = ( Start + End ) >> 1 ; System . out . print ( Str . charAt ( mid ) ) ; decrypt ( Str , mid + 1 , End ) ; decrypt ( Str , Start , mid - 1 ) ; } public static void main ( String [ ] args ) { int N = 4 ; String Str = " abcd " ; decrypt ( Str , 0 , N - 1 ) ; System . out . print ( "
"); N = 6 ; Str = " gyuitp " ; decrypt ( Str , 0 , N - 1 ) ; } }


"String hashing using Polynomial rolling hash function | Java implementation of the Polynomial Rolling Hash Function ; Function to calculate the hash of a String ; P and M ; Loop to calculate the hash value by iterating over the elements of String ; Driver Code ; Given Strings"
How can the above be solved in Java?

class GFG { static long polynomialRollingHash ( String str ) { int p = 31 ; int m = ( int ) ( 1e9 + 9 ) ; long power_of_p = 1 ; long hash_val = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { hash_val = ( hash_val + ( str . charAt ( i ) - ' a ' + 1 ) * power_of_p ) % m ; power_of_p = ( power_of_p * p ) % m ; } return hash_val ; } public static void main ( String [ ] args ) { String str1 = " geeksforgeeks " ; String str2 = " geeks " ; System . out . print ( " Hash ▁ of ▁ ' " + str1 + " ' ▁ = ▁ " + polynomialRollingHash ( str1 ) ) ; } }


"String matching with * ( that matches with any ) in any of the two strings | Java program for string matching with * ; Function to check if the two strings can be matched or not ; if the string don 't have *  then character at that position  must be same. ; Driver code"
How can the above be solved in Java?

import java . util . * ; public class GfG { public static int doMatch ( String A , String B ) { for ( int i = 0 ; i < A . length ( ) ; i ++ ) { if ( A . charAt ( i ) != ' * ' && B . charAt ( i ) != ' * ' ) { if ( A . charAt ( i ) != B . charAt ( i ) ) return 0 ; } } return 1 ; } public static void main ( String [ ] args ) { String A = " gee * sforgeeks " ; String B = " geeksforgeeks " ; System . out . println ( doMatch ( A , B ) ) ; } }


"String transformation using XOR and OR | Java program to check if string1 can be converted to string2 using XOR and OR operations ; function to check if conversion is possible or not ; if lengths are different ; iterate to check if both strings have 1 ; to check if there is even one 1 in string s1 ; to check if there is even one 1 in string s2 ; if both strings have only '0' ; if both string do not have a '1' . ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static boolean solve ( String s1 , String s2 ) { boolean flag1 = false , flag2 = false ; if ( s1 . length ( ) != s2 . length ( ) ) return false ; int l = s1 . length ( ) ; for ( int i = 0 ; i < l ; i ++ ) { if ( s1 . charAt ( i ) == '1' ) flag1 = true ; if ( s2 . charAt ( i ) == '1' ) flag2 = true ; if ( flag1 == true && flag2 == true ) return true ; } if ( ! flag1 && ! flag2 ) return true ; return false ; } public static void main ( String args [ ] ) { String s1 = "100101" ; String s2 = "100000" ; if ( solve ( s1 , s2 ) == true ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } }


"String which when repeated exactly K times gives a permutation of S | Java program to find a string which when repeated exactly k times gives a permutation of the given string ; Function to return a string which when repeated exactly k times gives a permutation of s ; size of string ; to frequency of each character ; get frequency of each character ; to store final answer ; check if frequency is divisible by k ; add to answer ; if frequency is not divisible by k ; Driver code ; function call"
How can the above be solved in Java?

class GfG { static String K_String ( String s , int k ) { int n = s . length ( ) ; int fre [ ] = new int [ 26 ] ; for ( int i = 0 ; i < n ; i ++ ) fre [ s . charAt ( i ) - ' a ' ] ++ ; String str = " " ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( fre [ i ] % k == 0 ) { int x = fre [ i ] / k ; while ( x != 0 ) { str += ( char ) ( i + ' a ' ) ; x -- ; } } else { return " - 1" ; } } return str ; } public static void main ( String [ ] args ) { String s = " aabb " ; int k = 2 ; System . out . println ( K_String ( s , k ) ) ; } }


"String with k distinct characters and no same characters adjacent | Java program to construct a n length string with k distinct characters such that no two same characters are adjacent . ; Function to find a string of length n with k distinct characters . ; Initialize result with first k Latin letters ; Fill remaining n - k letters by repeating k letters again and again . ; Driver code"
How can the above be solved in Java?

import java . io . * ; public class GFG { static String findString ( int n , int k ) { String res = " " ; for ( int i = 0 ; i < k ; i ++ ) res = res + ( char ) ( ' a ' + i ) ; int count = 0 ; for ( int i = 0 ; i < n - k ; i ++ ) { res = res + ( char ) ( ' a ' + count ) ; count ++ ; if ( count == k ) count = 0 ; } return res ; } static public void main ( String [ ] args ) { int n = 5 , k = 2 ; System . out . println ( findString ( n , k ) ) ; } }


"String with maximum number of unique characters | Java code to find the largest string ; Function to find string with maximum number of unique characters . ; Index of string with maximum unique characters ; iterate through all strings ; array indicating any alphabet included or not included ; count number of unique alphabets in each string ; keep track of maximum number of alphabets ; print result ; Driver code"
How can the above be solved in Java?

import java . lang . * ; import java . io . * ; import java . util . Arrays ; class Geek { public static void LargestString ( String na [ ] ) { int N = na . length ; int c [ ] = new int [ N ] ; int m = 0 ; for ( int j = 0 ; j < N ; j ++ ) { boolean character [ ] = new boolean [ 26 ] ; for ( int k = 0 ; k < na [ j ] . length ( ) ; k ++ ) { int x = na [ j ] . charAt ( k ) - ' A ' ; if ( ( na [ j ] . charAt ( k ) != ' ▁ ' ) && ( character [ x ] == false ) ) { c [ j ] ++ ; character [ x ] = true ; } } if ( c [ j ] > c [ m ] ) m = j ; } System . out . println ( na [ m ] ) ; } public static void main ( String [ ] args ) { String na [ ] = { " BOB " , " A ▁ AB ▁ C ▁ JOHNSON " , " ANJALI " , " ASKRIT " , " ARMAN ▁ MALLIK " } ; LargestString ( na ) ; } }


"Strings formed from given characters without any consecutive repeating characters | Java implementation of the above approach ; Function to print the strings which satisfy the mentioned conditions ; Iterate through all the strings in the array . ; check function to check the conditions for every string ; Function to check whether the string contains any consecutive repetitive characters and any characters other than those in str ; Valid characters check ; Nonrepetitive check ; Driver code"
How can the above be solved in Java?

import java . util . * ; public class GFG { public static void getStrings ( String str , String [ ] arr ) { for ( int i = 0 ; i < arr . length ; i ++ ) { if ( check ( arr [ i ] , str ) ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } } public static boolean check ( String s , String str ) { char [ ] chars = s . toCharArray ( ) ; for ( char c : chars ) { if ( ! str . contains ( String . valueOf ( c ) ) ) { return false ; } } for ( int i = 0 ; i < chars . length - 1 ; i ++ ) { if ( chars [ i ] == chars [ i + 1 ] ) { return false ; } } return true ; } public static void main ( String [ ] args ) { String str = " ABCD " ; String [ ] arr = { " AABCDA " , " ABCDZADC " , " ABCDBCA " , " ABCDABDCA " } ; getStrings ( str , arr ) ; } }


"Strings from an array which are not prefix of any other string | Java implementation of the approach ; Trie node ; isEndOfWord is true if the node represents end of a word ; Returns new trie node ( initialized to NULLs ) ; Function to insert a String into trie ; While inerting a word make each isEndOfWord as false ; Check if this word is prefix of some already inserted word If it is then don 't insert this word ; If present word is not prefix of any other word then insert it ; Function to display words in Trie ; If node is leaf node , it indicates end of String , so a null character is added and String is displayed ; If NON NULL child is found add parent key to str and call the display function recursively for child node ; Driver code ; Conclass trie"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static final int ALPHABET_SIZE = 26 ; static class TrieNode { TrieNode [ ] children ; boolean isEndOfWord ; TrieNode ( ) { this . children = new TrieNode [ ALPHABET_SIZE ] ; } } static TrieNode getNode ( ) { TrieNode pNode = new TrieNode ( ) ; pNode . isEndOfWord = false ; Arrays . fill ( pNode . children , null ) ; return pNode ; } static void insert ( TrieNode root , String key ) { TrieNode pCrawl = root ; for ( int i = 0 ; i < key . length ( ) ; i ++ ) { int index = key . charAt ( i ) - ' a ' ; if ( pCrawl . children [ index ] == null ) pCrawl . children [ index ] = getNode ( ) ; pCrawl . isEndOfWord = false ; pCrawl = pCrawl . children [ index ] ; } int i ; for ( i = 0 ; i < 26 ; i ++ ) { if ( pCrawl . children [ i ] != null ) { break ; } } if ( i == 26 ) { pCrawl . isEndOfWord = true ; } } static void display ( TrieNode root , char str [ ] , int level ) { if ( root . isEndOfWord ) { str [ level ] = ' \0' ; System . out . println ( str ) ; } int i ; for ( i = 0 ; i < ALPHABET_SIZE ; i ++ ) { if ( root . children [ i ] != null ) { str [ level ] = ( char ) ( i + ' a ' ) ; display ( root . children [ i ] , str , level + 1 ) ; } } } public static void main ( String [ ] args ) { String keys [ ] = { " apple " , " app " , " there " , " the " , " like " } ; int n = keys . length ; TrieNode root = getNode ( ) ; for ( int i = 0 ; i < n ; i ++ ) insert ( root , keys [ i ] ) ; char [ ] str = new char [ 100 ] ; display ( root , str , 0 ) ; } }


"Students with maximum average score of three subjects | Java program to find the list of students having maximum average score ; Function to find the list of students having maximum average score Driver code ; Variables to store average score of a student and maximum average score ; List to store names of students having maximum average score ; Traversing the file data ; finding average score of a student ; Clear the list and add name of student having current maximum average score in the list ; Printing the maximum average score and names of students having this maximum average score as per the order in the file . ; Driver code ; Number of elements in string array"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; import java . lang . * ; class GFG { static void getStudentsList ( String [ ] file ) { int avgScore ; int maxAvgScore = Integer . MIN_VALUE ; ArrayList < String > names = new ArrayList < > ( ) ; for ( int i = 0 ; i < file . length ; i += 4 ) { avgScore = ( Integer . parseInt ( file [ i + 1 ] ) + Integer . parseInt ( file [ i + 2 ] ) + Integer . parseInt ( file [ i + 3 ] ) ) / 3 ; if ( avgScore > maxAvgScore ) { maxAvgScore = avgScore ; names . clear ( ) ; names . add ( file [ i ] ) ; } else if ( avgScore == maxAvgScore ) names . add ( file [ i ] ) ; } for ( int i = 0 ; i < names . size ( ) ; i ++ ) { System . out . print ( names . get ( i ) + " ▁ " ) ; } System . out . print ( maxAvgScore ) ; } public static void main ( String args [ ] ) { String [ ] file = { " Shrikanth " , "20" , "30" , "10" , " Ram " , "100" , "50" , "10" } ; getStudentsList ( file ) ; } }


"Sub | Java code to find the sub - tree with minimum color difference in a 2 - coloured tree ; Tree traversal to compute minimum difference ; Initial min difference is the color of node ; Traversing its children ; Not traversing the parent ; If the child is adding positively to difference , we include it in the answer Otherwise , we leave the sub - tree and include 0 ( nothing ) in the answer ; DFS for colour difference : 1 colour - 2 colour ; Minimum colour difference is maximum answer value ; Clearing the current value to check for colour2 as well ; Interchanging the colours ; DFS for colour difference : 2 colour - 1 colour ; Checking if colour2 makes the minimum colour difference ; Driver code ; Nodes ; Adjacency list representation ; Edges ; Index represent the colour of that node There is no Node 0 , so we start from index 1 to N ; Printing the result"
How can the above be solved in Java?

import java . util . * ; class GFG { static void dfs ( int node , int parent , Vector < Integer > tree [ ] , int colour [ ] , int answer [ ] ) { answer [ node ] = colour [ node ] ; for ( Integer u : tree [ node ] ) { if ( u == parent ) continue ; dfs ( u , node , tree , colour , answer ) ; answer [ node ] += Math . max ( answer [ u ] , 0 ) ; } } static int maxDiff ( Vector < Integer > tree [ ] , int colour [ ] , int N ) { int [ ] answer = new int [ N + 1 ] ; dfs ( 1 , 0 , tree , colour , answer ) ; int high = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { high = Math . max ( high , answer [ i ] ) ; answer [ i ] = 0 ; } for ( int i = 1 ; i <= N ; i ++ ) { if ( colour [ i ] == - 1 ) colour [ i ] = 1 ; else colour [ i ] = - 1 ; } dfs ( 1 , 0 , tree , colour , answer ) ; for ( int i = 1 ; i < N ; i ++ ) high = Math . max ( high , answer [ i ] ) ; return high ; } public static void main ( String [ ] args ) { int N = 5 ; Vector < Integer > tree [ ] = new Vector [ N + 1 ] ; for ( int i = 0 ; i < N + 1 ; i ++ ) tree [ i ] = new Vector < Integer > ( ) ; tree [ 1 ] . add ( 2 ) ; tree [ 2 ] . add ( 1 ) ; tree [ 1 ] . add ( 3 ) ; tree [ 3 ] . add ( 1 ) ; tree [ 2 ] . add ( 4 ) ; tree [ 4 ] . add ( 2 ) ; tree [ 3 ] . add ( 5 ) ; tree [ 5 ] . add ( 3 ) ; int colour [ ] = { 0 , 1 , 1 , - 1 , - 1 , 1 } ; System . out . println ( maxDiff ( tree , colour , N ) ) ; } }


"Sub | Java implementation of above approach ; Function that counts all the sub - strings of length ' k ' which have all identical characters ; count of sub - strings , length , initial position of sliding window ; map to store the frequency of the characters of sub - string ; increase the frequency of the character and length of the sub - string ; if the length of the sub - string is greater than K ; remove the character from the beginning of sub - string ; if the length of the sub string is equal to k and frequency of one of its characters is equal to the length of the sub - string i . e . all the characters are same increase the count ; display the number of valid sub - strings ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void solve ( String s , int k ) { int count = 0 , length = 0 , pos = 0 ; HashMap < Character , Integer > m = new HashMap < Character , Integer > ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( m . containsKey ( s . charAt ( i ) ) ) m . put ( s . charAt ( i ) , m . get ( s . charAt ( i ) ) + 1 ) ; else m . put ( s . charAt ( i ) , 1 ) ; length ++ ; if ( length > k ) { m . put ( s . charAt ( pos ) , m . get ( s . charAt ( pos ) ) - 1 ) ; pos ++ ; length -- ; } if ( length == k && m . get ( s . charAt ( i ) ) == length ) count ++ ; } System . out . println ( count ) ; } public static void main ( String [ ] args ) { String s = " aaaabbbccdddd " ; int k = 4 ; solve ( s , k ) ; } }


"Sub | Java implementation of the approach ; Function that checks if the String contain exactly K characters having ASCII value greater than p ; if ASCII value is greater than ' p ' ; if count of satisfying characters is equal to ' K ' then return true ; otherwise return false ; function to count sub - Strings ; length of the String ; count of sub - Strings ; ' i ' is the starting index for the sub - String ; ' j ' is the no . of characters to include in the sub - String ; check if the sub - String satisfies the condition ; Driver code"
How can the above be solved in Java?

class GFG { boolean isValidSubString ( String r , int K , int p ) { int c = 0 ; for ( int i = 0 ; i < r . length ( ) ; i ++ ) { if ( ( int ) r . charAt ( i ) > p ) { c ++ ; } } if ( c == K ) { return true ; } else { return false ; } } void countSubStrings ( String s , int K , int p ) { int l = s . length ( ) ; int count = 0 ; for ( int i = 0 ; i < l ; i ++ ) { for ( int j = K ; ( i + j ) <= l ; j ++ ) { String r = s . substring ( i , ( i + j ) ) ; if ( isValidSubString ( r , K , p ) ) { count ++ ; } } } System . out . println ( count ) ; } public static void main ( String args [ ] ) { GFG g = new GFG ( ) ; String s = " abepztydba " ; int K = 4 ; int p = 110 ; g . countSubStrings ( s , K , p ) ; } }


"Sub | Java implementation of the approach ; Function that returns the index of next occurrence of the character c in string str starting from index start ; Starting from start ; If current character = c ; Not found ; Function to return the count of required sub - strings ; Stores running count of ' x ' starting from the end ; Next index of ' x ' starting from index 0 ; Next index of ' y ' starting from index 0 ; To store the count of required sub - strings ; If ' y ' appears before ' x ' it won 't contribute to a valid sub-string ; Find next occurrence of ' y ' ; If ' y ' appears after ' x ' every sub - string ending at an ' x ' appearing after this ' y ' and starting with the current ' x ' is a valid sub - string ; Find next occurrence of ' x ' ; Return the count ; Driver code"
How can the above be solved in Java?

public class GFG { static int nextIndex ( String str , int start , char c ) { for ( int i = start ; i < str . length ( ) ; i ++ ) { if ( str . charAt ( i ) == c ) return i ; } return - 1 ; } static int countSubStrings ( String str ) { int i , n = str . length ( ) ; int countX [ ] = new int [ n ] ; int count = 0 ; for ( i = n - 1 ; i >= 0 ; i -- ) { if ( str . charAt ( i ) == ' x ' ) count ++ ; countX [ i ] = count ; } int nextIndexX = nextIndex ( str , 0 , ' x ' ) ; int nextIndexY = nextIndex ( str , 0 , ' y ' ) ; count = 0 ; while ( nextIndexX != - 1 && nextIndexY != - 1 ) { if ( nextIndexX > nextIndexY ) { nextIndexY = nextIndex ( str , nextIndexY + 1 , ' y ' ) ; continue ; } else { count += countX [ nextIndexY ] ; nextIndexX = nextIndex ( str , nextIndexX + 1 , ' x ' ) ; } } return count ; } public static void main ( String [ ] args ) { String s = " xyyxx " ; System . out . println ( countSubStrings ( s ) ) ; } }


"Sub | Java implementation of the approach ; Function that returns true if every lowercase character appears atmost once ; every character frequency must be not greater than one ; Function that returns the modified good string if possible ; If the length of the string is less than n ; To store frequency of each character ; Sub - strings of length 26 ; Get the frequency of each character in the current sub - string ; Check if we can get sub - string containing all the 26 characters ; Find which character is missing ; Fill with missing characters ; Find the next missing character ; Return the modified good string ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean valid ( int [ ] cnt ) { for ( int i = 0 ; i < 26 ; i ++ ) { if ( cnt [ i ] >= 2 ) return false ; } return true ; } static String getGoodString ( String ss , int n ) { char [ ] s = ss . toCharArray ( ) ; if ( n < 26 ) return " - 1" ; int [ ] cnt = new int [ 27 ] ; for ( int i = 25 ; i < n ; i ++ ) { for ( int j = i ; j >= i - 25 ; j -- ) { if ( s [ j ] != ' ? ' ) cnt [ ( ( int ) s [ j ] - ( int ) ' a ' ) ] ++ ; } if ( valid ( cnt ) ) { int cur = 0 ; while ( cnt [ cur ] > 0 ) cur ++ ; for ( int j = i - 25 ; j <= i ; j ++ ) { if ( s [ j ] == ' ? ' ) { s [ j ] = ( char ) ( cur + ( int ) ( ' a ' ) ) ; cur ++ ; while ( cnt [ cur ] > 0 ) cur ++ ; } } return new String ( s ) ; } } return " - 1" ; } public static void main ( String [ ] args ) { String s = " abcdefghijkl ? nopqrstuvwxy ? " ; int n = s . length ( ) ; System . out . println ( getGoodString ( s , n ) ) ; } }


"Sub | Java implementation of the approach ; Function to return the count of sub - strings starting from startIndex that are also the prefixes of str ; Function to return the count of all possible sub - strings of str that are also the prefixes of str ; If current character is equal to the starting character of str ; Driver code ; Function Call"
How can the above be solved in Java?

public class GFG { public static int subStringsStartingHere ( String str , int n , int startIndex ) { int count = 0 , i = startIndex + 1 ; while ( i <= n ) { if ( str . startsWith ( str . substring ( startIndex , i ) ) ) { count ++ ; } else break ; i ++ ; } return count ; } public static int countSubStrings ( String str , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str . charAt ( i ) == str . charAt ( 0 ) ) count += subStringsStartingHere ( str , n , i ) ; } return count ; } public static void main ( String [ ] args ) { String str = " ababc " ; int n = str . length ( ) ; System . out . println ( countSubStrings ( str , n ) ) ; } }


"Sub | Java program to answer multiple queries of divisibility by 3 in substrings of a number ; Array to store the sum of digits ; Utility function to evaluate a character 's  integer value ; This function receives the string representation of the number and precomputes the sum array ; This function receives l and r representing the indices and prints the required output ; Driver code"
How can the above be solved in Java?

class GFG { static int sum [ ] = new int [ 1000005 ] ; static int toInt ( char x ) { return x - '0' ; } static void prepareSum ( String s ) { sum [ 0 ] = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { sum [ i + 1 ] = sum [ i ] + toInt ( s . charAt ( i ) ) ; } } static void query ( int l , int r ) { if ( ( sum [ r + 1 ] - sum [ l ] ) % 3 == 0 ) { System . out . println ( " Divisible ▁ by ▁ 3" ) ; } else { System . out . println ( " Not ▁ divisible ▁ by ▁ 3" ) ; } } public static void main ( String [ ] args ) { String n = "12468236544" ; prepareSum ( n ) ; query ( 0 , 1 ) ; query ( 1 , 2 ) ; query ( 3 , 6 ) ; query ( 0 , 10 ) ; } }


"Subarray / Substring vs Subsequence and Programs to Generate them | Java code to generate all possible subsequences . Time Complexity O ( n * 2 ^ n ) ; Number of subsequences is ( 2 * * n - 1 ) ; Run from counter 000. . 1 to 111. . 1 ; Check if jth bit in the counter is set If set then print jth element from arr [ ] ; Driver method to test the above function"
How can the above be solved in Java?

import java . math . BigInteger ; class Test { static int arr [ ] = new int [ ] { 1 , 2 , 3 , 4 } ; static void printSubsequences ( int n ) { int opsize = ( int ) Math . pow ( 2 , n ) ; for ( int counter = 1 ; counter < opsize ; counter ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( BigInteger . valueOf ( counter ) . testBit ( j ) ) System . out . print ( arr [ j ] + " ▁ " ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { System . out . println ( " All ▁ Non - empty ▁ Subsequences " ) ; printSubsequences ( arr . length ) ; } }


"Subarray / Substring vs Subsequence and Programs to Generate them | Java program toto generate all possible subarrays / subArrays Complexity - O ( n ^ 3 ) ; Prints all subarrays in arr [ 0. . n - 1 ] ; Pick starting point ; Pick ending point ; Print subarray between current starting and ending points ; Driver method to test the above function"
How can the above be solved in Java?

class Test { static int arr [ ] = new int [ ] { 1 , 2 , 3 , 4 } ; static void subArray ( int n ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { for ( int k = i ; k <= j ; k ++ ) System . out . print ( arr [ k ] + " ▁ " ) ; } } } public static void main ( String [ ] args ) { System . out . println ( " All ▁ Non - empty ▁ Subarrays " ) ; subArray ( arr . length ) ; } }


"Subarray of size K with prime sum | Java program to implement the above approach ; Generate all prime numbers in the range [ 1 , 1000000 ] ; Set all numbers as prime initially ; Mark 0 and 1 as non - prime ; If current element is prime ; Mark all its multiples as non - prime ; Function to print the subarray whose sum of elements is prime ; Store the current subarray of size K ; Calculate the sum of first K elements ; Check if currSum is prime ; Store the start and last index of subarray of size K ; Iterate over remaining array ; Check if currSum ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void sieve ( boolean prime [ ] ) { for ( int i = 0 ; i < 1000000 ; i ++ ) { prime [ i ] = true ; } prime [ 0 ] = prime [ 1 ] = false ; for ( int i = 2 ; i * i <= 1000000 ; i ++ ) { if ( prime [ i ] ) { for ( int j = i * i ; j < 1000000 ; j += i ) { prime [ j ] = false ; } } } } static void subPrimeSum ( int N , int K , int arr [ ] , boolean prime [ ] ) { int currSum = 0 ; for ( int i = 0 ; i < K ; i ++ ) { currSum += arr [ i ] ; } if ( prime [ currSum ] ) { for ( int i = 0 ; i < K ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } return ; } int st = 1 , en = K ; while ( en < N ) { currSum += arr [ en ] - arr [ st - 1 ] ; if ( prime [ currSum ] ) { for ( int i = st ; i <= en ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } return ; } en ++ ; st ++ ; } } public static void main ( String [ ] args ) { int arr [ ] = { 20 , 7 , 5 , 4 , 3 , 11 , 99 , 87 , 23 , 45 } ; int K = 4 ; int N = arr . length ; boolean [ ] prime = new boolean [ 1000000 ] ; sieve ( prime ) ; subPrimeSum ( N , K , arr , prime ) ; } }


"Subarray permutation that satisfies the given condition | Java implementation of the approach ; Function that returns true if the required subarray exists in the given array ; Map to store the positions of each integer in the original permutation ; To store the address of each entry in arr [ n ] but with 1 - based indexing ; To track minimum position sumcur for sum of aint positions tiint this position ; Summing up addresses ; Tracking minimum address encountered tiint now ; The sum of the addresses if it forms the required subarray ; If current sum of address is equal to val ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean subArray ( int [ ] arr , int n , int m ) { int i ; HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( i = 0 ; i < n ; i ++ ) { mp . put ( arr [ i ] , i + 1 ) ; } int sumcur = 0 ; int p = Integer . MAX_VALUE ; Vector < Integer > ans = new Vector < Integer > ( ) ; for ( i = 1 ; i <= m ; i ++ ) { sumcur += mp . get ( i ) ; p = Math . min ( p , mp . get ( i ) ) ; int val = p * i - i + ( i * ( i + 1 ) ) / 2 ; if ( i == m ) { if ( val == sumcur ) { return true ; } else return false ; } } return false ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 5 , 1 , 3 , 2 , 6 } ; int n = arr . length ; int m = 3 ; if ( subArray ( arr , n , m ) ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } }


"Subarray whose absolute sum is closest to K | Java code to find sub - array whose sum shows the minimum deviation ; Starting index , ending index , Deviation ; Iterate i and j to get all subarrays ; Found sub - array with less sum ; Exactly same sum ; Driver Code ; Array to store return values"
How can the above be solved in Java?

class GFG { public static int [ ] getSubArray ( int [ ] arr , int n , int K ) { int i = - 1 ; int j = - 1 ; int currSum = 0 ; int [ ] result = { i , j , Math . abs ( K - Math . abs ( currSum ) ) } ; for ( i = 0 ; i < n ; i ++ ) { currSum = 0 ; for ( j = i ; j < n ; j ++ ) { currSum += arr [ j ] ; int currDev = Math . abs ( K - Math . abs ( currSum ) ) ; if ( currDev < result [ 2 ] ) { result [ 0 ] = i ; result [ 1 ] = j ; result [ 2 ] = currDev ; } if ( currDev == 0 ) return result ; } } return result ; } public static void main ( String [ ] args ) { int [ ] arr = { 15 , - 3 , 5 , 2 , 7 , 6 , 34 , - 6 } ; int n = arr . length ; int K = 50 ; int [ ] ans = getSubArray ( arr , n , K ) ; if ( ans [ 0 ] == - 1 ) { System . out . println ( " The ▁ empty ▁ array ▁ " + " shows ▁ minimum ▁ Deviation " ) ; } else { for ( int i = ans [ 0 ] ; i <= ans [ 1 ] ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } } }


"Subarray with largest sum after excluding its maximum element | Java implementation to find the maximum sum subarray such by excluding the maximum element from the subarray ; Function to find the maximum sum subarray by excluding the maximum element from the array ; Loop to store all the positive elements in the map ; Loop to iterating over the map and considering as the maximum element of the current including subarray ; Make the current element maximum ; Iterate through array and apply kadane 's algorithm ; Condition if current element is greater than mx then make the element - infinity ; Store the indices in some variable ; Driver code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void maximumSumSubarray ( int arr [ ] , int n ) { Map < Integer , Integer > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] >= 0 ) mp . put ( arr [ i ] , 1 ) ; } int first = 0 ; int last = 0 ; int ans = 0 ; int INF = ( int ) 1e6 ; for ( Map . Entry < Integer , Integer > i : mp . entrySet ( ) ) { int mx = i . getKey ( ) ; int curr = 0 ; int curr_start = - 1 ; for ( int j = 0 ; j < n ; j ++ ) { if ( curr == 0 ) curr_start = j ; int val = arr [ j ] > mx ? - INF : arr [ j ] ; curr += val ; if ( curr < 0 ) curr = 0 ; if ( curr > ans ) { ans = curr ; first = curr_start ; last = j ; } } } System . out . print ( ( first + 1 ) + " ▁ " + ( last + 1 ) ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 5 , - 2 , 10 , - 1 , 4 } ; int size = arr . length ; maximumSumSubarray ( arr , size ) ; } }


"Subarray with no pair sum divisible by K | Java Program to find the subarray with no pair sum divisible by K ; function to find the subarray with no pair sum divisible by k ; hash table to store the remainders obtained on dividing by K ; s : starting index of the current subarray , e : ending index of the current subarray , maxs : starting index of the maximum size subarray so far , maxe : ending index of the maximum size subarray so far ; insert the first element in the set ; Removing starting elements of current subarray while there is an element in set which makes a pair with mod [ i ] such that the pair sum is divisible . ; include the current element in the current subarray the ending index of the current subarray increments by one ; compare the size of the current subarray with the maximum size so far ; Driver Code"
How can the above be solved in Java?

 import java . io . * ; import java . util . * ; public class GFG { static void subarrayDivisibleByK ( int [ ] arr , int n , int k ) { int [ ] mp = new int [ 1000 ] ; int s = 0 , e = 0 , maxs = 0 , maxe = 0 ; mp [ arr [ 0 ] % k ] ++ ; for ( int i = 1 ; i < n ; i ++ ) { int mod = arr [ i ] % k ; while ( mp [ k - mod ] != 0 || ( mod == 0 && mp [ mod ] != 0 ) ) { mp [ arr [ s ] % k ] -- ; s ++ ; } mp [ mod ] ++ ; e ++ ; if ( ( e - s ) > ( maxe - maxs ) ) { maxe = e ; maxs = s ; } } System . out . print ( " The ▁ maximum ▁ size ▁ is ▁ " + ( maxe - maxs + 1 ) + " and the subarray is as follows
"); for ( int i = maxs ; i <= maxe ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String args [ ] ) { int k = 3 ; int [ ] arr = { 5 , 10 , 15 , 20 , 25 } ; int n = arr . length ; subarrayDivisibleByK ( arr , n , k ) ; } }


"Subarrays whose sum is a perfect square | Java program to implement the above approach ; Function to print the start and end indices of all subarrays whose sum is a perfect square ; Stores the current subarray sum ; Update current subarray sum ; Stores the square root of currSubSum ; Check if currSubSum is a perfect square or not ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void PrintIndexes ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { int currSubSum = 0 ; for ( int j = i ; j < N ; j ++ ) { currSubSum += arr [ j ] ; int sq = ( int ) Math . sqrt ( currSubSum ) ; if ( sq * sq == currSubSum ) { System . out . print ( " ( " + i + " , " + j + " ) " + " ▁ " ) ; } } } } public static void main ( String [ ] args ) throws java . lang . Exception { int arr [ ] = { 65 , 79 , 81 } ; PrintIndexes ( arr , arr . length ) ; } }


"Subarrays with distinct elements | Java program to calculate sum of lengths of subarrays of distinct elements . ; Returns sum of lengths of all subarrays with distinct elements . ; For maintaining distinct elements . ; Initialize ending point and result ; Fix starting point ; Calculating and adding all possible length subarrays in arr [ i . . j ] ; Remove arr [ i ] as we pick new stating point from next ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class geeks { public static int sumoflength ( int [ ] arr , int n ) { Set < Integer > s = new HashSet < > ( ) ; int j = 0 , ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { while ( j < n && ! s . contains ( arr [ j ] ) ) { s . add ( arr [ i ] ) ; j ++ ; } ans += ( ( j - i ) * ( j - i + 1 ) ) / 2 ; s . remove ( arr [ i ] ) ; } return ans ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 } ; int n = arr . length ; System . out . println ( sumoflength ( arr , n ) ) ; } }


"Submatrix Sum Queries | Java program to compute submatrix query sum in O ( 1 ) time ; Function to preprcess input mat [ M ] [ N ] . This function mainly fills aux [ M ] [ N ] such that aux [ i ] [ j ] stores sum of elements from ( 0 , 0 ) to ( i , j ) ; Copy first row of mat [ ] [ ] to aux [ ] [ ] ; Do column wise sum ; Do row wise sum ; A O ( 1 ) time function to compute sum of submatrix between ( tli , tlj ) and ( rbi , rbj ) using aux [ ] [ ] which is built by the preprocess function ; result is now sum of elements between ( 0 , 0 ) and ( rbi , rbj ) ; Remove elements between ( 0 , 0 ) and ( tli - 1 , rbj ) ; Remove elements between ( 0 , 0 ) and ( rbi , tlj - 1 ) ; Add aux [ tli - 1 ] [ tlj - 1 ] as elements between ( 0 , 0 ) and ( tli - 1 , tlj - 1 ) are subtracted twice ; Driver code"
How can the above be solved in Java?

class GFG { static final int M = 4 ; static final int N = 5 ; static int preProcess ( int mat [ ] [ ] , int aux [ ] [ ] ) { for ( int i = 0 ; i < N ; i ++ ) aux [ 0 ] [ i ] = mat [ 0 ] [ i ] ; for ( int i = 1 ; i < M ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) aux [ i ] [ j ] = mat [ i ] [ j ] + aux [ i - 1 ] [ j ] ; for ( int i = 0 ; i < M ; i ++ ) for ( int j = 1 ; j < N ; j ++ ) aux [ i ] [ j ] += aux [ i ] [ j - 1 ] ; return 0 ; } static int sumQuery ( int aux [ ] [ ] , int tli , int tlj , int rbi , int rbj ) { int res = aux [ rbi ] [ rbj ] ; if ( tli > 0 ) res = res - aux [ tli - 1 ] [ rbj ] ; if ( tlj > 0 ) res = res - aux [ rbi ] [ tlj - 1 ] ; if ( tli > 0 && tlj > 0 ) res = res + aux [ tli - 1 ] [ tlj - 1 ] ; return res ; } public static void main ( String [ ] args ) { int mat [ ] [ ] = { { 1 , 2 , 3 , 4 , 6 } , { 5 , 3 , 8 , 1 , 2 } , { 4 , 6 , 7 , 5 , 5 } , { 2 , 4 , 8 , 9 , 4 } } ; int aux [ ] [ ] = new int [ M ] [ N ] ; preProcess ( mat , aux ) ; int tli = 2 , tlj = 2 , rbi = 3 , rbj = 4 ; System . out . print ( " Query1 : " + sumQuery ( aux , tli , tlj , rbi , rbj ) ) ; tli = 0 ; tlj = 0 ; rbi = 1 ; rbj = 1 ; System . out . print ( " Query2 : " + sumQuery ( aux , tli , tlj , rbi , rbj ) ) ; tli = 1 ; tlj = 2 ; rbi = 3 ; rbj = 3 ; System . out . print ( " Query3 : "  + sumQuery ( aux , tli , tlj , rbi , rbj ) ) ; } }


"Subsequence X of length K such that gcd ( X [ 0 ] , X [ 1 ] ) + ( X [ 2 ] , X [ 3 ] ) + ... is maximized | Java program to find the sum of the addition of all possible subsets ; Recursive function to find the maximum value of the given recurrence ; If we get K elements ; If we have reached the end and K elements are not there ; If the state has been visited ; Iterate for every element as the next possible element and take the element which gives the maximum answer ; If this element is the first element in the individual pair in the subsequence then simply recurrence with the last element as i - th index ; If this element is the second element in the individual pair , the find gcd with the previous element and add to the answer and recur for the next element ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MAX = 100 ; static int recur ( int ind , int cnt , int last , int a [ ] , int n , int k , int dp [ ] [ ] ) { if ( cnt == k ) return 0 ; if ( ind == n ) return ( int ) - 1e9 ; if ( dp [ ind ] [ cnt ] != - 1 ) return dp [ ind ] [ cnt ] ; int ans = 0 ; for ( int i = ind ; i < n ; i ++ ) { if ( cnt % 2 == 0 ) ans = Math . max ( ans , recur ( i + 1 , cnt + 1 , i , a , n , k , dp ) ) ; else ans = Math . max ( ans , __gcd ( a [ last ] , a [ i ] ) + recur ( i + 1 , cnt + 1 , 0 , a , n , k , dp ) ) ; } return dp [ ind ] [ cnt ] = ans ; } static int __gcd ( int a , int b ) { if ( b == 0 ) return a ; return __gcd ( b , a % b ) ; } public static void main ( String [ ] args ) { int a [ ] = { 4 , 5 , 3 , 7 , 8 , 10 , 9 , 8 } ; int n = a . length ; int k = 4 ; int [ ] [ ] dp = new int [ n ] [ MAX ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < MAX ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } System . out . println ( recur ( 0 , 0 , 0 , a , n , k , dp ) ) ; } }


"Subsequence of size k with maximum possible GCD | Java program to find subsequence of size k with maximum possible GCD ; function to find GCD of sub sequence of size k with max GCD in the array ; Computing highest element ; Array to store the count of divisors i . e . Potential GCDs ; Iterating over every element ; Calculating all the divisors ; Divisor found ; Incrementing count for divisor ; Element / divisor is also a divisor Checking if both divisors are not same ; Checking the highest potential GCD ; If this divisor can divide at least k numbers , it is a GCD of at least one sub sequence of size k ; Driver code ; Array in which sub sequence with size k with max GCD is to be found"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int findMaxGCD ( int [ ] arr , int n , int k ) { Arrays . sort ( arr ) ; int high = arr [ n - 1 ] ; int [ ] divisors = new int [ high + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 1 ; j <= Math . sqrt ( arr [ i ] ) ; j ++ ) { if ( arr [ i ] % j == 0 ) { divisors [ j ] ++ ; if ( j != arr [ i ] / j ) divisors [ arr [ i ] / j ] ++ ; } } } for ( int i = high ; i >= 1 ; i -- ) if ( divisors [ i ] >= k ) return i ; return 0 ; } static public void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 4 , 8 , 8 , 12 } ; int k = 3 ; int n = arr . length ; System . out . println ( findMaxGCD ( arr , n , k ) ) ; } }


"Subsequence pair from given Array having all unique and all same elements respectively | Java program for the above approach ; Function to find the maximum length of subsequences with given property ; To store the frequency ; Traverse the array to store the frequency ; M . size ( ) given count of distinct element in arr [ ] ; Traverse map to find max frequency ; Find the maximum length on the basis of two cases in the approach ; Driver Code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void maximumSubsequence ( int arr [ ] , int N ) { HashMap < Integer , Integer > M = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( M . containsKey ( arr [ i ] ) ) { M . put ( arr [ i ] , M . get ( arr [ i ] ) + 1 ) ; } else { M . put ( arr [ i ] , 1 ) ; } } int distinct_size = M . size ( ) ; int maxFreq = 1 ; for ( Map . Entry < Integer , Integer > it : M . entrySet ( ) ) { maxFreq = Math . max ( maxFreq , it . getValue ( ) ) ; } System . out . print ( Math . max ( Math . min ( distinct_size , maxFreq - 1 ) , Math . min ( distinct_size - 1 , maxFreq ) ) ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 4 , 4 , 4 , 4 , 5 } ; int N = arr . length ; maximumSubsequence ( arr , N ) ; } }


"Subsequence queries after removing substrings | Java program for answering queries to check whether a String subsequence or not after removing a substring . ; arrays to store results of preprocessing ; function to preprocess the strings ; initialize it as 0. ; store subsequence count in forward direction ; store number of matches till now ; store subsequence count in backward direction ; store number of matches till now ; function that gives the output ; length of remaining String A is less than B 's length ; Driver Code ; two queries"
How can the above be solved in Java?

 class GFG { static int [ ] fwd = new int [ 100 ] ; static int [ ] bwd = new int [ 100 ] ; static void preProcess ( String a , String b ) { int n = a . length ( ) ; int j = 0 ; for ( int i = 1 ; i <= a . length ( ) ; i ++ ) { if ( j < b . length ( ) && a . charAt ( i - 1 ) == b . charAt ( j ) ) { j ++ ; } fwd [ i ] = j ; } j = 0 ; for ( int i = a . length ( ) ; i >= 1 ; i -- ) { if ( j < b . length ( ) && a . charAt ( i - 1 ) == b . charAt ( b . length ( ) - j - 1 ) ) { j ++ ; } bwd [ i ] = j ; } } static void query ( String a , String b , int x , int y ) { if ( ( x - 1 + a . length ( ) - y ) < b . length ( ) ) { System . out . print ( "No
"); return ; } if ( fwd [ x - 1 ] + bwd [ y + 1 ] >= b . length ( ) ) { System . out . print ( "Yes
"); } else { System . out . print ( "No
"); } } public static void main ( String [ ] args ) { String a = " abcabcxy " , b = " acy " ; preProcess ( a , b ) ; int x = 2 , y = 5 ; query ( a , b , x , y ) ; x = 3 ; y = 6 ; query ( a , b , x , y ) ; } }


"Subsequence with maximum pairwise absolute difference and minimum size | Java program for the above approach ; Function to find the subsequence with maximum absolute difference ; To store the resultant subsequence ; First element should be included in the subsequence ; Traverse the given array arr [ ] ; If current element is greater than the previous element ; If the current element is not the local maxima then continue ; Else push it in subsequence ; If the current element is less then the previous element ; If the current element is not the local minima then continue ; Else push it in subsequence ; Last element should also be included in subsequence ; Print the element ; Driver Code ; Given array ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void getSubsequence ( int [ ] ar ) { int N = ar . length ; Vector < Integer > ans = new Vector < Integer > ( ) ; ans . add ( ar [ 0 ] ) ; for ( int i = 1 ; i < N - 1 ; i ++ ) { if ( ar [ i ] > ar [ i - 1 ] ) { if ( i < N - 1 && ar [ i ] <= ar [ i + 1 ] ) { continue ; } else { ans . add ( ar [ i ] ) ; } } else { if ( i < N - 1 && ar [ i + 1 ] < ar [ i ] ) { continue ; } else { ans . add ( ar [ i ] ) ; } } } ans . add ( ar [ N - 1 ] ) ; for ( int it : ans ) System . out . print ( it + " ▁ " ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 4 , 3 , 5 } ; getSubsequence ( arr ) ; } }


"Subsequences generated by including characters or ASCII value of characters of given string | Java program to implement the above approach ; Function to print subsequences containing ASCII value of the characters or the the characters of the given string ; Base Case ; If length of the subsequence exceeds 0 ; Print the subsequence ; Stores character present at i - th index of str ; If the i - th character is not included in the subsequence ; Including the i - th character in the subsequence ; Include the ASCII value of the ith character in the subsequence ; Driver Code ; Stores length of str"
How can the above be solved in Java?

class GFG { static void FindSub ( String str , String res , int i ) { if ( i == str . length ( ) ) { if ( res . length ( ) > 0 ) { System . out . print ( res + " ▁ " ) ; } return ; } char ch = str . charAt ( i ) ; FindSub ( str , res , i + 1 ) ; FindSub ( str , res + ch , i + 1 ) ; FindSub ( str , res + ( int ) ch , i + 1 ) ; ; } public static void main ( String [ ] args ) { String str = " ab " ; String res = " " ; int N = str . length ( ) ; FindSub ( str , res , 0 ) ; } }


"Subsequences of given string consisting of non | Javs program to implement the above approach ; Function to find all the subsequences of the string with non - repeating characters ; Base case ; Insert current subsequence ; If str [ i ] is not present in the current subsequence ; Insert str [ i ] into the set ; Insert str [ i ] into the current subsequence ; Remove str [ i ] from the set ; Not including str [ i ] from the current subsequence ; Utility function to print all subsequences of string with non - repeating characters ; Stores all possible subsequences with non - repeating characters ; Stores subsequence with non - repeating characters ; Traverse all possible subsequences containing non - repeating characters ; Print subsequence ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { public static void FindSub ( HashSet < String > sub , HashSet < Character > ch , String str , String res , int i ) { if ( i == str . length ( ) ) { sub . add ( res ) ; return ; } if ( ! ch . contains ( str . charAt ( i ) ) ) { ch . add ( str . charAt ( i ) ) ; FindSub ( sub , ch , str , res + str . charAt ( i ) , i + 1 ) ; ch . remove ( str . charAt ( i ) ) ; } FindSub ( sub , ch , str , res , i + 1 ) ; } public static void printSubwithUniqueChar ( String str , int N ) { HashSet < String > sub = new HashSet < > ( ) ; HashSet < Character > ch = new HashSet < > ( ) ; FindSub ( sub , ch , str , " " , 0 ) ; for ( String subString : sub ) { System . out . print ( subString + " ▁ " ) ; } } public static void main ( String args [ ] ) { String str = " abac " ; int N = str . length ( ) ; printSubwithUniqueChar ( str , N ) ; } }


"Subsequences of size three in an array whose sum is divisible by m | Java program to find count of subsequences of size three divisible by M . ; Storing frequencies of all remainders when divided by M . ; including i and j in the sum rem calculate the remainder required to make the sum divisible by M ; if the required number is less than j , we skip as we have already calculated for that value before . As j here starts with i and rem is less than j . ; if satisfies the first case . ; if satisfies the second case ; if satisfies the third case ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . Arrays ; class GFG { static int countSubSeq ( int A [ ] , int N , int M ) { int ans = 0 ; int h [ ] = new int [ M ] ; Arrays . fill ( h , 0 ) ; for ( int i = 0 ; i < N ; i ++ ) { A [ i ] = A [ i ] % M ; h [ A [ i ] ] ++ ; } for ( int i = 0 ; i < M ; i ++ ) { for ( int j = i ; j < M ; j ++ ) { int rem = ( M - ( i + j ) % M ) % M ; if ( rem < j ) continue ; if ( i == j && rem == j ) ans += h [ i ] * ( h [ i ] - 1 ) * ( h [ i ] - 2 ) / 6 ; else if ( i == j ) ans += h [ i ] * ( h [ i ] - 1 ) * h [ rem ] / 2 ; else if ( i == rem ) ans += h [ i ] * ( h [ i ] - 1 ) * h [ j ] / 2 ; else if ( rem == j ) ans += h [ j ] * ( h [ j ] - 1 ) * h [ i ] / 2 ; else ans = ans + h [ i ] * h [ j ] * h [ rem ] ; } } return ans ; } public static void main ( String args [ ] ) { int M = 3 ; int A [ ] = { 1 , 2 , 4 , 3 } ; int N = A . length ; System . out . println ( countSubSeq ( A , N , M ) ) ; } }


"Subsequences of size three in an array whose sum is divisible by m | Java program to find count of subsequences of size three divisible by M . ; Three nested loop to find all the sub sequences of length three in the given array A [ ] . ; checking if the sum of the chosen three number is divisible by m . ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int coutSubSeq ( int A [ ] , int N , int M ) { int sum = 0 ; int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { for ( int k = j + 1 ; k < N ; k ++ ) { sum = A [ i ] + A [ j ] + A [ k ] ; if ( sum % M == 0 ) ans ++ ; } } } return ans ; } public static void main ( String args [ ] ) { int M = 3 ; int A [ ] = { 1 , 2 , 4 , 3 } ; int N = A . length ; System . out . println ( coutSubSeq ( A , N , M ) ) ; } }