"Iterative Tower of Hanoi | Java program for iterative Tower of Hanoi ; A structure to represent a stack ; Function to create a stack of given capacity . ; Stack is full when the top is equal to the last index ; Stack is empty when top is equal to - 1 ; Function to add an item to stack . It increases top by 1 ; Function to remove an item from stack . It decreases top by 1 ; Function to show the movement of disks ; Function to implement legal movement between two poles ; When pole 1 is empty ; When pole2 pole is empty ; When top disk of pole1 > top disk of pole2 ; When top disk of pole1 < top disk of pole2 ; Function to implement TOH puzzle ; If number of disks is even , then interchange destination pole and auxiliary pole ; Larger disks will be pushed first ; Driver code ; Input : number of disks ; Create three stacks of size ' num _ of _ disks ' to hold the disks"
How can the above be solved in Java?

class TOH { class Stack { int capacity ; int top ; int array [ ] ; } Stack createStack ( int capacity ) { Stack stack = new Stack ( ) ; stack . capacity = capacity ; stack . top = - 1 ; stack . array = new int [ capacity ] ; return stack ; } boolean isFull ( Stack stack ) { return ( stack . top == stack . capacity - 1 ) ; } boolean isEmpty ( Stack stack ) { return ( stack . top == - 1 ) ; } void push ( Stack stack , int item ) { if ( isFull ( stack ) ) return ; stack . array [ ++ stack . top ] = item ; } int pop ( Stack stack ) { if ( isEmpty ( stack ) ) return Integer . MIN_VALUE ; return stack . array [ stack . top -- ] ; } void moveDisk ( char fromPeg , char toPeg , int disk ) { System . out . println ( " Move ▁ the ▁ disk ▁ " + disk + " ▁ from ▁ " + fromPeg + " ▁ to ▁ " + toPeg ) ; } void moveDisksBetweenTwoPoles ( Stack src , Stack dest , char s , char d ) { int pole1TopDisk = pop ( src ) ; int pole2TopDisk = pop ( dest ) ; if ( pole1TopDisk == Integer . MIN_VALUE ) { push ( src , pole2TopDisk ) ; moveDisk ( d , s , pole2TopDisk ) ; } else if ( pole2TopDisk == Integer . MIN_VALUE ) { push ( dest , pole1TopDisk ) ; moveDisk ( s , d , pole1TopDisk ) ; } else if ( pole1TopDisk > pole2TopDisk ) { push ( src , pole1TopDisk ) ; push ( src , pole2TopDisk ) ; moveDisk ( d , s , pole2TopDisk ) ; } else { push ( dest , pole2TopDisk ) ; push ( dest , pole1TopDisk ) ; moveDisk ( s , d , pole1TopDisk ) ; } } void tohIterative ( int num_of_disks , Stack src , Stack aux , Stack dest ) { int i , total_num_of_moves ; char s = ' S ' , d = ' D ' , a = ' A ' ; if ( num_of_disks % 2 == 0 ) { char temp = d ; d = a ; a = temp ; } total_num_of_moves = ( int ) ( Math . pow ( 2 , num_of_disks ) - 1 ) ; for ( i = num_of_disks ; i >= 1 ; i -- ) push ( src , i ) ; for ( i = 1 ; i <= total_num_of_moves ; i ++ ) { if ( i % 3 == 1 ) moveDisksBetweenTwoPoles ( src , dest , s , d ) ; else if ( i % 3 == 2 ) moveDisksBetweenTwoPoles ( src , aux , s , a ) ; else if ( i % 3 == 0 ) moveDisksBetweenTwoPoles ( aux , dest , a , d ) ; } } public...


"Iterative approach to print all combinations of an Array | Java implementation of the approach ; Data array for combination ; Number of elements in the combination ; The boolean array ; Starting index of the 1 st tract of trues ; Ending index of the 1 st tract of trues ; Constructor ; Set the 1 st r Booleans to true , initialize Start and End ; Generate the very first combination ; Update the starting ending indices of trues in the boolean array ; Function that returns true if another combination can still be generated ; Function to generate the next combination ; Only one true in the tract ; Move the End and reset the End ; Set all the values to false starting from index Start and ending at index End in the boolean array ; Set the beginning elements to true ; Reset the End ; Function to print the combination generated previouslt ; If current index is set to true in the boolean array then element at current index in the original array is part of the combination generated previously ; Driver code"
How can the above be solved in Java?

class Combination { private int [ ] Indices ; private int R ; private boolean [ ] Flags ; private int Start ; private int End ; public Combination ( int [ ] arr , int r ) { this . Indices = arr ; this . R = r ; } public void GetFirst ( ) { Flags = new boolean [ this . Indices . length ] ; for ( int i = 0 ; i < this . R ; ++ i ) { Flags [ i ] = true ; } this . Start = 0 ; this . End = this . R - 1 ; this . Output ( ) ; } public boolean HasNext ( ) { return End < ( this . Indices . length - 1 ) ; } public void Next ( ) { if ( this . Start == this . End ) { this . Flags [ this . End ] = false ; this . Flags [ this . End + 1 ] = true ; this . Start += 1 ; this . End += 1 ; while ( this . End + 1 < this . Indices . length && this . Flags [ this . End + 1 ] ) { ++ this . End ; } } else { if ( this . Start == 0 ) { Flags [ this . End ] = false ; Flags [ this . End + 1 ] = true ; this . End -= 1 ; } else { Flags [ this . End + 1 ] = true ; for ( int i = this . Start ; i <= this . End ; ++ i ) { Flags [ i ] = false ; } for ( int i = 0 ; i < this . End - this . Start ; ++ i ) { Flags [ i ] = true ; } this . End = this . End - this . Start - 1 ; this . Start = 0 ; } } this . Output ( ) ; } private void Output ( ) { for ( int i = 0 , count = 0 ; i < Indices . length && count < this . R ; ++ i ) { if ( Flags [ i ] ) { System . out . print ( Indices [ i ] ) ; System . out . print ( " ▁ " ) ; ++ count ; } } System . out . println ( ) ; } } class GFG { public static void main ( String [ ] args ) { int [ ] arr = { 0 , 1 , 2 , 3 } ; int r = 3 ; Combination com = new Combination ( arr , r ) ; com . GetFirst ( ) ; while ( com . HasNext ( ) ) { com . Next ( ) ; } } }


"Iterative approach to print all permutations of an Array | Java implementation of the approach ; The input array for permutation ; Index array to store indexes of input array ; The index of the first " increase " in the Index array which is the smallest i such that Indexes [ i ] < Indexes [ i + 1 ] ; Constructor ; Initialize and output the first permutation ; Allocate memory for Indexes array ; Initialize the values in Index array from 0 to n - 1 ; Set the Increase to 0 since Indexes [ 0 ] = 0 < Indexes [ 1 ] = 1 ; Output the first permutation ; Function that returns true if it is possible to generate the next permutation ; When Increase is in the end of the array , it is not possible to have next one ; Output the next permutation ; Increase is at the very beginning ; Swap Index [ 0 ] and Index [ 1 ] ; Update Increase ; Value at Indexes [ Increase + 1 ] is greater than Indexes [ 0 ] no need for binary search , just swap Indexes [ Increase + 1 ] and Indexes [ 0 ] ; Binary search to find the greatest value which is less than Indexes [ Increase + 1 ] ; Swap ; Invert 0 to Increase ; Reset Increase ; Function to output the input array ; Indexes of the input array are at the Indexes array ; Swap two values in the Indexes array ; Driver code"
How can the above be solved in Java?

class AllPermutation { private final int Arr [ ] ; private int Indexes [ ] ; private int Increase ; public AllPermutation ( int arr [ ] ) { this . Arr = arr ; this . Increase = - 1 ; this . Indexes = new int [ this . Arr . length ] ; } public void GetFirst ( ) { this . Indexes = new int [ this . Arr . length ] ; for ( int i = 0 ; i < Indexes . length ; ++ i ) { this . Indexes [ i ] = i ; } this . Increase = 0 ; this . Output ( ) ; } public boolean HasNext ( ) { return this . Increase != ( this . Indexes . length - 1 ) ; } public void GetNext ( ) { if ( this . Increase == 0 ) { this . Swap ( this . Increase , this . Increase + 1 ) ; this . Increase += 1 ; while ( this . Increase < this . Indexes . length - 1 && this . Indexes [ this . Increase ] > this . Indexes [ this . Increase + 1 ] ) { ++ this . Increase ; } } else { if ( this . Indexes [ this . Increase + 1 ] > this . Indexes [ 0 ] ) { this . Swap ( this . Increase + 1 , 0 ) ; } else { int start = 0 ; int end = this . Increase ; int mid = ( start + end ) / 2 ; int tVal = this . Indexes [ this . Increase + 1 ] ; while ( ! ( this . Indexes [ mid ] < tVal && this . Indexes [ mid - 1 ] > tVal ) ) { if ( this . Indexes [ mid ] < tVal ) { end = mid - 1 ; } else { start = mid + 1 ; } mid = ( start + end ) / 2 ; } this . Swap ( this . Increase + 1 , mid ) ; } for ( int i = 0 ; i <= this . Increase / 2 ; ++ i ) { this . Swap ( i , this . Increase - i ) ; } this . Increase = 0 ; } this . Output ( ) ; } private void Output ( ) { for ( int i = 0 ; i < this . Indexes . length ; ++ i ) { System . out . print ( this . Arr [ this . Indexes [ i ] ] ) ; System . out . print ( " ▁ " ) ; } System . out . println ( ) ; } private void Swap ( int p , int q ) { int tmp = this . Indexes [ p ] ; this . Indexes [ p ] = this . Indexes [ q ] ; this . Indexes [ q ] = tmp ; } } class AppDriver { public static void main ( String args [ ] ) { int [ ] arr = { 0 , 1 , 2 } ; AllPermutation perm = new AllPermutation ( arr ) ; perm . GetFirst ( ) ; while ( perm . HasNext ( ) ) { perm ....


"Iterative diagonal traversal of binary tree | Java program to con string from binary tree ; A binary tree node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node ; Iterative function to print diagonal view ; base case ; inbuilt queue of Treenode ; add root ; add delimiter ; if current is delimiter then insert another for next diagonal and cout nextline ; if queue is empty return ; output nextline ; add delimiter again ; if left child is present add into queue ; current equals to right child ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class solution { static class Node { int data ; Node left , right ; } ; static Node newNode ( int data ) { Node node = new Node ( ) ; node . data = data ; node . left = node . right = null ; return ( node ) ; } static void diagonalPrint ( Node root ) { if ( root == null ) return ; Queue < Node > q = new LinkedList < Node > ( ) ; q . add ( root ) ; q . add ( null ) ; while ( q . size ( ) > 0 ) { Node temp = q . peek ( ) ; q . remove ( ) ; if ( temp == null ) { if ( q . size ( ) == 0 ) return ; System . out . println ( ) ; q . add ( null ) ; } else { while ( temp != null ) { System . out . print ( temp . data + " ▁ " ) ; if ( temp . left != null ) q . add ( temp . left ) ; temp = temp . right ; } } } } public static void main ( String args [ ] ) { Node root = newNode ( 8 ) ; root . left = newNode ( 3 ) ; root . right = newNode ( 10 ) ; root . left . left = newNode ( 1 ) ; root . left . right = newNode ( 6 ) ; root . right . right = newNode ( 14 ) ; root . right . right . left = newNode ( 13 ) ; root . left . right . left = newNode ( 4 ) ; root . left . right . right = newNode ( 7 ) ; diagonalPrint ( root ) ; } }


"Iterative function to check if two trees are identical | Iterative Java program to check if two ; A Binary Tree Node ; Iterative method to find height of Binary Tree ; Return true if both trees are empty ; Return false if one is empty and other is not ; Create an empty queues for simultaneous traversals ; Enqueue Roots of trees in respective queues ; Get front nodes and compare them ; Remove front nodes from queues ; Enqueue left children of both nodes ; If one left child is empty and other is not ; Right child code ( Similar to left child code ) ; Utility function to create a new tree node ; Driver program to test above functions"
How can the above be solved in Java?

import java . util . * ; class GfG { static class Node { int data ; Node left , right ; } static boolean areIdentical ( Node root1 , Node root2 ) { if ( root1 == null && root2 == null ) return true ; if ( root1 == null root2 == null ) return false ; Queue < Node > q1 = new LinkedList < Node > ( ) ; Queue < Node > q2 = new LinkedList < Node > ( ) ; q1 . add ( root1 ) ; q2 . add ( root2 ) ; while ( ! q1 . isEmpty ( ) && ! q2 . isEmpty ( ) ) { Node n1 = q1 . peek ( ) ; Node n2 = q2 . peek ( ) ; if ( n1 . data != n2 . data ) return false ; q1 . remove ( ) ; q2 . remove ( ) ; if ( n1 . left != null && n2 . left != null ) { q1 . add ( n1 . left ) ; q2 . add ( n2 . left ) ; } else if ( n1 . left != null n2 . left != null ) return false ; if ( n1 . right != null && n2 . right != null ) { q1 . add ( n1 . right ) ; q2 . add ( n2 . right ) ; } else if ( n1 . right != null n2 . right != null ) return false ; } return true ; } static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . left = null ; temp . right = null ; return temp ; } public static void main ( String [ ] args ) { Node root1 = newNode ( 1 ) ; root1 . left = newNode ( 2 ) ; root1 . right = newNode ( 3 ) ; root1 . left . left = newNode ( 4 ) ; root1 . left . right = newNode ( 5 ) ; Node root2 = newNode ( 1 ) ; root2 . left = newNode ( 2 ) ; root2 . right = newNode ( 3 ) ; root2 . left . left = newNode ( 4 ) ; root2 . left . right = newNode ( 5 ) ; if ( areIdentical ( root1 , root2 ) == true ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Iterative method to check if two trees are mirror of each other | Java implementation to check whether the two binary tress are mirrors of each other or not ; structure of a node in binary tree ; Utility function to create and return a new node for a binary tree ; function to check whether the two binary trees are mirrors of each other or not ; iterative inorder traversal of 1 st tree and reverse inoder traversal of 2 nd tree ; if the corresponding nodes in the two traversal have different data values , then they are not mirrors of each other . ; if at any point one root becomes null and the other root is not null , then they are not mirrors . This condition verifies that structures of tree are mirrors of each other . ; we have visited the node and its left subtree . Now , it ' s ▁ right ▁ subtree ' s turn ; we have visited the node and its right subtree . Now , it ' s ▁ left ▁ subtree ' s turn ; both the trees have been completely traversed ; tress are mirrors of each other ; Driver program to test above ; 1 st binary tree formation ; 1 ; / \ ; 3 2 ; / \ ; 2 nd binary tree formation ; 1 ; / \ ; 2 3 ; / \ ; 4 5"
How can the above be solved in Java?

import java . util . * ; class GfG { static class Node { int data ; Node left , right ; } static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . left = null ; temp . right = null ; return temp ; } static String areMirrors ( Node root1 , Node root2 ) { Stack < Node > st1 = new Stack < Node > ( ) ; Stack < Node > st2 = new Stack < Node > ( ) ; while ( true ) { while ( root1 != null && root2 != null ) { if ( root1 . data != root2 . data ) return " No " ; st1 . push ( root1 ) ; st2 . push ( root2 ) ; root1 = root1 . left ; root2 = root2 . right ; } if ( ! ( root1 == null && root2 == null ) ) return " No " ; if ( ! st1 . isEmpty ( ) && ! st2 . isEmpty ( ) ) { root1 = st1 . peek ( ) ; root2 = st2 . peek ( ) ; st1 . pop ( ) ; st2 . pop ( ) ; root1 = root1 . right ; root2 = root2 . left ; } else break ; } return " Yes " ; } public static void main ( String [ ] args ) { Node root1 = newNode ( 1 ) ; root1 . left = newNode ( 3 ) ; root1 . right = newNode ( 2 ) ; root1 . right . left = newNode ( 5 ) ; root1 . right . right = newNode ( 4 ) ; Node root2 = newNode ( 1 ) ; root2 . left = newNode ( 2 ) ; root2 . right = newNode ( 3 ) ; root2 . left . left = newNode ( 4 ) ; root2 . left . right = newNode ( 5 ) ; System . out . println ( areMirrors ( root1 , root2 ) ) ; } }


"Iterative method to find ancestors of a given binary tree | Java program to print all ancestors of a given key ; Structure for a tree node ; A utility function to create a new tree node ; Iterative Function to print all ancestors of a given key ; Create a stack to hold ancestors ; Traverse the complete tree in postorder way till we find the key ; Traverse the left side . While traversing , push the nodes into the stack so that their right subtrees can be traversed later ; push current node ; move to next node ; If the node whose ancestors are to be printed is found , then break the while loop . ; Check if right sub - tree exists for the node at top If not then pop that node because we don 't   need this node any more.  ; If the popped node is right child of top , then remove the top as well . Left child of the top must have processed before . ; if stack is not empty then simply set the root as right child of top and start traversing right sub - tree . ; If stack is not empty , print contents of stack Here assumption is that the key is there in tree ; Driver code ; Let us construct a binary tree"
How can the above be solved in Java?

import java . util . * ; class GfG { static class Node { int data ; Node left , right ; } static Node newNode ( int data ) { Node node = new Node ( ) ; node . data = data ; node . left = null ; node . right = null ; return node ; } static void printAncestors ( Node root , int key ) { if ( root == null ) return ; Stack < Node > st = new Stack < Node > ( ) ; while ( 1 == 1 ) { while ( root != null && root . data != key ) { st . push ( root ) ; root = root . left ; } if ( root != null && root . data == key ) break ; if ( st . peek ( ) . right == null ) { root = st . peek ( ) ; st . pop ( ) ; while ( ! st . isEmpty ( ) && st . peek ( ) . right == root ) { root = st . peek ( ) ; st . pop ( ) ; } } root = st . isEmpty ( ) ? null : st . peek ( ) . right ; } while ( ! st . isEmpty ( ) ) { System . out . print ( st . peek ( ) . data + " ▁ " ) ; st . pop ( ) ; } } public static void main ( String [ ] args ) { Node root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 7 ) ; root . left . left = newNode ( 3 ) ; root . left . right = newNode ( 5 ) ; root . right . left = newNode ( 8 ) ; root . right . right = newNode ( 9 ) ; root . left . left . left = newNode ( 4 ) ; root . left . right . right = newNode ( 6 ) ; root . right . right . left = newNode ( 10 ) ; int key = 6 ; printAncestors ( root , key ) ; } }


"Iterative program to Calculate Size of a tree | Java programn to calculate Size of a tree ; Node Structure ; return size of tree ; if tree is empty it will return 0 ; Using level order Traversal . ; when the queue is empty : the poll ( ) method returns null . ; Increment count ; Enqueue left child ; Increment count ; Enqueue right child ; Driver code ; creating a binary tree and entering the nodes"
How can the above be solved in Java?

import java . util . LinkedList ; import java . util . Queue ; class Node { int data ; Node left , right ; public Node ( int item ) { data = item ; left = right = null ; } } class BinaryTree { Node root ; public int size ( ) { if ( root == null ) return 0 ; Queue < Node > q = new LinkedList < Node > ( ) ; q . offer ( root ) ; int count = 1 ; while ( ! q . isEmpty ( ) ) { Node tmp = q . poll ( ) ; if ( tmp != null ) { if ( tmp . left != null ) { count ++ ; q . offer ( tmp . left ) ; } if ( tmp . right != null ) { count ++ ; q . offer ( tmp . right ) ; } } } return count ; } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 1 ) ; tree . root . left = new Node ( 2 ) ; tree . root . right = new Node ( 3 ) ; tree . root . left . left = new Node ( 4 ) ; tree . root . left . right = new Node ( 5 ) ; System . out . println ( " The ▁ size ▁ of ▁ binary ▁ tree " + " ▁ is ▁ : ▁ " + tree . size ( ) ) ; } }


"Iterative program to count leaf nodes in a Binary Tree | Java Program for above approach ; Node class ; Program to count leaves ; If the node itself is " null " return 0 , as there are no leaves ; It the node is a leaf then both right and left children will be " null " ; Now we count the leaves in the left and right subtrees and return the sum ; Class newNode of Node type ; Driver Code ; get leaf count of the above created tree"
How can the above be solved in Java?

import java . util . LinkedList ; import java . util . Queue ; import java . io . * ; import java . util . * ; class GfG { static class Node { int data ; Node left , right ; } static int countLeaves ( Node node ) { if ( node == null ) return 0 ; if ( node . left == null && node . right == null ) return 1 ; return countLeaves ( node . left ) + countLeaves ( node . right ) ; } static Node newNode ( int data ) { Node node = new Node ( ) ; node . data = data ; node . left = node . right = null ; return ( node ) ; } public static void main ( String [ ] args ) { Node root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 3 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 5 ) ; System . out . println ( countLeaves ( root ) ) ; } }


"Iterative program to count leaf nodes in a Binary Tree | Java program to count leaf nodes in a Binary Tree ; A binary tree Node has data , pointer to left child and a pointer to right child ; Function to get the count of leaf Nodes in a binary tree ; If tree is empty ; Initialize empty queue . ; Do level order traversal starting from root Initialize count of leaves ; Helper function that allocates a new Node with the given data and null left and right pointers . ; Driver Code ; 1 / \ 2 3 / \ 4 5 Let us create Binary Tree shown in above example ; get leaf count of the above created tree"
How can the above be solved in Java?

import java . util . * ; class GFG { static class Node { int data ; Node left , right ; } static int getLeafCount ( Node node ) { if ( node == null ) { return 0 ; } Queue < Node > q = new LinkedList < > ( ) ; int count = 0 ; q . add ( node ) ; while ( ! q . isEmpty ( ) ) { Node temp = q . peek ( ) ; q . poll ( ) ; if ( temp . left != null ) { q . add ( temp . left ) ; } if ( temp . right != null ) { q . add ( temp . right ) ; } if ( temp . left == null && temp . right == null ) { count ++ ; } } return count ; } static Node newNode ( int data ) { Node node = new Node ( ) ; node . data = data ; node . left = node . right = null ; return ( node ) ; } public static void main ( String [ ] args ) { { Node root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 3 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 5 ) ; System . out . println ( getLeafCount ( root ) ) ; } } }


"Iterative selection sort for linked list |  ; Traverse the List ; Traverse the unsorted sublist ; Swap Data"
How can the above be solved in Java?

void selectionSort ( node head ) { node temp = head ; while ( temp ) { node min = temp ; node r = temp . next ; while ( r ) { if ( min . data > r . data ) min = r ; r = r . next ; } int x = temp . data ; temp . data = min . data ; min . data = x ; temp = temp . next ; } }


"Iterative selection sort for linked list | Java implementation of the approach ; Linked List Node ; Utility function to create a new Linked List Node ; Function to sort a linked list using selection sort algorithm by swapping the next pointers ; While b is not the last node ; While d is pointing to a valid node ; If d appears immediately after b ; Case 1 : b is the head of the linked list ; Move d before b ; Swap b and d pointers ; Update the head ; Skip to the next element as it is already in order ; Case 2 : b is not the head of the linked list ; Move d before b ; Swap b and d pointers ; Skip to the next element as it is already in order ; If b and d have some non - zero number of nodes in between them ; Case 3 : b is the head of the linked list ; Swap b . next and d . next ; Swap b and d pointers ; Skip to the next element as it is already in order ; Update the head ; Case 4 : b is not the head of the linked list ; Swap b . next and d . next ; Swap b and d pointers ; Skip to the next element as it is already in order ; Update c and skip to the next element as it is already in order ; Function to print the list ; Driver Code"
How can the above be solved in Java?

class GFG { static class Node { int data ; Node next ; } ; static Node newNode ( int val ) { Node temp = new Node ( ) ; temp . data = val ; temp . next = null ; return temp ; } static Node selectionSort ( Node head ) { Node a , b , c , d , r ; a = b = head ; while ( b . next != null ) { c = d = b . next ; while ( d != null ) { if ( b . data > d . data ) { if ( b . next == d ) { if ( b == head ) { b . next = d . next ; d . next = b ; r = b ; b = d ; d = r ; c = d ; head = b ; d = d . next ; } else { b . next = d . next ; d . next = b ; a . next = d ; r = b ; b = d ; d = r ; c = d ; d = d . next ; } } else { if ( b == head ) { r = b . next ; b . next = d . next ; d . next = r ; c . next = b ; r = b ; b = d ; d = r ; c = d ; d = d . next ; head = b ; } else { r = b . next ; b . next = d . next ; d . next = r ; c . next = b ; a . next = d ; r = b ; b = d ; d = r ; c = d ; d = d . next ; } } } else { c = d ; d = d . next ; } } a = b ; b = b . next ; } return head ; } static void printList ( Node head ) { while ( head != null ) { System . out . print ( head . data + " ▁ " ) ; head = head . next ; } } public static void main ( String args [ ] ) { Node head = newNode ( 5 ) ; head . next = newNode ( 4 ) ; head . next . next = newNode ( 3 ) ; head = selectionSort ( head ) ; printList ( head ) ; } }


"Iteratively Reverse a linked list using only 2 pointers ( An Interesting Method ) | Java program to reverse a linked list using two pointers . ; Link list node ; Function to reverse the linked list using 2 pointers ; At last prev points to new head ; This expression evaluates from left to right current . next = prev , changes the link fron next to prev node prev = current , moves prev to current node for next reversal of node This example of list will clear it more 1.2 . 3.4 initially prev = 1 , current = 2 Final expression will be current = 1 ^ 2 ^ 3 ^ 2 ^ 1 , as we know that bitwise XOR of two same numbers will always be 0 i . e ; 1 ^ 1 = 2 ^ 2 = 0 After the evaluation of expression current = 3 that means it has been moved by one node from its previous position ; Function to push a node ; Allocate node ; Put in the data ; Link the old list off the new node ; Move the head to point to the new node ; Function to print linked list ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class Main { static class Node { int data ; Node next ; } ; static Node head_ref = null ; static void reverse ( ) { Node prev = null ; Node current = head_ref ; while ( current != null ) { Node next = current . next ; current . next = prev ; prev = current ; current = next ; } head_ref = prev ; } static void push ( int new_data ) { Node new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = ( head_ref ) ; ( head_ref ) = new_node ; } static void printList ( ) { Node temp = head_ref ; while ( temp != null ) { System . out . print ( temp . data + " ▁ " ) ; temp = temp . next ; } } public static void main ( String [ ] args ) { push ( 20 ) ; push ( 4 ) ; push ( 15 ) ; push ( 85 ) ; System . out . print ( "Given linked list
"); printList ( ) ; reverse ( ) ; System . out . print ( " Reversed Linked list "); printList ( ) ; } }


"Jacobsthal and Jacobsthal | A DP based solution to find Jacobsthal and Jacobsthal - Lucas numbers ; Return nth Jacobsthal number . ; base case ; Return nth Jacobsthal - Lucas number . ; base case ; Driver function"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; public class GfG { public static int Jacobsthal ( int n ) { int [ ] dp = new int [ n + 1 ] ; dp [ 0 ] = 0 ; dp [ 1 ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) dp [ i ] = dp [ i - 1 ] + 2 * dp [ i - 2 ] ; return dp [ n ] ; } public static int Jacobsthal_Lucas ( int n ) { int [ ] dp = new int [ n + 1 ] ; dp [ 0 ] = 2 ; dp [ 1 ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) dp [ i ] = dp [ i - 1 ] + 2 * dp [ i - 2 ] ; return dp [ n ] ; } public static void main ( String argc [ ] ) { int n = 5 ; System . out . println ( " Jacobsthal ▁ number : ▁ " + Jacobsthal ( n ) ) ; System . out . println ( " Jacobsthal - Lucas ▁ number : ▁ " + Jacobsthal_Lucas ( n ) ) ; } }


"Jaro and Jaro | Java implementation of above approach ; Function to calculate the Jaro Similarity of two Strings ; If the Strings are equal ; Length of two Strings ; Maximum distance upto which matching is allowed ; Count of matches ; Hash for matches ; Traverse through the first String ; Check if there is any matches ; If there is a match ; If there is no match ; Number of transpositions ; Count number of occurrences where two characters match but there is a third matched character in between the indices ; Find the next matched character in second String ; Return the Jaro Similarity ; Driver code ; Print jaro Similarity of two Strings"
How can the above be solved in Java?

 class GFG { static double jaro_distance ( String s1 , String s2 ) { if ( s1 == s2 ) return 1.0 ; int len1 = s1 . length ( ) , len2 = s2 . length ( ) ; int max_dist = ( int ) ( Math . floor ( Math . max ( len1 , len2 ) / 2 ) - 1 ) ; int match = 0 ; int hash_s1 [ ] = new int [ s1 . length ( ) ] ; int hash_s2 [ ] = new int [ s2 . length ( ) ] ; for ( int i = 0 ; i < len1 ; i ++ ) { for ( int j = Math . max ( 0 , i - max_dist ) ; j < Math . min ( len2 , i + max_dist + 1 ) ; j ++ ) if ( s1 . charAt ( i ) == s2 . charAt ( j ) && hash_s2 [ j ] == 0 ) { hash_s1 [ i ] = 1 ; hash_s2 [ j ] = 1 ; match ++ ; break ; } } if ( match == 0 ) return 0.0 ; double t = 0 ; int point = 0 ; for ( int i = 0 ; i < len1 ; i ++ ) if ( hash_s1 [ i ] == 1 ) { while ( hash_s2 [ point ] == 0 ) point ++ ; if ( s1 . charAt ( i ) != s2 . charAt ( point ++ ) ) t ++ ; } t /= 2 ; return ( ( ( double ) match ) / ( ( double ) len1 ) + ( ( double ) match ) / ( ( double ) len2 ) + ( ( double ) match - t ) / ( ( double ) match ) ) / 3.0 ; } public static void main ( String [ ] args ) { String s1 = " CRATE " , s2 = " TRACE " ; System . out . print ( jaro_distance ( s1 , s2 ) + "
"); } }


"Jaro and Jaro | Java implementation of above approach ; Function to calculate the Jaro Similarity of two strings ; If the strings are equal ; Length of two strings ; Maximum distance upto which matching is allowed ; Count of matches ; Hash for matches ; Traverse through the first string ; Check if there is any matches ; If there is a match ; If there is no match ; Number of transpositions ; Count number of occurrences where two characters match but there is a third matched character in between the indices ; Find the next matched character in second string ; Return the Jaro Similarity ; Jaro Winkler Similarity ; If the jaro Similarity is above a threshold ; Find the length of common prefix ; If the characters match ; Else break ; Maximum of 4 characters are allowed in prefix ; Calculate jaro winkler Similarity ; Driver code ; Print Jaro - Winkler Similarity of two strings"
How can the above be solved in Java?

class GFG { static double jaro_distance ( String s1 , String s2 ) { if ( s1 == s2 ) return 1.0 ; int len1 = s1 . length ( ) , len2 = s2 . length ( ) ; if ( len1 == 0 len2 == 0 ) return 0.0 ; int max_dist = ( int ) Math . floor ( Math . max ( len1 , len2 ) / 2 ) - 1 ; int match = 0 ; int hash_s1 [ ] = new int [ s1 . length ( ) ] ; int hash_s2 [ ] = new int [ s2 . length ( ) ] ; for ( int i = 0 ; i < len1 ; i ++ ) { for ( int j = Math . max ( 0 , i - max_dist ) ; j < Math . min ( len2 , i + max_dist + 1 ) ; j ++ ) if ( s1 . charAt ( i ) == s2 . charAt ( j ) && hash_s2 [ j ] == 0 ) { hash_s1 [ i ] = 1 ; hash_s2 [ j ] = 1 ; match ++ ; break ; } } if ( match == 0 ) return 0.0 ; double t = 0 ; int point = 0 ; for ( int i = 0 ; i < len1 ; i ++ ) if ( hash_s1 [ i ] == 1 ) { while ( hash_s2 [ point ] == 0 ) point ++ ; if ( s1 . charAt ( i ) != s2 . charAt ( point ++ ) ) t ++ ; } t /= 2 ; return ( ( ( double ) match ) / ( ( double ) len1 ) + ( ( double ) match ) / ( ( double ) len2 ) + ( ( double ) match - t ) / ( ( double ) match ) ) / 3.0 ; } static double jaro_Winkler ( String s1 , String s2 ) { double jaro_dist = jaro_distance ( s1 , s2 ) ; if ( jaro_dist > 0.7 ) { int prefix = 0 ; for ( int i = 0 ; i < Math . min ( s1 . length ( ) , s2 . length ( ) ) ; i ++ ) { if ( s1 . charAt ( i ) == s2 . charAt ( i ) ) prefix ++ ; else break ; } prefix = Math . min ( 4 , prefix ) ; jaro_dist += 0.1 * prefix * ( 1 - jaro_dist ) ; } return jaro_dist ; } public static void main ( String [ ] args ) { String s1 = " TRATE " , s2 = " TRACE " ; System . out . println ( " Jaro - Winkler ▁ Similarity ▁ = " + jaro_Winkler ( s1 , s2 ) ) ; } }


"Job Selection Problem | Java implementation of the above approach ; Create a min - heap ( priority queue ) ; Add all goods to the Queue ; Pop Goods from Queue as long as it is not empty ; Print the good ; Add the Queue to the vector so that total voulme can be calculated ; Calclulating volume of goods left when all are produced . Move from right to left of sequence multiplying each volume by increasing powers of 1 - P starting from 0 ; Print result ; Driver code ; For implementation simplicity days are numbered from 1 to N . Hence 1 based indexing is used ; 10 % loss per day"
How can the above be solved in Java?

import java . util . * ; class GFG { static void optimum_sequence_jobs ( int [ ] V , double P ) { int j = 1 , N = V . length - 1 ; double result = 0 ; PriorityQueue < Integer > Queue = new PriorityQueue < > ( ) ; for ( int i = 1 ; i <= N ; i ++ ) Queue . add ( V [ i ] ) ; while ( ! Queue . isEmpty ( ) ) { System . out . print ( Queue . peek ( ) + " ▁ " ) ; V [ j ++ ] = Queue . peek ( ) ; Queue . remove ( ) ; } for ( int i = N ; i >= 1 ; i -- ) result += Math . pow ( ( 1 - P ) , N - i ) * V [ i ] ; System . out . printf ( " % .2f ", result ); } public static void main ( String [ ] args ) { int [ ] V = { - 1 , 3 , 5 , 4 , 1 , 2 , 7 , 6 , 8 , 9 , 10 } ; double P = 0.10 ; optimum_sequence_jobs ( V , P ) ; } }


"Josephus Circle implementation using STL list | Java Code to find the last man Standing ; Node class to store data ; Function to find the only person left after one in every m - th node is killed in a circle of n nodes ; Create a circular linked list of size N . ; Connect last node to first ; while only one node is left in the linked list ; Find m - th node ; Remove the m - th node ; Driver program to test above functions"
How can the above be solved in Java?

public class GFG { static class Node { public int data ; public Node next ; public Node ( int data ) { this . data = data ; } } static void getJosephusPosition ( int m , int n ) { Node head = new Node ( 1 ) ; Node prev = head ; for ( int i = 2 ; i <= n ; i ++ ) { prev . next = new Node ( i ) ; prev = prev . next ; } prev . next = head ; Node ptr1 = head , ptr2 = head ; while ( ptr1 . next != ptr1 ) { int count = 1 ; while ( count != m ) { ptr2 = ptr1 ; ptr1 = ptr1 . next ; count ++ ; } ptr2 . next = ptr1 . next ; ptr1 = ptr2 . next ; } System . out . println ( " Last ▁ person ▁ left ▁ standing ▁ " + " ( Josephus ▁ Position ) ▁ is ▁ " + ptr1 . data ) ; } public static void main ( String args [ ] ) { int n = 14 , m = 2 ; getJosephusPosition ( m , n ) ; } }


"Josephus Problem Using Bit Magic | Java program for josephus problem ; method to find the position of the Most Significant Bit ; keeps shifting bits to the right until we are left with 0 ; method to return at which place Josephus should sit to avoid being killed ; Getting the position of the Most Significant Bit ( MSB ) . The leftmost '1' . If the number is '41' then its binary is '101001' . So msbPos ( 41 ) = 6 ; ' j ' stores the number with which to XOR the number ' n ' . Since we need '100000' We will do 1 << 6 - 1 to get '100000' ; Toggling the Most Significant Bit . Changing the leftmost '1' to '0' . 101001 ^ 100000 = 001001 ( 9 ) ; Left - shifting once to add an extra '0' to the right end of the binary number 001001 = 010010 ( 18 ) ; Toggling the '0' at the end to '1' which is essentially the same as putting the MSB at the rightmost place . 010010 | 1 = 010011 ( 19 ) ; Driver Method"
How can the above be solved in Java?

public class GFG { static int msbPos ( int n ) { int pos = 0 ; while ( n != 0 ) { pos ++ ; n = n >> 1 ; } return pos ; } static int josephify ( int n ) { int position = msbPos ( n ) ; int j = 1 << ( position - 1 ) ; n = n ^ j ; n = n << 1 ; n = n | 1 ; return n ; } public static void main ( String [ ] args ) { int n = 41 ; System . out . println ( josephify ( n ) ) ; } }


"Josephus Problem | ( Iterative Solution ) | Iterative solution for Josephus Problem ; Method for finding the winning child . ; For finding out the removed chairs in each iteration ; Driver Program to test above method"
How can the above be solved in Java?

class Test { private int josephus ( int n , int k ) { int sum = 0 ; for ( int i = 2 ; i <= n ; i ++ ) { sum = ( sum + k ) % i ; } return sum + 1 ; } public static void main ( String [ ] args ) { int n = 14 ; int k = 2 ; Test obj = new Test ( ) ; System . out . println ( obj . josephus ( n , k ) ) ; } }


"Jump Search | Java program to implement Jump Search . ; Finding block size to be jumped ; Finding the block where element is present ( if it is present ) ; Doing a linear search for x in block beginning with prev . ; If we reached next block or end of array , element is not present . ; If element is found ; Driver program to test function ; Find the index of ' x ' using Jump Search ; Print the index where ' x ' is located"
How can the above be solved in Java?

public class JumpSearch { public static int jumpSearch ( int [ ] arr , int x ) { int n = arr . length ; int step = ( int ) Math . floor ( Math . sqrt ( n ) ) ; int prev = 0 ; while ( arr [ Math . min ( step , n ) - 1 ] < x ) { prev = step ; step += ( int ) Math . floor ( Math . sqrt ( n ) ) ; if ( prev >= n ) return - 1 ; } while ( arr [ prev ] < x ) { prev ++ ; if ( prev == Math . min ( step , n ) ) return - 1 ; } if ( arr [ prev ] == x ) return prev ; return - 1 ; } public static void main ( String [ ] args ) { int arr [ ] = { 0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89 , 144 , 233 , 377 , 610 } ; int x = 55 ; int index = jumpSearch ( arr , x ) ; System . out . println ( " Number " ▁ + ▁ x ▁ + ▁ " is at index " + index); } }


"Jump in rank of a student after updating marks | Java implementation of the approach ; Function to print the name of student who stood first after updation in rank ; Array of students ; Store the name of the student ; Update the marks of the student ; Store the current rank of the student ; Print the name and jump in rank ; Driver code ; Names of the students ; Marks of the students ; Updates that are to be done ; Number of students"
How can the above be solved in Java?

import java . util . * ; class GFG { static class Student { String name ; int marks , prev_rank ; Student ( ) { this . marks = 0 ; this . prev_rank = 0 ; } } static void nameRank ( String [ ] names , int [ ] marks , int [ ] updates , int n ) { Student [ ] x = new Student [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { x [ i ] = new Student ( ) ; x [ i ] . name = names [ i ] ; x [ i ] . marks = marks [ i ] + updates [ i ] ; x [ i ] . prev_rank = i + 1 ; } Student highest = x [ 0 ] ; for ( int j = 1 ; j < n ; j ++ ) { if ( x [ j ] . marks >= highest . marks ) highest = x [ j ] ; } System . out . print ( " Name : ▁ " + highest . name + " , ▁ Jump : ▁ " + Math . abs ( highest . prev_rank - 1 ) ) ; } public static void main ( String [ ] args ) { String [ ] names = { " sam " , " ram " , " geek " } ; int [ ] marks = { 80 , 79 , 75 } ; int [ ] updates = { 0 , 5 , - 9 } ; int n = marks . length ; nameRank ( names , marks , updates , n ) ; } }


"Junction Numbers | Java program for above approach ; Function to find the sum Of digits of N ; To store sum of N and sumOfdigitsof ( N ) ; extracting digit ; Function to check Junction numbers ; To store count of ways n can be represented as i + SOD ( i ) ; Driver Code ; Function Call"
How can the above be solved in Java?

class GFG { static int sum ( int n ) { int sum = 0 ; while ( n != 0 ) { int r = n % 10 ; sum = sum + r ; n = n / 10 ; } return sum ; } static boolean isJunction ( int n ) { int count = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { if ( i + sum ( i ) == n ) count ++ ; } return count >= 2 ; } public static void main ( String [ ] args ) { int N = 111 ; if ( isJunction ( N ) ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } }


"K 'th smallest element in BST using O(1) Extra Space | Java program to find k 'th largest element in BST ; A BST node ; A function to find ; Count to iterate over elements till we get the kth smallest number ; store the Kth smallest ; to store the current node ; Like Morris traversal if current does not have left child rather than printing as we did in inorder , we will just increment the count as the number will be in an increasing order ; if count is equal to K then we found the kth smallest , so store it in ksmall ; go to current 's right child ; we create links to Inorder Successor and count using these links ; building links ; link made to Inorder Successor ; While breaking the links in so made temporary threaded tree we will check for the K smallest condition ; Revert the changes made in if part ( break link from the Inorder Successor ) ; If count is equal to K then we found the kth smallest and so store it in ksmall ; return the found value ; A utility function to create a new BST node ; A utility function to insert a new node with given key in BST ; If the tree is empty , return a new node ; Otherwise , recur down the tree ; return the ( unchanged ) node pointer ; Driver Program to test above functions ; Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80"
How can the above be solved in Java?

import java . util . * ; class GfG { static class Node { int key ; Node left , right ; } static int KSmallestUsingMorris ( Node root , int k ) { int count = 0 ; int ksmall = Integer . MIN_VALUE ; Node curr = root ; while ( curr != null ) { if ( curr . left == null ) { count ++ ; if ( count == k ) ksmall = curr . key ; curr = curr . right ; } else { Node pre = curr . left ; while ( pre . right != null && pre . right != curr ) pre = pre . right ; if ( pre . right == null ) { pre . right = curr ; curr = curr . left ; } else { pre . right = null ; count ++ ; if ( count == k ) ksmall = curr . key ; curr = curr . right ; } } } return ksmall ; } static Node newNode ( int item ) { Node temp = new Node ( ) ; temp . key = item ; temp . left = null ; temp . right = null ; return temp ; } static Node insert ( Node node , int key ) { if ( node == null ) return newNode ( key ) ; if ( key < node . key ) node . left = insert ( node . left , key ) ; else if ( key > node . key ) node . right = insert ( node . right , key ) ; return node ; } public static void main ( String [ ] args ) { Node root = null ; root = insert ( root , 50 ) ; insert ( root , 30 ) ; insert ( root , 20 ) ; insert ( root , 40 ) ; insert ( root , 70 ) ; insert ( root , 60 ) ; insert ( root , 80 ) ; for ( int k = 1 ; k <= 7 ; k ++ ) System . out . print ( KSmallestUsingMorris ( root , k ) + " ▁ " ) ; } }


"K Centers Problem | Set 1 ( Greedy Approximate Algorithm ) | Java program for the above approach ; Index of city having the maximum distance to it 's  closest center ; Updating the distance of the cities to their closest centers ; Updating the index of the city with the maximum distance to it 's closest center ; Printing the maximum distance of a city to a center that is our answer ; Printing the cities that were chosen to be made centers ; Driver Code ; Function Call"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int maxindex ( int [ ] dist , int n ) { int mi = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( dist [ i ] > dist [ mi ] ) mi = i ; } return mi ; } static void selectKcities ( int n , int weights [ ] [ ] , int k ) { int [ ] dist = new int [ n ] ; ArrayList < Integer > centers = new ArrayList < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { dist [ i ] = Integer . MAX_VALUE ; } int max = 0 ; for ( int i = 0 ; i < k ; i ++ ) { centers . add ( max ) ; for ( int j = 0 ; j < n ; j ++ ) { dist [ j ] = Math . min ( dist [ j ] , weights [ max ] [ j ] ) ; } max = maxindex ( dist , n ) ; } System . out . println ( dist [ max ] ) ; for ( int i = 0 ; i < centers . size ( ) ; i ++ ) { System . out . print ( centers . get ( i ) + " ▁ " ) ; } System . out . print ( "
"); } public static void main ( String [ ] args ) { int n = 4 ; int [ ] [ ] weights = new int [ ] [ ] { { 0 , 4 , 8 , 5 } , { 4 , 0 , 10 , 7 } , { 8 , 10 , 0 , 9 } , { 5 , 7 , 9 , 0 } } ; int k = 2 ; selectKcities ( n , weights , k ) ; } }


"K length words that can be formed from given characters without repetition | Java implementation of the approach ; Function to return the required count ; To store the count of distinct characters in str ; Traverse str character by character ; If current character is appearing for the first time in str ; Increment the distinct character count ; Update the appearance of the current character ; Since P ( n , r ) = n ! / ( n - r ) ! ; Return the answer ; Driver code"
How can the above be solved in Java?

import java . util . * ; class solution { static int findPermutation ( String str , int k ) { boolean [ ] has = new boolean [ 26 ] ; Arrays . fill ( has , false ) ; int cnt = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( ! has [ str . charAt ( i ) - ' a ' ] ) { cnt ++ ; has [ str . charAt ( i ) - ' a ' ] = true ; } } int ans = 1 ; for ( int i = 2 ; i <= cnt ; i ++ ) ans *= i ; for ( int i = cnt - k ; i > 1 ; i -- ) ans /= i ; return ans ; } public static void main ( String args [ ] ) { String str = " geeksforgeeks " ; int k = 4 ; System . out . println ( findPermutation ( str , k ) ) ; } }


"K most occurring strings | Java program for the above approach ; Function that returns list of K most frequent strings ; Hash map to store the frequency of each string ; Set the default frequency of each string 0 ; Lambda expression is used set the priority , if frequencies are not equal than the string with greater frequency is returned else the string which is lexically smaller is returned ; Traverse the HashMap ; Remove top ( N - K ) elements ; Order queue has K most frequent strings in a reverse order ; Reverse the ArrayList so as to get in the desired order ; Driver Code ; Given array ; Function Call ; Print the K most occurring strings"
How can the above be solved in Java?

import java . util . * ; class FrequentWords { public static ArrayList < String > frequentWords ( ArrayList < String > arr , int K ) { HashMap < String , Integer > Freq = new HashMap < > ( ) ; for ( String word : arr ) { Freq . put ( word , Freq . getOrDefault ( word , 0 ) + 1 ) ; } PriorityQueue < String > Order = new PriorityQueue < > ( ( a , b ) -> ( Freq . get ( a ) != Freq . get ( b ) ) ? Freq . get ( a ) - Freq . get ( b ) : b . compareTo ( a ) ) ; for ( String word : Freq . keySet ( ) ) { Order . offer ( word ) ; if ( Order . size ( ) > K ) { Order . poll ( ) ; } } ArrayList < String > ans = new ArrayList < > ( ) ; while ( ! Order . isEmpty ( ) ) { ans . add ( Order . poll ( ) ) ; } Collections . reverse ( ans ) ; return ans ; } public static void main ( String [ ] args ) { int N = 3 , K = 2 ; ArrayList < String > arr = new ArrayList < String > ( ) ; arr . add ( " car " ) ; arr . add ( " bus " ) ; arr . add ( " car " ) ; ArrayList < String > ans = frequentWords ( arr , K ) ; for ( String word : ans ) { System . out . println ( word + " ▁ " ) ; } } }


"K | Java Program to find kth element from two sorted arrays ; Driver Code"
How can the above be solved in Java?

class Main { static int kth ( int arr1 [ ] , int arr2 [ ] , int m , int n , int k ) { int [ ] sorted1 = new int [ m + n ] ; int i = 0 , j = 0 , d = 0 ; while ( i < m && j < n ) { if ( arr1 [ i ] < arr2 [ j ] ) sorted1 [ d ++ ] = arr1 [ i ++ ] ; else sorted1 [ d ++ ] = arr2 [ j ++ ] ; } while ( i < m ) sorted1 [ d ++ ] = arr1 [ i ++ ] ; while ( j < n ) sorted1 [ d ++ ] = arr2 [ j ++ ] ; return sorted1 [ k - 1 ] ; } public static void main ( String [ ] args ) { int arr1 [ ] = { 2 , 3 , 6 , 7 , 9 } ; int arr2 [ ] = { 1 , 4 , 8 , 10 } ; int k = 5 ; System . out . print ( kth ( arr1 , arr2 , 5 , 4 , k ) ) ; } }


"K | Java Program to find kth element from two sorted arrays ; Function to find K - th min ; Declaring a min heap ; Pushing elements for array a to min - heap ; Pushing elements for array b to min - heap ; Poping - out K - 1 elements ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int kth ( int a [ ] , int b [ ] , int n , int m , int k ) { PriorityQueue < Integer > pq = new PriorityQueue < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { pq . offer ( a [ i ] ) ; } for ( int i = 0 ; i < m ; i ++ ) { pq . offer ( b [ i ] ) ; } while ( k -- > 1 ) { pq . remove ( ) ; } return pq . peek ( ) ; } public static void main ( String [ ] args ) { int arr1 [ ] = { 2 , 3 , 6 , 7 , 9 } ; int arr2 [ ] = { 1 , 4 , 8 , 10 } ; int k = 5 ; System . out . print ( kth ( arr1 , arr2 , 5 , 4 , k ) ) ; } }


"K | Java Program to find kth element from two sorted arrays ; In case we have reached end of array 1 ; In case we have reached end of array 2 ; k should never reach 0 or exceed sizes of arrays ; Compare first elements of arrays and return ; Size of array 1 is less than k / 2 ; Last element of array 1 is not kth We can directly return the ( k - m ) th element in array 2 ; Size of array 2 is less than k / 2 ; Normal comparison , move starting index of one array k / 2 to the right ; Driver code"
How can the above be solved in Java?

class GFG { static int kth ( int arr1 [ ] , int arr2 [ ] , int m , int n , int k , int st1 , int st2 ) { if ( st1 == m ) { return arr2 [ st2 + k - 1 ] ; } if ( st2 == n ) { return arr1 [ st1 + k - 1 ] ; } if ( k == 0 || k > ( m - st1 ) + ( n - st2 ) ) { return - 1 ; } if ( k == 1 ) { return ( arr1 [ st1 ] < arr2 [ st2 ] ) ? arr1 [ st1 ] : arr2 [ st2 ] ; } int curr = k / 2 ; if ( curr - 1 >= m - st1 ) { if ( arr1 [ m - 1 ] < arr2 [ st2 + curr - 1 ] ) { return arr2 [ st2 + ( k - ( m - st1 ) - 1 ) ] ; } else { return kth ( arr1 , arr2 , m , n , k - curr , st1 , st2 + curr ) ; } } if ( curr - 1 >= n - st2 ) { if ( arr2 [ n - 1 ] < arr1 [ st1 + curr - 1 ] ) { return arr1 [ st1 + ( k - ( n - st2 ) - 1 ) ] ; } else { return kth ( arr1 , arr2 , m , n , k - curr , st1 + curr , st2 ) ; } } else if ( arr1 [ curr + st1 - 1 ] < arr2 [ curr + st2 - 1 ] ) { return kth ( arr1 , arr2 , m , n , k - curr , st1 + curr , st2 ) ; } else { return kth ( arr1 , arr2 , m , n , k - curr , st1 , st2 + curr ) ; } } public static void main ( String [ ] args ) { int arr1 [ ] = { 2 , 3 , 6 , 7 , 9 } ; int arr2 [ ] = { 1 , 4 , 8 , 10 } ; int k = 5 ; int st1 = 0 , st2 = 0 ; System . out . println ( kth ( arr1 , arr2 , 5 , 4 , k , st1 , st2 ) ) ; } }


"K | Java Program to find kth element from two sorted arrays Time Complexity : O ( log k ) ; let m > n ; Check if arr1 is empty returning k - th element of arr2 ; Check if k = 1 return minimum of first two elements of both arrays ; Now the divide and conquer part ; Now we need to find only k - j th element since we have found out the lowest j ; Now we need to find only k - i th element since we have found out the lowest i ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; class Gfg { static int kth ( int arr1 [ ] , int m , int arr2 [ ] , int n , int k ) { if ( k > ( m + n ) k < 1 ) return - 1 ; if ( m > n ) return kth ( arr2 , n , arr1 , m , k ) ; if ( m == 0 ) return arr2 [ k - 1 ] ; if ( k == 1 ) return Math . min ( arr1 [ 0 ] , arr2 [ 0 ] ) ; int i = Math . min ( m , k / 2 ) ; int j = Math . min ( n , k / 2 ) ; if ( arr1 [ i - 1 ] > arr2 [ j - 1 ] ) { int temp [ ] = Arrays . copyOfRange ( arr2 , j , n ) ; return kth ( arr1 , m , temp , n - j , k - j ) ; } int temp [ ] = Arrays . copyOfRange ( arr1 , i , m ) ; return kth ( temp , m - i , arr2 , n , k - i ) ; } public static void main ( String [ ] args ) { int arr1 [ ] = { 2 , 3 , 6 , 7 , 9 } ; int arr2 [ ] = { 1 , 4 , 8 , 10 } ; int m = arr1 . length ; int n = arr2 . length ; int k = 5 ; int ans = kth ( arr1 , m , arr2 , n , k ) ; if ( ans == - 1 ) System . out . println ( " Invalid ▁ query " ) ; else System . out . println ( ans ) ; } }


"K | Java implementation of above approach ; Function that finds the Nth element of K - Fibonacci series ; If N is less than K then the element is '1' ; first k elements are 1 ; ( K + 1 ) th element is K ; find the elements of the K - Fibonacci series ; subtract the element at index i - k - 1 and add the element at index i - i from the sum ( sum contains the sum of previous ' K ' elements ) ; set the new sum ; Driver code ; get the Nth value of K - Fibonacci series"
How can the above be solved in Java?

public class GFG { static void solve ( int N , int K ) { int Array [ ] = new int [ N + 1 ] ; if ( N <= K ) { System . out . println ( "1" ) ; return ; } int i = 0 ; int sum = K ; for ( i = 1 ; i <= K ; ++ i ) { Array [ i ] = 1 ; } Array [ i ] = sum ; for ( i = K + 2 ; i <= N ; ++ i ) { Array [ i ] = sum - Array [ i - K - 1 ] + Array [ i - 1 ] ; sum = Array [ i ] ; } System . out . println ( Array [ N ] ) ; } public static void main ( String args [ ] ) { int N = 4 , K = 2 ; solve ( N , K ) ; } }


"K | Java implementation of the above approach ; Set to store the unique substring ; String to create each substring ; Adding to set ; Converting set into a list ; Sorting the strings int the list into lexicographical order ; Printing kth substring ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { public static void kThLexString ( String st , int k , int n ) { Set < String > z = new HashSet < String > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { String pp = " " ; for ( int j = i ; j < i + k ; j ++ ) { if ( j >= n ) break ; pp += st . charAt ( j ) ; z . add ( pp ) ; } } Vector < String > fin = new Vector < String > ( ) ; fin . addAll ( z ) ; Collections . sort ( fin ) ; System . out . print ( fin . get ( k - 1 ) ) ; } public static void main ( String [ ] args ) { String s = " geeksforgeeks " ; int k = 5 ; int n = s . length ( ) ; kThLexString ( s , k , n ) ; } }


"K | Java program for finding k - th digit in a ^ b ; To compute k - th digit in a ^ b ; Computing a ^ b ; Getting last digit ; Increasing count by 1 ; If current number is required digit ; Remove last digit ; Driver Code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; public class GfG { public static int kthdigit ( int a , int b , int k ) { int p = ( int ) Math . pow ( a , b ) ; int count = 0 ; while ( p > 0 && count < k ) { int rem = p % 10 ; count ++ ; if ( count == k ) return rem ; p = p / 10 ; } return 0 ; } public static void main ( String argc [ ] ) { int a = 5 , b = 2 ; int k = 1 ; System . out . println ( kthdigit ( a , b , k ) ) ; } }


"K | Java program for the above approach ; Function to calculate K - th smallest solution ( Y ) of equation X + Y = X | Y ; Initialize the variable to store the answer ; The i - th bit of X is off ; The i - bit of K is on ; Divide K by 2 ; If K becomes 0 then break ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static long KthSolution ( long X , long K ) { long ans = 0 ; for ( int i = 0 ; i < 64 ; i ++ ) { if ( ( X & ( 1 << i ) ) == 0 ) { if ( ( K & 1 ) > 0 ) { ans |= ( 1 << i ) ; } K >>= 1 ; if ( K == 0 ) { break ; } } } return ans ; } public static void main ( String [ ] args ) { long X = 5 , K = 5 ; System . out . println ( KthSolution ( X , K ) ) ; } }


"K | Java program for the above approach ; Function to find the kth digit from last in an integer n ; If k is less than equal to 0 ; Convert integer into string ; If k is greater than length of the string temp ; Print the k digit from last ; Driver code ; Given Input ; Function call"
How can the above be solved in Java?

import java . io . * ; class GFG { public static void kthDigitFromLast ( int n , int k ) { if ( k <= 0 ) { System . out . println ( - 1 ) ; return ; } String temp = Integer . toString ( n ) ; if ( k > temp . length ( ) ) { System . out . println ( - 1 ) ; } else { int index = temp . length ( ) - k ; int res = temp . charAt ( index ) - '0' ; System . out . println ( res ) ; } } public static void main ( String [ ] args ) { int n = 2354 ; int k = 2 ; kthDigitFromLast ( n , k ) ; } }


"K | Java program for the above approach ; Function to find the kth digit from last in an integer n ; If k is less than equal to 0 ; Divide the number n by 10 upto k - 1 times ; If the number n is equal 0 ; Print the right most digit ; Driver code ; Given input ; Function call"
How can the above be solved in Java?

import java . io . * ; class GFG { public static void kthDigitFromLast ( int n , int k ) { if ( k <= 0 ) { System . out . println ( - 1 ) ; return ; } while ( ( k - 1 ) > 0 && n > 0 ) { n = n / 10 ; k -- ; } if ( n == 0 ) { System . out . println ( - 1 ) ; } else { System . out . println ( n % 10 ) ; } } public static void main ( String [ ] args ) { int n = 2354 ; int k = 2 ; kthDigitFromLast ( n , k ) ; } }


"K | Java program for the above approach ; Recursive function to find the Kth smallest binary string ; Base Case ; Return string of all 1 's  of length B ; Return string of all 0 's  of length A ; Function to find the Kth lexicographically smallest binary string with exactly A zeroes and B ones ; Stores the recurring states ; Calculate the dp values iteratively ; The last character was '0' ; The last character was '1' ; Print the binary string obtained ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static String KthString ( int A , int B , long K , int [ ] [ ] dp ) { if ( A == 0 ) { String ans = " " ; for ( int i = 0 ; i < B ; i ++ ) { ans += '1' ; } return ans ; } if ( B == 0 ) { String ans = " " ; for ( int i = 0 ; i < A ; i ++ ) { ans += '0' ; } return ans ; } if ( K <= dp [ A - 1 ] [ B ] ) { return "0" + KthString ( A - 1 , B , K , dp ) ; } else { return "1" + KthString ( A , B - 1 , K - dp [ A - 1 ] [ B ] , dp ) ; } } static int KthStringUtil ( int A , int B , int K ) { int [ ] [ ] dp = new int [ A + 1 ] [ B + 1 ] ; dp [ 0 ] [ 0 ] = 1 ; for ( int i = 0 ; i <= A ; ++ i ) { for ( int j = 0 ; j <= B ; ++ j ) { if ( i > 0 ) { dp [ i ] [ j ] += dp [ i - 1 ] [ j ] ; } if ( j > 0 ) { dp [ i ] [ j ] += dp [ i ] [ j - 1 ] ; } } } System . out . println ( KthString ( A , B , K , dp ) ) ; return 0 ; } public static void main ( String [ ] args ) { int A = 3 , B = 3 , K = 7 ; KthStringUtil ( A , B , K ) ; } }


"K | Java program to count all those numbers in given range whose count of prime factors is k ; Returns the sum of first n odd numbers ; Count prime factors of all numbers till B . ; Print all numbers with k prime factors ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void printKPFNums ( int A , int B , int K ) { int p_factors [ ] = new int [ B + 1 ] ; Arrays . fill ( p_factors , 0 ) ; for ( int p = 2 ; p <= B ; p ++ ) if ( p_factors [ p ] == 0 ) for ( int i = p ; i <= B ; i += p ) p_factors [ i ] ++ ; for ( int i = A ; i <= B ; i ++ ) if ( p_factors [ i ] == K ) System . out . print ( i + " ▁ " ) ; } public static void main ( String args [ ] ) { int A = 14 , B = 18 , K = 2 ; printKPFNums ( A , B , K ) ; } }


"K | Java program to find k - th term of N merged Arithmetic Progressions ; Function to count and return the number of values less than equal to N present in the set ; Check whether j - th bit is set bit or not ; Function to implement Binary Search to find K - th element ; Find middle index of the array ; Search in the left half ; Search in the right half ; If exactly K elements are present ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static final int maxm = 1000000000 ; static int count ( int [ ] v , int n ) { int i , odd = 0 , even = 0 ; int j , d , count ; int t = ( int ) 1 << v . length ; int size = v . length ; for ( i = 1 ; i < t ; i ++ ) { d = 1 ; count = 0 ; for ( j = 0 ; j < size ; j ++ ) { if ( ( i & ( 1 << j ) ) > 0 ) { d *= v [ j ] ; count ++ ; } } if ( count % 2 == 1 ) odd += n / d ; else even += n / d ; } return ( odd - even ) ; } static int BinarySearch ( int l , int r , int [ ] v , int key ) { int mid ; while ( r - l > 1 ) { mid = ( l + r ) / 2 ; if ( key <= count ( v , mid ) ) { r = mid ; } else { l = mid ; } } if ( key == count ( v , l ) ) return l ; else return r ; } public static void main ( String [ ] args ) { int N = 2 , K = 10 ; int [ ] v = { 2 , 3 } ; System . out . print ( BinarySearch ( 1 , maxm , v , K ) + "
"); } }


"K | Java program to find the K - th lexicographical String of length N ; Initialize the array to store the base 26 representation of K with all zeroes , that is , the initial String consists of N a 's ; Start filling all the N slots for the base 26 representation of K ; Store the remainder ; Reduce K ; If K is greater than the possible number of Strings that can be represented by a String of length N ; Store the Kth lexicographical String ; Driver Code ; Reducing k value by 1 because our stored value starts from 0"
How can the above be solved in Java?

class GFG { static String find_kth_String_of_n ( int n , int k ) { int [ ] d = new int [ n ] ; for ( int i = n - 1 ; i > - 1 ; i -- ) { d [ i ] = k % 26 ; k /= 26 ; } if ( k > 0 ) return " - 1" ; String s = " " ; for ( int i = 0 ; i < n ; i ++ ) s += ( char ) ( d [ i ] + ( ' a ' ) ) ; return s ; } public static void main ( String [ ] args ) { int n = 3 ; int k = 10 ; k -= 1 ; System . out . println ( find_kth_String_of_n ( n , k ) ) ; } }


"K | Java program to find the K - th smallest element after removing some integers from natural number . ; Return the K - th smallest element . ; Making an array , and mark all number as unmarked . ; Marking the number present in the given array . ; If j is unmarked , reduce k by 1. ; If k is 0 return j . ; Driven code"
How can the above be solved in Java?

class GFG { static final int MAX = 1000000 ; static int ksmallest ( int arr [ ] , int n , int k ) { int b [ ] = new int [ MAX ] ; for ( int i = 0 ; i < n ; i ++ ) { b [ arr [ i ] ] = 1 ; } for ( int j = 1 ; j < MAX ; j ++ ) { if ( b [ j ] != 1 ) { k -- ; } if ( k != 1 ) { return j ; } } return Integer . MAX_VALUE ; } public static void main ( String [ ] args ) { int k = 1 ; int arr [ ] = { 1 } ; int n = arr . length ; System . out . println ( ksmallest ( arr , n , k ) ) ; } }


"K | Java program to find the Kth smallest element after removing some integer from first n natural number . ; Return the K - th smallest element . ; sort ( arr , arr + n ) ; ; Checking if k lies before 1 st element ; If k is the first element of array arr [ ] . ; If k is more than last element ; If first element of array is 1. ; Reducing k by numbers before arr [ 0 ] . ; Finding k 'th smallest  element after removing  array elements. ; Finding count of element between i - th and ( i - 1 ) - th element . ; Driven Code"
How can the above be solved in Java?

import java . util . Arrays ; import java . io . * ; class GFG { static int ksmallest ( int arr [ ] , int n , int k ) { Arrays . sort ( arr ) ; if ( k < arr [ 0 ] ) return k ; if ( k == arr [ 0 ] ) return arr [ 0 ] + 1 ; if ( k > arr [ n - 1 ] ) return k + n ; if ( arr [ 0 ] == 1 ) k -- ; else k -= ( arr [ 0 ] - 1 ) ; for ( int i = 1 ; i < n ; i ++ ) { int c = arr [ i ] - arr [ i - 1 ] - 1 ; if ( k <= c ) return arr [ i - 1 ] + k ; else k -= c ; } return arr [ n - 1 ] + k ; } public static void main ( String [ ] args ) { int k = 1 ; int arr [ ] = { 1 } ; int n = arr . length ; System . out . println ( ksmallest ( arr , n , k ) ) ; } }


"Kaprekar Constant | Java program to demonstrate working of Kaprekar constant ; This function checks validity of kaprekar ' s ▁ constant . ▁ It ▁ returns ▁ kaprekar ' s constant for any four digit number " n " such that all digits of n are not same . ; Store current n as previous number ; Get four digits of given number ; Sort all four dgits in ascending order And giet in the form of number " asc " ; Get all four dgits in descending order in the form of number " desc " ; Get the difference of two numbers ; If difference is same as previous , we have reached kaprekar 's constant ; Else recur ; A wrapper over kaprekarRec ( ) ; Driver code ; Trying few four digit numbers , we always get 6174"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static int kaprekarRec ( int n , int prev ) { if ( n == 0 ) return 0 ; prev = n ; int [ ] digits = new int [ 4 ] ; for ( int i = 0 ; i < 4 ; i ++ ) { digits [ i ] = n % 10 ; n = n / 10 ; } Arrays . sort ( digits ) ; int asc = 0 ; for ( int i = 0 ; i < 4 ; i ++ ) asc = asc * 10 + digits [ i ] ; Arrays . sort ( digits ) ; int desc = 0 ; for ( int i = 3 ; i >= 0 ; i -- ) desc = desc * 10 + digits [ i ] ; int diff = Math . abs ( asc - desc ) ; if ( diff == prev ) return diff ; return kaprekarRec ( diff , prev ) ; } static int kaprekar ( int n ) { int prev = 0 ; return kaprekarRec ( n , prev ) ; } public static void main ( String [ ] args ) { System . out . println ( kaprekar ( 1000 ) ) ; System . out . println ( kaprekar ( 1112 ) ) ; System . out . println ( kaprekar ( 9812 ) ) ; } }


"Kaprekar Number | Java program to check if a number is Kaprekar number or not ; Returns true if n is a Kaprekar number , else false ; Count number of digits in square ; Split the square at different poitns and see if sum of any pair of splitted numbers is equal to n . ; To avoid numbers like 10 , 100 , 1000 ( These are not Karprekar numbers ; Find sum of current parts and compare with n ; compare with original number ; Driver method"
How can the above be solved in Java?

class GFG { static boolean iskaprekar ( int n ) { if ( n == 1 ) return true ; int sq_n = n * n ; int count_digits = 0 ; while ( sq_n != 0 ) { count_digits ++ ; sq_n /= 10 ; } for ( int r_digits = 1 ; r_digits < count_digits ; r_digits ++ ) { int eq_parts = ( int ) Math . pow ( 10 , r_digits ) ; if ( eq_parts == n ) continue ; int sum = sq_n / eq_parts + sq_n % eq_parts ; if ( sum == n ) return true ; } return false ; } public static void main ( String [ ] args ) { System . out . println ( " Printing ▁ first ▁ few ▁ Kaprekar ▁ Numbers " + " ▁ using ▁ iskaprekar ( ) " ) ; for ( int i = 1 ; i < 10000 ; i ++ ) if ( iskaprekar ( i ) ) System . out . print ( i + " ▁ " ) ; } }


"Karp 's minimum mean (or average) weight cycle algorithm | Java program to find minimum average weight of a cycle in connected and directed graph . ; a struct to represent edges ; vector to store edges @ SuppressWarnings ( " unchecked " ) ; calculates the shortest path ; initializing all distances as - 1 ; shortest distance from first vertex to in tself consisting of 0 edges ; filling up the dp table ; Returns minimum value of average weight of a cycle in graph . ; array to store the avg values ; Compute average values for all vertices using weights of shortest paths store in dp . ; Find minimum value in avg [ ] ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int V = 4 ; static class Edge { int from , weight ; Edge ( int from , int weight ) { this . from = from ; this . weight = weight ; } } static Vector < Edge > [ ] edges = new Vector [ V ] ; static { for ( int i = 0 ; i < V ; i ++ ) edges [ i ] = new Vector < > ( ) ; } static void addedge ( int u , int v , int w ) { edges [ v ] . add ( new Edge ( u , w ) ) ; } static void shortestpath ( int [ ] [ ] dp ) { for ( int i = 0 ; i <= V ; i ++ ) for ( int j = 0 ; j < V ; j ++ ) dp [ i ] [ j ] = - 1 ; dp [ 0 ] [ 0 ] = 0 ; for ( int i = 1 ; i <= V ; i ++ ) { for ( int j = 0 ; j < V ; j ++ ) { for ( int k = 0 ; k < edges [ j ] . size ( ) ; k ++ ) { if ( dp [ i - 1 ] [ edges [ j ] . elementAt ( k ) . from ] != - 1 ) { int curr_wt = dp [ i - 1 ] [ edges [ j ] . elementAt ( k ) . from ] + edges [ j ] . elementAt ( k ) . weight ; if ( dp [ i ] [ j ] == - 1 ) dp [ i ] [ j ] = curr_wt ; else dp [ i ] [ j ] = Math . min ( dp [ i ] [ j ] , curr_wt ) ; } } } } } static double minAvgWeight ( ) { int [ ] [ ] dp = new int [ V + 1 ] [ V ] ; shortestpath ( dp ) ; double [ ] avg = new double [ V ] ; for ( int i = 0 ; i < V ; i ++ ) avg [ i ] = - 1 ; for ( int i = 0 ; i < V ; i ++ ) { if ( dp [ V ] [ i ] != - 1 ) { for ( int j = 0 ; j < V ; j ++ ) if ( dp [ j ] [ i ] != - 1 ) avg [ i ] = Math . max ( avg [ i ] , ( ( double ) dp [ V ] [ i ] - dp [ j ] [ i ] ) / ( V - j ) ) ; } } double result = avg [ 0 ] ; for ( int i = 0 ; i < V ; i ++ ) if ( avg [ i ] != - 1 && avg [ i ] < result ) result = avg [ i ] ; return result ; } public static void main ( String [ ] args ) { addedge ( 0 , 1 , 1 ) ; addedge ( 0 , 2 , 10 ) ; addedge ( 1 , 2 , 3 ) ; addedge ( 2 , 3 , 2 ) ; addedge ( 3 , 1 , 0 ) ; addedge ( 3 , 0 , 8 ) ; System . out . printf ( " % .5f " , minAvgWeight ( ) ) ; } }


"Keith Number | Java program to check if a number is Keith or not ; Returns true if x is Keith , else false . ; Store all digits of x in a vector " terms " Also find number of digits and store in " n " . ; int temp = x , n = 0 ; n is number of digits in x ; To get digits in right order ( from MSB to LSB ) ; Keep finding next trms of a sequence generated using digits of x until we either reach x or a number greate than x ; Next term is sum of previous n terms ; When the control comes out of the while loop , either the next_term is equal to the number or greater than it . If next_term is equal to x , then x is a Keith number , else not ; Driver program"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static boolean isKeith ( int x ) { ArrayList < Integer > terms = new ArrayList < Integer > ( ) ; while ( temp > 0 ) { terms . add ( temp % 10 ) ; temp = temp / 10 ; n ++ ; } Collections . reverse ( terms ) ; int next_term = 0 , i = n ; while ( next_term < x ) { next_term = 0 ; for ( int j = 1 ; j <= n ; j ++ ) next_term += terms . get ( i - j ) ; terms . add ( next_term ) ; i ++ ; } return ( next_term == x ) ; } public static void main ( String [ ] args ) { if ( isKeith ( 14 ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; if ( isKeith ( 12 ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; if ( isKeith ( 197 ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Keyword Cipher | Java program for encoding the string using classical cipher ; Function generates the encoded text ; This array represents the 26 letters of alphabets ; This loop inserts the keyword at the start of the encoded string ; To check whether the character is inserted earlier in the encoded string or not ; This loop inserts the remaining characters in the encoded string . ; Function that generates encodes ( cipher ) the message ; This loop ciphered the message . Spaces , special characters and numbers remain same . ; Driver code ; Hold the Keyword ; Function call to generate encoded text ; Message that need to encode ; Function call to print ciphered text"
How can the above be solved in Java?

class GFG { static String encoder ( char [ ] key ) { String encoded = " " ; boolean [ ] arr = new boolean [ 26 ] ; for ( int i = 0 ; i < key . length ; i ++ ) { if ( key [ i ] >= ' A ' && key [ i ] <= ' Z ' ) { if ( arr [ key [ i ] - 65 ] == false ) { encoded += ( char ) key [ i ] ; arr [ key [ i ] - 65 ] = true ; } } else if ( key [ i ] >= ' a ' && key [ i ] <= ' z ' ) { if ( arr [ key [ i ] - 97 ] == false ) { encoded += ( char ) ( key [ i ] - 32 ) ; arr [ key [ i ] - 97 ] = true ; } } } for ( int i = 0 ; i < 26 ; i ++ ) { if ( arr [ i ] == false ) { arr [ i ] = true ; encoded += ( char ) ( i + 65 ) ; } } return encoded ; } static String cipheredIt ( String msg , String encoded ) { String cipher = " " ; for ( int i = 0 ; i < msg . length ( ) ; i ++ ) { if ( msg . charAt ( i ) >= ' a ' && msg . charAt ( i ) <= ' z ' ) { int pos = msg . charAt ( i ) - 97 ; cipher += encoded . charAt ( pos ) ; } else if ( msg . charAt ( i ) >= ' A ' && msg . charAt ( i ) <= ' Z ' ) { int pos = msg . charAt ( i ) - 65 ; cipher += encoded . charAt ( pos ) ; } else { cipher += msg . charAt ( i ) ; } } return cipher ; } public static void main ( String [ ] args ) { String key ; key = " Computer " ; System . out . println ( " Keyword ▁ : ▁ " + key ) ; String encoded = encoder ( key . toCharArray ( ) ) ; String message = " GeeksforGeeks " ; System . out . println ( " Message ▁ before ▁ Ciphering ▁ : ▁ " + message ) ; System . out . println ( " Ciphered ▁ Text ▁ : ▁ " + cipheredIt ( message , encoded ) ) ; } }


"Knapsack with large Weights | Java implementation of the approach ; To store the states of DP ; Function to solve the recurrence relation ; Base cases ; Marking state as solved ; Recurrence relation ; Function to return the maximum weight ; Iterating through all possible values to find the the largest value that can be represented by the given weights ; Driver code"
How can the above be solved in Java?

class GFG { static final int V_SUM_MAX = 1000 ; static final int N_MAX = 100 ; static final int W_MAX = 10000000 ; static int dp [ ] [ ] = new int [ V_SUM_MAX + 1 ] [ N_MAX ] ; static boolean v [ ] [ ] = new boolean [ V_SUM_MAX + 1 ] [ N_MAX ] ; static int solveDp ( int r , int i , int w [ ] , int val [ ] , int n ) { if ( r <= 0 ) return 0 ; if ( i == n ) return W_MAX ; if ( v [ r ] [ i ] ) return dp [ r ] [ i ] ; v [ r ] [ i ] = true ; dp [ r ] [ i ] = Math . min ( solveDp ( r , i + 1 , w , val , n ) , w [ i ] + solveDp ( r - val [ i ] , i + 1 , w , val , n ) ) ; return dp [ r ] [ i ] ; } static int maxWeight ( int w [ ] , int val [ ] , int n , int c ) { for ( int i = V_SUM_MAX ; i >= 0 ; i -- ) { if ( solveDp ( i , 0 , w , val , n ) <= c ) { return i ; } } return 0 ; } public static void main ( String [ ] args ) { int w [ ] = { 3 , 4 , 5 } ; int val [ ] = { 30 , 50 , 60 } ; int n = w . length ; int C = 8 ; System . out . println ( maxWeight ( w , val , n , C ) ) ; } }


"Koko Eating Bananas | Java implementation for the above approach ; to get the ceil value ; in case of odd number ; in case of even number ; check if time is less than or equals to given hour ; as minimum speed of eating must be 1 ; Maximum speed of eating is the maximum bananas in given piles ; Check if the mid ( hours ) is valid ; If valid continue to search lower speed ; If cant finish bananas in given hours , then increase the speed ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean check ( int [ ] bananas , int mid_val , int H ) { int time = 0 ; for ( int i = 0 ; i < bananas . length ; i ++ ) { if ( bananas [ i ] % mid_val != 0 ) { time += ( ( bananas [ i ] / mid_val ) + 1 ) ; } else { time += ( bananas [ i ] / mid_val ) ; } } if ( time <= H ) { return true ; } else { return false ; } } static int minEatingSpeed ( int [ ] piles , int H ) { int start = 1 ; int end = Arrays . stream ( piles ) . max ( ) . getAsInt ( ) ; while ( start < end ) { int mid = start + ( end - start ) / 2 ; if ( ( check ( piles , mid , H ) ) == true ) { end = mid ; } else { start = mid + 1 ; } } return end ; } public static void main ( String [ ] args ) { int [ ] piles = { 30 , 11 , 23 , 4 , 20 } ; int H = 6 ; System . out . print ( minEatingSpeed ( piles , H ) ) ; } }


"Kruskal 's Algorithm (Simple Implementation for Adjacency Matrix) | Simple Java implementation for Kruskal 's algorithm ; Find set of vertex i ; Does union of i and j . It returns false if i and j are already in same set . ; Finds MST using Kruskal 's algorithm ; Initialize sets of disjoint sets . ; Include minimum weight edges one by one ; Driver code ; Let us create the following graph 2 3 ( 0 ) -- ( 1 ) -- ( 2 ) | / \ | 6 | 8 / \ 5 | 7 | / \ | ( 3 ) -- -- -- - ( 4 ) 9 ; Print the solution"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int V = 5 ; static int [ ] parent = new int [ V ] ; static int INF = Integer . MAX_VALUE ; static int find ( int i ) { while ( parent [ i ] != i ) i = parent [ i ] ; return i ; } static void union1 ( int i , int j ) { int a = find ( i ) ; int b = find ( j ) ; parent [ a ] = b ; } static void kruskalMST ( int cost [ ] [ ] ) { for ( int i = 0 ; i < V ; i ++ ) parent [ i ] = i ; int edge_count = 0 ; while ( edge_count < V - 1 ) { int min = INF , a = - 1 , b = - 1 ; for ( int i = 0 ; i < V ; i ++ ) { for ( int j = 0 ; j < V ; j ++ ) { if ( find ( i ) != find ( j ) && cost [ i ] [ j ] < min ) { min = cost [ i ] [ j ] ; a = i ; b = j ; } } } union1 ( a , b ) ; System . out . printf ( "Edge %d:(%d, %d) cost:%d
", edge_count++, a, b, min); mincost += min ; } System . out . printf ( " Minimum cost = % d ", mincost); } public static void main ( String [ ] args ) { int cost [ ] [ ] = { { INF , 2 , INF , 6 , INF } , { 2 , INF , 3 , 8 , 5 } , { INF , 3 , INF , INF , 7 } , { 6 , 8 , INF , INF , 9 } , { INF , 5 , 7 , 9 , INF } , } ; kruskalMST ( cost ) ; } }


"Kth Smallest Element in a sorted array formed by reversing subarrays from a random index | Java program for the above approach ; Function to find the Kth element in a sorted and rotated array at random point ; Set the boundaries for binary search ; Apply binary search to find R ; Initialize the middle element ; Check in the right side of mid ; Else check in the left side ; Random point either l or h ; Return the kth smallest element ; Driver Code ; Given Input ; Function Call"
How can the above be solved in Java?

class GFG { public static int findkthElement ( int arr [ ] , int n , int K ) { int l = 0 ; int h = n - 1 , r ; while ( l + 1 < h ) { int mid = ( l + h ) / 2 ; if ( arr [ l ] >= arr [ mid ] ) l = mid ; else h = mid ; } if ( arr [ l ] < arr [ h ] ) r = l ; else r = h ; if ( K <= r + 1 ) return arr [ r + 1 - K ] ; else return arr [ n - ( K - ( r + 1 ) ) ] ; } public static void main ( String args [ ] ) { int [ ] arr = { 10 , 8 , 6 , 5 , 2 , 1 , 13 , 12 } ; int n = arr . length ; int K = 3 ; System . out . println ( findkthElement ( arr , n , K ) ) ; } }


"Kth Smallest Element of a Matrix of given dimensions filled with product of indices | Java program to implement the above approach ; Function that returns true if the count of elements is less than mid ; To store count of elements less than mid ; Loop through each row ; Count elements less than mid in the ith row ; Function that returns the Kth smallest element in the NxM Matrix after sorting in an array ; Initialize low and high ; Perform binary search ; Find the mid ; Check if the count of elements is less than mid ; Return Kth smallest element of the matrix ; Driver code"
How can the above be solved in Java?

class GFG { public static boolean countLessThanMid ( int mid , int N , int M , int K ) { int count = 0 ; for ( int i = 1 ; i <= Math . min ( N , mid ) ; ++ i ) { count = count + Math . min ( mid / i , M ) ; } if ( count >= K ) return false ; else return true ; } public static int findKthElement ( int N , int M , int K ) { int low = 1 , high = N * M ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( countLessThanMid ( mid , N , M , K ) ) low = mid + 1 ; else high = mid - 1 ; } return high + 1 ; } public static void main ( String [ ] args ) { int N = 2 , M = 3 ; int K = 5 ; System . out . println ( findKthElement ( N , M , K ) ) ; } }


"Kth Smallest element in a Perfect Binary Search Tree | Java program to find K - th smallest element in a perfect BST ; A BST node ; A utility function to create a new BST node ; A utility function to insert a new node with given key in BST ; If the tree is empty ; Recur down the left subtree for smaller values ; Recur down the right subtree for smaller values ; Return the ( unchanged ) node pointer ; FUnction to find Kth Smallest element in a perfect BST ; Find the median ( division operation is floored ) ; If the element is at the median ; calculate the number of nodes in the right and left sub - trees ( division operation is floored ) ; If median is located higher ; If median is located lower ; Driver Code ; Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 / \ / \ / \ / \ 14 25 35 45 55 65 75 85 ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static class Node { int key ; Node left , right ; } ; static int kth_smallest ; public static Node newNode ( int item ) { Node temp = new Node ( ) ; temp . key = item ; temp . left = temp . right = null ; return temp ; } static Node insert ( Node node , int key ) { if ( node == null ) return newNode ( key ) ; if ( key < node . key ) node . left = insert ( node . left , key ) ; else if ( key > node . key ) node . right = insert ( node . right , key ) ; return node ; } static boolean KSmallestPerfectBST ( Node root , int k , int treeSize ) { if ( root == null ) return false ; int median_loc = ( treeSize / 2 ) + 1 ; if ( k == median_loc ) { kth_smallest = root . key ; return true ; } int newTreeSize = treeSize / 2 ; if ( k < median_loc ) { return KSmallestPerfectBST ( root . left , k , newTreeSize ) ; } int newK = k - median_loc ; return KSmallestPerfectBST ( root . right , newK , newTreeSize ) ; } public static void main ( String [ ] args ) { Node root = null ; root = insert ( root , 50 ) ; insert ( root , 30 ) ; insert ( root , 20 ) ; insert ( root , 40 ) ; insert ( root , 70 ) ; insert ( root , 60 ) ; insert ( root , 80 ) ; insert ( root , 14 ) ; insert ( root , 25 ) ; insert ( root , 35 ) ; insert ( root , 45 ) ; insert ( root , 55 ) ; insert ( root , 65 ) ; insert ( root , 75 ) ; insert ( root , 85 ) ; int n = 15 , k = 5 ; if ( KSmallestPerfectBST ( root , k , n ) ) { System . out . print ( kth_smallest + " ▁ " ) ; } } }


"Kth ancestor of a node in binary tree | Set 2 | Java program to calculate Kth ancestor of given node ; A Binary Tree Node ; temporary node to keep track of Node returned from previous recursive call during backtrack ; recursive function to calculate Kth ancestor ; Base case ; print the kth ancestor ; return null to stop further backtracking ; return current node to previous call ; Utility function to create a new tree node ; Driver code ; print kth ancestor of given node ; check if parent is not null , it means there is no Kth ancestor of the node"
How can the above be solved in Java?

class Solution { static class Node { int data ; Node left , right ; } ; static Node temp = null ; static int k ; static Node kthAncestorDFS ( Node root , int node ) { if ( root == null ) return null ; if ( root . data == node || ( temp = kthAncestorDFS ( root . left , node ) ) != null || ( temp = kthAncestorDFS ( root . right , node ) ) != null ) { if ( k > 0 ) k -- ; else if ( k == 0 ) { System . out . print ( " Kth ▁ ancestor ▁ is : ▁ " + root . data ) ; return null ; } return root ; } return null ; } static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . left = temp . right = null ; return temp ; } public static void main ( String args [ ] ) { Node root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 3 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 5 ) ; k = 2 ; int node = 5 ; Node parent = kthAncestorDFS ( root , node ) ; if ( parent != null ) System . out . println ( " - 1" ) ; } }


"Kth character from the Nth string obtained by the given operations | Java program for the above approach ; String reverse ; Function to return Kth character from recursive String ; If N is 1 then return A ; Iterate a loop and generate the recursive String ; Update current String ; Change A to B and B to A ; Reverse the previous String ; Return the kth character ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static String reverse ( String input ) { char [ ] a = input . toCharArray ( ) ; int l , r = a . length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { char temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return String . valueOf ( a ) ; } static char findKthChar ( int n , int k ) { String prev = " A " ; String cur = " " ; if ( n == 1 ) { return ' A ' ; } for ( int j = 2 ; j <= n ; j ++ ) { cur = prev + " B " ; for ( int i = 0 ; i < prev . length ( ) ; i ++ ) { if ( prev . charAt ( i ) == ' A ' ) { prev . replace ( prev . charAt ( i ) , ' B ' ) ; } else { prev . replace ( prev . charAt ( i ) , ' A ' ) ; } } prev = reverse ( prev ) ; cur += prev ; prev = cur ; } return cur . charAt ( k ) ; } public static void main ( String [ ] args ) { int N = 4 ; int K = 3 ; System . out . print ( findKthChar ( N , K ) ) ; } }


"Kth diagonal from the top left of a given matrix | Java implementation of the above approach ; Function returns required diagonal ; Initialize values to print upper diagonals ; Initialize values to print lower diagonals ; Traverse the diagonal ; Print its contents ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void printDiagonal ( int K , int N , int [ ] [ ] M ) { int startrow , startcol ; if ( K - 1 < N ) { startrow = K - 1 ; startcol = 0 ; } else { startrow = N - 1 ; startcol = K - N ; } for ( ; startrow >= 0 && startcol < N ; startrow -- , startcol ++ ) { System . out . print ( M [ startrow ] [ startcol ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 3 , K = 4 ; int [ ] [ ] M = { { 4 , 7 , 8 } , { 9 , 2 , 3 } , { 0 , 4 , 1 } } ; printDiagonal ( K , N , M ) ; } }


"Kth element in permutation of first N natural numbers having all even numbers placed before odd numbers in increasing order | Java program for the above approach ; Function to find the K - th element in the required permutation ; Stores the required permutation ; Insert all the even numbers less than or equal to N ; Now , insert all odd numbers less than or equal to N ; Print the Kth element ; Driver code ; functions call"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void findKthElement ( int N , int K ) { ArrayList < Integer > v = new ArrayList < > ( ) ; for ( int i = 1 ; i <= N ; i ++ ) { if ( i % 2 == 0 ) { v . add ( i ) ; } } for ( int i = 1 ; i <= N ; i ++ ) { if ( i % 2 != 0 ) { v . add ( i ) ; } } System . out . println ( v . get ( K - 1 ) ) ; } public static void main ( String [ ] args ) { int N = 10 , K = 3 ; findKthElement ( N , K ) ; } }


"Kth element in permutation of first N natural numbers having all even numbers placed before odd numbers in increasing order | Java program for the above approach ; Function to find the Kth element in the required permutation ; Store the required result ; If K is in the first N / 2 elements , print K * 2 ; Otherwise , K is greater than N / 2 ; If N is even ; If N is odd ; Print the required result ; Driver code ; functions call"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void findKthElement ( int N , int K ) { int ans = 0 ; if ( K <= N / 2 ) { ans = K * 2 ; } else { if ( N % 2 == 0 ) { ans = ( K * 2 ) - N - 1 ; } else { ans = ( K * 2 ) - N ; } } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int N = 10 , K = 3 ; findKthElement ( N , K ) ; } }


"Kth highest XOR of diagonal elements from a Matrix | Java Program to implement the above approach ; Function to find K - th maximum XOR of any diagonal in the matrix ; Number or rows ; Number of columns ; Store XOR of diagonals ; Traverse each diagonal ; Starting column of diagonal ; Count total elements in the diagonal ; Store XOR of current diagonal ; Push XOR of current diagonal ; Sort XOR values of diagonals ; Print the K - th Maximum XOR ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findXOR ( int [ ] [ ] mat , int K ) { int N = mat . length ; int M = mat [ 0 ] . length ; ArrayList < Integer > digXOR = new ArrayList < Integer > ( ) ; for ( int l = 1 ; l <= ( N + M - 1 ) ; l ++ ) { int s_col = Math . max ( 0 , l - N ) ; int count = Math . min ( l , Math . min ( ( M - s_col ) , N ) ) ; int currXOR = 0 ; for ( int j = 0 ; j < count ; j ++ ) { currXOR = ( currXOR ^ mat [ Math . min ( N , l ) - j - 1 ] [ s_col + j ] ) ; } digXOR . add ( currXOR ) ; } Collections . sort ( digXOR ) ; System . out . print ( digXOR . get ( N + M - 1 - K ) ) ; } public static void main ( String [ ] args ) { int [ ] [ ] mat = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; int K = 3 ; findXOR ( mat , K ) ; } }


"Kth largest node among all directly connected nodes to the given node in an undirected graph | Java implementation of the approach ; pair class ; Function to print Kth node for each node ; Vector to store nodes directly connected to ith node along with their values ; Add edges to the Vector along with the values of the node ; Sort neighbors of every node and find the Kth node ; Get the kth node ; If total nodes are < k ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static class pair { int first , second ; pair ( int a , int b ) { first = a ; second = b ; } } static void findKthNode ( int u [ ] , int v [ ] , int n , int val [ ] , int V , int k ) { Vector < Vector < pair > > g = new Vector < Vector < pair > > ( ) ; for ( int i = 0 ; i < V ; i ++ ) g . add ( new Vector < pair > ( ) ) ; for ( int i = 0 ; i < n ; i ++ ) { g . get ( u [ i ] ) . add ( new pair ( val [ v [ i ] ] , v [ i ] ) ) ; g . get ( v [ i ] ) . add ( new pair ( val [ u [ i ] ] , u [ i ] ) ) ; } for ( int i = 0 ; i < V ; i ++ ) { if ( g . get ( i ) . size ( ) > 0 ) Collections . sort ( g . get ( i ) , new Comparator < pair > ( ) { public int compare ( pair p1 , pair p2 ) { return p1 . first - p2 . first ; } } ) ; if ( k <= g . get ( i ) . size ( ) ) System . out . printf ( "%d
", g.get(i).get(g.get(i).size() - k).second); else System . out . printf ( "-1
"); } return ; } public static void main ( String args [ ] ) { int V = 3 ; int val [ ] = { 2 , 4 , 3 } ; int u [ ] = { 0 , 0 , 1 } ; int v [ ] = { 2 , 1 , 2 } ; int n = u . length ; int k = 2 ; findKthNode ( u , v , n , val , V , k ) ; } }


"Kth odd number in an array | Java implementation of the approach ; Function to return the kth odd element from the array ; Traverse the array ; If current element is odd ; If kth odd element is found ; Total odd elements in the array are < k ; Driver code"
How can the above be solved in Java?

public class GFG { static int kthOdd ( int arr [ ] , int n , int k ) { for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % 2 == 1 ) k -- ; if ( k == 0 ) return arr [ i ] ; } return - 1 ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = arr . length ; int k = 2 ; System . out . print ( kthOdd ( arr , n , k ) ) ; } }


"Kth smallest element from an array of intervals | Java program to implement the above approach ; Function to get the Kth smallest element from an array of intervals ; Store all the intervals so that it returns the minimum element in O ( 1 ) ; Insert all Intervals into the MinHeap ; Stores the count of popped elements ; Iterate over MinHeap ; Stores minimum element from all remaining intervals ; Check if the minimum of the current interval is less than the maximum of the current interval ; Insert new interval ; Driver Code ; Intervals given ; Size of the arr"
How can the above be solved in Java?

import java . util . * ; import java . io . * ; class GFG { public static int KthSmallestNum ( int arr [ ] [ ] , int n , int k ) { PriorityQueue < int [ ] > pq = new PriorityQueue < > ( ( a , b ) -> a [ 0 ] - b [ 0 ] ) ; for ( int i = 0 ; i < n ; i ++ ) { pq . add ( new int [ ] { arr [ i ] [ 0 ] , arr [ i ] [ 1 ] } ) ; } int cnt = 1 ; while ( cnt < k ) { int [ ] interval = pq . poll ( ) ; if ( interval [ 0 ] < interval [ 1 ] ) { pq . add ( new int [ ] { interval [ 0 ] + 1 , interval [ 1 ] } ) ; } cnt ++ ; } return pq . peek ( ) [ 0 ] ; } public static void main ( String args [ ] ) { int arr [ ] [ ] = { { 5 , 11 } , { 10 , 15 } , { 12 , 20 } } ; int n = arr . length ; int k = 12 ; System . out . println ( KthSmallestNum ( arr , n , k ) ) ; } }


"Kth smallest element in a row | Java program for kth largest element in a 2d array sorted row - wise and column - wise ; A structure to store entry of heap . The entry contains value from 2D array , row and column numbers of the value ; Value to be stored ; Row number of value in 2D array ; Column number of value in 2D array ; A utility function to swap two HeapNode items . ; A utility function to minheapify the node harr [ i ] of a heap stored in harr [ ] ; This function returns kth smallest element in a 2D array mat [ ] [ ] ; k must be greater than 0 and smaller than n * n ; Create a min heap of elements from first row of 2D array ; Get current heap root ; Get next value from column of root 's  value. If the value stored at root was  last value in its column, then assign  INFINITE as next value ; Update heap root with next value ; Heapify root ; Return the value at last extracted root ; Driver code"
How can the above be solved in Java?

class GFG { static class HeapNode { int val ; int r ; int c ; HeapNode ( int val , int r , int c ) { this . val = val ; this . c = c ; this . r = r ; } } static void swap ( int i , int min , HeapNode [ ] arr ) { HeapNode temp = arr [ i ] ; arr [ i ] = arr [ min ] ; arr [ min ] = temp ; } static void minHeapify ( HeapNode harr [ ] , int i , int heap_size ) { int l = 2 * i + 1 ; int r = 2 * i + 2 ; int min = i ; if ( l < heap_size && harr [ l ] . val < harr [ min ] . val ) { min = l ; } if ( r < heap_size && harr [ r ] . val = 0 ) { minHeapify ( harr , i , n ) ; i -- ; } } public static int kthSmallest ( int [ ] [ ] mat , int n , int k ) { if ( k > 0 && k < n * n ) { return Integer . MAX_VALUE ; } HeapNode harr [ ] = new HeapNode [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { harr [ i ] = new HeapNode ( mat [ 0 ] [ i ] , 0 , i ) ; } HeapNode hr = new HeapNode ( 0 , 0 , 0 ) ; for ( int i = 1 ; i <= k ; i ++ ) { hr = harr [ 0 ] ; int nextVal = hr . r < n - 1 ? mat [ hr . r + 1 ] [ hr . c ] : Integer . MAX_VALUE ; harr [ 0 ] = new HeapNode ( nextVal , hr . r + 1 , hr . c ) ; minHeapify ( harr , 0 , n ) ; } return hr . val ; } public static void main ( String args [ ] ) { int mat [ ] [ ] = { { 10 , 20 , 30 , 40 } , { 15 , 25 , 35 , 45 } , { 25 , 29 , 37 , 48 } , { 32 , 33 , 39 , 50 } } ; int res = kthSmallest ( mat , 4 , 7 ) ; System . out . print ( "7th ▁ smallest ▁ element ▁ is ▁ " + res ) ; } }


"Kth smallest element in the array using constant space when array can 't be modified | Java implementation of the approach ; Function to return the kth smallest element from the array ; Minimum and maximum element from the array ; Modified binary search ; To store the count of elements from the array which are less than mid and the elements which are equal to mid ; If mid is the kth smallest ; If the required element is less than mid ; If the required element is greater than mid ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int kthSmallest ( int [ ] arr , int k , int n ) { int low = Arrays . stream ( arr ) . min ( ) . getAsInt ( ) ; int high = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; int countless = 0 , countequal = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( arr [ i ] < mid ) ++ countless ; else if ( arr [ i ] == mid ) ++ countequal ; } if ( countless < k && ( countless + countequal ) >= k ) { return mid ; } else if ( countless >= k ) { high = mid - 1 ; } else if ( countless < k && countless + countequal < k ) { low = mid + 1 ; } } return Integer . MIN_VALUE ; } public static void main ( String [ ] args ) { int arr [ ] = { 7 , 10 , 4 , 3 , 20 , 15 } ; int n = arr . length ; int k = 3 ; System . out . println ( kthSmallest ( arr , k , n ) ) ; } }


"Kth smallest positive integer Y such that its sum with X is same as its bitwise OR with X | package whatever do not write package name here ; Function to calculate K - th smallest solution ( Y ) of equation X + Y = X | Y ; Initialize the variable to store the answer ; The i - th bit of X is off ; The i - bit of K is on ; Divide K by 2 ; If K becomes 0 then break ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static long KthSolution ( long X , long K ) { long ans = 0 ; for ( int i = 0 ; i < 64 ; i ++ ) { if ( ( X & ( 1 << i ) ) == 0 ) { if ( ( K & 1 ) > 0 ) { ans |= ( 1 << i ) ; } K >>= 1 ; if ( K == 0 ) { break ; } } } return ans ; } public static void main ( String [ ] args ) { long X = 10 ; long K = 5 ; System . out . println ( KthSolution ( X , K ) ) ; } }


"Kth space | Java program for the above approach ; Function to print kth integer in a given string ; Size of the string ; Pointer for iteration ; If space char found decrement K ; If K becomes 1 , the next string is the required one ; Print the required number ; Driver Code ; Given string ; Given K ; Function call"
How can the above be solved in Java?

import java . io . * ; class GFG { static void print_kth_string ( String s , int K ) { int N = s . length ( ) ; int i ; for ( i = 0 ; i < N ; i ++ ) { if ( s . charAt ( i ) == ' ▁ ' ) K -- ; if ( K == 1 ) break ; } while ( i ++ < N - 1 && s . charAt ( i ) != ' ▁ ' ) System . out . print ( s . charAt ( i ) ) ; } public static void main ( String [ ] args ) { String s = "10 ▁ 20 ▁ 30 ▁ 40" ; int K = 4 ; print_kth_string ( s , K ) ; } }


"Kth space | Java program of the above approach ; Function to extract integer at key position in the given String ; StringTokenizer ( ) : Extracts the number at key c_str ( ) : Type cast String to char * ; Driver Code ; Given String ; Given K ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void print_kth_String ( String str , int K ) { StringTokenizer st = new StringTokenizer ( str ) ; int count = 1 ; while ( st . hasMoreTokens ( ) && K > 0 ) { if ( count == K ) System . out . println ( st . nextToken ( ) ) ; count ++ ; st . nextToken ( ) ; } } public static void main ( String [ ] args ) { String s = ( "10 ▁ 20 ▁ 30 ▁ 40" ) ; int K = 2 ; print_kth_String ( s , K ) ; } }