"Sort only non | Java program to sort only non primes ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Function to print the array such that only non primes are sorted ; vector v will store all non prime numbers ; If not prime , insert into vector ; sorting vector of non primes ; print the required array ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class solution { static boolean prime [ ] = new boolean [ 100006 ] ; static void SieveOfEratosthenes ( int n ) { for ( int i = 1 ; i <= n ; i ++ ) prime [ i ] = true ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= n ; i += p ) prime [ i ] = false ; } } } static void sortedArray ( int arr [ ] , int n ) { SieveOfEratosthenes ( 100005 ) ; Vector < Integer > v = new Vector < Integer > ( ) ; for ( int i = 0 ; i < n ; ++ i ) { if ( prime [ arr [ i ] ] == false ) v . add ( arr [ i ] ) ; } Collections . sort ( v ) ; int j = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( prime [ arr [ i ] ] == true ) System . out . print ( arr [ i ] + " ▁ " ) ; else { System . out . print ( v . get ( j ) + " ▁ " ) ; j ++ ; } } } public static void main ( String args [ ] ) { int n = 6 ; int arr [ ] = { 100 , 11 , 500 , 2 , 17 , 1 } ; sortedArray ( arr , n ) ; } }


"Sort string of characters using Stack | Java program to sort string of characters using stack ; Function to print the characters in sorted order ; Primary stack ; Secondary stack ; Append first character ; Iterate for all character in string ; i - th character ASCII ; Stack 's top element ASCII  ; If greater or equal to top element then push to stack ; If smaller , then push all element to the temporary stack ; Push all greater elements ; Push operation ; Push till the stack is not - empty ; Push the i - th character ; Push the tempstack back to stack ; Print the stack in reverse order ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { public static void printSorted ( String s , int l ) { Stack < Character > stack = new Stack < Character > ( ) ; Stack < Character > tempstack = new Stack < Character > ( ) ; stack . push ( s . charAt ( 0 ) ) ; for ( int i = 1 ; i < l ; i ++ ) { int a = s . charAt ( i ) ; int b = ( int ) ( ( char ) stack . peek ( ) ) ; if ( ( a - b ) >= 1 || ( a == b ) ) { stack . push ( s . charAt ( i ) ) ; } else if ( ( b - a ) >= 1 ) { while ( ( b - a ) >= 1 ) { tempstack . push ( stack . peek ( ) ) ; stack . pop ( ) ; if ( stack . size ( ) > 0 ) { b = ( int ) ( ( char ) stack . peek ( ) ) ; } else { break ; } } stack . push ( s . charAt ( i ) ) ; while ( tempstack . size ( ) > 0 ) { stack . push ( tempstack . peek ( ) ) ; tempstack . pop ( ) ; } } } String answer = " " ; while ( stack . size ( ) > 0 ) { answer = stack . peek ( ) + answer ; stack . pop ( ) ; } System . out . println ( answer ) ; } public static void main ( String [ ] args ) { String s = " geeksforgeeks " ; int l = s . length ( ) ; printSorted ( s , l ) ; } }


"Sort string of characters | Java program to sort a string of characters ; function to print string in sorted order ; Hash array to keep count of characters . Initially count of all charters is initialized to zero . ; Traverse string and increment count of characters ; ' a ' - ' a ' will be 0 , ' b ' - ' a ' will be 1 , so for location of character in count array we will do str [ i ] - ' a ' . ; Traverse the hash array and print characters ; Driver program to test above function"
How can the above be solved in Java?

public class SortString { static final int MAX_CHAR = 26 ; static void sortString ( String str ) { int letters [ ] = new int [ MAX_CHAR ] ; for ( char x : str . toCharArray ( ) ) { letters [ x - ' a ' ] ++ ; } for ( int i = 0 ; i < MAX_CHAR ; i ++ ) { for ( int j = 0 ; j < letters [ i ] ; j ++ ) { System . out . print ( ( char ) ( i + ' a ' ) ) ; } } } public static void main ( String [ ] args ) { sortString ( " geeksforgeeks " ) ; } }


"Sort the Array by reversing the numbers in it | Java implementation of the approach ; Function to return the reverse of n ; Function to sort the array according to the reverse of elements ; Vector to store the reverse with respective elements ; Inserting reverse with elements in the vector pair ; Sort the vector , this will sort the pair according to the reverse of elements ; Print the sorted vector content ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static int reversDigits ( int num ) { int rev_num = 0 ; while ( num > 0 ) { rev_num = rev_num * 10 + num % 10 ; num = num / 10 ; } return rev_num ; } static void sortArr ( int arr [ ] , int n ) { ArrayList < int [ ] > vp = new ArrayList < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { vp . add ( new int [ ] { reversDigits ( arr [ i ] ) , arr [ i ] } ) ; } Collections . sort ( vp , ( a , b ) -> a [ 0 ] - b [ 0 ] ) ; for ( int i = 0 ; i < vp . size ( ) ; i ++ ) System . out . print ( vp . get ( i ) [ 1 ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 12 , 10 , 102 , 31 , 15 } ; int n = arr . length ; sortArr ( arr , n ) ; } }


"Sort the Queue using Recursion | Java implementation of the approach ; Function to push element in last by popping from front until size becomes 0 ; Base condition ; pop front element and push this last in a queue ; Recursive call for pushing element ; Function to push an element in the queue while maintaining the sorted order ; Base condition ; If current element is less than the element at the front ; Call stack with front of queue ; Recursive call for inserting a front element of the queue to the last ; Push front element into last in a queue ; Recursive call for pushing element in a queue ; Function to sort the given queue using recursion ; Return if queue is empty ; Get the front element which will be stored in this variable throughout the recursion stack ; Remove the front element ; Recursive call ; Push the current element into the queue according to the sorting order ; Driver code ; Push elements to the queue ; Sort the queue ; Print the elements of the queue after sorting"
How can the above be solved in Java?

import java . util . * ; class GFG { static void FrontToLast ( Queue < Integer > q , int qsize ) { if ( qsize <= 0 ) return ; q . add ( q . peek ( ) ) ; q . remove ( ) ; FrontToLast ( q , qsize - 1 ) ; } static void pushInQueue ( Queue < Integer > q , int temp , int qsize ) { if ( q . isEmpty ( ) qsize == 0 ) { q . add ( temp ) ; return ; } else if ( temp <= q . peek ( ) ) { q . add ( temp ) ; FrontToLast ( q , qsize ) ; } else { q . add ( q . peek ( ) ) ; q . remove ( ) ; pushInQueue ( q , temp , qsize - 1 ) ; } } static void sortQueue ( Queue < Integer > q ) { if ( q . isEmpty ( ) ) return ; int temp = q . peek ( ) ; q . remove ( ) ; sortQueue ( q ) ; pushInQueue ( q , temp , q . size ( ) ) ; } public static void main ( String [ ] args ) { Queue < Integer > qu = new LinkedList < > ( ) ; qu . add ( 10 ) ; qu . add ( 7 ) ; qu . add ( 16 ) ; qu . add ( 9 ) ; qu . add ( 20 ) ; qu . add ( 5 ) ; sortQueue ( qu ) ; while ( ! qu . isEmpty ( ) ) { System . out . print ( qu . peek ( ) + " ▁ " ) ; qu . remove ( ) ; } } }


"Sort the character array based on ASCII % N | Java implementation of the approach ; This function takes last element as pivot , places the pivot element at its correct position in sorted array , and places all smaller ( smaller than pivot ) to left of pivot and all greater elements to right of pivot ; pivot ; Index of smaller element ; If current element is smaller than or equal to pivot Instead of values , ASCII % m values are compared ; Increment index of smaller element ; swap ; The main function that implements QuickSort arr [ ] -- > Array to be sorted , low -- > Starting index , high -- > Ending index ; pi is partitioning index , arr [ p ] is now at right place ; Separately sort elements before partition and after partition ; Function to print the given array ; Driver code ; Sort the given array ; Print the sorted array"
How can the above be solved in Java?

class GFG { static int partition ( char arr [ ] , int low , int high , int mod ) { char pivot = arr [ high ] ; int i = ( low - 1 ) ; int piv = pivot % mod ; for ( int j = low ; j <= high - 1 ; j ++ ) { int a = arr [ j ] % mod ; if ( a <= piv ) { i ++ ; char t = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = t ; } } char t = arr [ i + 1 ] ; arr [ i + 1 ] = arr [ high ] ; arr [ high ] = t ; return ( i + 1 ) ; } static void quickSort ( char arr [ ] , int low , int high , int mod ) { if ( low < high ) { int pi = partition ( arr , low , high , mod ) ; quickSort ( arr , low , pi - 1 , mod ) ; quickSort ( arr , pi + 1 , high , mod ) ; } } static void printArray ( char arr [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { char arr [ ] = { ' g ' , ' e ' , ' e ' , ' k ' , ' s ' } ; int n = arr . length ; int mod = 8 ; quickSort ( arr , 0 , n - 1 , mod ) ; printArray ( arr , n ) ; } }


"Sort the given Matrix | Memory Efficient Approach | Java implementation to sort the given matrix in strict order ; Function to sort the matrix ; Number of elements in matrix ; Loop to sort the matrix using Bubble Sort ; Condition to check if the Adjacent elements ; Swap if previous value is greater ; Loop to print the matrix ; Driver Code ; Function call to sort ; Function call to print matrix"
How can the above be solved in Java?

class GFG { static void sortMat ( int [ ] [ ] data , int row , int col ) { int size = row * col ; for ( int i = 0 ; i < size ; i ++ ) { for ( int j = 0 ; j < size - 1 ; j ++ ) { if ( data [ j / col ] [ j % col ] > data [ ( j + 1 ) / col ] [ ( j + 1 ) % col ] ) { int temp = data [ j / col ] [ j % col ] ; data [ j / col ] [ j % col ] = data [ ( j + 1 ) / col ] [ ( j + 1 ) % col ] ; data [ ( j + 1 ) / col ] [ ( j + 1 ) % col ] = temp ; } } } } static void printMat ( int [ ] [ ] mat , int row , int col ) { for ( int i = 0 ; i < row ; i ++ ) { for ( int j = 0 ; j < col ; j ++ ) { System . out . print ( mat [ i ] [ j ] + " ▁ " ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { int [ ] [ ] mat = { { 5 , 4 , 7 } , { 1 , 3 , 8 } , { 2 , 9 , 6 } } ; int row = mat . length ; int col = mat [ 0 ] . length ; sortMat ( mat , row , col ) ; printMat ( mat , row , col ) ; } }


"Sort the given stack elements based on their modulo with K | Java implementation of the above approach ; Function to sort the stack using another stack based on the values of elements modulo k ; Pop out the first element ; While temporary stack is not empty ; The top of the stack modulo k is greater than ( temp & k ) or if they are equal then compare the values ; Pop from temporary stack and push it to the input stack ; Push temp in temporary of stack ; Push all the elements in the original stack to get the ascending order ; Print the sorted elements ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void sortStack ( Stack < Integer > input , int k ) { Stack < Integer > tmpStack = new Stack < Integer > ( ) ; while ( ! input . isEmpty ( ) ) { int tmp = input . peek ( ) ; input . pop ( ) ; while ( ! tmpStack . isEmpty ( ) ) { int tmpStackMod = tmpStack . peek ( ) % k ; int tmpMod = tmp % k ; if ( ( tmpStackMod > tmpMod ) || ( tmpStackMod == tmpMod && tmpStack . peek ( ) > tmp ) ) { input . push ( tmpStack . peek ( ) ) ; tmpStack . pop ( ) ; } else break ; } tmpStack . push ( tmp ) ; } while ( ! tmpStack . isEmpty ( ) ) { input . push ( tmpStack . peek ( ) ) ; tmpStack . pop ( ) ; } while ( ! input . empty ( ) ) { System . out . print ( input . peek ( ) + " ▁ " ) ; input . pop ( ) ; } } public static void main ( String args [ ] ) { Stack < Integer > input = new Stack < Integer > ( ) ; input . push ( 10 ) ; input . push ( 3 ) ; input . push ( 2 ) ; input . push ( 6 ) ; input . push ( 12 ) ; int k = 4 ; sortStack ( input , k ) ; } }


"Sort the given string using character search | Java implementation to sort the given String without using any sorting technique ; A character array to store the no . of occurrences of each character between ' a ' to ' z ' ; to store the final sorted String ; To store each occurrence of character by relative indexing ; To traverse the character array and append it to new_str ; Driver code"
How can the above be solved in Java?

class GFG { static String sortString ( String str , int n ) { int i ; char [ ] arr = new char [ 26 ] ; String new_str = " " ; for ( i = 0 ; i < n ; i ++ ) ++ arr [ str . charAt ( i ) - ' a ' ] ; for ( i = 0 ; i < 26 ; i ++ ) while ( arr [ i ] -- > 0 ) { new_str += String . valueOf ( ( char ) ( i + ' a ' ) ) ; } return new_str ; } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; int n = str . length ( ) ; System . out . print ( sortString ( str , n ) ) ; } }


"Sort the given string using character search | Java implementation to sort the given string without using any sorting technique ; function to sort the given string without using any sorting technique ; to store the final sorted string ; for each character ' i ' ; if character ' i ' is present at a particular index then add character ' i ' to ' new _ str ' ; required final sorted string ; Driver code"
How can the above be solved in Java?

class GFG { static String sortString ( String str , int n ) { String new_str = " " ; for ( int i = ' a ' ; i <= ' z ' ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) if ( str . charAt ( j ) == i ) new_str += str . charAt ( j ) ; return new_str ; } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; int n = str . length ( ) ; System . out . print ( sortString ( str , n ) ) ; } }


"Sort the linked list in the order of elements appearing in the array | Efficient JAVA program to sort given list in order elements are appearing in an array ; Linked list node ; Function to insert a node at the beginning of the linked list ; function to print the linked list ; Function that sort list in order of apperaing elements in an array ; Store frequencies of elements in a hash table . ; One by one put elements in lis according to their appearance in array ; Update ' frequency ' nodes with value equal to arr [ i ] ; Modify list data as element appear in an array ; Driver Code ; creating the linked list ; Function call to sort the list in order elements are apperaing in an array ; print the modified linked list"
How can the above be solved in Java?

 import java . util . * ; class GFG { static class Node { int data ; Node next ; } ; static Node push ( Node head_ref , int new_data ) { Node new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = head_ref ; head_ref = new_node ; return head_ref ; } static void printList ( Node head ) { while ( head != null ) { System . out . print ( head . data + " - > " ) ; head = head . next ; } } static void sortlist ( int arr [ ] , int N , Node head ) { HashMap < Integer , Integer > hash = new HashMap < Integer , Integer > ( ) ; Node temp = head ; while ( temp != null ) { if ( hash . containsKey ( temp . data ) ) hash . put ( temp . data , hash . get ( temp . data ) + 1 ) ; else hash . put ( temp . data , 1 ) ; temp = temp . next ; } temp = head ; for ( int i = 0 ; i < N ; i ++ ) { int frequency = hash . get ( arr [ i ] ) ; while ( frequency -- > 0 ) { temp . data = arr [ i ] ; temp = temp . next ; } } } public static void main ( String [ ] args ) { Node head = null ; int arr [ ] = { 5 , 1 , 3 , 2 , 8 } ; int N = arr . length ; head = push ( head , 3 ) ; head = push ( head , 2 ) ; head = push ( head , 5 ) ; head = push ( head , 8 ) ; head = push ( head , 5 ) ; head = push ( head , 2 ) ; head = push ( head , 1 ) ; sortlist ( arr , N , head ) ; System . out . print ( " Sorted ▁ List : " + "
"); printList ( head ) ; } }


"Sort the major diagonal of the matrix | Java implementation to sort the major diagonal of the matrix ; Function to sort the major diagonal of the matrix ; Loop to find the ith minimum element from the major diagonal ; Loop to find the minimum element from the unsorted matrix ; Swap to put the minimum element at the beginning of the major diagonal of matrix ; Loop to print the matrix ; Driven Code ; Sort the major Diagonal"
How can the above be solved in Java?

class GFG { static void sortDiagonal ( int a [ ] [ ] , int M , int N ) { for ( int i = 0 ; i < M ; i ++ ) { int sm = a [ i ] [ i ] ; int pos = i ; for ( int j = i + 1 ; j < N ; j ++ ) { if ( sm > a [ j ] [ j ] ) { sm = a [ j ] [ j ] ; pos = j ; } } swap ( a , i , i , pos , pos ) ; } for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) System . out . print ( a [ i ] [ j ] + " ▁ " ) ; System . out . println ( ) ; } } static void swap ( int [ ] [ ] a , int i , int i2 , int pos , int pos2 ) { int temp = a [ i ] [ i2 ] ; a [ i ] [ i2 ] = a [ pos ] [ pos2 ] ; a [ pos ] [ pos2 ] = temp ; } public static void main ( String [ ] args ) { int a [ ] [ ] = { { 4 , 2 } , { 3 , 1 } } ; sortDiagonal ( a , 2 , 2 ) ; } }


"Sort the strings based on the numbers of matchsticks required to represent them | Java implementation to sort the strings with the number of sticks required to represent them ; Stick [ ] stores the count of sticks required to represent the alphabets ; Number [ ] stores the count of sticks required to represent the numerals ; Utility Pair implementation ; Function that return the count of sticks required to represent the given string str ; Loop to iterate over every character of the string ; Add the count of sticks required to represent the current character ; Function to sort the array according to the number of sticks required to represent it ; ArrayList to store the number of sticks required with respective strings ; Inserting number of sticks with respective strings ; Sort the list , ; Print the sorted vector ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int sticks [ ] = { 6 , 7 , 4 , 6 , 5 , 4 , 6 , 5 , 2 , 4 , 4 , 3 , 6 , 6 , 6 , 5 , 7 , 6 , 5 , 3 , 5 , 4 , 6 , 4 , 3 , 4 } ; static int number [ ] = { 6 , 2 , 5 , 5 , 4 , 5 , 6 , 3 , 7 , 6 } ; static class Pair implements Comparable < Pair > { int num_sticks ; String str ; Pair ( int n , String s ) { num_sticks = n ; str = s ; } public int compareTo ( Pair p ) { return this . num_sticks - p . num_sticks ; } } static int countSticks ( String str ) { int cnt = 0 ; int n = str . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { char ch = str . charAt ( i ) ; if ( ch >= ' A ' && ch <= ' Z ' ) { cnt += sticks [ ch - ' A ' ] ; } else { cnt += number [ ch - '0' ] ; } } return cnt ; } static void sortArr ( String arr [ ] , int n ) { ArrayList < Pair > list = new ArrayList < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { list . add ( new Pair ( countSticks ( arr [ i ] ) , arr [ i ] ) ) ; } Collections . sort ( list ) ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) System . out . print ( list . get ( i ) . str + " ▁ " ) ; } public static void main ( String [ ] args ) { String arr [ ] = { " GEEKS " , " FOR " , " GEEKSFORGEEKS " } ; int n = arr . length ; sortArr ( arr , n ) ; } }


"Sort ugly numbers in an array at their relative positions | Java implementation of the approach ; Function that returns true if n is an ugly number ; While divisible by 2 , keep dividing ; While divisible by 3 , keep dividing ; While divisible by 5 , keep dividing ; n must be 1 if it was ugly ; Function to sort ugly numbers in their relative positions ; To store the ugly numbers from the array ; If current element is an ugly number ; Add it to the ArrayList and set arr [ i ] to - 1 ; Sort the ugly numbers ; Position of an ugly number ; Driver code"
How can the above be solved in Java?

import java . util . ArrayList ; import java . util . Collections ; class GFG { static boolean isUgly ( int n ) { while ( n % 2 == 0 ) n = n / 2 ; while ( n % 3 == 0 ) n = n / 3 ; while ( n % 5 == 0 ) n = n / 5 ; if ( n == 1 ) return true ; return false ; } static void sortUglyNumbers ( int arr [ ] , int n ) { ArrayList < Integer > list = new ArrayList < > ( ) ; int i ; for ( i = 0 ; i < n ; i ++ ) { if ( isUgly ( arr [ i ] ) ) { list . add ( arr [ i ] ) ; arr [ i ] = - 1 ; } } Collections . sort ( list ) ; int j = 0 ; for ( i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == - 1 ) System . out . print ( list . get ( j ++ ) + " ▁ " ) ; else System . out . print ( arr [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 7 , 12 , 10 } ; int n = arr . length ; sortUglyNumbers ( arr , n ) ; } }


"Sorted insert for circular linked list | Case 2 of the above algo ; swap the data part of head node and new node assuming that we have a function swap ( int * , int * )"
How can the above be solved in Java?

else if ( current . data >= new_node . data ) { Node tmp = current . data ; current . data = new_node . data ; new_node . data = tmp ; new_node . next = ( head_ref ) . next ; ( head_ref ) . next = new_node ; }


"Sorted insert in a doubly linked list with head and tail pointers | Java program to insetail nodes in doubly linked list such that list remains in ascending order on printing from left to right ; A linked list node ; Function to insetail new node ; If first node to be insetailed in doubly linked list ; If node to be insetailed has value less than first node ; If node to be insetailed has value more than last node ; Find the node before which we need to insert p . ; Insert new node before temp ; Function to print nodes in from left to right ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class Node { int info ; Node prev , next ; } class GFG { static Node head , tail ; static void nodeInsetail ( int key ) { Node p = new Node ( ) ; p . info = key ; p . next = null ; if ( head == null ) { head = p ; tail = p ; head . prev = null ; return ; } if ( p . info < head . info ) { p . prev = null ; head . prev = p ; p . next = head ; head = p ; return ; } if ( p . info > tail . info ) { p . prev = tail ; tail . next = p ; tail = p ; return ; } Node temp = head . next ; while ( temp . info < p . info ) temp = temp . next ; ( temp . prev ) . next = p ; p . prev = temp . prev ; temp . prev = p ; p . next = temp ; } static void printList ( Node temp ) { while ( temp != null ) { System . out . print ( temp . info + " ▁ " ) ; temp = temp . next ; } } public static void main ( String args [ ] ) { head = tail = null ; nodeInsetail ( 30 ) ; nodeInsetail ( 50 ) ; nodeInsetail ( 90 ) ; nodeInsetail ( 10 ) ; nodeInsetail ( 40 ) ; nodeInsetail ( 110 ) ; nodeInsetail ( 60 ) ; nodeInsetail ( 95 ) ; nodeInsetail ( 23 ) ; System . out . println ( " Doubly ▁ linked ▁ list ▁ on ▁ printing ▁ from ▁ left ▁ to ▁ right " ) ; printList ( head ) ; } }


"Sorted merge of two sorted doubly circular linked lists | Java implementation for Sorted merge of two sorted doubly circular linked list ; A utility function to insert a new node at the beginning of doubly circular linked list ; allocate space ; put in the data ; if list is empty ; pointer points to last Node ; setting up previous and next of new node ; update next and previous pointers of head_ref and last . ; update head_ref pointer ; function for Sorted merge of two sorted doubly linked list ; If first list is empty ; If second list is empty ; Pick the smaller value and adjust the links ; function for Sorted merge of two sorted doubly circular linked list ; if 1 st list is empty ; if 2 nd list is empty ; get pointer to the node which will be the last node of the final list ; store null to the ' next ' link of the last nodes of the two lists ; sorted merge of head1 and head2 ; ' prev ' of 1 st node pointing the last node ' next ' of last node pointing to 1 st node ; function to print the list ; Driver code ; list 1 : ; list 2 :"
How can the above be solved in Java?

class GFG { static class Node { int data ; Node next , prev ; } ; static Node insert ( Node head_ref , int data ) { Node new_node = new Node ( ) ; new_node . data = data ; if ( head_ref == null ) { new_node . next = new_node ; new_node . prev = new_node ; } else { Node last = ( head_ref ) . prev ; new_node . next = head_ref ; new_node . prev = last ; last . next = ( head_ref ) . prev = new_node ; } head_ref = new_node ; return head_ref ; } static Node merge ( Node first , Node second ) { if ( first == null ) return second ; if ( second == null ) return first ; if ( first . data < second . data ) { first . next = merge ( first . next , second ) ; first . next . prev = first ; first . prev = null ; return first ; } else { second . next = merge ( first , second . next ) ; second . next . prev = second ; second . prev = null ; return second ; } } static Node mergeUtil ( Node head1 , Node head2 ) { if ( head1 == null ) return head2 ; if ( head2 == null ) return head1 ; Node last_node ; if ( head1 . prev . data < head2 . prev . data ) last_node = head2 . prev ; else last_node = head1 . prev ; head1 . prev . next = head2 . prev . next = null ; Node finalHead = merge ( head1 , head2 ) ; finalHead . prev = last_node ; last_node . next = finalHead ; return finalHead ; } static void printList ( Node head ) { Node temp = head ; while ( temp . next != head ) { System . out . print ( temp . data + " ▁ " ) ; temp = temp . next ; } System . out . print ( temp . data + " ▁ " ) ; } public static void main ( String args [ ] ) { Node head1 = null , head2 = null ; head1 = insert ( head1 , 8 ) ; head1 = insert ( head1 , 5 ) ; head1 = insert ( head1 , 3 ) ; head1 = insert ( head1 , 1 ) ; head2 = insert ( head2 , 11 ) ; head2 = insert ( head2 , 9 ) ; head2 = insert ( head2 , 7 ) ; head2 = insert ( head2 , 2 ) ; Node newHead = mergeUtil ( head1 , head2 ) ; System . out . print ( " Final ▁ Sorted ▁ List : ▁ " ) ; printList ( newHead ) ; } }


"Sorted order printing of a given array that represents a BST | JAVA Code for Sorted order printing of a given array that represents a BST ; print left subtree ; print root ; print right subtree ; driver program to test above function"
How can the above be solved in Java?

class GFG { private static void printSorted ( int [ ] arr , int start , int end ) { if ( start > end ) return ; printSorted ( arr , start * 2 + 1 , end ) ; System . out . print ( arr [ start ] + " ▁ " ) ; printSorted ( arr , start * 2 + 2 , end ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 2 , 5 , 1 , 3 } ; printSorted ( arr , 0 , arr . length - 1 ) ; } }


"Sorting Strings using Bubble Sort | Java implementation ; Sorting strings using bubble sort ; Driver code"
How can the above be solved in Java?

class GFG { static int MAX = 100 ; public static void sortStrings ( String [ ] arr , int n ) { String temp ; for ( int j = 0 ; j < n - 1 ; j ++ ) { for ( int i = j + 1 ; i < n ; i ++ ) { if ( arr [ j ] . compareTo ( arr [ i ] ) > 0 ) { temp = arr [ j ] ; arr [ j ] = arr [ i ] ; arr [ i ] = temp ; } } } } public static void main ( String [ ] args ) { String [ ] arr = { " GeeksforGeeks " , " Quiz " , " Practice " , " Gblogs " , " Coding " } ; int n = arr . length ; sortStrings ( arr , n ) ; System . out . println ( " Strings ▁ in ▁ sorted ▁ order ▁ are ▁ : ▁ " ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . println ( " String ▁ " + ( i + 1 ) + " ▁ is ▁ " + arr [ i ] ) ; } }


"Sorting a Queue without extra space | Java program to implement sorting a queue data structure ; Queue elements after sortIndex are already sorted . This function returns index of minimum element from front to sortIndex ; This is dequeue ( ) in Java STL ; we add the condition i <= sortIndex because we don 't want to traverse  on the sorted part of the queue,  which is the right part. ; This is enqueue ( ) in C ++ STL ; Moves given minimum element to rear of queue ; SortQueue Function ; Driver function ; Sort Queue ; print sorted Queue"
How can the above be solved in Java?

import java . util . LinkedList ; import java . util . Queue ; class GFG { public static int minIndex ( Queue < Integer > list , int sortIndex ) { int min_index = - 1 ; int min_value = Integer . MAX_VALUE ; int s = list . size ( ) ; for ( int i = 0 ; i < s ; i ++ ) { int current = list . peek ( ) ; list . poll ( ) ; if ( current <= min_value && i <= sortIndex ) { min_index = i ; min_value = current ; } list . add ( current ) ; } return min_index ; } public static void insertMinToRear ( Queue < Integer > list , int min_index ) { int min_value = 0 ; int s = list . size ( ) ; for ( int i = 0 ; i < s ; i ++ ) { int current = list . peek ( ) ; list . poll ( ) ; if ( i != min_index ) list . add ( current ) ; else min_value = current ; } list . add ( min_value ) ; } public static void sortQueue ( Queue < Integer > list ) { for ( int i = 1 ; i <= list . size ( ) ; i ++ ) { int min_index = minIndex ( list , list . size ( ) - i ) ; insertMinToRear ( list , min_index ) ; } } public static void main ( String [ ] args ) { Queue < Integer > list = new LinkedList < Integer > ( ) ; list . add ( 30 ) ; list . add ( 11 ) ; list . add ( 15 ) ; list . add ( 4 ) ; sortQueue ( list ) ; while ( list . isEmpty ( ) == false ) { System . out . print ( list . peek ( ) + " ▁ " ) ; list . poll ( ) ; } } }


"Sorting all array elements except one | Java program to sort all elements except element at index k . ; Move k - th element to end ; Sort all elements except last ; Store last element ( originally k - th ) ; Move all elements from k - th to one position ahead . ; Restore k - th element ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static int sortExceptK ( int arr [ ] , int k , int n ) { int temp = arr [ k ] ; arr [ k ] = arr [ n - 1 ] ; arr [ n - 1 ] = temp ; Arrays . sort ( arr , 0 , n - 1 ) ; int last = arr [ n - 1 ] ; for ( int i = n - 1 ; i > k ; i -- ) arr [ i ] = arr [ i - 1 ] ; arr [ k ] = last ; return 0 ; } public static void main ( String [ ] args ) { int a [ ] = { 10 , 4 , 11 , 7 , 6 , 20 } ; int k = 2 ; int n = a . length ; sortExceptK ( a , k , n ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( a [ i ] + " ▁ " ) ; } }


"Sorting array elements with set bits equal to K | Java program for sorting array elements with set bits equal to K ; Represents node of a doubly linked list ; Function to sort elements with set bits equal to k ; initialise two vectors ; first vector contains indices of required element ; second vector contains required elements ; sorting the elements in second vector ; replacing the elements with k set bits with the sorted elements ; printing the new sorted array elements ; Driver code"
How can the above be solved in Java?

import java . util . * ; class Node { static void sortWithSetbits ( int arr [ ] , int n , int k ) { Vector < Integer > v1 = new Vector < > ( ) , v2 = new Vector < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( Integer . bitCount ( arr [ i ] ) == k ) { v1 . add ( i ) ; v2 . add ( arr [ i ] ) ; } } Collections . sort ( v2 ) ; for ( int i = 0 ; i < v1 . size ( ) ; i ++ ) { arr [ v1 . get ( i ) ] = v2 . get ( i ) ; } for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 14 , 255 , 1 , 7 , 13 } ; int n = arr . length ; int k = 3 ; sortWithSetbits ( arr , n , k ) ; } }


"Sorting array except elements in a subarray | Java program to sort all elements except given subarray . ; Sort whole array a [ ] except elements in range a [ l . . r ] ; Copy all those element that need to be sorted to an auxiliary array b [ ] ; sort the array b ; Copy sorted elements back to a [ ] ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; import java . io . * ; public class GFG { public static void sortExceptUandL ( int a [ ] , int l , int u , int n ) { int b [ ] = new int [ n - ( u - l + 1 ) ] ; for ( int i = 0 ; i < l ; i ++ ) b [ i ] = a [ i ] ; for ( int i = u + 1 ; i < n ; i ++ ) b [ l + ( i - ( u + 1 ) ) ] = a [ i ] ; Arrays . sort ( b ) ; for ( int i = 0 ; i < l ; i ++ ) a [ i ] = b [ i ] ; for ( int i = u + 1 ; i < n ; i ++ ) a [ i ] = b [ l + ( i - ( u + 1 ) ) ] ; } public static void main ( String args [ ] ) { int a [ ] = { 5 , 4 , 3 , 12 , 14 , 9 } ; int n = a . length ; int l = 2 , u = 4 ; sortExceptUandL ( a , l , u , n ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( a [ i ] + " ▁ " ) ; } }


"Sorting array of strings ( or words ) using Trie | Java program to sort an array of strings using Trie ; index is set when node is a leaf node , otherwise - 1 ; ; to make new trie ; function to insert in trie ; taking ascii value to find index of child node ; making new path if not already ; go to next node ; Mark leaf ( end of word ) and store index of word in arr [ ] ; function for preorder traversal ; if leaf node then print key ; insert all keys of dictionary into trie ; print keys in lexicographic order ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static final int MAX_CHAR = 26 ; static class Trie { int index ; Trie child [ ] = new Trie [ MAX_CHAR ] ; Trie ( ) { for ( int i = 0 ; i < MAX_CHAR ; i ++ ) child [ i ] = null ; index = - 1 ; } } static void insert ( Trie root , String str , int index ) { Trie node = root ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { int ind = str . charAt ( i ) - ' a ' ; if ( node . child [ ind ] == null ) node . child [ ind ] = new Trie ( ) ; node = node . child [ ind ] ; } node . index = index ; } static boolean preorder ( Trie node , String arr [ ] ) { if ( node == null ) { return false ; } for ( int i = 0 ; i < MAX_CHAR ; i ++ ) { if ( node . child [ i ] != null ) { if ( node . child [ i ] . index != - 1 ) { System . out . print ( arr [ node . child [ i ] . index ] + " ▁ " ) ; } preorder ( node . child [ i ] , arr ) ; } } return false ; } static void printSorted ( String arr [ ] , int n ) { Trie root = new Trie ( ) ; for ( int i = 0 ; i < n ; ++ i ) { insert ( root , arr [ i ] , i ) ; } preorder ( root , arr ) ; } public static void main ( String [ ] args ) { String arr [ ] = { " abc " , " xy " , " bcd " } ; int n = arr . length ; printSorted ( arr , n ) ; } }


"Sorting array using Stacks | Java program to sort an array using stack ; This function return the sorted stack ; pop out the first element ; while temporary stack is not empty and top of stack is smaller than temp ; pop from temporary stack and push it to the input stack ; push temp in tempory of stack ; push array elements to stack ; Sort the temporary stack ; Put stack elements in arrp [ ] ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static Stack < Integer > sortStack ( Stack < Integer > input ) { Stack < Integer > tmpStack = new Stack < Integer > ( ) ; while ( ! input . empty ( ) ) { int tmp = input . peek ( ) ; input . pop ( ) ; while ( ! tmpStack . empty ( ) && tmpStack . peek ( ) < tmp ) { input . push ( tmpStack . peek ( ) ) ; tmpStack . pop ( ) ; } tmpStack . push ( tmp ) ; } return tmpStack ; } static void sortArrayUsingStacks ( int [ ] arr , int n ) { Stack < Integer > input = new Stack < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) input . push ( arr [ i ] ) ; Stack < Integer > tmpStack = sortStack ( input ) ; for ( int i = 0 ; i < n ; i ++ ) { arr [ i ] = tmpStack . peek ( ) ; tmpStack . pop ( ) ; } } public static void main ( String args [ ] ) { int [ ] arr = { 10 , 5 , 15 , 45 } ; int n = arr . length ; sortArrayUsingStacks ( arr , n ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } }


"Sorting array with conditional swapping | Java program to Check if it is possible to sort the array in ascending order . ; Function to check if it is possible to sort the array ; Calculating max_element at each iteration . ; if we can not swap the i - th element . ; if it is impossible to swap the max_element then we can not sort the array . ; Otherwise , we can sort the array . ; Driven Program"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { public static String possibleToSort ( int arr [ ] , int n , String str ) { int max_element = - 1 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { max_element = Math . max ( max_element , arr [ i ] ) ; if ( str . charAt ( i ) == '0' ) { if ( max_element > i + 1 ) return " No " ; } } return " Yes " ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 5 , 3 , 4 , 6 } ; int n = arr . length ; String str = "01110" ; System . out . println ( possibleToSort ( arr , n , str ) ) ; } }


"Sorting array with reverse around middle | Java program to find possibility to sort by multiple subarray reverse operation ; making the copy of the original array ; sorting the copied array ; checking mirror image of elements of sorted copy array and equivalent element of original array ; driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean ifPossible ( int arr [ ] , int n ) { int copy [ ] = Arrays . copyOf ( arr , arr . length ) ; Arrays . sort ( copy ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! ( arr [ i ] == copy [ i ] ) && ! ( arr [ n - 1 - i ] == copy [ i ] ) ) return false ; } return true ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 7 , 6 , 4 , 5 , 3 , 2 , 8 } ; int n = arr . length ; if ( ifPossible ( arr , n ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Sorting objects using In | Java implementation of the approach ; Partition function which will partition the array and into two parts ; Compare hash values of objects ; Classic quicksort algorithm ; Function to sort and print the objects ; Create a hash table ; As the sorting order is blue objects , red objects and then yellow objects ; Quick sort function ; Printing the sorted array ; Driver code ; Let 's represent objects as strings"
How can the above be solved in Java?

import java . util . * ; class GFG { static int partition ( Vector < String > objects , int l , int r , Map < String , Integer > hash ) { int j = l - 1 ; int last_element = hash . get ( objects . get ( r ) ) ; for ( int i = l ; i < r ; i ++ ) { if ( hash . get ( objects . get ( i ) ) <= last_element ) { j ++ ; Collections . swap ( objects , i , j ) ; } } j ++ ; Collections . swap ( objects , j , r ) ; return j ; } static void quicksort ( Vector < String > objects , int l , int r , Map < String , Integer > hash ) { if ( l < r ) { int mid = partition ( objects , l , r , hash ) ; quicksort ( objects , l , mid - 1 , hash ) ; quicksort ( objects , mid + 1 , r , hash ) ; } } static void sortObj ( Vector < String > objects ) { Map < String , Integer > hash = new HashMap < > ( ) ; hash . put ( " blue " , 1 ) ; hash . put ( " red " , 2 ) ; hash . put ( " yellow " , 3 ) ; quicksort ( objects , 0 , objects . size ( ) - 1 , hash ) ; for ( int i = 0 ; i < objects . size ( ) ; i ++ ) System . out . print ( objects . get ( i ) + " ▁ " ) ; } public static void main ( String [ ] args ) { Vector < String > objects = new Vector < > ( Arrays . asList ( " red " , " blue " , " red " , " yellow " , " blue " ) ) ; sortObj ( objects ) ; } }


"Sorting without comparison of elements | Java program to sort an array without comparison operator . ; Represents node of a doubly linked list ; Count of elements in given range ; Count frequencies of all elements ; Traverse through range . For every element , print it its count times . ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class Node { static void sortArr ( int arr [ ] , int n , int min , int max ) { int m = max - min + 1 ; int [ ] c = new int [ m ] ; for ( int i = 0 ; i < n ; i ++ ) { c [ arr [ i ] - min ] ++ ; } for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 0 ; j < c [ i ] ; j ++ ) { System . out . print ( ( i + min ) + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 10 , 1 , 4 , 4 , 100 , 0 } ; int min = 0 , max = 100 ; int n = arr . length ; sortArr ( arr , n , min , max ) ; } }


"Source to destination in 2 | Java implementation of the approach ; Function that returns true if it is possible to move from source to the destination with the given moves ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static boolean isPossible ( int Sx , int Sy , int Dx , int Dy , int x , int y ) { if ( Math . abs ( Sx - Dx ) % x == 0 && Math . abs ( Sy - Dy ) % y == 0 && ( Math . abs ( Sx - Dx ) / x ) % 2 == ( Math . abs ( Sy - Dy ) / y ) % 2 ) return true ; return false ; } public static void main ( String [ ] args ) { int Sx = 0 , Sy = 0 , Dx = 0 , Dy = 0 ; int x = 3 , y = 4 ; if ( isPossible ( Sx , Sy , Dx , Dy , x , y ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Space efficient iterative method to Fibonacci number | Java code to find nth fibonacci ; get second MSB ; consectutively set all the bits ; returns the second MSB ; Multiply function ; Function to calculate F [ ] [ ] raise to the power n ; Base case ; take 2D array to store number 's ; run loop till MSB > 0 ; To return fibonacci number ; Driver Code ; Given n"
How can the above be solved in Java?


"Space optimization using bit manipulations | Java code to for marking multiples ; index >> 5 corresponds to dividing index by 32 index & 31 corresponds to modulo operation of index by 32 Function to check value of bit position whether it is zero or one ; Sets value of bit for corresponding index ; Driver code ; Size that will be used is actual_size / 32 ceil is used to initialize the array with positive number ; Array is dynamically initialized as we are calculating size at run time ; Iterate through every index from a to b and call setbit ( ) if it is a multiple of 2 or 5"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static boolean checkbit ( int array [ ] , int index ) { int val = array [ index >> 5 ] & ( 1 << ( index & 31 ) ) ; if ( val == 0 ) return false ; return true ; } static void setbit ( int array [ ] , int index ) { array [ index >> 5 ] |= ( 1 << ( index & 31 ) ) ; } public static void main ( String args [ ] ) { int a = 2 , b = 10 ; int size = Math . abs ( b - a ) ; size = ( int ) Math . ceil ( ( double ) size / 32 ) ; int [ ] array = new int [ size ] ; for ( int i = a ; i <= b ; i ++ ) if ( i % 2 == 0 i % 5 == 0 ) setbit ( array , i - a ) ; System . out . println ( " MULTIPLES ▁ of ▁ 2 ▁ and ▁ 5 : " ) ; for ( int i = a ; i <= b ; i ++ ) if ( checkbit ( array , i - a ) ) System . out . print ( i + " ▁ " ) ; } }


"Space optimization using bit manipulations | Java program to mark numbers as multiple of 2 or 5 ; Driver code ; Iterate through a to b , If it is a multiple of 2 or 5 Mark index in array as 1"
How can the above be solved in Java?

import java . lang . * ; class GFG { public static void main ( String [ ] args ) { int a = 2 , b = 10 ; int size = Math . abs ( b - a ) + 1 ; int array [ ] = new int [ size ] ; for ( int i = a ; i <= b ; i ++ ) if ( i % 2 == 0 i % 5 == 0 ) array [ i - a ] = 1 ; System . out . println ( " MULTIPLES ▁ of ▁ 2" + " ▁ and ▁ 5 : " ) ; for ( int i = a ; i <= b ; i ++ ) if ( array [ i - a ] == 1 ) System . out . printf ( i + " ▁ " ) ; } }


"Spanning Tree With Maximum Degree ( Using Kruskal 's Algorithm) | Java implementation of the approach ; par and rank will store the parent and rank of particular node in the Union Find Algorithm ; Find function of Union Find Algorithm ; Union function of Union Find Algorithm ; Function to find the required spanning tree ; Initialising parent of a node by itself ; Variable to store the node with maximum degree ; Finding the node with maximum degree ; Union of all edges incident on vertex with maximum degree ; Carrying out normal Kruskal Algorithm ; Driver code ; Number of nodes ; Number of edges ; ArrayList to store the graph ; Array to store the degree of each node in the graph ; Add edges and update degrees"
How can the above be solved in Java?

import java . util . * ; public class GFG { static int par [ ] , rank [ ] ; static int find ( int x ) { if ( par [ x ] != x ) par [ x ] = find ( par [ x ] ) ; return par [ x ] ; } static void union ( int u , int v ) { int x = find ( u ) ; int y = find ( v ) ; if ( x == y ) return ; if ( rank [ x ] > rank [ y ] ) par [ y ] = x ; else if ( rank [ x ] < rank [ y ] ) par [ x ] = y ; else { par [ x ] = y ; rank [ y ] ++ ; } } static void findSpanningTree ( int deg [ ] , int n , int m , ArrayList < Integer > g [ ] ) { par = new int [ n + 1 ] ; rank = new int [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) par [ i ] = i ; int max = 1 ; for ( int i = 2 ; i <= n ; i ++ ) if ( deg [ i ] > deg [ max ] ) max = i ; for ( int v : g [ max ] ) { System . out . println ( max + " ▁ " + v ) ; union ( max , v ) ; } for ( int u = 1 ; u <= n ; u ++ ) { for ( int v : g [ u ] ) { int x = find ( u ) ; int y = find ( v ) ; if ( x == y ) continue ; union ( x , y ) ; System . out . println ( u + " ▁ " + v ) ; } } } public static void main ( String args [ ] ) { int n = 5 ; int m = 5 ; ArrayList < Integer > g [ ] = new ArrayList [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) g [ i ] = new ArrayList < > ( ) ; int deg [ ] = new int [ n + 1 ] ; g [ 1 ] . add ( 2 ) ; g [ 2 ] . add ( 1 ) ; deg [ 1 ] ++ ; deg [ 2 ] ++ ; g [ 1 ] . add ( 5 ) ; g [ 5 ] . add ( 1 ) ; deg [ 1 ] ++ ; deg [ 5 ] ++ ; g [ 2 ] . add ( 3 ) ; g [ 3 ] . add ( 2 ) ; deg [ 2 ] ++ ; deg [ 3 ] ++ ; g [ 5 ] . add ( 3 ) ; g [ 3 ] . add ( 5 ) ; deg [ 3 ] ++ ; deg [ 5 ] ++ ; g [ 3 ] . add ( 4 ) ; g [ 4 ] . add ( 3 ) ; deg [ 3 ] ++ ; deg [ 4 ] ++ ; findSpanningTree ( deg , n , m , g ) ; } }


"Sparse Search | Java program to implement binary search in a sparse array . ; Binary Search in an array with blanks ; Modified Part ; Search for both side for a non empty string ; No non - empty string on both sides ; Normal Binary Search ; Driver code"
How can the above be solved in Java?

class solution { static int binarySearch ( String arr [ ] , int low , int high , String x ) { if ( low > high ) return - 1 ; int mid = ( low + high ) / 2 ; if ( arr [ mid ] == " " ) { int left = mid - 1 ; int right = mid + 1 ; while ( true ) { if ( left < low && right > high ) return - 1 ; if ( left >= low && arr [ left ] != " " ) { mid = left ; break ; } else if ( right <= high && arr [ right ] != " " ) { mid = right ; break ; } left -- ; right ++ ; } } if ( arr [ mid ] == x ) return mid ; else if ( x . compareTo ( arr [ mid ] ) < 0 ) return binarySearch ( arr , low , mid - 1 , x ) ; else return binarySearch ( arr , mid + 1 , high , x ) ; } static int sparseSearch ( String arr [ ] , String x , int n ) { return binarySearch ( arr , 0 , n - 1 , x ) ; } public static void main ( String args [ ] ) { String arr [ ] = { " for " , " geeks " , " " , " " , " " , " " , " ide " , " practice " , " " , " " , " " , " quiz " } ; String x = " geeks " ; int n = x . length ( ) ; int index = sparseSearch ( arr , x , n ) ; if ( index != - 1 ) System . out . println ( x + " ▁ found ▁ at ▁ index ▁ " + index ) ; else System . out . println ( x + " ▁ not ▁ found " ) ; } }


"Special prime numbers | Java program to check whether there exist at least k or not in range [ 2. . n ] ; Generating all the prime numbers from 2 to n . ; If a prime number is Special prime number , then we increments the value of k . ; If at least k Special prime numbers are present , then we return 1. else we return 0 from outside of the outer loop . ; Driver function"
How can the above be solved in Java?

import java . util . * ; class GFG { static ArrayList < Integer > primes = new ArrayList < Integer > ( ) ; static void SieveofEratosthenes ( int n ) { boolean [ ] visited = new boolean [ n * n + 2 ] ; for ( int i = 2 ; i <= n + 1 ; i ++ ) if ( ! visited [ i ] ) { for ( int j = i * i ; j <= n + 1 ; j += i ) visited [ j ] = true ; primes . add ( i ) ; } } static boolean specialPrimeNumbers ( int n , int k ) { SieveofEratosthenes ( n ) ; int count = 0 ; for ( int i = 0 ; i < primes . size ( ) ; i ++ ) { for ( int j = 0 ; j < i - 1 ; j ++ ) { if ( primes . get ( j ) + primes . get ( j + 1 ) + 1 == primes . get ( i ) ) { count ++ ; break ; } } if ( count == k ) return true ; } return false ; } public static void main ( String [ ] args ) { int n = 27 , k = 2 ; if ( specialPrimeNumbers ( n , k ) ) System . out . println ( " YES " ) ; else System . out . println ( " NO " ) ; } }


"Special two digit numbers in a Binary Search Tree | A binary tree node ; Function to create a new node ; If the tree is empty , return a new , single node ; Otherwise , recur down the tree ; return the ( unchanged ) node pointer ; Function to find if number is special or not ; Check if number is two digit or not ; Function to count number of special two digit number ; Driver code ; Function call"
How can the above be solved in Java?

class Node { int info ; Node left , right ; Node ( int d ) { info = d ; left = right = null ; } } class BinaryTree { static Node head ; static int count ; Node insert ( Node node , int info ) { if ( node == null ) { return ( new Node ( info ) ) ; } else { if ( info <= node . info ) { node . left = insert ( node . left , info ) ; } else { node . right = insert ( node . right , info ) ; } return node ; } } static int check ( int num ) { int sum = 0 , i = num , sum_of_digits , prod_of_digits ; if ( num < 10 num > 99 ) return 0 ; else { sum_of_digits = ( i % 10 ) + ( i / 10 ) ; prod_of_digits = ( i % 10 ) * ( i / 10 ) ; sum = sum_of_digits + prod_of_digits ; } if ( sum == num ) return 1 ; else return 0 ; } static void countSpecialDigit ( Node rt ) { int x ; if ( rt == null ) return ; else { x = check ( rt . info ) ; if ( x == 1 ) count = count + 1 ; countSpecialDigit ( rt . left ) ; countSpecialDigit ( rt . right ) ; } } public static void main ( String [ ] args ) { BinaryTree tree = new BinaryTree ( ) ; Node root = null ; root = tree . insert ( root , 50 ) ; tree . insert ( root , 29 ) ; tree . insert ( root , 59 ) ; tree . insert ( root , 19 ) ; tree . insert ( root , 53 ) ; tree . insert ( root , 556 ) ; tree . insert ( root , 56 ) ; tree . insert ( root , 94 ) ; tree . insert ( root , 13 ) ; countSpecialDigit ( root ) ; System . out . println ( count ) ; } }


"Spell Checker using Trie | Java program to implement the above approach ; Structure of a Trie node ; Store address of a character ; Check if the character is last character of a string or not ; Constructor function ; Function to insert a string into Trie ; Traverse the string , s ; Initialize a node ; Update temp ; Mark the last character of the string to true ; Function to print suggestions of the string ; If current character is the last character of a string ; Iterate over all possible characters of the string ; If current character present in the Trie ; Insert current character into Trie ; Function to check if the string is present in Trie or not ; Traverse the string ; If current character not present in the Trie ; Update root ; Driver Code ; Given array of strings ; Initialize a Trie ; Insert strings to trie"
How can the above be solved in Java?

import java . io . * ; class TrieNode { TrieNode Trie [ ] ; boolean isEnd ; public TrieNode ( ) { Trie = new TrieNode [ 256 ] ; for ( int i = 0 ; i < 256 ; i ++ ) { Trie [ i ] = null ; } isEnd = false ; } } class GFG { static void InsertTrie ( TrieNode root , String s ) { TrieNode temp = root ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( temp . Trie [ s . charAt ( i ) ] == null ) { temp . Trie [ s . charAt ( i ) ] = new TrieNode ( ) ; } temp = temp . Trie [ s . charAt ( i ) ] ; } temp . isEnd = true ; } static void printSuggestions ( TrieNode root , String res ) { if ( root . isEnd == true ) { System . out . print ( res + " ▁ " ) ; } for ( int i = 0 ; i < 256 ; i ++ ) { if ( root . Trie [ i ] != null ) { res += ( char ) i ; printSuggestions ( root . Trie [ i ] , res ) ; res = res . substring ( 0 , res . length ( ) - 2 ) ; } } } static boolean checkPresent ( TrieNode root , String key ) { for ( int i = 0 ; i < key . length ( ) ; i ++ ) { if ( root . Trie [ key . charAt ( i ) ] == null ) { printSuggestions ( root , key . substring ( 0 , i ) ) ; return false ; } root = root . Trie [ key . charAt ( i ) ] ; } if ( root . isEnd == true ) { return true ; } printSuggestions ( root , key ) ; return false ; } public static void main ( String [ ] args ) { String str [ ] = { " gee " , " geeks " , " ape " , " apple " , " geeksforgeeks " } ; String key = " geek " ; TrieNode root = new TrieNode ( ) ; for ( int i = 0 ; i < str . length ; i ++ ) { InsertTrie ( root , str [ i ] ) ; } if ( checkPresent ( root , key ) ) { System . out . println ( " YES " ) ; } } }


"Sphenic Number | Java program to check whether a number is a Sphenic number or not ; create a global array of size 10001 ; ; This functions finds all primes smaller than ' limit ' using simple sieve of eratosthenes . ; initialize all entries of it as true . A value in mark [ p ] will finally be false if ' p ' is Not a prime , else true . ; One by one traverse all numbers so that their multiples can be marked as composite . ; If p is not changed , then it is a prime ; Update all multiples of p ; to store the 8 divisors ; to count the number of divisor ; finally check if there re 8 divisor and all the numbers are distinct prime no return 1 else return 0 ) ; ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean [ ] arr = new boolean [ 1001 ] ; static void simpleSieve ( ) { Arrays . fill ( arr , true ) ; for ( int p = 2 ; p * p < 1001 ; p ++ ) { if ( arr [ p ] ) { for ( int i = p * 2 ; i < 1001 ; i = i + p ) arr [ i ] = false ; } } } static int find_sphene ( int N ) { int [ ] arr1 = new int [ 8 ] ; int count = 0 ; int j = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { if ( N % i == 0 && count < 8 ) { count ++ ; arr1 [ j ++ ] = i ; } } if ( count == 8 && ( arr [ arr1 [ 1 ] ] && arr [ arr1 [ 2 ] ] && arr [ arr1 [ 3 ] ] ) ) return 1 ; return 0 ; } public static void main ( String [ ] args ) { int n = 60 ; simpleSieve ( ) ; int ans = find_sphene ( n ) ; if ( ans == 1 ) System . out . print ( " Yes " ) ; else System . out . print ( " NO " ) ; } }


"Split Array into min number of subsets with difference between each pair greater than 1 | Java program for the above approach ; Function to split the array into minimum number of subsets with difference strictly > 1 ; Sort the array ; Traverse through the sorted array ; Check the pairs of elements with difference 1 ; If we find even a single pair with difference equal to 1 , then 2 partitions else only 1 partition ; Print the count of partitions ; Driver Code ; Given array ; Size of the array ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void split ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int count = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] - arr [ i - 1 ] == 1 ) { count = 2 ; break ; } } System . out . print ( count ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 4 , 6 } ; int n = arr . length ; split ( arr , n ) ; } }


"Split N ^ 2 numbers into N groups of equal sum | Java implementation of the above approach ; Function to print N groups of equal sum ; No . of Groups ; n / 2 pairs ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void printGroups ( int n ) { int x = 1 ; int y = n * n ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= n / 2 ; j ++ ) { System . out . print ( " { ▁ " + x + " , ▁ " + y + " } ▁ " ) ; x ++ ; y -- ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { int n = 4 ; printGroups ( n ) ; } }


"Split N as the sum of K numbers satisfying the given conditions | Java Program to implement the above approach ; Vector to store prime numbers ; Function to generate prime numbers using SieveOfEratosthenes ; Boolean array to store primes ; If p is a prime ; Mark all its multiples as non - prime ; Print all prime numbers ; Function to generate n as the sum of k numbers where atleast K - 1 are distinct and are product of 2 primes ; Stores the product of every pair of prime number ; Sort the products ; If sum exceeds n ; Otherwise , print the k required numbers ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static Vector < Integer > primes = new Vector < > ( ) ; static void SieveOfEratosthenes ( ) { boolean [ ] prime = new boolean [ 10005 ] ; Arrays . fill ( prime , true ) ; for ( int p = 2 ; p * p <= 1000 ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= 1000 ; i += p ) prime [ i ] = false ; } } for ( int p = 2 ; p <= 1000 ; p ++ ) if ( prime [ p ] ) primes . add ( p ) ; } static void generate ( int n , int k ) { Vector < Integer > prod = new Vector < > ( ) ; SieveOfEratosthenes ( ) ; int l = primes . size ( ) ; for ( int i = 0 ; i < l ; i ++ ) { for ( int j = i + 1 ; j < l ; j ++ ) { if ( primes . get ( i ) * primes . get ( j ) > 0 ) prod . add ( primes . get ( i ) * primes . get ( j ) ) ; } } Collections . sort ( prod ) ; int sum = 0 ; for ( int i = 0 ; i < k - 1 ; i ++ ) sum += prod . get ( i ) ; if ( sum > n ) System . out . print ( " - 1" ) ; else { for ( int i = 0 ; i < k - 1 ; i ++ ) { System . out . print ( prod . get ( i ) + " , ▁ " ) ; } System . out . print ( n - sum + "
"); } } public static void main ( String [ ] args ) { int n = 52 , k = 5 ; generate ( n , k ) ; } }


"Split N into two integers whose addition to A and B makes them equal | Java program to implement the above approach ; Function to calculate the splitted numbers ; Calculate X ; If X is odd ; No pair is possible ; Otherwise ; Calculate X ; Calculate Y ; Driver function"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findPair ( int A , int B , int N ) { int X , Y ; X = N - B + A ; if ( X % 2 != 0 ) { System . out . print ( " - 1" ) ; } else { X = X / 2 ; Y = N - X ; System . out . print ( X + " ▁ " + Y ) ; } } public static void main ( String [ ] args ) { int A = 1 ; int B = 3 ; int N = 4 ; findPair ( A , B , N ) ; } }


"Split N natural numbers into two sets having GCD of their sums greater than 1 | Java program to split N natural numbers into two sets having GCD of their sums greater than 1 ; Function to create and print the two sets ; For n <= 2 such sets can never be formed ; Check if N is even or odd and store the element which divides the sum of N natural numbers accordingly ; First set ; Print elements of second set ; Driver code"
How can the above be solved in Java?

 class GFG { static void createSets ( long n ) { if ( n <= 2 ) { System . out . print ( " - 1" ) ; return ; } else { long x = ( n % 2 == 0 ) ? ( n / 2 ) : ( ( n + 1 ) / 2 ) ; System . out . print ( x + "
"); for ( int i = 1 ; i <= n ; i ++ ) { if ( i == x ) continue ; System . out . print ( i + " ▁ " ) ; } } return ; } public static void main ( String [ ] args ) { long N = 7 ; createSets ( N ) ; } }


"Split N natural numbers into two sets having GCD of their sums greater than 1 | Java program to split N natural numbers into two sets having GCD of their sums greater than 1 ; Function to create and print the two sets ; No such split possible for N <= 2 ; Print the first set consisting of even elements ; Print the second set consisting of odd ones ; Driver Code"
How can the above be solved in Java?

 class GFG { static void createSets ( int N ) { if ( N <= 2 ) { System . out . println ( " - 1" ) ; return ; } for ( int i = 2 ; i <= N ; i += 2 ) System . out . print ( i + " ▁ " ) ; System . out . print ( "
") ; for ( int i = 1 ; i <= N ; i += 2 ) { System . out . print ( i + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 6 ; createSets ( N ) ; } }


"Split N powers of 2 into two subsets such that their difference of sum is minimum | Java program to find the minimum difference possible by splitting all powers of 2 up to N into two sets of equal size ; Store the largest ; Form two separate groups ; Initialize the sum for two groups as 0 ; Insert 2 ^ n in the first group ; Calculate the sum of least n / 2 - 1 elements added to the first set ; Sum of remaining n / 2 - 1 elements ; Min difference between the two groups ; Driver Code"
How can the above be solved in Java?

import java . lang . Math ; class GFG { public static void MinDiff ( int n ) { int val = ( int ) Math . pow ( 2 , n ) ; int sep = n / 2 ; int grp1 = 0 ; int grp2 = 0 ; grp1 = grp1 + val ; for ( int i = 1 ; i < sep ; i ++ ) grp1 = grp1 + ( int ) Math . pow ( 2 , i ) ; for ( int i = sep ; i < n ; i ++ ) grp2 = grp2 + ( int ) Math . pow ( 2 , i ) ; System . out . println ( Math . abs ( grp1 - grp2 ) ) ; } public static void main ( String args [ ] ) { int n = 4 ; MinDiff ( n ) ; } }


"Split a Numeric String into Fibonacci Sequence | Java program of the above approach ; Function that returns true if Fibonacci sequence is found ; Base condition : If pos is equal to length of S and seq length is greater than 3 ; Return true ; Stores current number ; Add current digit to num ; Avoid integer overflow ; Avoid leading zeros ; If current number is greater than last two number of seq ; If seq length is less 2 or current number is is equal to the last two of the seq ; Add to the seq ; Recur for i + 1 ; Remove last added number ; If no sequence is found ; Function that prints the Fibonacci sequence from the split of string S ; Initialize a vector to store the sequence ; Call helper function ; If sequence length is greater than 3 ; Print the sequence ; If no sequence is found ; Print - 1 ; Driver code ; Given String ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean splitIntoFibonacciHelper ( int pos , String S , ArrayList < Long > seq ) { if ( pos == S . length ( ) && ( seq . size ( ) >= 3 ) ) { return true ; } long num = 0 ; for ( int i = pos ; i < S . length ( ) ; i ++ ) { num = num * 10 + ( S . charAt ( i ) - '0' ) ; if ( num > Integer . MAX_VALUE ) break ; if ( S . charAt ( pos ) == '0' && i > pos ) break ; if ( seq . size ( ) > 2 && ( num > ( ( long ) seq . get ( seq . size ( ) - 1 ) + ( long ) seq . get ( seq . size ( ) - 2 ) ) ) ) break ; if ( seq . size ( ) < 2 || ( num == ( ( long ) seq . get ( seq . size ( ) - 1 ) + ( long ) seq . get ( seq . size ( ) - 2 ) ) ) ) { seq . add ( num ) ; if ( splitIntoFibonacciHelper ( i + 1 , S , seq ) ) return true ; seq . remove ( seq . size ( ) - 1 ) ; } } return false ; } static void splitIntoFibonacci ( String S ) { ArrayList < Long > seq = new ArrayList < > ( ) ; splitIntoFibonacciHelper ( 0 , S , seq ) ; if ( seq . size ( ) >= 3 ) { for ( int i = 0 ; i < seq . size ( ) ; i ++ ) System . out . print ( seq . get ( i ) + " ▁ " ) ; } else { System . out . print ( " - 1" ) ; } } public static void main ( String [ ] args ) { String S = "11235813" ; splitIntoFibonacci ( S ) ; } }


"Split a binary string into K subsets minimizing sum of products of occurrences of 0 and 1 | Java Program to split a given String into K segments such that the sum of product of occurence of characters in them is minimized ; Function to return the minimum sum of products of occurences of 0 and 1 in each segments ; Store the length of the String ; Not possible to generate subsets greater than the length of String ; If the number of subsets equals the length ; Precompute the sum of products for all index ; Calculate the minimum sum of products for K subsets ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int minSumProd ( String S , int K ) { int len = S . length ( ) ; if ( K > len ) return - 1 ; if ( K == len ) return 0 ; int [ ] dp = new int [ len ] ; int count_zero = 0 , count_one = 0 ; for ( int j = 0 ; j < len ; j ++ ) { if ( S . charAt ( j ) == '0' ) count_zero ++ ; else count_one ++ ; dp [ j ] = count_zero * count_one ; } for ( int i = 1 ; i < K ; i ++ ) { for ( int j = len - 1 ; j >= i ; j -- ) { count_zero = 0 ; count_one = 0 ; dp [ j ] = Integer . MAX_VALUE ; for ( int k = j ; k >= i ; k -- ) { if ( S . charAt ( k ) == '0' ) count_zero ++ ; else count_one ++ ; dp [ j ] = Math . min ( dp [ j ] , count_zero * count_one + dp [ k - 1 ] ) ; } } } return dp [ len - 1 ] ; } public static void main ( String [ ] args ) { String S = "1011000110110100" ; int K = 5 ; System . out . print ( minSumProd ( S , K ) ) ; } }


"Split a given array into K subarrays minimizing the difference between their maximum and minimum | Java program for the above approach ; Function to find the subarray ; Add the difference to vectors ; Sort vector to find minimum k ; Initialize result ; Adding first k - 1 values ; Return the minimized sum ; Driver Code ; Given array arr [ ] ; Given K ; Function Call"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int find ( int a [ ] , int n , int k ) { Vector < Integer > v = new Vector < Integer > ( ) ; for ( int i = 1 ; i < n ; ++ i ) { v . add ( a [ i - 1 ] - a [ i ] ) ; } Collections . sort ( v ) ; int res = a [ n - 1 ] - a [ 0 ] ; for ( int i = 0 ; i < k - 1 ; ++ i ) { res += v . get ( i ) ; } return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 8 , 15 , 16 , 23 , 42 } ; int N = arr . length ; int K = 3 ; System . out . print ( find ( arr , N , K ) + "
"); } }


"Split a number as sum of K numbers which are not divisible by K | Java program to split a number as sum of K numbers which are not divisible by K ; Function to split into K parts and print them ; Print 1 K - 1 times ; Print N - K + 1 ; Print 1 K - 2 times ; Print 2 and N - K ; Driver code"
How can the above be solved in Java?

 class GFG { static void printKParts ( int N , int K ) { if ( N % K == 0 ) { for ( int i = 1 ; i < K ; i ++ ) System . out . print ( "1 , ▁ " ) ; System . out . print ( N - ( K - 1 ) + "
"); } else { if ( K == 2 ) { System . out . print ( " Not ▁ Possible " + "
"); return ; } for ( int i = 1 ; i < K - 1 ; i ++ ) System . out . print ( 1 + " , ▁ " ) ; System . out . print ( 2 + " , ▁ " + ( N - K ) + "
"); } } public static void main ( String [ ] args ) { int N = 18 , K = 5 ; printKParts ( N , K ) ; } }


"Split a number into 3 parts such that none of the parts is divisible by 3 | Java program to split a number into three parts such than none of them is divisible by 3. ; Print x = 1 , y = 1 and z = N - 2 ; Otherwise , print x = 1 , y = 2 and z = N - 3 ; Driver code"
How can the above be solved in Java?

import java . util . * ; class solution { static void printThreeParts ( int N ) { if ( N % 3 == 0 ) System . out . println ( " x ▁ = ▁ 1 , ▁ y ▁ = ▁ 1 , ▁ z ▁ = ▁ " + ( N - 2 ) ) ; else System . out . println ( " ▁ x ▁ = ▁ 1 , ▁ y ▁ = ▁ 2 , ▁ z ▁ = ▁ " + ( N - 3 ) ) ; } public static void main ( String args [ ] ) { int N = 10 ; printThreeParts ( N ) ; } }


"Split a string in equal parts such that all parts are palindromes | Java implementation of the approach ; Function to return the frequency array for the given string ; Function to return the required count ; Add frequencies of the even appearing characters ; Count of the characters that appeared odd number of times ; If there are no characters with odd frequency ; If there are no characters with even frequency ; Only a single character with odd frequency ; More than 1 character with odd frequency string isn 't a palindrome ; All odd appearing characters can also contribute to the even length palindrome if one character is removed from the frequency leaving it as even ; If k palindromes are possible where k is the number of characters with odd frequency ; Current character can no longer be an element in a string other than the mid character ; If current character has odd frequency > 1 take two characters which can be used in any of the parts ; Update the frequency ; If not possible , then every character of the string will act as a separate palindrome ; Driver code"
How can the above be solved in Java?

import java . util . * ; public class GFG { static int [ ] getFrequencies ( String str ) { int freq [ ] = new int [ 26 ] ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { freq [ str . charAt ( i ) - ' a ' ] ++ ; } return freq ; } static int countMinParts ( String str ) { int n = str . length ( ) ; int freq [ ] = getFrequencies ( str ) ; List < Integer > oddFreq = new ArrayList < > ( ) ; List < Integer > evenFreq = new ArrayList < > ( ) ; int i , sumEven = 0 ; for ( i = 0 ; i < 26 ; i ++ ) { if ( freq [ i ] == 0 ) continue ; if ( freq [ i ] % 2 == 0 ) evenFreq . add ( freq [ i ] ) ; else oddFreq . add ( freq [ i ] ) ; } for ( i = 0 ; i < evenFreq . size ( ) ; i ++ ) { sumEven += evenFreq . get ( i ) ; } if ( oddFreq . size ( ) == 0 ) return 1 ; if ( sumEven == 0 ) { if ( oddFreq . size ( ) == 1 ) return 1 ; return 0 ; } i = 0 ; while ( i < oddFreq . size ( ) ) { if ( ( sumEven / 2 ) % oddFreq . size ( ) == 0 ) return oddFreq . size ( ) ; if ( oddFreq . get ( i ) == 1 ) { i ++ ; continue ; } sumEven += 2 ; oddFreq . set ( i , oddFreq . get ( i ) - 2 ) ; } return n ; } public static void main ( String [ ] args ) { String s = " noonpeep " ; System . out . println ( countMinParts ( s ) ) ; } }


"Split a string into maximum number of unique substrings | Java program for the above approach ; Function to find the maximum count of unique substrings by splitting a string into maximum number of unique substrings ; Utility function to find maximum count of unique substrings by splitting the string ; Stores maximum count of unique substring by splitting the string into substrings ; Iterate over the characters of the string ; Stores prefix substring ; Check if the current substring already exists ; Insert tmp into set ; Recursively call for remaining characters of string ; Remove from the set ; Return answer ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class Solution { public int maxUniqueSplit ( String S ) { return maxUnique ( S , new HashSet < String > ( ) ) ; } public int maxUnique ( String S , Set < String > set ) { int max = 0 ; for ( int i = 1 ; i <= S . length ( ) ; i ++ ) { String tmp = S . substring ( 0 , i ) ; if ( ! set . contains ( tmp ) ) { set . add ( tmp ) ; max = Math . max ( max , maxUnique ( S . substring ( i ) , set ) + 1 ) ; set . remove ( tmp ) ; } } return max ; } } class GFG { public static void main ( String [ ] args ) { Solution st = new Solution ( ) ; String S = " ababccc " ; int res = st . maxUniqueSplit ( S ) ; System . out . println ( res ) ; } }


"Split an Array to maximize subarrays having equal count of odd and even elements for a cost not exceeding K | Java program for the above approach ; Function to find the cost of splitting the arrays into subarray with cost less than K ; Store the possible splits ; Stores the cost of each split ; Stores the count of even numbers ; Stores the count of odd numbers ; Count of odd & even elements ; Check the required conditions for a valid split ; Sort the cost of splits ; Find the minimum split costs adding up to sum less than K ; Driver Code ; Given array and K ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int make_cuts ( int arr [ ] , int n , int K ) { int ans = 0 ; Vector < Integer > poss = new Vector < Integer > ( ) ; int ce = 0 ; int co = 0 ; for ( int x = 0 ; x < n - 1 ; x ++ ) { if ( arr [ x ] % 2 == 0 ) ce ++ ; else co ++ ; if ( ce == co && co > 0 && ce > 0 ) { poss . add ( Math . abs ( arr [ x ] - arr [ x + 1 ] ) ) ; } } Collections . sort ( poss ) ; for ( int x : poss ) { if ( K >= x ) { ans ++ ; K -= x ; } else break ; } return ans ; } public static void main ( String [ ] args ) { int N = 6 ; int K = 4 ; int arr [ ] = { 1 , 2 , 5 , 10 , 15 , 20 } ; System . out . print ( make_cuts ( arr , N , K ) ) ; } }


"Split an array into equal length subsequences consisting of equal elements only | Java program for the above approach ; Function to find the GCD of two numbers a and b ; Function to check if it is possible to split the array into equal length subsequences such that all elements in the subsequence are equal ; Store frequencies of array elements ; Traverse the array ; Update frequency of arr [ i ] ; Store the GCD of frequencies of all array elements ; Traverse the map ; update gcd ; If the GCD is greater than 1 , print YES otherwise print NO ; Driver Code ; Given array ; Store the size of the array"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } void splitArray ( int arr [ ] , int N ) { TreeMap < Integer , Integer > mp = new TreeMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( mp . containsKey ( arr [ i ] ) ) { mp . put ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) ; } else { mp . put ( arr [ i ] , 1 ) ; } } int G = 0 ; for ( Map . Entry < Integer , Integer > m : mp . entrySet ( ) ) { Integer i = m . getValue ( ) ; G = gcd ( G , i . intValue ( ) ) ; } if ( G > 1 ) System . out . print ( " YES " ) ; else System . out . print ( " NO " ) ; } public static void main ( String [ ] args ) { int [ ] arr = new int [ ] { 1 , 2 , 3 , 4 , 4 , 3 , 2 , 1 } ; int n = arr . length ; new GFG ( ) . splitArray ( arr , n ) ; } }


"Split an array into minimum number of non | Java program for the above approach ; Function to split the array into minimum count of subarrays such that each subarray is either non - increasing or non - decreasing ; Initialize variable to keep track of current sequence ; Stores the required result ; Traverse the array , arr [ ] ; If current sequence is neither non - increasing nor non - decreasing ; If previous element is greater ; Update current ; If previous element is equal to the current element ; Update current ; Otherwise ; Update current ; If current sequence is in non - decreasing ; If previous element is less than or equal to the current element ; Otherwise ; Update current as N and increment answer by 1 ; If current sequence is Non - Increasing ; If previous element is greater or equal to the current element ; Otherwise ; Update current as N and increment answer by 1 ; Print the answer ; Driver Code ; Given array ; Given size of array"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void minimumSubarrays ( int [ ] arr , int n ) { char current = ' N ' ; int answer = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( current == ' N ' ) { if ( arr [ i ] < arr [ i - 1 ] ) { current = ' D ' ; } else if ( arr [ i ] == arr [ i - 1 ] ) { current = ' N ' ; } else { current = ' I ' ; } } else if ( current == ' I ' ) { if ( arr [ i ] >= arr [ i - 1 ] ) { current = ' I ' ; } else { current = ' N ' ; answer += 1 ; } } else { if ( arr [ i ] <= arr [ i - 1 ] ) { current = ' D ' ; } else { current = ' N ' ; answer += 1 ; } } } System . out . print ( answer ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 9 , 5 , 4 , 6 , 8 } ; int n = arr . length ; minimumSubarrays ( arr , n ) ; } }


"Split array into K non | Java program for the above approach ; Function find maximum sum of minimum and maximum of K subsets ; Stores the result ; Sort the array arr [ ] in decreasing order ; Traverse the range [ 0 , K ] ; Sort the array S [ ] in ascending order ; Traverse the array S [ ] ; If S { i ] is 1 ; Stores the index of the minimum element of the i - th subset ; Traverse the array S [ ] ; Update the counter ; Return the resultant sum ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static int maximumSum ( int arr [ ] , int S [ ] , int N , int K ) { int ans = 0 ; Arrays . sort ( arr ) ; for ( int i = 0 ; i < N / 2 ; i ++ ) { int temp = arr [ i ] ; arr [ i ] = arr [ N - 1 - i ] ; arr [ N - 1 - i ] = temp ; } for ( int i = 0 ; i < K ; i ++ ) ans += arr [ i ] ; Arrays . sort ( S ) ; for ( int i = 0 ; i < K ; i ++ ) { if ( S [ i ] == 1 ) ans += arr [ i ] ; S [ i ] -- ; } int counter = K - 1 ; for ( int i = 0 ; i < K ; i ++ ) { counter = counter + S [ i ] ; if ( S [ i ] != 0 ) ans += arr [ counter ] ; } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 13 , 7 , 17 } ; int S [ ] = { 1 , 3 } ; int N = arr . length ; int K = S . length ; System . out . println ( maximumSum ( arr , S , N , K ) ) ; } }


"Split array into K subsets to maximize sum of their second largest elements | Java program for the above approach ; Function to split array into K subsets having maximum sum of their second maximum elements ; Sort the array ; Stores the maximum possible sum of second maximums ; Add second maximum of current subset ; Proceed to the second maximum of next subset ; Print the maximum sum obtained ; Drive Code ; Given array arr [ ] ; Size of array ; Function Call"
How can the above be solved in Java?

import java . io . * ; import java . util . Arrays ; class GFG { static void splitArray ( int arr [ ] , int n , int K ) { Arrays . sort ( arr ) ; int i = n - 1 ; int result = 0 ; while ( K -- != 0 ) { result += arr [ i - 1 ] ; i -= 2 ; } System . out . print ( result ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 3 , 1 , 5 , 1 , 3 } ; int N = arr . length ; int K = 2 ; splitArray ( arr , N , K ) ; } }


"Split array into K | Java implementation for the above approach ; Function to find the minimum sum of 2 nd smallest elements of each subset ; Sort the array ; Stores minimum sum of second elements of each subset ; Traverse first K 2 nd smallest elements ; Update their sum ; Print the sum ; Driver Code ; Given Array ; Given length of array ; Given subset lengths"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { public static void findMinimum ( int arr [ ] , int N , int K ) { Arrays . sort ( arr ) ; int ans = 0 ; for ( int i = 1 ; i < 2 * ( N / K ) ; i += 2 ) { ans += arr [ i ] ; } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 11 , 20 , 5 , 7 , 8 , 14 , 2 , 17 , 16 , 10 } ; int N = arr . length ; int K = 5 ; findMinimum ( arr , N , K ) ; } }


"Split array into equal length subsets with maximum sum of Kth largest element of each subset | Java program to implement the above approach ; Function to find the maximum sum of Kth largest element of M equal length partition ; Stores sum of K_th largest element of equal length partitions ; If N is not divisible by M ; Stores length of each partition ; If K is greater than length of partition ; Sort array in descending porder ; Traverse the array ; Update maxSum ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . util . Collections ; class GFG { static int maximumKthLargestsumPart ( int [ ] arr , int N , int M , int K ) { int maxSum = 0 ; if ( N % M != 0 ) return - 1 ; int sz = ( N / M ) ; if ( K > sz ) return - 1 ; Arrays . sort ( arr ) ; int i , k , t ; for ( i = 0 ; i < N / 2 ; i ++ ) { t = arr [ i ] ; arr [ i ] = arr [ N - i - 1 ] ; arr [ N - i - 1 ] = t ; } for ( i = 1 ; i <= M ; i ++ ) { maxSum += arr [ i * K - 1 ] ; } return maxSum ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 , 6 } ; int M = 2 ; int K = 1 ; int N = arr . length ; System . out . println ( maximumKthLargestsumPart ( arr , N , M , K ) ) ; } }


"Split array into minimum number of subarrays having GCD of its first and last element exceeding 1 | Java program for the above approach ; Function to find the minimum number of subarrays ; Right pointer ; Left pointer ; Count of subarrays ; Find GCD ( left , right ) ; Found a valid large subarray between arr [ left , right ] ; Searched the arr [ 0. . right ] and found no subarray having size > 1 and having gcd ( left , right ) > 1 ; Driver Code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int minSubarrays ( int arr [ ] , int n ) { int right = n - 1 ; int left = 0 ; int subarrays = 0 ; while ( right >= 0 ) { for ( left = 0 ; left <= right ; left += 1 ) { if ( __gcd ( arr [ left ] , arr [ right ] ) > 1 ) { subarrays += 1 ; right = left - 1 ; break ; } if ( left == right && __gcd ( arr [ left ] , arr [ right ] ) == 1 ) { return 0 ; } } } return subarrays ; } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } public static void main ( String [ ] args ) { int N = 6 ; int arr [ ] = { 2 , 3 , 4 , 4 , 4 , 3 } ; System . out . print ( minSubarrays ( arr , N ) ) ; } }


"Split array into minimum number of subsets having maximum pair sum at most K | Java program to implement the above approach ; Function to get the minimum count of subsets that satisfy the given condition ; Store the minimum count of subsets that satisfy the given condition ; Stores start index of the sorted array . ; Stores end index of the sorted array ; Sort the given array ; Traverse the array ; If only two elements of sorted array left ; If only one elements left in the array ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int cntMinSub ( int arr [ ] , int N , int K ) { int res = 0 ; int start = 0 ; int end = N - 1 ; Arrays . sort ( arr ) ; while ( end - start > 1 ) { if ( arr [ start ] + arr [ end ] <= K ) { start ++ ; } else { res ++ ; end -- ; } } if ( end - start == 1 ) { if ( arr [ start ] + arr [ end ] <= K ) { res ++ ; start ++ ; end -- ; } else { res ++ ; end -- ; } } if ( start == end ) { res ++ ; } return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 6 , 8 , 10 , 20 , 25 } ; int N = arr . length ; int K = 26 ; System . out . print ( cntMinSub ( arr , N , K ) ) ; } }


"Split array into minimum number of subsets such that elements of all pairs are present in different subsets at least once | Java program to implement the above approach ; Function to find minimum count of ways to split the array into two subset such that elements of each pair occurs in two different subset ; Stores minimum count of ways to split array into two subset such that elements of each pair occurs in two different subset ; If N is odd ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MinimumNoOfWays ( int arr [ ] , int n ) { int mini_no_of_ways ; if ( n % 2 == 0 ) { mini_no_of_ways = n / 2 ; } else { mini_no_of_ways = n / 2 + 1 ; } return mini_no_of_ways ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 4 , 2 , 1 , 5 } ; int N = arr . length ; System . out . print ( MinimumNoOfWays ( arr , N ) ) ; } }


"Split array into subarrays at minimum cost by minimizing count of repeating elements in each subarray | Java program for the above approach ; Function to find the minimum cost of splitting the array into subarrays ; Get the maximum element ; dp [ ] will store the minimum cost upto index i ; Initialize the result array ; Initialise the first element ; Create the frequency array ; Update the frequency ; Counting the cost of the duplicate element ; Minimum cost of operation from 0 to j ; Total cost of the array ; Driver Code ; Given cost K ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static long findMinCost ( int [ ] a , int k , int n ) { int max_ele = Arrays . stream ( a ) . max ( ) . getAsInt ( ) ; long [ ] dp = new long [ n + 1 ] ; for ( int i = 1 ; i <= n ; ++ i ) dp [ i ] = Integer . MAX_VALUE ; dp [ 0 ] = 0 ; for ( int i = 0 ; i < n ; ++ i ) { int [ ] freq = new int [ max_ele + 1 ] ; for ( int j = i ; j < n ; ++ j ) { freq [ a [ j ] ] ++ ; int cost = 0 ; for ( int x = 0 ; x <= max_ele ; ++ x ) { cost += ( freq [ x ] == 1 ) ? 0 : freq [ x ] ; } dp [ j + 1 ] = Math . min ( dp [ i ] + cost + k , dp [ j + 1 ] ) ; } } return dp [ n ] ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 1 , 1 , 1 } ; int K = 2 ; int n = arr . length ; System . out . print ( findMinCost ( arr , K , n ) ) ; } }


"Split array into subarrays such that sum of difference between their maximums and minimums is maximum | Java program for the above approach ; Function to find maximum sum of difference between maximums and minimums in the splitted subarrays ; Base Case ; Traverse the array ; Stores the maximum and minimum elements upto the i - th index ; Traverse the range [ 0 , i ] ; Update the minimum ; Update the maximum ; Update dp [ i ] ; Return the maximum sum of difference ; Driver Code"
How can the above be solved in Java?

import java . util . * ; public class Main { static int getValue ( int [ ] arr , int N ) { int dp [ ] = new int [ N ] ; dp [ 0 ] = 0 ; for ( int i = 1 ; i < N ; i ++ ) { int min = arr [ i ] ; int max = arr [ i ] ; for ( int j = i ; j >= 0 ; j -- ) { min = Math . min ( arr [ j ] , min ) ; max = Math . max ( arr [ j ] , max ) ; dp [ i ] = Math . max ( dp [ i ] , max - min + ( ( j >= 1 ) ? dp [ j - 1 ] : 0 ) ) ; } } return dp [ N - 1 ] ; } public static void main ( String args [ ] ) { int arr [ ] = { 8 , 1 , 7 , 9 , 2 } ; int N = arr . length ; System . out . println ( getValue ( arr , N ) ) ; } }


"Split array into two equal length subsets such that all repetitions of a number lies in a single subset | Java program for the above approach ; Function to create the frequency array of the given array arr [ ] ; Hashmap to store the frequencies ; Store freq for each element ; Get the total frequencies ; Store frequencies in subset [ ] array ; Return frequency array ; Function to check is sum N / 2 can be formed using some subset ; dp [ i ] [ j ] store the answer to form sum j using 1 st i elements ; Initialize dp [ ] [ ] with true ; Fill the subset table in the bottom up manner ; If current element is less than j ; Update current state ; Return the result ; Function to check if the given array can be split into required sets ; Store frequencies of arr [ ] ; If size of arr [ ] is odd then print " Yes " ; Check if answer is true or not ; Print the result ; Driver Code ; Given array arr [ ] ; Function Call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { private static int [ ] findSubsets ( int [ ] arr ) { HashMap < Integer , Integer > M = new HashMap < > ( ) ; for ( int i = 0 ; i < arr . length ; i ++ ) { M . put ( arr [ i ] , M . getOrDefault ( arr [ i ] , 0 ) + 1 ) ; } int [ ] subsets = new int [ M . size ( ) ] ; int i = 0 ; for ( Map . Entry < Integer , Integer > playerEntry : M . entrySet ( ) ) { subsets [ i ++ ] = playerEntry . getValue ( ) ; } return subsets ; } private static boolean subsetSum ( int [ ] subsets , int target ) { boolean [ ] [ ] dp = new boolean [ subsets . length + 1 ] [ target + 1 ] ; for ( int i = 0 ; i < dp . length ; i ++ ) dp [ i ] [ 0 ] = true ; for ( int i = 1 ; i <= subsets . length ; i ++ ) { for ( int j = 1 ; j <= target ; j ++ ) { dp [ i ] [ j ] = dp [ i - 1 ] [ j ] ; if ( j >= subsets [ i - 1 ] ) { dp [ i ] [ j ] |= dp [ i - 1 ] [ j - subsets [ i - 1 ] ] ; } } } return dp [ subsets . length ] [ target ] ; } public static void divideInto2Subset ( int [ ] arr ) { int [ ] subsets = findSubsets ( arr ) ; if ( ( arr . length ) % 2 == 1 ) { System . out . println ( " No " ) ; return ; } boolean isPossible = subsetSum ( subsets , arr . length / 2 ) ; if ( isPossible ) { System . out . println ( " Yes " ) ; } else { System . out . println ( " No " ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 2 , 1 , 2 , 3 } ; divideInto2Subset ( arr ) ; } }


"Split array into two subarrays such that difference of their maximum is minimum | Java Program to split a given array such that the difference between their maximums is minimized . ; Sort the array ; Return the difference between two highest elements ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findMinDif ( int arr [ ] , int N ) { Arrays . sort ( arr ) ; return ( arr [ N - 1 ] - arr [ N - 2 ] ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 7 , 9 , 5 , 10 } ; int N = arr . length ; System . out . println ( findMinDif ( arr , N ) ) ; } }


"Split array into two subarrays such that difference of their sum is minimum | Java Program for above approach ; Function to return minimum difference between sum of two subarrays ; To store total sum of array ; Calculate the total sum of the array ; Stores the prefix sum ; Stores the minimum difference ; Traverse the given array ; To store minimum difference ; Update minDiff ; Return minDiff ; Driver Code ; Given array ; Length of the array"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static int minDiffSubArray ( int arr [ ] , int n ) { int total_sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) total_sum += arr [ i ] ; int prefix_sum = 0 ; int minDiff = Integer . MAX_VALUE ; for ( int i = 0 ; i < n - 1 ; i ++ ) { prefix_sum += arr [ i ] ; int diff = Math . abs ( ( total_sum - prefix_sum ) - prefix_sum ) ; if ( diff < minDiff ) minDiff = diff ; } return minDiff ; } public static void main ( String [ ] args ) { int [ ] arr = { 7 , 9 , 5 , 10 } ; int n = arr . length ; System . out . println ( minDiffSubArray ( arr , n ) ) ; } }


"Split array into two subarrays such that difference of their sum is minimum | Java Program for above approach ; Function to return minimum difference between two subarray sums ; To store prefix sums ; Generate prefix sum array ; To store suffix sums ; Generate suffix sum array ; Stores the minimum difference ; Traverse the given array ; Calculate the difference ; Update minDiff ; Return minDiff ; Driver Code ; Given array ; Length of the array"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static int minDiffSubArray ( int arr [ ] , int n ) { int [ ] prefix_sum = new int [ n ] ; prefix_sum [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) prefix_sum [ i ] = prefix_sum [ i - 1 ] + arr [ i ] ; int [ ] suffix_sum = new int [ n ] ; suffix_sum [ n - 1 ] = arr [ n - 1 ] ; for ( int i = n - 2 ; i >= 0 ; i -- ) suffix_sum [ i ] = suffix_sum [ i + 1 ] + arr [ i ] ; int minDiff = Integer . MAX_VALUE ; for ( int i = 0 ; i < n - 1 ; i ++ ) { int diff = Math . abs ( prefix_sum [ i ] - suffix_sum [ i + 1 ] ) ; if ( diff < minDiff ) minDiff = diff ; } return minDiff ; } public static void main ( String [ ] args ) { int [ ] arr = { 7 , 9 , 5 , 10 } ; int n = arr . length ; System . out . println ( minDiffSubArray ( arr , n ) ) ; } }


"Split array into two subsequences having minimum count of pairs with sum equal to X | Java program for the above approach ; Function to split the array into two subsequences ; Stores the two subsequences ; Flag to set / reset to split arrays elements alternately into two arrays ; Traverse the given array ; If 2 * arr [ i ] is less than X ; Push element into the first array ; If 2 * arr [ i ] is greater than X ; Push element into the second array ; If 2 * arr [ i ] is equal to X ; Alternatively place the elements into the two arrays ; Print both the arrays ; Driver Code ; Size of the array ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void solve ( int arr [ ] , int N , int X ) { Vector < Integer > A = new Vector < Integer > ( ) , B = new Vector < Integer > ( ) ; int c = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( ( 2 * arr [ i ] ) < X ) { A . add ( arr [ i ] ) ; } else if ( ( 2 * arr [ i ] ) > X ) { B . add ( arr [ i ] ) ; } else { if ( c % 2 == 0 ) { A . add ( arr [ i ] ) ; } else { B . add ( arr [ i ] ) ; } c ++ ; } } System . out . print ( " The ▁ First ▁ Array ▁ is ▁ - ▁ " ) ; for ( int i = 0 ; i < A . size ( ) ; i ++ ) { System . out . print ( A . get ( i ) + " ▁ " ) ; } System . out . println ( ) ; System . out . print ( " The ▁ Second ▁ Array ▁ is ▁ - ▁ " ) ; for ( int i = 0 ; i < B . size ( ) ; i ++ ) { System . out . print ( B . get ( i ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 5 , 4 , 3 , 6 , 2 , 4 , 3 } ; int X = 7 ; int N = arr . length ; solve ( arr , N , X ) ; } }


"Split first N natural numbers into two subsequences with non | Java program for the above approach ; Function to split 1 to N into two subsequences with non - coprime sums ; Driver code"
How can the above be solved in Java?

class GFG { public static void printSubsequence ( int N ) { System . out . print ( " { ▁ " ) ; for ( int i = 1 ; i < N - 1 ; i ++ ) { System . out . print ( i + " , ▁ " ) ; } System . out . println ( N - 1 + " ▁ } " ) ; System . out . print ( " { ▁ " + N + " ▁ } " ) ; } public static void main ( String [ ] args ) { int N = 8 ; printSubsequence ( N ) ; } }


"Split given arrays into subarrays to maximize the sum of maximum and minimum in each subarrays | Java program for the above approach ; Function to find the maximum sum of differences of subarrays by splitting array into non - overlapping subarrays ; Stores the answer for prefix and initialize with zero ; Assume i - th index as right endpoint ; Choose the current value as the maximum and minimum ; Find the left endpoint and update the array dp [ ] ; Return answer ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int maxDiffSum ( int [ ] arr , int n ) { int [ ] dp = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { int maxVal = arr [ i ] , minVal = arr [ i ] ; for ( int j = i ; j >= 0 ; j -- ) { minVal = Math . min ( minVal , arr [ j ] ) ; maxVal = Math . max ( maxVal , arr [ j ] ) ; if ( j - 1 >= 0 ) dp [ i ] = Math . max ( dp [ i ] , maxVal - minVal + dp [ j - 1 ] ) ; else dp [ i ] = Math . max ( dp [ i ] , maxVal - minVal ) ; } } return dp [ n - 1 ] ; } public static void main ( String [ ] args ) { int [ ] arr = { 8 , 1 , 7 , 9 , 2 } ; int N = arr . length ; System . out . print ( maxDiffSum ( arr , N ) ) ; } }


"Split given isosceles triangle of height H into N equal parts | Java Code for above approach ; Function to divide the isosceles triangle in equal parts by making N - 1 cuts parallel to the base ; Iterate over the range [ 1 , n - 1 ] ; Driver code ; Given N ; Given H ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findPoint ( int n , int h ) { for ( int i = 1 ; i < n ; i ++ ) System . out . printf ( " % .2f ▁ " , Math . sqrt ( i / ( n * 1.0 ) ) * h ) ; } public static void main ( String [ ] args ) { int n = 3 ; int h = 2 ; findPoint ( n , h ) ; } }


"Split n into maximum composite numbers | Java program to split a number into maximum number of composite numbers . ; function to calculate the maximum number of composite numbers adding upto n ; 4 is the smallest composite number ; stores the remainder when n is divided by 4 ; if remainder is 0 , then it is perfectly divisible by 4. ; if the remainder is 1 ; If the number is less then 9 , that is 5 , then it cannot be expressed as 4 is the only composite number less than 5 ; If the number is greater then 8 , and has a remainder of 1 , then express n as n - 9 a and it is perfectly divisible by 4 and for 9 , count 1. ; When remainder is 2 , just subtract 6 from n , so that n is perfectly divisible by 4 and count 1 for 6 which is subtracted . ; if the number is 7 , 11 which cannot be expressed as sum of any composite numbers ; when the remainder is 3 , then subtract 15 from it and n becomes perfectly divisible by 4 and we add 2 for 9 and 6 , which is getting subtracted to make n perfectly divisible by 4. ; Driver program"
How can the above be solved in Java?

import java . io . * ; class GFG { static int count ( int n ) { if ( n < 4 ) return - 1 ; int rem = n % 4 ; if ( rem == 0 ) return n / 4 ; if ( rem == 1 ) { if ( n < 9 ) return - 1 ; return ( n - 9 ) / 4 + 1 ; } if ( rem == 2 ) return ( n - 6 ) / 4 + 1 ; if ( rem == 3 ) { if ( n < 15 ) return - 1 ; return ( n - 15 ) / 4 + 2 ; } return 0 ; } public static void main ( String [ ] args ) { int n = 90 ; System . out . println ( count ( n ) ) ; n = 143 ; System . out . println ( count ( n ) ) ; } }


"Split numeric , alphabetic and special symbols from a String | java program to split an alphanumeric string using stringbuffer ; Driver method"
How can the above be solved in Java?

class Test { static void splitString ( String str ) { StringBuffer alpha = new StringBuffer ( ) , num = new StringBuffer ( ) , special = new StringBuffer ( ) ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( Character . isDigit ( str . charAt ( i ) ) ) num . append ( str . charAt ( i ) ) ; else if ( Character . isAlphabetic ( str . charAt ( i ) ) ) alpha . append ( str . charAt ( i ) ) ; else special . append ( str . charAt ( i ) ) ; } System . out . println ( alpha ) ; System . out . println ( num ) ; System . out . println ( special ) ; } public static void main ( String args [ ] ) { String str = " geeks01 $ $ for02geeks03 ! @ ! ! " ; splitString ( str ) ; } }


"Split the array and add the first part to the end | Java program to split array and move first part to end . ; Function to spilt array and move first part to end ; make a temporary array with double the size ; copy array element in to new array twice ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { public static void SplitAndAdd ( int [ ] A , int length , int rotation ) { int [ ] tmp = new int [ length * 2 ] ; System . arraycopy ( A , 0 , tmp , 0 , length ) ; System . arraycopy ( A , 0 , tmp , length , length ) ; for ( int i = rotation ; i < rotation + length ; i ++ ) A [ i - rotation ] = tmp [ i ] ; } public static void main ( String [ ] args ) { int arr [ ] = { 12 , 10 , 5 , 6 , 52 , 36 } ; int n = arr . length ; int position = 2 ; SplitAndAdd ( arr , n , position ) ; for ( int i = 0 ; i < n ; ++ i ) System . out . print ( arr [ i ] + " ▁ " ) ; } }


"Split the array and add the first part to the end | Java program to split array and move first part to end . ; Rotate array by 1. ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { public static void splitArr ( int arr [ ] , int n , int k ) { for ( int i = 0 ; i < k ; i ++ ) { int x = arr [ 0 ] ; for ( int j = 0 ; j < n - 1 ; ++ j ) arr [ j ] = arr [ j + 1 ] ; arr [ n - 1 ] = x ; } } public static void main ( String [ ] args ) { int arr [ ] = { 12 , 10 , 5 , 6 , 52 , 36 } ; int n = arr . length ; int position = 2 ; splitArr ( arr , 6 , position ) ; for ( int i = 0 ; i < n ; ++ i ) System . out . print ( arr [ i ] + " ▁ " ) ; } }