codeparrot/xlcost-text-to-code huggingface dataset:
Minimum characters required to be removed to make frequency of each character unique | Java program to implement the above approach ; Function to find the minimum count of characters required to be deleted to make frequencies of all characters unique ; Stores frequency of each distinct character of str ; Store frequency of each distinct character such that the largest frequency is present at the top ; Stores minimum count of characters required to be deleted to make frequency of each character unique ; Traverse the String ; Update frequency of str [ i ] ; Traverse the map ; Insert current frequency into pq ; Traverse the priority_queue ; Stores topmost element of pq ; Pop the topmost element ; If pq is empty ; Return cntChar ; If frequent and topmost element of pq are equal ; If frequency of the topmost element is greater than 1 ; Insert the decremented value of frequent ; Update cntChar ; Driver Code ; Stores length of str
import java . util . * ; class GFG { static int minCntCharDeletionsfrequency ( char [ ] str , int N ) { HashMap < Character , Integer > mp = new HashMap < > ( ) ; PriorityQueue < Integer > pq = new PriorityQueue < > ( ( x , y ) -> Integer . compare ( y , x ) ) ; int cntChar = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( mp . containsKey ( str [ i ] ) ) { mp . put ( str [ i ] , mp . get ( str [ i ] ) + 1 ) ; } else { mp . put ( str [ i ] , 1 ) ; } } for ( Map . Entry < Character , Integer > it : mp . entrySet ( ) ) { pq . add ( it . getValue ( ) ) ; } while ( ! pq . isEmpty ( ) ) { int frequent = pq . peek ( ) ; pq . remove ( ) ; if ( pq . isEmpty ( ) ) { return cntChar ; } if ( frequent == pq . peek ( ) ) { if ( frequent > 1 ) { pq . add ( frequent - 1 ) ; } cntChar ++ ; } } return cntChar ; } public static void main ( String [ ] args ) { String str = " abbbcccd " ; int N = str . length ( ) ; System . out . print ( minCntCharDeletionsfrequency ( str . toCharArray ( ) , N ) ) ; } }
Replace specified matrix elements such that no two adjacent elements are equal | Java program for the above approach ; Function to check if current position is safe or not ; Directions for adjacent cells ; Check if any adjacent cell is same ; Current index is valid ; Recursive function for backtracking ; Free cell ; All positions covered ; If position is valid for 1 ; If position is valid for 2 ; Recursive call for next unoccupied position ; If above conditions fails ; Function to print valid matrix ; Driver Code ; Give dimensions ; Function call
import java . io . * ; class GFG { public static boolean issafe ( char v [ ] [ ] , int i , int j , int n , int m , char ch ) { int rowN [ ] = { 1 , - 1 , 0 , 0 } ; int colN [ ] = { 0 , 0 , 1 , - 1 } ; for ( int k = 0 ; k < 4 ; k ++ ) { if ( i + rowN [ k ] >= 0 && i + rowN [ k ] < n && j + colN [ k ] >= 0 && j + colN [ k ] < m && v [ i + rowN [ k ] ] [ j + colN [ k ] ] == ch ) { return false ; } } return true ; } public static boolean place ( char v [ ] [ ] , int n , int m ) { int i = 0 , j = 0 ; for ( i = 0 ; i < n ; i ++ ) { for ( j = 0 ; j < m ; j ++ ) { if ( v [ i ] [ j ] == ' F ' ) { break ; } } if ( j != m ) { break ; } } if ( i == n && j == m ) { return true ; } if ( issafe ( v , i , j , n , m , '1' ) ) { v [ i ] [ j ] = '1' ; if ( place ( v , n , m ) ) { return true ; } v [ i ] [ j ] = ' F ' ; } if ( issafe ( v , i , j , n , m , '2' ) ) { v [ i ] [ j ] = '2' ; if ( place ( v , n , m ) ) { return true ; } v [ i ] [ j ] = ' F ' ; } return false ; } public static void printMatrix ( char arr [ ] [ ] , int n , int m ) { place ( arr , n , m ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { System . out . print ( arr [ i ] [ j ] ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { char arr [ ] [ ] = { { ' F ' , ' F ' , ' F ' , ' F ' } , { ' F ' , ' O ' , ' F ' , ' F ' } , { ' F ' , ' F ' , ' O ' , ' F ' } , { ' F ' , ' F ' , ' F ' , ' F ' } , } ; int n = 4 , m = 4 ; printMatrix ( arr , n , m ) ; } }
Program for Mean and median of an unsorted array | Java program to find mean and median of an array ; Function for calculating mean ; Function for calculating median ; First we sort the array ; check for even case ; Driver code ; Function call
import java . util . * ; class GFG { public static double findMean ( int a [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += a [ i ] ; return ( double ) sum / ( double ) n ; } public static double findMedian ( int a [ ] , int n ) { Arrays . sort ( a ) ; if ( n % 2 != 0 ) return ( double ) a [ n / 2 ] ; return ( double ) ( a [ ( n - 1 ) / 2 ] + a [ n / 2 ] ) / 2.0 ; } public static void main ( String args [ ] ) { int a [ ] = { 1 , 3 , 4 , 2 , 7 , 5 , 8 , 6 } ; int n = a . length ; System . out . println ( " Mean ▁ = ▁ " + findMean ( a , n ) ) ; System . out . println ( " Median ▁ = ▁ " + findMedian ( a , n ) ) ; } }
Find sum of all left leaves in a given Binary Tree | Java program to find sum of all left leaves ; A binary tree node ; A constructor to create a new Node ; Return the sum of left leaf nodes ; Using a stack_ for Depth - First Traversal of the tree ; sum holds the sum of all the left leaves ; Check if currentNode 's left  child is a leaf node ; if currentNode is a leaf , add its data to the sum ; Driver Code
import java . util . * ; class GFG { static class Node { int key ; Node left , right ; Node ( int key_ ) { this . key = key_ ; this . left = null ; this . right = null ; } } ; static int sumOfLeftLeaves ( Node root ) { if ( root == null ) return 0 ; Stack < Node > stack_ = new Stack < > ( ) ; stack_ . push ( root ) ; int sum = 0 ; while ( stack_ . size ( ) > 0 ) { Node currentNode = stack_ . peek ( ) ; stack_ . pop ( ) ; if ( currentNode . left != null ) { stack_ . add ( currentNode . left ) ; if ( currentNode . left . left == null && currentNode . left . right == null ) { sum = sum + currentNode . left . key ; } } if ( currentNode . right != null ) stack_ . add ( currentNode . right ) ; } return sum ; } public static void main ( String [ ] args ) { Node root = new Node ( 20 ) ; root . left = new Node ( 9 ) ; root . right = new Node ( 49 ) ; root . right . left = new Node ( 23 ) ; root . right . right = new Node ( 52 ) ; root . right . right . left = new Node ( 50 ) ; root . left . left = new Node ( 5 ) ; root . left . right = new Node ( 12 ) ; root . left . right . right = new Node ( 12 ) ; System . out . print ( " Sum ▁ of ▁ left ▁ leaves ▁ is ▁ " + sumOfLeftLeaves ( root ) + "NEW_LINE"); } }
Find a pair with sum N having minimum absolute difference | Java program to implement the above approach ; Function to find the value of X and Y having minimum value of Math . abs ( X - Y ) ; If N is an odd number ; If N is an even number ; Driver Code
import java . util . * ; class GFG { static void findXandYwithminABSX_Y ( int N ) { if ( N % 2 == 1 ) { System . out . print ( ( N / 2 ) + " ▁ " + ( N / 2 + 1 ) ) ; } else { System . out . print ( ( N / 2 - 1 ) + " ▁ " + ( N / 2 + 1 ) ) ; } } public static void main ( String [ ] args ) { int N = 12 ; findXandYwithminABSX_Y ( N ) ; } }
Maximum sum possible by assigning alternate positive and negative sign to elements in a subsequence | Java program for the above approach ; Function to find the maximum sum subsequence ; Base Case ; If current state is already calculated then use it ; If current element is positive ; Update ans and recursively call with update value of flag ; Else current element is negative ; Update ans and recursively call with update value of flag ; Return maximum sum subsequence ; Function that finds the maximum sum of element of the subsequence with alternate + ve and - ve signs ; Create auxiliary array dp [ ] [ ] ; Initialize dp [ ] [ ] ; Function Call ; Driver Code ; Given array arr [ ] ; Function call
import java . io . * ; import java . util . Arrays ; class GFG { static int findMax ( int [ ] a , int dp [ ] [ ] , int i , int flag ) { if ( i == ( int ) a . length ) { return 0 ; } if ( dp [ i ] [ flag ] != - 1 ) { return dp [ i ] [ flag ] ; } int ans ; if ( flag == 0 ) { ans = Math . max ( findMax ( a , dp , i + 1 , 0 ) , a [ i ] + findMax ( a , dp , i + 1 , 1 ) ) ; } else { ans = Math . max ( findMax ( a , dp , i + 1 , 1 ) , - 1 * a [ i ] + findMax ( a , dp , i + 1 , 0 ) ) ; } return dp [ i ] [ flag ] = ans ; } static void findMaxSumUtil ( int [ ] arr , int N ) { int dp [ ] [ ] = new int [ N ] [ 2 ] ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < 2 ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } System . out . println ( findMax ( arr , dp , 0 , 0 ) ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 , 1 , 2 } ; int N = arr . length ; findMaxSumUtil ( arr , N ) ; } }
Find the player to last modify a string such that even number of consonants and no vowels are left in the string | Java program for the above approach ; Function to find a winner of the game if both the player plays optimally ; Stores the count of vowels and consonants ; Traverse the String ; Check if character is vowel ; Increment vowels count ; Otherwise increment the consonants count ; Check if Player B wins ; Check if Player A wins ; Check if Player A wins ; If game ends in a Draw ; Driver Code ; Given String s ; Function Call
class GFG { static void findWinner ( char [ ] s ) { int vowels_count = 0 , consonants_count = 0 ; for ( int i = 0 ; i < s . length ; i ++ ) { if ( s [ i ] == ' a ' s [ i ] == ' e ' s [ i ] == ' i ' s [ i ] == ' o ' s [ i ] == ' u ' ) { vowels_count ++ ; } else { consonants_count ++ ; } } if ( vowels_count == 0 ) { if ( consonants_count % 2 == 0 ) { System . out . print ( " Player ▁ B " ) ; } else { System . out . print ( " Player ▁ A " ) ; } } else if ( vowels_count == 1 && consonants_count % 2 != 0 ) { System . out . print ( " Player ▁ A " ) ; } else { System . out . print ( " D " ) ; } } public static void main ( String [ ] args ) { String s = " abcd " ; findWinner ( s . toCharArray ( ) ) ; } }
Lexicographically smallest permutation of size A having B integers exceeding all preceding integers | Java program for the above approach ; Function to find lexicographically smallest permutation of [ 1 , A ] having B integers greater than all the previous elements ; Initial array ; Resultant array ; Append the first ( B - 1 ) elements to the resultant array ; Append the maximum from the initial array ; Copy the remaining elements ; Print the answer ; Driver Code
import java . util . * ; class GFG { @ SuppressWarnings ( " unchecked " ) static void getSmallestArray ( int A , int B ) { Vector arr = new Vector ( ) ; for ( int i = 0 ; i < A ; i ++ ) arr . add ( i + 1 ) ; Vector ans = new Vector ( ) ; for ( int i = 0 ; i < B - 1 ; i ++ ) ans . add ( arr . get ( i ) ) ; ans . add ( arr . get ( A - 1 ) ) ; for ( int i = B ; i < A ; i ++ ) ans . add ( arr . get ( i - 1 ) ) ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) System . out . print ( ans . get ( i ) + " ▁ " ) ; } public static void main ( String args [ ] ) { int A = 3 ; int B = 2 ; getSmallestArray ( A , B ) ; } }
k smallest elements in same order using O ( 1 ) extra space | Java for printing smallest k numbers in order ; Function to print smallest k numbers in arr [ 0. . n - 1 ] ; For each arr [ i ] find whether it is a part of n - smallest with insertion sort concept ; Find largest from top n - element ; If largest is greater than arr [ i ] shift all element one place left ; make arr [ k - 1 ] = arr [ i ] ; print result ; Driver function
import java . util . * ; import java . lang . * ; public class GfG { public static void printSmall ( int arr [ ] , int n , int k ) { for ( int i = k ; i < n ; ++ i ) { int max_var = arr [ k - 1 ] ; int pos = k - 1 ; for ( int j = k - 2 ; j >= 0 ; j -- ) { if ( arr [ j ] > max_var ) { max_var = arr [ j ] ; pos = j ; } } if ( max_var > arr [ i ] ) { int j = pos ; while ( j < k - 1 ) { arr [ j ] = arr [ j + 1 ] ; j ++ ; } arr [ k - 1 ] = arr [ i ] ; } } for ( int i = 0 ; i < k ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String argc [ ] ) { int [ ] arr = { 1 , 5 , 8 , 9 , 6 , 7 , 3 , 4 , 2 , 0 } ; int n = 10 ; int k = 5 ; printSmall ( arr , n , k ) ; } }
Find k pairs with smallest sums in two arrays | Java code to print first k pairs with least sum from two arrays . ; Function to find k pairs with least sum such that one elemennt of a pair is from arr1 [ ] and other element is from arr2 [ ] ; Stores current index in arr2 [ ] for every element of arr1 [ ] . Initially all values are considered 0. Here current index is the index before which all elements are considered as part of output . ; Initialize current pair sum as infinite ; To pick next pair , traverse for all elements of arr1 [ ] , for every element , find corresponding current element in arr2 [ ] and pick minimum of all formed pairs . ; Check if current element of arr1 [ ] plus element of array2 to be used gives minimum sum ; Update index that gives minimum ; update minimum sum ; Driver code
import java . io . * ; class KSmallestPair { static void kSmallestPair ( int arr1 [ ] , int n1 , int arr2 [ ] , int n2 , int k ) { if ( k > n1 * n2 ) { System . out . print ( " k ▁ pairs ▁ don ' t ▁ exist " ) ; return ; } int index2 [ ] = new int [ n1 ] ; while ( k > 0 ) { int min_sum = Integer . MAX_VALUE ; int min_index = 0 ; for ( int i1 = 0 ; i1 < n1 ; i1 ++ ) { if ( index2 [ i1 ] < n2 && arr1 [ i1 ] + arr2 [ index2 [ i1 ] ] < min_sum ) { min_index = i1 ; min_sum = arr1 [ i1 ] + arr2 [ index2 [ i1 ] ] ; } } System . out . print ( " ( " + arr1 [ min_index ] + " , ▁ " + arr2 [ index2 [ min_index ] ] + " ) ▁ " ) ; index2 [ min_index ] ++ ; k -- ; } } public static void main ( String [ ] args ) { int arr1 [ ] = { 1 , 3 , 11 } ; int n1 = arr1 . length ; int arr2 [ ] = { 2 , 4 , 8 } ; int n2 = arr2 . length ; int k = 4 ; kSmallestPair ( arr1 , n1 , arr2 , n2 , k ) ; } }
Maximize count of strings of length 3 that can be formed from N 1 s and M 0 s | Java program for the above approach ; Function that counts the number of Strings of length 3 that can be made with given m 0 s and n 1 s ; Print the count of Strings ; Driver Code ; Given count of 1 s and 0 s ; Function Call
class GFG { static void number_of_Strings ( int N , int M ) { System . out . print ( Math . min ( N , Math . min ( M , ( N + M ) / 3 ) ) ) ; } public static void main ( String [ ] args ) { int N = 4 , M = 19 ; number_of_Strings ( N , M ) ; } }
Maximize count of subsets having product of smallest element and size of the subset at least X | Java program to implement the above approach ; Function to return the maximum count of subsets possible which satisfy the above condition ; Sort the array in descending order ; Stores the count of subsets ; Stores the size of the current subset ; Check for the necessary conditions ; Driver Code
import java . util . * ; class GFG { static int maxSubset ( Integer arr [ ] , int N , int X ) { Arrays . sort ( arr , Collections . reverseOrder ( ) ) ; int counter = 0 ; int sz = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sz ++ ; if ( arr [ i ] * sz >= X ) { counter ++ ; sz = 0 ; } } return counter ; } public static void main ( String [ ] args ) { Integer arr [ ] = { 7 , 11 , 2 , 9 , 5 } ; int N = arr . length ; int X = 10 ; System . out . print ( maxSubset ( arr , N , X ) ) ; } }
Maximize modulus by replacing adjacent pairs with their modulus for any permutation of given Array | Java Program to implement the above approach ; Function to find the maximum value possible of the given expression from all permutations of the array ; Stores the minimum value from the array ; Return the answer ; Driver Code
import java . io . * ; class GFG { static int maximumModuloValue ( int A [ ] , int n ) { int mn = Integer . MAX_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { mn = Math . min ( A [ i ] , mn ) ; } return mn ; } public static void main ( String [ ] args ) { int A [ ] = { 7 , 10 , 12 } ; int n = A . length ; System . out . println ( maximumModuloValue ( A , n ) ) ; } }
Final Matrix after incrementing submatrices by K in range given by Q queries | Java program for the above approach ; Query data type ; Function to update the given query ; Update top cell ; Update bottom left cell ; Update bottom right cell ; Update top right cell ; Function that updates the matrix mat [ ] [ ] by adding elements of aux [ ] [ ] ; Compute the prefix sum of all columns ; Compute the prefix sum of all rows ; Get the final matrix by adding mat and aux matrix at each cell ; Function that prints matrix mat [ ] ; Traverse each row ; Traverse each columns ; Function that performs each query in the given matrix and print the updated matrix after each operation performed ; Initialize all elements to 0 ; Update auxiliary matrix by traversing each query ; Update Query ; Compute the final answer ; Print the updated matrix ; Driver Code ; Given Matrix ; Given Queries ; Function Call
class GFG { static final int N = 3 ; static final int M = 4 ; static class query { int x1 , x2 , y1 , y2 , K ; public query ( int x1 , int x2 , int y1 , int y2 , int k ) { this . x1 = x1 ; this . x2 = x2 ; this . y1 = y1 ; this . y2 = y2 ; K = k ; } } ; static void updateQuery ( int from_x , int from_y , int to_x , int to_y , int k , int aux [ ] [ ] ) { aux [ from_x ] [ from_y ] += k ; if ( to_x + 1 < N ) aux [ to_x + 1 ] [ from_y ] -= k ; if ( to_x + 1 < N && to_y + 1 < M ) aux [ to_x + 1 ] [ to_y + 1 ] += k ; if ( to_y + 1 < M ) aux [ from_x ] [ to_y + 1 ] -= k ; } static void updateMatrix ( int mat [ ] [ ] , int aux [ ] [ ] ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 1 ; j < M ; j ++ ) { aux [ i ] [ j ] += aux [ i ] [ j - 1 ] ; } } for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 1 ; j < N ; j ++ ) { aux [ j ] [ i ] += aux [ j - 1 ] [ i ] ; } } for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { mat [ i ] [ j ] += aux [ i ] [ j ] ; } } } static void printMatrix ( int mat [ ] [ ] ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { System . out . print ( mat [ i ] [ j ] + " ▁ " ) ; } System . out . print ( "NEW_LINE"); } } static void matrixQuery ( int mat [ ] [ ] , int Q , query q [ ] ) { int [ ] [ ] aux = new int [ N ] [ M ] ; for ( int i = 0 ; i < Q ; i ++ ) { updateQuery ( q [ i ] . x1 , q [ i ] . x2 , q [ i ] . y1 , q [ i ] . y2 , q [ i ] . K , aux ) ; } updateMatrix ( mat , aux ) ; printMatrix ( mat ) ; } public static void main ( String [ ] args ) { int mat [ ] [ ] = { { 1 , 0 , 1 , 2 } , { 0 , 2 , 4 , 1 } , { 1 , 2 , 1 , 0 } } ; int Q = 1 ; query q [ ] = { new query ( 0 , 0 , 1 , 1 , 2 ) } ; matrixQuery ( mat , Q , q ) ; } }
Find Second largest element in an array | Java program to find second largest element in an array ; Function to print the second largest elements ; There should be atleast two elements ; Sort the array ; Start from second last element as the largest element is at last ; If the element is not equal to largest element ; Driver code
import java . util . * ; class GFG { static void print2largest ( int arr [ ] , int arr_size ) { int i , first , second ; if ( arr_size < 2 ) { System . out . printf ( " ▁ Invalid ▁ Input ▁ " ) ; return ; } Arrays . sort ( arr ) ; for ( i = arr_size - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] != arr [ arr_size - 1 ] ) { System . out . printf ( " The ▁ second ▁ largest ▁ " + "element is %dNEW_LINE", arr[i]); return ; } } System . out . printf ( " There ▁ is ▁ no ▁ second ▁ " + "largest elementNEW_LINE"); } public static void main ( String [ ] args ) { int arr [ ] = { 12 , 35 , 1 , 10 , 34 , 1 } ; int n = arr . length ; print2largest ( arr , n ) ; } }
Find sum of all left leaves in a given Binary Tree | Java program to find sum of all left leaves ; A binary tree node ; constructor to create a new Node ; Return the sum of left leaf nodes ; A queue of pairs to do bfs traversal and keep track if the node is a left or right child if boolean value is true then it is a left child . ; do bfs traversal ; if temp is a leaf node and left child of its parent ; if it is not leaf then push its children nodes into queue ; boolean value is true here because it is left child of its parent ; boolean value is false here because it is right child of its parent ; Driver Code
import java . util . * ; class GFG { static class Node { int key ; Node left , right ; Node ( int key_ ) { key = key_ ; left = null ; right = null ; } } ; static class pair { Node first ; boolean second ; public pair ( Node first , boolean second ) { this . first = first ; this . second = second ; } } static int sumOfLeftLeaves ( Node root ) { if ( root == null ) return 0 ; Queue < pair > q = new LinkedList < > ( ) ; q . add ( new pair ( root , false ) ) ; int sum = 0 ; while ( ! q . isEmpty ( ) ) { Node temp = q . peek ( ) . first ; boolean is_left_child = q . peek ( ) . second ; q . remove ( ) ; if ( is_left_child ) sum = sum + temp . key ; if ( temp . left != null && temp . right != null && is_left_child ) sum = sum - temp . key ; if ( temp . left != null ) { q . add ( new pair ( temp . left , true ) ) ; } if ( temp . right != null ) { q . add ( new pair ( temp . right , false ) ) ; } } return sum ; } public static void main ( String [ ] args ) { Node root = new Node ( 20 ) ; root . left = new Node ( 9 ) ; root . right = new Node ( 49 ) ; root . right . left = new Node ( 23 ) ; root . right . right = new Node ( 52 ) ; root . right . right . left = new Node ( 50 ) ; root . left . left = new Node ( 5 ) ; root . left . right = new Node ( 12 ) ; root . left . right . right = new Node ( 12 ) ; System . out . print ( " Sum ▁ of ▁ left ▁ leaves ▁ is ▁ " + sumOfLeftLeaves ( root ) + "NEW_LINE"); } }
Count of nested polygons that can be drawn by joining vertices internally | Java program for the above approach ; Function that counts the nested polygons inside another polygons ; Stores the count ; Child polygons can only existss if parent polygon has sides > 5 ; Get next nested polygon ; Return the count ; Driver Code ; Given side of polygon ; Function Call
class GFG { static int countNestedPolygons ( int sides ) { int count = 0 ; while ( sides > 5 ) { sides /= 2 ; count += 1 ; } return count ; } public static void main ( String [ ] args ) { int N = 12 ; System . out . print ( countNestedPolygons ( N ) ) ; } }
Find Second largest element in an array | Java program to find second largest element in an array ; Function to print the second largest elements ; There should be atleast two elements ; Find the largest element ; Find the second largest element ; Driver code
class GFG { static void print2largest ( int arr [ ] , int arr_size ) { int i , first , second ; if ( arr_size < 2 ) { System . out . printf ( " ▁ Invalid ▁ Input ▁ " ) ; return ; } int largest = second = Integer . MIN_VALUE ; for ( i = 0 ; i < arr_size ; i ++ ) { largest = Math . max ( largest , arr [ i ] ) ; } for ( i = 0 ; i < arr_size ; i ++ ) { if ( arr [ i ] != largest ) second = Math . max ( second , arr [ i ] ) ; } if ( second == Integer . MIN_VALUE ) System . out . printf ( " There ▁ is ▁ no ▁ second ▁ " + "largest elementNEW_LINE"); else System . out . printf ( " The ▁ second ▁ largest ▁ " + "element is %dNEW_LINE", second); } public static void main ( String [ ] args ) { int arr [ ] = { 12 , 35 , 1 , 10 , 34 , 1 } ; int n = arr . length ; print2largest ( arr , n ) ; } }
Find Second largest element in an array | JAVA Code for Find Second largest element in an array ; Function to print the second largest elements ; There should be atleast two elements ; If current element is smaller than first then update both first and second ; If arr [ i ] is in between first and second then update second ; Driver program to test above function
class GFG { public static void print2largest ( int arr [ ] , int arr_size ) { int i , first , second ; if ( arr_size < 2 ) { System . out . print ( " ▁ Invalid ▁ Input ▁ " ) ; return ; } first = second = Integer . MIN_VALUE ; for ( i = 0 ; i < arr_size ; i ++ ) { if ( arr [ i ] > first ) { second = first ; first = arr [ i ] ; } else if ( arr [ i ] > second && arr [ i ] != first ) second = arr [ i ] ; } if ( second == Integer . MIN_VALUE ) System . out . print ( " There ▁ is ▁ no ▁ second ▁ largest " + " elementNEW_LINE"); else System . out . print ( " The ▁ second ▁ largest ▁ element " + " ▁ is ▁ " + second ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 12 , 35 , 1 , 10 , 34 , 1 } ; int n = arr . length ; print2largest ( arr , n ) ; } }