codeparrot/xlcost-text-to-code huggingface dataset:
Search in a sorted 2D matrix ( Stored in row major order ) | C # program to find whether a given element is present in the given 2 - D matrix ; Basic binary search to find an element in a 1 - D array ; if element found return true ; if middle less than K then skip the left part of the array else skip the right part ; if not found return false ; Function to search an element in a matrix based on Divide and conquer approach ; if the element lies in the range of this row then call 1 - D binary search on this row ; if the element is less then the starting element of that row then search in upper rows else search in the lower rows ; if not found ; Driver code
using System ; class GFG { static int M = 3 ; static int N = 4 ; static bool binarySearch1D ( int [ ] arr , int K ) { int low = 0 ; int high = N - 1 ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( arr [ mid ] == K ) { return true ; } if ( arr [ mid ] < K ) { low = mid + 1 ; } else { high = mid - 1 ; } } return false ; } static bool searchMatrix ( int [ , ] matrix , int K ) { int low = 0 ; int high = M - 1 ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( K >= matrix [ mid , 0 ] && K <= matrix [ mid , N - 1 ] ) { return binarySearch1D ( GetRow ( matrix , mid ) , K ) ; } if ( K < matrix [ mid , 0 ] ) { high = mid - 1 ; } else { low = mid + 1 ; } } return false ; } public static int [ ] GetRow ( int [ , ] matrix , int row ) { var rowLength = matrix . GetLength ( 1 ) ; var rowVector = new int [ rowLength ] ; for ( var i = 0 ; i < rowLength ; i ++ ) rowVector [ i ] = matrix [ row , i ] ; return rowVector ; } public static void Main ( String [ ] args ) { int [ , ] matrix = { { 1 , 3 , 5 , 7 } , { 10 , 11 , 16 , 20 } , { 23 , 30 , 34 , 50 } } ; int K = 3 ; if ( searchMatrix ( matrix , K ) ) { Console . WriteLine ( " Found " ) ; } else { Console . WriteLine ( " Not ▁ found " ) ; } } }
Program to find Nth term divisible by a or b | C # program to find nth term divisible by a or b ; Function to return gcd of a and b ; Function to calculate how many numbers from 1 to num are divisible by a or b ; calculate number of terms divisible by a and by b then , remove the terms which is are divisible by both a and b ; Binary search to find the nth term divisible by a or b ; set low to 1 and high to max ( a , b ) * n , here we have taken high as 10 ^ 18 ; if the current term is less than n then we need to increase low to mid + 1 ; if current term is greater than equal to n then high = mid ; Driver code
using System ; class GFG { static int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } static int divTermCount ( int a , int b , int lcm , int num ) { return num / a + num / b - num / lcm ; } static int findNthTerm ( int a , int b , int n ) { int low = 1 , high = int . MaxValue , mid ; int lcm = ( a * b ) / gcd ( a , b ) ; while ( low < high ) { mid = low + ( high - low ) / 2 ; if ( divTermCount ( a , b , lcm , mid ) < n ) low = mid + 1 ; else high = mid ; } return low ; } static public void Main ( ) { int a = 2 , b = 5 , n = 10 ; Console . WriteLine ( findNthTerm ( a , b , n ) ) ; } }
Replace all occurrences of pi with 3.14 in a given string | C # program to replace all pi in a given string with 3.14 ; Function to replace all occurrences of pi in a given with 3.14 ; Iterate through second last element of the string ; If current and current + 1 alphabets form the word ' pi ' append 3.14 to output ; Append the current letter ; Return the output string ; Driver Code
using System ; class gfg { public string replacePi ( string input ) { string output = " " ; int size = input . Length ; for ( int i = 0 ; i < size ; ++ i ) { if ( i + 1 < size && input [ i ] == ' p ' && input [ i + 1 ] == ' i ' ) { output += "3.14" ; i ++ ; } else { output += input [ i ] ; } } return output ; } } class geek { public static int Main ( ) { gfg g = new gfg ( ) ; string input = "2 ▁ * ▁ pi ▁ + ▁ 3 ▁ * ▁ pi ▁ = ▁ 5 ▁ * ▁ pi " ; Console . WriteLine ( g . replacePi ( input ) ) ; return 0 ; } }
Number of elements that can be seen from right side | C # program to find number of elements that can be seen from right side . ; Driver code
using System ; class GFG { public static int numberOfElements ( int [ ] height , int n ) { int max_so_far = 0 ; int coun = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( height [ i ] > max_so_far ) { max_so_far = height [ i ] ; coun ++ ; } } return coun ; } public static void Main ( ) { int n = 6 ; int [ ] height = { 4 , 8 , 2 , 0 , 0 , 5 } ; Console . WriteLine ( numberOfElements ( height , n ) ) ; } }
Check if a pair with given product exists in Linked list | C # code to find the pair with given product ; Link list node ; Given a reference ( pointer to pointer ) to the head of a list and an int , push a new node on the front of the list . ; Function to check if pair with given product exists in the list Takes head pointer of the linked list and product ; Check if pair exits ; Driver code ; Start with the empty list ; Use push ( ) to construct linked list ; function to print the result
using System ; using System . Collections . Generic ; class GFG { static readonly int MAX = 100000 ; public class Node { public int data ; public Node next ; } static Node push ( Node head_ref , int new_data ) { Node new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = ( head_ref ) ; ( head_ref ) = new_node ; return head_ref ; } static bool check_pair_product ( Node head , int prod ) { List < int > s = new List < int > ( ) ; Node p = head ; while ( p != null ) { int curr = p . data ; if ( ( prod % curr == 0 ) && ( s . Contains ( prod / curr ) ) ) { Console . Write ( curr + " ▁ " + ( prod / curr ) ) ; return true ; } s . Add ( p . data ) ; p = p . next ; } return false ; } public static void Main ( String [ ] args ) { Node head = null ; head = push ( head , 1 ) ; head = push ( head , 2 ) ; head = push ( head , 1 ) ; head = push ( head , 12 ) ; head = push ( head , 1 ) ; head = push ( head , 18 ) ; head = push ( head , 47 ) ; head = push ( head , 16 ) ; head = push ( head , 12 ) ; head = push ( head , 14 ) ; bool res = check_pair_product ( head , 24 ) ; if ( res == false ) Console . Write ( " NO ▁ PAIR ▁ EXIST " ) ; } }
Largest element in the array that is repeated exactly k times | C # implementation of the above approach ; Function that finds the largest element which is repeated ' k ' times ; sort the array ; if the value of ' k ' is 1 and the largest appears only once in the array ; counter to count the repeated elements ; check if the element at index ' i ' is equal to the element at index ' i + 1' then increase the count ; else set the count to 1 to start counting the frequency of the new number ; if the count is equal to k and the previous element is not equal to this element ; if there is no such element ; Driver code ; find the largest element that is repeated K times
using System ; class GFG { static void solve ( int [ ] arr , int n , int k ) { Array . Sort ( arr ) ; if ( k == 1 && arr [ n - 2 ] != arr [ n - 1 ] ) { Console . WriteLine ( arr [ n - 1 ] ) ; return ; } int count = 1 ; for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] == arr [ i + 1 ] ) count ++ ; else count = 1 ; if ( count == k && ( i == 0 || ( arr [ i - 1 ] != arr [ i ] ) ) ) { Console . WriteLine ( arr [ i ] ) ; return ; } } Console . WriteLine ( " No ▁ such ▁ element " ) ; } static public void Main ( ) { int [ ] arr = { 1 , 1 , 2 , 3 , 3 , 4 , 5 , 5 , 6 , 6 , 6 } ; int k = 2 ; int n = arr . Length ; solve ( arr , n , k ) ; } }
Largest element in the array that is repeated exactly k times | C # Implementation of the above approach ; Function that finds the largest element that occurs exactly ' k ' times ; store the frequency of each element ; to store the maximum element ; If current element has frequency ' k ' and current maximum hasn 't been set ; set the current maximum ; if current element has frequency ' k ' and it is greater than the current maximum ; change the current maximum ; if there is no element with frequency ' k ' ; print the largest element with frequency ' k ' ; Driver code ; find the largest element that is repeated K times
using System ; using System . Collections . Generic ; class GfG { static void solve ( int [ ] arr , int n , int k ) { Dictionary < int , int > m = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( m . ContainsKey ( arr [ i ] ) ) { var val = m [ arr [ i ] ] ; m . Remove ( arr [ i ] ) ; m . Add ( arr [ i ] , val + 1 ) ; } else { m . Add ( arr [ i ] , 1 ) ; } } int max = int . MinValue ; for ( int i = 0 ; i < n ; i ++ ) { if ( m [ arr [ i ] ] == k && max == int . MinValue ) { max = arr [ i ] ; } else if ( m [ arr [ i ] ] == k && max < arr [ i ] ) { max = arr [ i ] ; } } if ( max == int . MinValue ) Console . WriteLine ( " No ▁ such ▁ element " ) ; else Console . WriteLine ( max ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 1 , 2 , 3 , 3 , 4 , 5 , 5 , 6 , 6 , 6 } ; int k = 4 ; int n = arr . Length ; solve ( arr , n , k ) ; } }
Sum and Product of minimum and maximum element of an Array | C # program to find the sum and product of minimum and maximum element in an array ; Function to find minimum element ; Function to find maximum element ; Function to get Sum ; Function to get product ; Driver Code ; Sum of min and max element ; Product of min and max element
using System ; class GFG { static int getMin ( int [ ] arr , int n ) { int res = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) res = Math . Min ( res , arr [ i ] ) ; return res ; } static int getMax ( int [ ] arr , int n ) { int res = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) res = Math . Max ( res , arr [ i ] ) ; return res ; } static int findSum ( int [ ] arr , int n ) { int min = getMin ( arr , n ) ; int max = getMax ( arr , n ) ; return min + max ; } static int findProduct ( int [ ] arr , int n ) { int min = getMin ( arr , n ) ; int max = getMax ( arr , n ) ; return min * max ; } public static void Main ( ) { int [ ] arr = { 12 , 1234 , 45 , 67 , 1 } ; int n = arr . Length ; Console . WriteLine ( " Sum ▁ = ▁ " + findSum ( arr , n ) ) ; Console . WriteLine ( " Product ▁ = ▁ " + findProduct ( arr , n ) ) ; } }
Count the number of pop operations on stack to get each element of the array | C # implementation of the above approach : ; Function to find the count ; Hashmap to store all the elements which are popped once . ; Check if the number is present in the hashmap Or in other words been popped out from the stack before . ; Keep popping the elements while top is not equal to num ; Pop the top ie . equal to num ; Print the number of elements popped . ; Driver code
using System ; using System . Collections . Generic ; class GFG { public static void countEle ( Stack < int > s , int [ ] a , int N ) { Dictionary < int , bool > mp = new Dictionary < int , bool > ( ) ; for ( int i = 0 ; i < N ; ++ i ) { int num = a [ i ] ; if ( mp . ContainsKey ( num ) ) Console . Write ( "0 ▁ " ) ; else { int cnt = 0 ; while ( s . Peek ( ) != num ) { mp . Add ( s . Peek ( ) , true ) ; s . Pop ( ) ; cnt ++ ; } s . Pop ( ) ; cnt ++ ; Console . Write ( cnt + " ▁ " ) ; } } } public static void Main ( String [ ] args ) { int N = 5 ; Stack < int > s = new Stack < int > ( ) ; s . Push ( 1 ) ; s . Push ( 2 ) ; s . Push ( 3 ) ; s . Push ( 4 ) ; s . Push ( 6 ) ; int [ ] a = { 6 , 3 , 4 , 1 , 2 } ; countEle ( s , a , N ) ; } }
Queries to check whether a given digit is present in the given Range | C # program to answer Queries to check whether a given digit is present in the given range ; Segment Tree with set at each node ; Funtiom to build the segment tree ; Left child node ; Right child node ; Merging child nodes to get parent node . Since set is used , it will remove redundant digits . ; Function to query a range ; Complete Overlapp condition return true if digit is present . else false . ; No Overlapp condition Return false ; If digit is found in any child return true , else False ; Driver Code ; Build the tree ; Query 1 ; Query 2
using System ; using System . Collections . Generic ; class GFG { static int N = 6 ; static SortedSet < int > [ ] Tree = new SortedSet < int > [ 6 * N ] ; static void buildTree ( int [ ] arr , int idx , int s , int e ) { if ( s == e ) { Tree [ idx ] . Add ( arr [ s ] ) ; return ; } int mid = ( s + e ) / 2 ; buildTree ( arr , 2 * idx , s , mid ) ; buildTree ( arr , 2 * idx + 1 , mid + 1 , e ) ; foreach ( int it in Tree [ 2 * idx ] ) Tree [ idx ] . Add ( it ) ; foreach ( int it in Tree [ 2 * idx + 1 ] ) Tree [ idx ] . Add ( it ) ; } static bool query ( int idx , int s , int e , int qs , int qe , int x ) { if ( qs <= s && e <= qe ) { if ( Tree [ idx ] . Contains ( x ) ) return true ; else return false ; } if ( qe < s < qs ) return false ; int mid = ( s + e ) / 2 ; bool LeftAns = query ( 2 * idx , s , mid , qs , qe , x ) ; bool RightAns = query ( 2 * idx + 1 , mid + 1 , e , qs , qe , x ) ; return ( LeftAns RightAns ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 3 , 3 , 9 , 8 , 7 } ; int n = arr . Length ; for ( int i = 0 ; i < 6 * N ; i ++ ) Tree [ i ] = new SortedSet < int > ( ) ; buildTree ( arr , 1 , 0 , n - 1 ) ; int l , r , x ; l = 0 ; r = 3 ; x = 2 ; if ( query ( 1 , 0 , n - 1 , l , r , x ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; l = 2 ; r = 5 ; x = 3 ; if ( query ( 1 , 0 , n - 1 , l , r , x ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
Count characters with same neighbors | C # implementation of above approach ; Function to count the characters with same adjacent characters ; if length is less than 3 then return length as there will be only two characters ; Traverse the string ; Increment the count if the previous and next character is same ; Return count ; Driver code
using System ; class GFG { static int countChar ( String str ) { int n = str . Length ; if ( n <= 2 ) return n ; int count = 2 ; for ( int i = 1 ; i < n - 1 ; i ++ ) if ( str [ i - 1 ] == str [ i + 1 ] ) count ++ ; return count ; } public static void Main ( ) { String str = " egeeksk " ; Console . WriteLine ( countChar ( str ) ) ; } }
Length of largest sub | C # implementation of above approach ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Function to find the length of longest subarray having count of primes more than count of non - primes ; unordered_map ' um ' implemented as hash table ; traverse the given array ; consider - 1 as non primes and 1 as primes ; when subarray starts form index '0' ; make an entry for ' sum ' if it is not present in ' um ' ; check if ' sum - 1' is present in ' um ' or not ; update maxLength ; required maximum length ; Driver code
using System ; using System . Collections . Generic ; class GfG { static bool [ ] prime = new bool [ 1000000 + 5 ] ; static void findPrime ( ) { Array . Fill ( prime , true ) ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= 1000000 ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= 1000000 ; i += p ) prime [ i ] = false ; } } } static int lenOfLongSubarr ( int [ ] arr , int n ) { Dictionary < int , int > um = new Dictionary < int , int > ( ) ; int sum = 0 , maxLen = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += prime [ arr [ i ] ] == false ? - 1 : 1 ; if ( sum == 1 ) maxLen = i + 1 ; else if ( ! um . ContainsKey ( sum ) ) um [ sum ] = i ; if ( um . ContainsKey ( sum - 1 ) ) { if ( maxLen < ( i - um [ sum - 1 ] ) ) maxLen = i - um [ sum - 1 ] ; } } return maxLen ; } public static void Main ( ) { findPrime ( ) ; int [ ] arr = { 1 , 9 , 3 , 4 , 5 , 6 , 7 , 8 } ; int n = arr . Length ; Console . WriteLine ( lenOfLongSubarr ( arr , n ) ) ; } }
First strictly smaller element in a sorted array in Java | C # program to find first element that is strictly smaller than given target . ; Minimum size of the array should be 1 ; If target lies beyond the max element , than the index of strictly smaller value than target should be ( end - 1 ) ; Move to the left side if the target is smaller ; Move right side ; Driver code
using System ; class GfG { private static int next ( int [ ] arr , int target ) { int start = 0 , end = arr . Length - 1 ; if ( end == 0 ) return - 1 ; if ( target > arr [ end ] ) return end ; int ans = - 1 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; if ( arr [ mid ] >= target ) { end = mid - 1 ; } else { ans = mid ; start = mid + 1 ; } } return ans ; } public static void Main ( ) { int [ ] arr = { 1 , 2 , 3 , 5 , 8 , 12 } ; Console . WriteLine ( next ( arr , 5 ) ) ; } }
First strictly greater element in a sorted array in Java | C # program to find first element that is strictly greater than given target . ; Move to right side if target is greater . ; Move left side . ; Driver code
using System ; class GfG { private static int next ( int [ ] arr , int target ) { int start = 0 , end = arr . Length - 1 ; int ans = - 1 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; if ( arr [ mid ] <= target ) { start = mid + 1 ; } else { ans = mid ; end = mid - 1 ; } } return ans ; } public static void Main ( ) { int [ ] arr = { 1 , 2 , 3 , 5 , 8 , 12 } ; Console . WriteLine ( next ( arr , 8 ) ) ; } }
Reallocation of elements based on Locality of Reference | C # program to implement search for an item that is searched again and again . ; A function to perform sequential search . ; Linearly search the element ; If not found ; Shift elements before one position ; Driver Code
using System ; class GFG { static bool search ( int [ ] arr , int n , int x ) { int res = - 1 ; for ( int i = 0 ; i < n ; i ++ ) if ( x == arr [ i ] ) res = i ; if ( res == - 1 ) return false ; int temp = arr [ res ] ; for ( int i = res ; i > 0 ; i -- ) arr [ i ] = arr [ i - 1 ] ; arr [ 0 ] = temp ; return true ; } public static void Main ( ) { int [ ] arr = { 12 , 25 , 36 , 85 , 98 , 75 , 89 , 15 , 63 , 66 , 64 , 74 , 27 , 83 , 97 } ; int [ ] q = { 63 , 63 , 86 , 63 , 78 } ; int n = arr . Length ; int m = q . Length ; for ( int i = 0 ; i < m ; i ++ ) { if ( search ( arr , n , q [ i ] ) == true ) Console . Write ( " Yes ▁ " ) ; else Console . Write ( " No ▁ " ) ; } } }
Probability of a key K present in array | C # code to find the probability of search key K present in array ; Function to find the probability ; find probability ; Driver Code
using System ; class GFG { static float kPresentProbability ( int [ ] a , int n , int k ) { float count = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( a [ i ] == k ) count ++ ; return count / n ; } public static void Main ( ) { int [ ] A = { 4 , 7 , 2 , 0 , 8 , 7 , 5 } ; int K = 2 ; int N = A . Length ; double n = kPresentProbability ( A , N , K ) ; double p = ( double ) Math . Round ( n * 100 ) / 100 ; Console . Write ( p ) ; } }
Find the slope of the given number | C # implementation to find slope of a number ; function to find slope of a number ; to store slope of the given number ' num ' ; loop from the 2 nd digit up to the 2 nd last digit of the given number ' num ' ; if the digit is a maxima ; if the digit is a minima ; required slope ; Driver code
class GFG { static int slopeOfNum ( string num , int n ) { int slope = 0 ; for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( num [ i ] > num [ i - 1 ] && num [ i ] > num [ i + 1 ] ) slope ++ ; else if ( num [ i ] < num [ i - 1 ] && num [ i ] < num [ i + 1 ] ) slope ++ ; } return slope ; } public static void Main ( ) { string num = "1213321" ; int n = num . Length ; System . Console . WriteLine ( " Slope ▁ = ▁ " + slopeOfNum ( num , n ) ) ; } }
Sudo Placement | Beautiful Pairs | C # code for finding required pairs ; The function to check if beautiful pair exists ; Set for hashing ; Traversing the first array ; Traversing the second array to check for every j corresponding to single i ; x + y = z = > x = y - z ; if such x exists then we return true ; hash to make use of it next time ; no pair exists ; Driver Code ; If pair exists then 1 else 0 2 nd argument as size of first array fourth argument as sizeof 2 nd array
using System ; using System . Collections . Generic ; class GFG { static bool pairExists ( int [ ] arr1 , int m , int [ ] arr2 , int n ) { HashSet < int > s = new HashSet < int > ( ) ; for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( s . Contains ( arr2 [ j ] - arr1 [ i ] ) ) return true ; } s . Add ( arr1 [ i ] ) ; } return false ; } public static void Main ( ) { int [ ] arr1 = { 1 , 5 , 10 , 8 } ; int [ ] arr2 = { 2 , 20 , 13 } ; if ( pairExists ( arr1 , 4 , arr2 , 3 ) ) Console . WriteLine ( 1 ) ; else Console . WriteLine ( 0 ) ; } }
Sudo Placement | Placement Tour | C # Program to find the optimal number of elements such that the cumulative value should be less than given number ; This function returns true if the value cumulative according to received integer K is less than budget B , otherwise returns false ; Initialize a temporary array which stores the cumulative value of the original array ; Sort the array to find the smallest K values ; Check if the value is less than budget ; This function prints the optimal number of elements and respective cumulative value which is less than the given number ; Initialize answer as zero as optimal value may not exists ; If the current Mid Value is an optimal value , then try to maximize it ; Call Again to set the corresponding cumulative value for the optimal ans ; Driver Code ; Budget
using System ; class GFG { static int value ; static bool canBeOptimalValue ( int K , int [ ] arr , int N , int B ) { int [ ] tmp = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) tmp [ i ] = ( arr [ i ] + K * ( i + 1 ) ) ; Array . Sort ( tmp ) ; value = 0 ; for ( int i = 0 ; i < K ; i ++ ) value += tmp [ i ] ; return value <= B ; } static void findNoOfElementsandValue ( int [ ] arr , int N , int B ) { int ans = 0 ; value = 0 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; if ( canBeOptimalValue ( mid , arr , N , B ) ) { ans = mid ; start = mid + 1 ; } else end = mid - 1 ; } canBeOptimalValue ( ans , arr , N , B ) ; Console . Write ( ans + " ▁ " + value + " STRNEWLINE " ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 5 , 6 , 3 } ; int N = arr . Length ; int B = 90 ; findNoOfElementsandValue ( arr , N , B ) ; } }
Previous greater element | C # program previous greater element A naive solution to print previous greater element for every element in an array . ; Previous greater for first element never exists , so we print - 1. ; Let us process remaining elements . ; Find first element on left side that is greater than arr [ i ] . ; If all elements on left are smaller . ; Driver Code
using System ; class GFG { static void prevGreater ( int [ ] arr , int n ) { Console . Write ( " - 1 , ▁ " ) ; for ( int i = 1 ; i < n ; i ++ ) { int j ; for ( j = i - 1 ; j >= 0 ; j -- ) { if ( arr [ i ] < arr [ j ] ) { Console . Write ( arr [ j ] + " , ▁ " ) ; break ; } } if ( j == - 1 ) Console . Write ( " - 1 , ▁ " ) ; } } public static void Main ( ) { int [ ] arr = { 10 , 4 , 2 , 20 , 40 , 12 , 30 } ; int n = arr . Length ; prevGreater ( arr , n ) ; } }
Previous greater element | C # program previous greater element An efficient solution to print previous greater element for every element in an array . ; Create a stack and push index of first element to it ; Previous greater for first element is always - 1. ; Traverse remaining elements ; Pop elements from stack while stack is not empty and top of stack is smaller than arr [ i ] . We always have elements in decreasing order in a stack . ; If stack becomes empty , then no element is greater on left side . Else top of stack is previous greater . ; Driver Code
using System ; using System . Collections . Generic ; class GFG { static void prevGreater ( int [ ] arr , int n ) { Stack < int > s = new Stack < int > ( ) ; s . Push ( arr [ 0 ] ) ; Console . Write ( " - 1 , ▁ " ) ; for ( int i = 1 ; i < n ; i ++ ) { while ( s . Count != 0 && s . Peek ( ) < arr [ i ] ) s . Pop ( ) ; if ( s . Count == 0 ) Console . Write ( " - 1 , ▁ " ) ; else Console . Write ( s . Peek ( ) + " , ▁ " ) ; s . Push ( arr [ i ] ) ; } } public static void Main ( String [ ] args ) { int [ ] arr = { 10 , 4 , 2 , 20 , 40 , 12 , 30 } ; int n = arr . Length ; prevGreater ( arr , n ) ; } }