text
stringlengths
17
3.65k
code
stringlengths
60
5.26k
Count of numbers between range having only non | C # implementation of the approach ; states - position , sum , rem , tight sum can have values upto 162 , if we are dealing with numbers upto 10 ^ 18 when all 18 digits are 9 , then sum is 18 * 9 = 162 ; n is the sum of digits and number should be divisible by m ; Function to return the count of required numbers from 0 to num ; Last position ; If this result is already computed simply return it ; Maximum limit upto which we can place digit . If tight is 1 , means number has already become smaller so we can place any digit , otherwise num [ pos ] ; If the current digit is zero and nonz is 1 , we can 't place it ; Function to convert x into its digit vector and uses count ( ) function to return the required count ; Initialize dp ; Driver code
using System ; using System . Collections . Generic ; class GFG { static int M = 20 ; static int [ , , , ] dp = new int [ M , 165 , M , 2 ] ; static int n , m ; static int count ( int pos , int sum , int rem , int tight , int nonz , List < int > num ) { if ( pos == num . Count ) { if ( rem == 0 && sum == n ) return 1 ; return 0 ; } if ( dp [ pos , sum , rem , tight ] != - 1 ) return dp [ pos , sum , rem , tight ] ; int ans = 0 ; int limit = ( tight != 0 ? 9 : num [ pos ] ) ; for ( int d = 0 ; d <= limit ; d ++ ) { if ( d == 0 && nonz != 0 ) continue ; int currSum = sum + d ; int currRem = ( rem * 10 + d ) % m ; int currF = ( tight != 0 || ( d < num [ pos ] ) ) ? 1 : 0 ; ans += count ( pos + 1 , currSum , currRem , currF , ( nonz != 0 d != 0 ) ? 1 : 0 , num ) ; } return dp [ pos , sum , rem , tight ] = ans ; } static int solve ( int x ) { List < int > num = new List < int > ( ) ; while ( x != 0 ) { num . Add ( x % 10 ) ; x /= 10 ; } num . Reverse ( ) ; for ( int i = 0 ; i < M ; i ++ ) for ( int j = 0 ; j < 165 ; j ++ ) for ( int k = 0 ; k < M ; k ++ ) for ( int l = 0 ; l < 2 ; l ++ ) dp [ i , j , k , l ] = - 1 ; return count ( 0 , 0 , 0 , 0 , 0 , num ) ; } public static void Main ( String [ ] args ) { int L = 1 , R = 100 ; n = 8 ; m = 2 ; Console . Write ( solve ( R ) - solve ( L ) ) ; } }
Count of Numbers in Range where the number does not contain more than K non zero digits | C # Program to find the count of numbers in a range where the number does not contain more than K non zero digits ; states - position , count , tight ; K is the number of non zero digits ; This function returns the count of required numbers from 0 to num ; Last position ; If count of non zero digits is less than or equal to K ; If this result is already computed simply return it ; Maximum limit upto which we can place digit . If tight is 1 , means number has already become smaller so we can place any digit , otherwise num [ pos ] ; If the current digit is nonzero increment currCnt ; At this position , number becomes smaller ; Next recursive call ; This function converts a number into its digit vector and uses above function to compute the answer ; Initialize dp ; Driver Code
using System ; using System . Collections . Generic ; class GFG { static int M = 20 ; static int [ , , ] dp = new int [ M , M , 2 ] ; static int K ; static List < int > num ; static int countInRangeUtil ( int pos , int cnt , int tight ) { if ( pos == num . Count ) { if ( cnt <= K ) return 1 ; return 0 ; } if ( dp [ pos , cnt , tight ] != - 1 ) return dp [ pos , cnt , tight ] ; int ans = 0 ; int limit = ( tight != 0 ? 9 : num [ pos ] ) ; for ( int dig = 0 ; dig <= limit ; dig ++ ) { int currCnt = cnt ; if ( dig != 0 ) currCnt ++ ; int currTight = tight ; if ( dig < num [ pos ] ) currTight = 1 ; ans += countInRangeUtil ( pos + 1 , currCnt , currTight ) ; } return dp [ pos , cnt , tight ] = ans ; } static int countInRange ( int x ) { num = new List < int > ( ) ; while ( x != 0 ) { num . Add ( x % 10 ) ; x /= 10 ; } num . Reverse ( ) ; for ( int i = 0 ; i < M ; i ++ ) for ( int j = 0 ; j < M ; j ++ ) for ( int k = 0 ; k < 2 ; k ++ ) dp [ i , j , k ] = - 1 ; return countInRangeUtil ( 0 , 0 , 0 ) ; } public static void Main ( ) { int L = 1 , R = 1000 ; K = 3 ; Console . WriteLine ( countInRange ( R ) - countInRange ( L - 1 ) ) ; L = 9995 ; R = 10005 ; K = 2 ; Console . WriteLine ( countInRange ( R ) - countInRange ( L - 1 ) ) ; } }
Balanced expressions such that given positions have opening brackets | Set 2 | C # implementation of above approach using memoization ; Function to find Number of proper bracket expressions ; If open - closed brackets < 0 ; If index reaches the end of expression ; If brackets are balanced ; If already stored in dp ; If the current index has assigned open bracket ; Move forward increasing the length of open brackets ; Move forward by inserting open as well as closed brackets on that index ; return the answer ; Driver code ; DP array to precompute the answer ; Open brackets at position 1 ; Calling the find function to calculate the answer
using System ; class GFG { static readonly int N = 1000 ; static int find ( int index , int openbrk , int n , int [ , ] dp , int [ ] adj ) { if ( openbrk < 0 ) { return 0 ; } if ( index == n ) { if ( openbrk == 0 ) { return 1 ; } else { return 0 ; } } if ( dp [ index , openbrk ] != - 1 ) { return dp [ index , openbrk ] ; } if ( adj [ index ] == 1 ) { dp [ index , openbrk ] = find ( index + 1 , openbrk + 1 , n , dp , adj ) ; } else { dp [ index , openbrk ] = find ( index + 1 , openbrk + 1 , n , dp , adj ) + find ( index + 1 , openbrk - 1 , n , dp , adj ) ; } return dp [ index , openbrk ] ; } public static void Main ( ) { int [ , ] dp = new int [ N , N ] ; int n = 2 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { dp [ i , j ] = - 1 ; } } int [ ] adj = { 1 , 0 , 0 , 0 } ; Console . WriteLine ( find ( 0 , 0 , 2 * n , dp , adj ) ) ; } }
Maximize array elements upto given number | C # code to find maximum value of number obtained by using array elements recursively . ; Utility function to find maximum possible value ; If entire array is traversed , then compare current value in num to overall maximum obtained so far . ; Case 1 : Subtract current element from value so far if result is greater than or equal to zero . ; Case 2 : Add current element to value so far if result is less than or equal to maxLimit . ; Function to find maximum possible value that can be obtained using array elements and given number . ; variable to store maximum value that can be obtained . ; variable to store current index position . ; call to utility function to find maximum possible value that can be obtained . ; Driver code
using System ; using System . Collections . Generic ; class GFG { static void findMaxValUtil ( int [ ] arr , int n , int num , int maxLimit , int ind , ref int ans ) { if ( ind == n ) { ans = Math . Max ( ans , num ) ; return ; } if ( num - arr [ ind ] >= 0 ) { findMaxValUtil ( arr , n , num - arr [ ind ] , maxLimit , ind + 1 , ref ans ) ; } if ( num + arr [ ind ] <= maxLimit ) { findMaxValUtil ( arr , n , num + arr [ ind ] , maxLimit , ind + 1 , ref ans ) ; } } static int findMaxVal ( int [ ] arr , int n , int num , int maxLimit ) { int ans = 0 ; int ind = 0 ; findMaxValUtil ( arr , n , num , maxLimit , ind , ref ans ) ; return ans ; } public static void Main ( ) { int num = 1 ; int [ ] arr = { 3 , 10 , 6 , 4 , 5 } ; int n = arr . Length ; int maxLimit = 15 ; Console . Write ( findMaxVal ( arr , n , num , maxLimit ) ) ; } }
Print equal sum sets of array ( Partition problem ) | Set 1 | C # program to print equal sum two subsets of an array if it can be partitioned into subsets . ; / Function to print the equal sum sets of the array . ; / Print set 1. ; / Print set 2. ; Utility function to find the sets of the array which have equal sum . ; If entire array is traversed , compare both the sums . ; If sums are equal print both sets and return true to show sets are found . ; If sums are not equal then return sets are not found . ; Add current element to set 1. ; Recursive call after adding current element to set 1. ; If this inclusion results in equal sum sets partition then return true to show desired sets are found . ; If not then backtrack by removing current element from set1 and include it in set 2. ; Recursive call after including current element to set 2. ; Return true if array arr can be partitioned into two equal sum sets or not . ; Calculate sum of elements in array . ; If sum is odd then array cannot be partitioned . ; Declare Lists to store both the sets . ; / Find both the sets . ; Driver code
using System ; using System . Collections . Generic ; using System . Linq ; using System . Collections ; class GFG { static void printSets ( List < int > set1 , List < int > set2 ) { int i ; for ( i = 0 ; i < set1 . Count ; i ++ ) { Console . Write ( set1 [ i ] + " ▁ " ) ; } Console . WriteLine ( ) ; for ( i = 0 ; i < set2 . Count ; i ++ ) { Console . Write ( set2 [ i ] + " ▁ " ) ; } } static bool findSets ( int [ ] arr , int n , ref List < int > set1 , ref List < int > set2 , int sum1 , int sum2 , int pos ) { if ( pos == n ) { if ( sum1 == sum2 ) { printSets ( set1 , set2 ) ; return true ; } else return false ; } set1 . Add ( arr [ pos ] ) ; bool res = findSets ( arr , n , ref set1 , ref set2 , sum1 + arr [ pos ] , sum2 , pos + 1 ) ; if ( res == true ) return res ; set1 . RemoveAt ( set1 . Count - 1 ) ; set2 . Add ( arr [ pos ] ) ; res = findSets ( arr , n , ref set1 , ref set2 , sum1 , sum2 + arr [ pos ] , pos + 1 ) ; if ( res == false ) if ( set2 . Count > 0 ) set2 . RemoveAt ( set2 . Count - 1 ) ; return res ; } static bool isPartitionPoss ( int [ ] arr , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; if ( sum % 2 != 0 ) return false ; List < int > set1 = new List < int > ( ) ; List < int > set2 = new List < int > ( ) ; return findSets ( arr , n , ref set1 , ref set2 , 0 , 0 , 0 ) ; } public static void Main ( ) { int [ ] arr = { 5 , 5 , 1 , 11 } ; int n = arr . Length ; if ( isPartitionPoss ( arr , n ) == false ) { Console . Write ( " - 1" ) ; } } }
Maximum subarray sum in O ( n ) using prefix sum | C # program to find out maximum subarray sum in linear time using prefix sum . ; Function to compute maximum subarray sum in linear time . ; Initialize minimum prefix sum to 0. ; Initialize maximum subarray sum so far to - infinity . ; Initialize and compute the prefix sum array . ; loop through the array , keep track of minimum prefix sum so far and maximum subarray sum . ; Driver Program ; Test case 1 ; Test case 2
using System ; class GFG { static int maximumSumSubarray ( int [ ] arr , int n ) { int min_prefix_sum = 0 ; int res = int . MinValue ; int [ ] prefix_sum = new int [ n ] ; prefix_sum [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) prefix_sum [ i ] = prefix_sum [ i - 1 ] + arr [ i ] ; for ( int i = 0 ; i < n ; i ++ ) { res = Math . Max ( res , prefix_sum [ i ] - min_prefix_sum ) ; min_prefix_sum = Math . Min ( min_prefix_sum , prefix_sum [ i ] ) ; } return res ; } public static void Main ( ) { int [ ] arr1 = { - 2 , - 3 , 4 , - 1 , - 2 , 1 , 5 , - 3 } ; int n1 = arr1 . Length ; Console . WriteLine ( maximumSumSubarray ( arr1 , n1 ) ) ; int [ ] arr2 = { 4 , - 8 , 9 , - 4 , 1 , - 8 , - 1 , 6 } ; int n2 = arr2 . Length ; Console . WriteLine ( maximumSumSubarray ( arr2 , n2 ) ) ; } }
Counting numbers of n digits that are monotone | C # program to count numbers of n digits that are monotone . ; Considering all possible digits as { 1 , 2 , 3 , . .9 } ; DP [ i ] [ j ] is going to store monotone numbers of length i + 1 considering j + 1 digits . ; Unit length numbers ; Single digit numbers ; Filling rest of the entries in bottom up manner . ; Driver code .
using System ; class GFG { static int DP_s = 9 ; static int getNumMonotone ( int len ) { int [ , ] DP = new int [ len , DP_s ] ; for ( int i = 0 ; i < DP_s ; ++ i ) DP [ 0 , i ] = i + 1 ; for ( int i = 0 ; i < len ; ++ i ) DP [ i , 0 ] = 1 ; for ( int i = 1 ; i < len ; ++ i ) for ( int j = 1 ; j < DP_s ; ++ j ) DP [ i , j ] = DP [ i - 1 , j ] + DP [ i , j - 1 ] ; return DP [ len - 1 , DP_s - 1 ] ; } public static void Main ( ) { Console . WriteLine ( getNumMonotone ( 10 ) ) ; } }
Newman | C # Code for Newman - Conway Sequence ; Function to find the n - th element ; Declare array to store sequence ; Driver Code
using System ; class GFG { static int sequence ( int n ) { int [ ] f = new int [ n + 1 ] ; f [ 0 ] = 0 ; f [ 1 ] = 1 ; f [ 2 ] = 1 ; int i ; for ( i = 3 ; i <= n ; i ++ ) f [ i ] = f [ f [ i - 1 ] ] + f [ i - f [ i - 1 ] ] ; return f [ n ] ; } public static void Main ( ) { int n = 10 ; Console . Write ( sequence ( n ) ) ; } }
Maximum product of an increasing subsequence | Dynamic programming C # implementation of maximum product of an increasing subsequence ; Returns product of maximum product increasing subsequence . ; Initialize MPIS values ; Compute optimized MPIS values considering every element as ending element of sequence ; Pick maximum of all product values ; Driver program to test above function
using System ; using System . Linq ; public class GFG { static long lis ( long [ ] arr , long n ) { long [ ] mpis = new long [ n ] ; for ( int i = 0 ; i < n ; i ++ ) mpis [ i ] = arr [ i ] ; for ( int i = 1 ; i < n ; i ++ ) for ( int j = 0 ; j < i ; j ++ ) if ( arr [ i ] > arr [ j ] && mpis [ i ] < ( mpis [ j ] * arr [ i ] ) ) mpis [ i ] = mpis [ j ] * arr [ i ] ; return mpis . Max ( ) ; } static public void Main ( ) { long [ ] arr = { 3 , 100 , 4 , 5 , 150 , 6 } ; long n = arr . Length ; Console . WriteLine ( lis ( arr , n ) ) ; } }
Hosoya 's Triangle | C # Program to print Hosoya 's triangle of height n. ; Base case ; Recursive step ; Print the Hosoya triangle of height n . ; Driver program to test above function
using System ; class GFG { static int Hosoya ( int n , int m ) { if ( ( n == 0 && m == 0 ) || ( n == 1 && m == 0 ) || ( n == 1 && m == 1 ) || ( n == 2 && m == 1 ) ) return 1 ; if ( n > m ) return Hosoya ( n - 1 , m ) + Hosoya ( n - 2 , m ) ; else if ( m == n ) return Hosoya ( n - 1 , m - 1 ) + Hosoya ( n - 2 , m - 2 ) ; else return 0 ; } static void printHosoya ( int n ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j <= i ; j ++ ) Console . Write ( Hosoya ( i , j ) + " ▁ " ) ; Console . WriteLine ( " " ) ; } } public static void Main ( ) { int n = 5 ; printHosoya ( n ) ; } }
Eulerian Number | C # program to find Eulerian number A ( n , m ) ; Return eulerian number A ( n , m ) ; driver code
using System ; class Eulerian { public static int eulerian ( int n , int m ) { if ( m >= n n == 0 ) return 0 ; if ( m == 0 ) return 1 ; return ( n - m ) * eulerian ( n - 1 , m - 1 ) + ( m + 1 ) * eulerian ( n - 1 , m ) ; } public static void Main ( ) { int n = 3 , m = 1 ; Console . WriteLine ( eulerian ( n , m ) ) ; } }
Largest divisible pairs subset | C # program to find the largest subset which where each pair is divisible . ; function to find the longest Subsequence ; dp [ i ] is going to store size of largest divisible subset beginning with a [ i ] . ; Since last element is largest , d [ n - 1 ] is 1 ; Fill values for smaller elements . ; Find all multiples of a [ i ] and consider the multiple that has largest subset beginning with it . ; Return maximum value from dp [ ] ; driver code to check the above function
using System ; using System . Linq ; public class GFG { static int largestSubset ( int [ ] a , int n ) { int [ ] dp = new int [ n ] ; dp [ n - 1 ] = 1 ; for ( int i = n - 2 ; i >= 0 ; i -- ) { int mxm = 0 ; for ( int j = i + 1 ; j < n ; j ++ ) if ( a [ j ] % a [ i ] == 0 a [ i ] % a [ j ] == 0 ) mxm = Math . Max ( mxm , dp [ j ] ) ; dp [ i ] = 1 + mxm ; } return dp . Max ( ) ; } static public void Main ( ) { int [ ] a = { 1 , 3 , 6 , 13 , 17 , 18 } ; int n = a . Length ; Console . WriteLine ( largestSubset ( a , n ) ) ; } }
How to solve a Dynamic Programming Problem ? | initialize to - 1 ; this function returns the number of arrangements to form ' n ' ; base case ; checking if already calculated ; storing the result and returning
public static int [ ] dp = new int [ MAXN ] ; static int solve ( int n ) { if ( n < 0 ) return 0 ; if ( n == 0 ) return 1 ; if ( dp [ n ] != - 1 ) return dp [ n ] ; return dp [ n ] = solve ( n - 1 ) + solve ( n - 3 ) + solve ( n - 5 ) ; }
Friends Pairing Problem | C # program solution for friends pairing problem ; Returns count of ways n people can remain single or paired up . ; Filling dp [ ] in bottom - up manner using recursive formula explained above . ; Driver code
using System ; class GFG { static int countFriendsPairings ( int n ) { int [ ] dp = new int [ n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) { if ( i <= 2 ) dp [ i ] = i ; else dp [ i ] = dp [ i - 1 ] + ( i - 1 ) * dp [ i - 2 ] ; } return dp [ n ] ; } public static void Main ( ) { int n = 4 ; Console . Write ( countFriendsPairings ( n ) ) ; } }
Friends Pairing Problem | Returns count of ways n people can remain single or paired up . ; Driver code
using System ; class GFG { static int countFriendsPairings ( int n ) { int a = 1 , b = 2 , c = 0 ; if ( n <= 2 ) { return n ; } for ( int i = 3 ; i <= n ; i ++ ) { c = b + ( i - 1 ) * a ; a = b ; b = c ; } return c ; } public static void Main ( String [ ] args ) { int n = 4 ; Console . WriteLine ( countFriendsPairings ( n ) ) ; } }
Check whether row or column swaps produce maximum size binary sub | C # program to find maximum binary sub - matrix with row swaps and column swaps . ; Precompute the number of consecutive 1 below the ( i , j ) in j - th column and the number of consecutive 1 s on right side of ( i , j ) in i - th row . ; Travesing the 2d matrix from top - right . ; If ( i , j ) contain 0 , do nothing ; } Counting consecutive 1 on right side ; Travesing the 2d matrix from bottom - left . ; If ( i , j ) contain 0 , do nothing ; } Counting consecutive 1 down to ( i , j ) . ; Return maximum size submatrix with row swap allowed . ; Copying the column ; Sort the copied array ; Find maximum submatrix size . ; Return maximum size submatrix with column swap allowed . ; Copying the row . ; Sort the copied array ; Find maximum submatrix size . ; Solving for row swap and column swap ; Comparing both . ; Driven Program
using System ; public class GFG { static int R = 5 ; static int C = 3 ; static void precompute ( int [ , ] mat , int [ , ] ryt , int [ , ] dwn ) { for ( int j = C - 1 ; j >= 0 ; j -- ) { for ( int i = 0 ; i < R ; ++ i ) { if ( mat [ i , j ] == 0 ) { ryt [ i , j ] = 0 ; else { ryt [ i , j ] = ryt [ i , j + 1 ] + 1 ; } } } for ( int i = R - 1 ; i >= 0 ; i -- ) { for ( int j = 0 ; j < C ; ++ j ) { if ( mat [ i , j ] == 0 ) { dwn [ i , j ] = 0 ; else { dwn [ i , j ] = dwn [ i + 1 , j ] + 1 ; } } } } static int solveRowSwap ( int [ , ] ryt ) { int [ ] b = new int [ R ] ; int ans = 0 ; for ( int j = 0 ; j < C ; j ++ ) { for ( int i = 0 ; i < R ; i ++ ) { b [ i ] = ryt [ i , j ] ; } Array . Sort ( b ) ; for ( int i = 0 ; i < R ; ++ i ) { ans = Math . Max ( ans , b [ i ] * ( R - i ) ) ; } } return ans ; } static int solveColumnSwap ( int [ , ] dwn ) { int [ ] b = new int [ C ] ; int ans = 0 ; for ( int i = 0 ; i < R ; ++ i ) { for ( int j = 0 ; j < C ; ++ j ) { b [ j ] = dwn [ i , j ] ; } Array . Sort ( b ) ; for ( int k = 0 ; k < C ; ++ k ) { ans = Math . Max ( ans , b [ k ] * ( C - k ) ) ; } } return ans ; } static void findMax1s ( int [ , ] mat ) { int [ , ] ryt = new int [ R + 2 , C + 2 ] ; int [ , ] dwn = new int [ R + 2 , C + 2 ] ; precompute ( mat , ryt , dwn ) ; int rswap = solveRowSwap ( ryt ) ; int cswap = solveColumnSwap ( dwn ) ; if ( rswap > cswap ) { Console . WriteLine ( " Row ▁ Swap STRNEWLINE " + rswap ) ; } else { Console . WriteLine ( " Column ▁ Swap STRNEWLINE " + cswap ) ; } } public static void Main ( ) { int [ , ] mat = { { 0 , 0 , 0 } , { 1 , 1 , 0 } , { 1 , 1 , 0 } , { 0 , 0 , 0 } , { 1 , 1 , 0 } } ; findMax1s ( mat ) ; } }
LCS ( Longest Common Subsequence ) of three strings | C # program to find LCS of three strings ; Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] and Z [ 0. . o - 1 ] ; Following steps build L [ m + 1 ] [ n + 1 ] [ o + 1 ] in bottom up fashion . Note that L [ i ] [ j ] [ k ] contains length of LCS of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] and Z [ 0. . ... k - 1 ] ; L [ m ] [ n ] [ o ] contains length of LCS for X [ 0. . n - 1 ] and Y [ 0. . m - 1 ] and Z [ 0. . o - 1 ] ; Driver Code
using System ; class GFG { static int lcsOf3 ( String X , String Y , String Z , int m , int n , int o ) { int [ , , ] L = new int [ m + 1 , n + 1 , o + 1 ] ; for ( int i = 0 ; i <= m ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { for ( int k = 0 ; k <= o ; k ++ ) { if ( i == 0 j == 0 k == 0 ) L [ i , j , k ] = 0 ; else if ( X [ i - 1 ] == Y [ j - 1 ] && X [ i - 1 ] == Z [ k - 1 ] ) L [ i , j , k ] = L [ i - 1 , j - 1 , k - 1 ] + 1 ; else L [ i , j , k ] = Math . Max ( Math . Max ( L [ i - 1 , j , k ] , L [ i , j - 1 , k ] ) , L [ i , j , k - 1 ] ) ; } } } return L [ m , n , o ] ; } public static void Main ( ) { string X = " AGGT12" ; string Y = "12TXAYB " ; string Z = "12XBA " ; int m = X . Length ; int n = Y . Length ; int o = Z . Length ; Console . Write ( " Length ▁ of ▁ LCS ▁ is ▁ " + lcsOf3 ( X , Y , Z , m , n , o ) ) ; } }
Printing Shortest Common Supersequence | A dynamic programming based C # program print shortest supersequence of two strings ; returns shortest supersequence of X and Y ; dp [ i , j ] contains length of shortest supersequence for X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] ; Fill table in bottom up manner ; Below steps follow recurrence relation ; string to store the shortest supersequence ; Start from the bottom right corner and one by one push characters in output string ; If current character in X and Y are same , then current character is part of shortest supersequence ; Put current character in result ; reduce values of i , j and index ; If current character in X and Y are different ; Put current character of Y in result ; reduce values of j and index ; Put current character of X in result ; reduce values of i and index ; If Y reaches its end , put remaining characters of X in the result string ; If X reaches its end , put remaining characters of Y in the result string ; reverse the string and return it ; Swap values of left and right ; Driver code
using System ; class GFG { static String printShortestSuperSeq ( String X , String Y ) { int m = X . Length ; int n = Y . Length ; int [ , ] dp = new int [ m + 1 , n + 1 ] ; int i , j ; for ( i = 0 ; i <= m ; i ++ ) { for ( j = 0 ; j <= n ; j ++ ) { if ( i == 0 ) { dp [ i , j ] = j ; } else if ( j == 0 ) { dp [ i , j ] = i ; } else if ( X [ i - 1 ] == Y [ j - 1 ] ) { dp [ i , j ] = 1 + dp [ i - 1 , j - 1 ] ; } else { dp [ i , j ] = 1 + Math . Min ( dp [ i - 1 , j ] , dp [ i , j - 1 ] ) ; } } } String str = " " ; i = m ; j = n ; while ( i > 0 && j > 0 ) { if ( X [ i - 1 ] == Y [ j - 1 ] ) { str += ( X [ i - 1 ] ) ; i -- ; j -- ; } else if ( dp [ i - 1 , j ] > dp [ i , j - 1 ] ) { str += ( Y [ j - 1 ] ) ; j -- ; } else { str += ( X [ i - 1 ] ) ; i -- ; } } while ( i > 0 ) { str += ( X [ i - 1 ] ) ; i -- ; } while ( j > 0 ) { str += ( Y [ j - 1 ] ) ; j -- ; } str = reverse ( str ) ; return str ; } static String reverse ( String input ) { char [ ] temparray = input . ToCharArray ( ) ; int left , right = 0 ; right = temparray . Length - 1 ; for ( left = 0 ; left < right ; left ++ , right -- ) { char temp = temparray [ left ] ; temparray [ left ] = temparray [ right ] ; temparray [ right ] = temp ; } return String . Join ( " " , temparray ) ; } public static void Main ( String [ ] args ) { String X = " AGGTAB " ; String Y = " GXTXAYB " ; Console . WriteLine ( printShortestSuperSeq ( X , Y ) ) ; } }
Longest Repeating Subsequence | C # program to find the longest repeating subsequence ; Function to find the longest repeating subsequence ; Create and initialize DP table ; Fill dp table ( similar to LCS loops ) ; If characters match and indexes are not same ; If characters do not match ; driver program to check above function
using System ; class GFG { static int findLongestRepeatingSubSeq ( string str ) { int n = str . Length ; int [ , ] dp = new int [ n + 1 , n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( str [ i - 1 ] == str [ j - 1 ] && i != j ) dp [ i , j ] = 1 + dp [ i - 1 , j - 1 ] ; else dp [ i , j ] = Math . Max ( dp [ i , j - 1 ] , dp [ i - 1 , j ] ) ; } } return dp [ n , n ] ; } public static void Main ( ) { string str = " aabb " ; Console . Write ( " The ▁ length ▁ of ▁ the ▁ largest ▁ " + " subsequence ▁ that ▁ repeats ▁ itself ▁ is ▁ : ▁ " + findLongestRepeatingSubSeq ( str ) ) ; } }
Count total number of N digit numbers such that the difference between sum of even and odd digits is 1 | A memoization based recursive program to count numbers with difference between odd and even digit sums as 1 ; A lookup table used for memoization . ; Memoization based recursive function to count numbers with even and odd digit sum difference as 1. This function considers leading zero as a digit ; Base Case ; If current subproblem is already computed ; Initialize result ; If current digit is odd , then add it to odd sum and recur ; else Add to even sum and recur ; Store current result in lookup table and return the same ; This is mainly a wrapper over countRec . It explicitly handles leading digit and calls countRec ( ) for remaining digits . ; Initialize number digits considered so far ; Initialize all entries of lookup table ; Initialize final answer ; Initialize even and odd sums ; Explicitly handle first digit and call recursive function countRec for remaining digits . Note that the first digit is considered as even digit . ; Driver code
using System ; class GFG { static int [ , , , ] lookup = new int [ 50 , 1000 , 1000 , 2 ] ; static int countRec ( int digits , int esum , int osum , int isOdd , int n ) { if ( digits == n ) return ( esum - osum == 1 ) ? 1 : 0 ; if ( lookup [ digits , esum , osum , isOdd ] != - 1 ) return lookup [ digits , esum , osum , isOdd ] ; int ans = 0 ; if ( isOdd == 1 ) for ( int i = 0 ; i <= 9 ; i ++ ) ans += countRec ( digits + 1 , esum , osum + i , 0 , n ) ; for ( int i = 0 ; i <= 9 ; i ++ ) ans += countRec ( digits + 1 , esum + i , osum , 1 , n ) ; return lookup [ digits , esum , osum , isOdd ] = ans ; } static int finalCount ( int n ) { int digits = 0 ; for ( int i = 0 ; i < 50 ; i ++ ) for ( int j = 0 ; j < 1000 ; j ++ ) for ( int k = 0 ; k < 1000 ; k ++ ) for ( int l = 0 ; l < 2 ; l ++ ) lookup [ i , j , k , l ] = - 1 ; int ans = 0 ; int esum = 0 , osum = 0 ; for ( int i = 1 ; i <= 9 ; i ++ ) ans += countRec ( digits + 1 , esum + i , osum , 1 , n ) ; return ans ; } public static void Main ( String [ ] args ) { int n = 3 ; Console . WriteLine ( " Count ▁ of ▁ " + n + " ▁ digit ▁ numbers ▁ is ▁ " + finalCount ( n ) ) ; } }
Count all possible paths from top left to bottom right of a mXn matrix | Returns count of possible paths to reach cell at row number m and column number n from the topmost leftmost cell ( cell at 1 , 1 ) ; Create a 1D array to store results of subproblems ; Driver Code
using System ; class GFG { static int numberOfPaths ( int m , int n ) { int [ ] dp = new int [ n ] ; dp [ 0 ] = 1 ; for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 1 ; j < n ; j ++ ) { dp [ j ] += dp [ j - 1 ] ; } } return dp [ n - 1 ] ; } public static void Main ( ) { Console . Write ( numberOfPaths ( 3 , 3 ) ) ; } }
Longest Arithmetic Progression | DP | C # program to find Length of the longest AP ( llap ) in a given sorted set . ; Returns length of the longest AP subset in a given set ; Driver Code
using System ; class GFG { static int Solution ( int [ ] A ) { int ans = 2 ; int n = A . Length ; if ( n <= 2 ) return n ; int [ ] llap = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) llap [ i ] = 2 ; Array . Sort ( A ) ; for ( int j = n - 2 ; j >= 0 ; j -- ) { int i = j - 1 ; int k = j + 1 ; while ( i >= 0 && k < n ) { if ( A [ i ] + A [ k ] == 2 * A [ j ] ) { llap [ j ] = Math . Max ( llap [ k ] + 1 , llap [ j ] ) ; ans = Math . Max ( ans , llap [ j ] ) ; i -= 1 ; k += 1 ; } else if ( A [ i ] + A [ k ] < 2 * A [ j ] ) k += 1 ; else i -= 1 ; } } return ans ; } public static void Main ( String [ ] args ) { int [ ] a = { 9 , 4 , 7 , 2 , 10 } ; Console . Write ( Solution ( a ) + " STRNEWLINE " ) ; } }
Minimum numbers to be appended such that mean of Array is equal to 1 | C # program for above approach ; Function to calculate minimum Number of operations ; Storing sum of array arr [ ] ; Driver Code ; Function Call
using System ; class GFG { static void minumumOperation ( int N , int [ ] arr ) { int sum_arr = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum_arr = sum_arr + arr [ i ] ; } if ( sum_arr >= N ) Console . Write ( sum_arr - N ) ; else Console . Write ( 1 ) ; } static public void Main ( ) { int N = 4 ; int [ ] arr = { 8 , 4 , 6 , 2 } ; minumumOperation ( N , arr ) ; } }
Find Nth term of series 1 , 4 , 15 , 72 , 420. . . | C # program to find N - th term of the series : 1 , 4 , 15 , 72 , 420 ; Function to find factorial of N ; base condition ; use recursion ; calculate Nth term of series ; Driver Code
using System ; class GFG { static int factorial ( int N ) { if ( N == 0 N == 1 ) return 1 ; return N * factorial ( N - 1 ) ; } static int nthTerm ( int N ) { return ( factorial ( N ) * ( N + 2 ) / 2 ) ; } public static void Main ( ) { int N = 6 ; Console . Write ( nthTerm ( N ) ) ; } }
Modify string by increasing each character by its distance from the end of the word | C # implementation of the above approach ; Function to transform the given string ; Size of string ; Stores resultant string ; Iterate over given string ; End of word is reached ; Append the word ; For the last word ; Function to transform and return the transformed word ; Stores resulting word ; Iterate over the word ; Add the position value to the letter ; Convert it back to character ; Add it to the string ; Driver Code ; Given string ; Function Call
using System ; class GFG { public static void manipulate ( String s ) { int n = s . Length ; int i = 0 , j = 0 ; String res = " " ; while ( i < n ) { if ( s [ i ] == ' ▁ ' ) { res += util ( s . Substring ( j , i - j ) ) ; res = res + " ▁ " ; j = i + 1 ; i = j + 1 ; } else { i ++ ; } } res = res + util ( s . Substring ( j , i - j ) ) ; Console . WriteLine ( res ) ; } public static String util ( String sub ) { int n = sub . Length ; int i = 0 ; String ret = " " ; while ( i < n ) { int t = ( sub [ i ] - ' a ' ) + n - 1 - i ; char ch = ( char ) ( t % 26 + 97 ) ; ret = ret + String . Join ( " " , ch ) ; i ++ ; } return ret ; } public static void Main ( String [ ] args ) { String s = " acm ▁ fkz " ; manipulate ( s ) ; } }
Count of lexicographically smaller characters on right | Function to count the smaller characters on the right of index i ; store the length of String ; initialize each elements of arr to zero ; array to store count of smaller characters on the right side of that index ; initialize the variable to store the count of characters smaller than that at index i ; adding the count of characters smaller than index i ; print the count of characters smaller than index i stored in ans array ; Driver Code
using System ; class GFG { static void countSmaller ( String str ) { int n = str . Length ; int [ ] arr = new int [ 26 ] ; int [ ] ans = new int [ n ] ; for ( int i = n - 1 ; i >= 0 ; i -- ) { arr [ str [ i ] - ' a ' ] ++ ; int ct = 0 ; for ( int j = 0 ; j < str [ i ] - ' a ' ; j ++ ) { ct += arr [ j ] ; } ans [ i ] = ct ; } for ( int i = 0 ; i < n ; i ++ ) { Console . Write ( ans [ i ] + " ▁ " ) ; } } public static void Main ( String [ ] args ) { String str = " edcbaa " ; countSmaller ( str ) ; } }
Reverse all the word in a String represented as a Linked List | Linked List Implementation ; Function to create a linked list from the given String ; Generates characters from the given string ; Function to reverse the words Assume str = " practice ▁ makes ▁ man ▁ perfect " to understand proper understanding of the code ; Initialize wordStartPosition to header ie . node ' p ' first letter of the word ' practice ' ; Navigate the linked list until a space ( ' ▁ ' ) is found or header is null ( this is for handing if there is only one word in the given sentence ) ; Keep track the previous node . This will become the last node of the linked list ; Keep moving to the next node ; If header is null then there is only one word in the given sentance so set header to the first / wordStartPosition node and return . ; store the node which is next to space ( ' ▁ ' ) ' m ' which is the first letter of the word ' make ' ; Setting sentenceStartPosition to node ' m ' ( first letter of the word ' make ' ) ; Again Navigate the linked list until a space ( ' ▁ ' ) is found or header == null end of the linked list ; When the next space is found , change the pointer to point the previous space ie . the word is being converted to " m - > a - > k - > e - > s - > ▁ - > p - > r - > a - > c - > t - > i - > c - > e " ; Newly found space will point to ' m ' first letter of the word ' make ' ; Repeat the loop until the end of the linked list is reached ; Set the last node 's next to null ie. ->m->a->k->e->s-> ->p->r->a->->c->t->i->c->e->null ; Function to print the Linked List ; Navigate till the end and print the data in each node ; Driver code ; Convert given string to a linked list with character as data in each node
using System ; public class Node { public Node ( char data , Node next ) { Data = data ; Next = next ; } public char Data ; public Node Next ; } class GFG { private static Node CreateList ( String s ) { Node header = null ; Node temp = null ; for ( int i = 0 ; i < s . Length ; i ++ ) { char c = s [ i ] ; Node node = new Node ( c , null ) ; if ( header == null ) { header = node ; temp = header ; } else { temp . Next = node ; temp = temp . Next ; } } return header ; } private static Node Reverse ( Node header ) { if ( header == null ) return header ; Node wordStartPosition = null ; Node endOfSentence = null ; Node sentenceStartPosition = null ; wordStartPosition = header ; while ( header != null && header . Data != ' ▁ ' ) { endOfSentence = header ; header = header . Next ; } if ( header == null ) { header = wordStartPosition ; return header ; } do { Node temp = header . Next ; header . Next = wordStartPosition ; wordStartPosition = header ; header = temp ; Node prev = null ; sentenceStartPosition = header ; while ( header != null && header . Data != ' ▁ ' ) { prev = header ; header = header . Next ; } prev . Next = wordStartPosition ; wordStartPosition = sentenceStartPosition ; if ( header == null ) break ; } while ( header != null ) ; header = sentenceStartPosition ; endOfSentence . Next = null ; return header ; } private static void PrintList ( Node Header ) { Node temp = Header ; while ( temp != null ) { Console . Write ( temp . Data ) ; temp = temp . Next ; } } public static void Main ( String [ ] args ) { String s = " practice ▁ makes ▁ a ▁ man ▁ perfect " ; Node header = CreateList ( s ) ; Console . WriteLine ( " Before : " ) ; PrintList ( header ) ; header = Reverse ( header ) ; Console . WriteLine ( " After : " PrintList ( header ) ; } }
Find the longest sub | C # program to find that substring which is its suffix prefix and also found somewhere in betweem ; Z - algorithm function ; BIT array ; bit update function which updates values from index " idx " to last by value " val " ; Query function in bit ; Driver Code ; Making the z array ; update in the bit array from index z [ i ] by increment of 1 ; if the value in z [ i ] is not equal to ( n - i ) then no need to move further ; queryng for the maximum length substring from bit array
using System ; class GFG { static int [ ] z_function ( char [ ] s ) { int n = s . Length ; int [ ] z = new int [ n ] ; for ( int i = 1 , l = 0 , r = 0 ; i < n ; i ++ ) { if ( i <= r ) z [ i ] = Math . Min ( r - i + 1 , z [ i - l ] ) ; while ( i + z [ i ] < n && s [ z [ i ] ] == s [ i + z [ i ] ] ) z [ i ] ++ ; if ( i + z [ i ] - 1 > r ) { l = i ; r = i + z [ i ] - 1 ; } } return z ; } static int n , len = 0 ; static int [ ] bit = new int [ 1000005 ] ; static String s ; static int [ ] z ; static void update ( int idx , int val ) { if ( idx == 0 ) return ; while ( idx <= n ) { bit [ idx ] += val ; idx += ( idx & - idx ) ; } } static int pref ( int idx ) { int ans = 0 ; while ( idx > 0 ) { ans += bit [ idx ] ; idx -= ( idx & - idx ) ; } return ans ; } public static void Main ( String [ ] args ) { s = " geeksisforgeeksinplatformgeeks " ; z = new int [ s . Length ] ; n = s . Length ; z = z_function ( s . ToCharArray ( ) ) ; for ( int i = 1 ; i < n ; i ++ ) { update ( z [ i ] , 1 ) ; } for ( int i = n - 1 ; i > 1 ; i -- ) { if ( z [ i ] != ( n - i ) ) continue ; if ( pref ( n ) - pref ( z [ i ] - 1 ) >= 2 ) { len = Math . Max ( len , z [ i ] ) ; } } if ( len == 0 ) Console . WriteLine ( " - 1" ) ; else Console . WriteLine ( s . Substring ( 0 , len ) ) ; } }
Count of words ending at the given suffix in Java | C # implementation of the approach ; Function to return the count of words in the given sentence that end with the given suffix ; To store the count ; Extract words from the sentence ; For every word ; If it ends with the given suffix ; Driver code
using System ; class GFG { static int endingWith ( string str , string suff ) { int cnt = 0 ; string [ ] sep = { " ▁ " } ; string [ ] words = str . Split ( sep , StringSplitOptions . RemoveEmptyEntries ) ; for ( int i = 0 ; i < words . Length ; i ++ ) { if ( words [ i ] . EndsWith ( suff ) ) cnt ++ ; } return cnt ; } public static void Main ( string [ ] args ) { string str = " GeeksForGeeks ▁ is ▁ a ▁ computer " + " ▁ science ▁ portal ▁ for ▁ geeks " ; string suff = " ks " ; Console . Write ( endingWith ( str , suff ) ) ; } }
Character whose frequency is equal to the sum of frequencies of other characters of the given string | C # implementation of the above approach . ; Function that returns true if some character exists in the given string whose frequency is equal to the sum frequencies of other characters of the string ; If string is of odd length ; To store the frequency of each character of the string ; Update the frequencies of the characters ; No such character exists ; Driver code
using System ; class GFG { static bool isFrequencyEqual ( String str , int len ) { if ( len % 2 == 1 ) { return false ; } int i ; int [ ] freq = new int [ 26 ] ; for ( i = 0 ; i < len ; i ++ ) { freq [ str [ i ] - ' a ' ] ++ ; } for ( i = 0 ; i < 26 ; i ++ ) { if ( freq [ i ] == len / 2 ) { return true ; } } return false ; } public static void Main ( ) { String str = " geeksforgeeks " ; int len = str . Length ; if ( isFrequencyEqual ( str , len ) ) { Console . WriteLine ( " Yes " ) ; } else { Console . WriteLine ( " No " ) ; } } }
Minimum replacements to make adjacent characters unequal in a ternary string | C # program to count the minimal replacements such that adjacent characters are unequal ; Function to count the number of minimal replacements ; Find the length of the String ; Iterate in the String ; Check if adjacent is similar ; If not the last pair ; Check for character which is not same in i + 1 and i - 1 ; else Last pair ; Check for character which is not same in i - 1 index ; Driver Code
using System ; class GFG { static readonly int MAX = 26 ; static int countMinimalReplacements ( char [ ] s ) { int n = s . Length ; int cnt = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( s [ i ] == s [ i - 1 ] ) { cnt += 1 ; if ( i != ( n - 1 ) ) { foreach ( char it in "012" . ToCharArray ( ) ) { if ( it != s [ i + 1 ] && it != s [ i - 1 ] ) { s [ i ] = it ; break ; } } } { foreach ( char it in "012" . ToCharArray ( ) ) { if ( it != s [ i - 1 ] ) { s [ i ] = it ; break ; } } } } } return cnt ; } public static void Main ( String [ ] args ) { String s = "201220211" ; Console . WriteLine ( countMinimalReplacements ( s . ToCharArray ( ) ) ) ; } }
Sub | C # implementation of the approach ; Function that returns the index of next occurrence of the character c in string str starting from index start ; Starting from start ; If current character = c ; Not found ; Function to return the count of required sub - strings ; Stores running count of ' x ' starting from the end ; Next index of ' x ' starting from index 0 ; Next index of ' y ' starting from index 0 ; To store the count of required sub - strings ; If ' y ' appears before ' x ' it won 't contribute to a valid sub-string ; Find next occurrence of ' y ' ; If ' y ' appears after ' x ' every sub - string ending at an ' x ' appearing after this ' y ' and starting with the current ' x ' is a valid sub - string ; Find next occurrence of ' x ' ; Return the count ; Driver code
using System ; public class GFG { static int nextIndex ( string str , int start , char c ) { for ( int i = start ; i < str . Length ; i ++ ) { if ( str [ i ] == c ) return i ; } return - 1 ; } static int countSubStrings ( string str ) { int i , n = str . Length ; int [ ] countX = new int [ n ] ; int count = 0 ; for ( i = n - 1 ; i >= 0 ; i -- ) { if ( str [ i ] == ' x ' ) count ++ ; countX [ i ] = count ; } int nextIndexX = nextIndex ( str , 0 , ' x ' ) ; int nextIndexY = nextIndex ( str , 0 , ' y ' ) ; count = 0 ; while ( nextIndexX != - 1 && nextIndexY != - 1 ) { if ( nextIndexX > nextIndexY ) { nextIndexY = nextIndex ( str , nextIndexY + 1 , ' y ' ) ; continue ; } else { count += countX [ nextIndexY ] ; nextIndexX = nextIndex ( str , nextIndexX + 1 , ' x ' ) ; } } return count ; } public static void Main ( ) { string s = " xyyxx " ; Console . WriteLine ( countSubStrings ( s ) ) ; } }
Check whether the frequencies of all the characters in a string are prime or not | C # implementation of above approach ; function that returns true if n is prime else false ; 1 is not prime ; check if there is any factor or not ; function that returns true if the frequencies of all the characters of s are prime ; create a map to store the frequencies of characters ; for ( int i = 0 ; i < s . Length ; i ++ ) update the frequency ; check whether all the frequencies are prime or not ; Driver code ; if all the frequencies are prime
using System ; using System . Collections . Generic ; class GFG { static bool isPrime ( int n ) { int i ; if ( n == 1 ) { return false ; } for ( i = 2 ; i <= Math . Sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { return false ; } } return true ; } static bool check_frequency ( char [ ] s ) { Dictionary < char , int > m = new Dictionary < char , int > ( ) ; { if ( m . ContainsKey ( s [ i ] ) ) { var c = m [ s [ i ] ] + 1 ; m . Remove ( s [ i ] ) ; m . Add ( s [ i ] , c ) ; } else { m . Add ( s [ i ] , 1 ) ; } } for ( char ch = ' a ' ; ch <= ' z ' ; ch ++ ) { if ( m . ContainsKey ( ch ) && m [ ch ] > 0 && ! isPrime ( m [ ch ] ) ) { return false ; } } return true ; } public static void Main ( String [ ] args ) { String s = " geeksforgeeks " ; if ( check_frequency ( s . ToCharArray ( ) ) ) { Console . WriteLine ( " Yes " ) ; } else { Console . WriteLine ( " No " ) ; } } }
Find the count of substrings in alphabetic order | C # to find the number of substrings in alphabetical order ; Function to find number of substrings ; Iterate over string length ; if any two chars are in alphabetic order ; find next char not in order ; return the result ; Driver function
using System ; public class Solution { public static int findSubstringCount ( string str ) { int result = 0 ; int n = str . Length ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( ( char ) ( str [ i ] + 1 ) == str [ i + 1 ] ) { result ++ ; while ( ( char ) ( str [ i ] + 1 ) == str [ i + 1 ] ) { i ++ ; } } } return result ; } public static void Main ( string [ ] args ) { string str = " alphabet " ; Console . WriteLine ( findSubstringCount ( str ) ) ; } }
Reduce the string by removing K consecutive identical characters | C # implementation of the above approach ; Function to find the reduced string ; Base Case ; Creating a stack of type Pair ; Length of the string S ; iterate through the string ; if stack is empty then simply add the character with count 1 else check if character is same as top of stack ; if character at top of stack is same as current character increase the number of repetitions in the top of stack by 1 ; if character at top of stack is not same as current character push the character along with count 1 into the top of stack ; iterate through the stack Use string ( int , char ) in order to replicate the character multiple times and convert into string then add in front of output string ; Driver code
using System ; using System . Collections . Generic ; public class GFG { public static String reduced_String ( int k , String s ) { if ( k == 1 ) { return " " ; } Stack < Pair > st = new Stack < Pair > ( ) ; int l = s . Length ; for ( int i = 0 ; i < l ; i ++ ) { if ( st . Count == 0 ) { st . Push ( new Pair ( s [ i ] , 1 ) ) ; continue ; } if ( st . Peek ( ) . c == s [ i ] ) { Pair p = st . Peek ( ) ; st . Pop ( ) ; p . ctr += 1 ; if ( p . ctr == k ) { continue ; } else { st . Push ( p ) ; } } else { st . Push ( new Pair ( s [ i ] , 1 ) ) ; } } String ans = " " ; while ( st . Count > 0 ) { char c = st . Peek ( ) . c ; int cnt = st . Peek ( ) . ctr ; while ( cnt -- > 0 ) ans = c + ans ; st . Pop ( ) ; } return ans ; } public static void Main ( String [ ] args ) { int k = 2 ; String st = " geeksforgeeks " ; String ans = reduced_String ( k , st ) ; Console . Write ( ans ) ; } public class Pair { public char c ; public int ctr ; public Pair ( char c , int ctr ) { this . c = c ; this . ctr = ctr ; } } }
First non | C # program to find first non - repeating character using 1D array and one traversal . ; The function returns index of the first non - repeating character in a string . If all characters are repeating then returns INT_MAX ; Initialize all characters as absent . ; After below loop , the value of arr [ x ] is going to be index of x if x appears only once . Else the value is going to be either - 1 or - 2. ; If this character occurs only once and appears before the current result , then update the result ; Driver Code
using System ; class GFG { static int firstNonRepeating ( String str ) { int NO_OF_CHARS = 256 ; int [ ] arr = new int [ NO_OF_CHARS ] ; for ( int i = 0 ; i < NO_OF_CHARS ; i ++ ) arr [ i ] = - 1 ; for ( int i = 0 ; i < str . Length ; i ++ ) { if ( arr [ str [ i ] ] == - 1 ) arr [ str [ i ] ] = i ; else arr [ str [ i ] ] = - 2 ; } int res = int . MaxValue ; for ( int i = 0 ; i < NO_OF_CHARS ; i ++ ) if ( arr [ i ] >= 0 ) res = Math . Min ( res , arr [ i ] ) ; return res ; } public static void Main ( ) { String str = " geeksforgeeks " ; int index = firstNonRepeating ( str ) ; if ( index == int . MaxValue ) Console . Write ( " Either ▁ all ▁ characters ▁ are ▁ " + " repeating ▁ or ▁ string ▁ is ▁ empty " ) ; else Console . Write ( " First ▁ non - repeating ▁ character " + " ▁ is ▁ " + str [ index ] ) ; } }
Character replacement after removing duplicates from a string | C # program for character replacement after String minimization ; Function to minimize String ; duplicate characters are removed ; checks if character has previously occurred or not if not then add it to the minimized String ' mstr ' ; return mstr ; minimized String ; Utility function to print the minimized , replaced String ; Creating final String by replacing character ; index calculation ; final String ; Driver Code
using System ; class GFG { static String minimize ( string str ) { string mstr = " ▁ " ; int l , i ; int [ ] flagchar = new int [ 26 ] ; char ch ; l = str . Length ; for ( i = 0 ; i < str . Length ; i ++ ) { ch = str [ i ] ; if ( flagchar [ ch - 97 ] == 0 ) { mstr = mstr + ch ; flagchar [ ch - 97 ] = 1 ; } } } static void replaceMinimizeUtil ( string str ) { string minimizedStr , finalStr = " " ; int i , index , l ; char ch ; l = str . Length ; for ( i = 0 ; i < minimizedStr . Length ; i ++ ) { ch = minimizedStr [ i ] ; index = ( ch * ch ) % l ; finalStr = finalStr + str [ index ] ; } Console . Write ( " Final ▁ String : ▁ " + finalStr ) ; } public static void Main ( ) { string str = " geeks " ; replaceMinimizeUtil ( str ) ; } }
Latin alphabet cipher | C # program to demonstrate Latin Alphabet Cipher ; function for calculating the encryption ; Driver Code
using System ; public class LatinCipher { static void cipher ( String str ) { for ( int i = 0 ; i < str . Length ; i ++ ) { if ( ! char . IsLetter ( str [ i ] ) && str [ i ] != ' ▁ ' ) { Console . WriteLine ( " Enter ▁ only ▁ alphabets ▁ and ▁ space " ) ; return ; } } Console . WriteLine ( " Encrypted ▁ Code ▁ using ▁ Latin ▁ Alphabet " ) ; for ( int i = 0 ; i < str . Length ; i ++ ) { if ( str [ i ] >= ' A ' && str [ i ] <= ' Z ' ) { Console . Write ( str [ i ] - ' A ' + 1 + " ▁ " ) ; } else if ( str [ i ] >= ' a ' && str [ i ] <= ' z ' ) { Console . Write ( str [ i ] - ' a ' + 1 + " ▁ " ) ; } if ( str [ i ] == ' ▁ ' ) Console . Write ( str [ i ] ) ; } Console . WriteLine ( ) ; } public static void Main ( String [ ] args ) { String str = " geeksforgeeks " ; cipher ( str ) ; } }
Count palindrome words in a sentence | C # program to count number of palindrome words in a sentence ; Function to check if a word is palindrome ; Function to count palindrome words ; to check last word for palindrome ; to store each word ; extracting each word ; Driver code
using System ; class GFG { public static bool checkPalin ( string word ) { int n = word . Length ; word = word . ToLower ( ) ; for ( int i = 0 ; i < n ; i ++ , n -- ) { if ( word [ i ] != word [ n - 1 ] ) { return false ; } } return true ; } public static int countPalin ( string str ) { str = str + " ▁ " ; string word = " " ; int count = 0 ; for ( int i = 0 ; i < str . Length ; i ++ ) { char ch = str [ i ] ; if ( ch != ' ▁ ' ) { word = word + ch ; } else { if ( checkPalin ( word ) ) { count ++ ; } word = " " ; } } return count ; } public static void Main ( string [ ] args ) { Console . WriteLine ( countPalin ( " Madam ▁ " + " Arora ▁ teaches ▁ malayalam " ) ) ; Console . WriteLine ( countPalin ( " Nitin ▁ " + " speaks ▁ malayalam " ) ) ; } }
Remove the forbidden strings | C # program to remove forbidden strings ; number of forbidden strings ; original string ; forbidden strings ; to store original string as character array ; letter to replace and occur max number of times ; pre [ ] keeps record of the characters of w that need to be changed ; Function to check if the particular substring is present in w at position ; If length of substring from this position is greater than length of w then return ; n and n1 are used to check for substring without considering the case of the letters in w by comparing the difference of ASCII values ; If same == true then it means a substring was found starting at position therefore all characters from position to length of substring found need to be changed therefore they need to be marked ; Function performing calculations . ; To verify if any substring is starting from index i ; Modifying the string w according to th rules ; This condition checks if w [ i ] = upper ( letter ) ; This condition checks if w [ i ] is any lowercase letter apart from letter . If true replace it with letter ; This condition checks if w [ i ] is any uppercase letter apart from letter . If true then replace it with upper ( letter ) . ; Driver Code
using System ; class GFG { public static int n ; public static string z ; public static string [ ] s = new string [ 100 ] ; public static char [ ] w ; public static char letter ; public static bool [ ] pre = new bool [ 100 ] ; public static void verify ( int position , int index ) { int l = z . Length ; int k = s [ index ] . Length ; if ( position + k > l ) { return ; } bool same = true ; for ( int i = position ; i < position + k ; i ++ ) { int n , n1 ; char ch = w [ i ] ; char ch1 = s [ index ] [ i - position ] ; if ( ch >= ' a ' && ch <= ' z ' ) { n = ch - ' a ' ; } else { n = ch - ' A ' ; } if ( ch1 >= ' a ' && ch1 <= ' z ' ) { n1 = ch1 - ' a ' ; } else { n1 = ch1 - ' A ' ; } if ( n != n1 ) { same = false ; } } if ( same == true ) { for ( int i = position ; i < position + k ; i ++ ) { pre [ i ] = true ; } return ; } } public static void solve ( ) { w = z . ToCharArray ( ) ; letter = ' d ' ; int l = z . Length ; int p = letter - ' a ' ; for ( int i = 0 ; i < 100 ; i ++ ) { pre [ i ] = false ; } for ( int i = 0 ; i < l ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { verify ( i , j ) ; } } for ( int i = 0 ; i < l ; i ++ ) { if ( pre [ i ] == true ) { if ( w [ i ] == letter ) { w [ i ] = ( letter == ' a ' ) ? ' b ' : ' a ' ; } else if ( w [ i ] == ( char ) ( ( int ) ' A ' + p ) ) { w [ i ] = ( letter == ' a ' ) ? ' B ' : ' A ' ; } else if ( w [ i ] >= ' a ' && w [ i ] <= ' z ' ) { w [ i ] = letter ; } else if ( w [ i ] >= ' A ' && w [ i ] <= ' Z ' ) { w [ i ] = ( char ) ( ( int ) ' A ' + p ) ; } } } Console . WriteLine ( w ) ; } public static void Main ( string [ ] args ) { n = 3 ; s [ 0 ] = " etr " ; s [ 1 ] = " ed " ; s [ 2 ] = " ied " ; z = " PEtrUnited " ; solve ( ) ; } }
Round the given number to nearest multiple of 10 | C # Code for Round the given number to nearest multiple of 10 ; function to round the number ; Smaller multiple ; Larger multiple ; Return of closest of two ; Driver program
using System ; class GFG { static int round ( int n ) { int a = ( n / 10 ) * 10 ; int b = a + 10 ; return ( n - a > b - n ) ? b : a ; } public static void Main ( ) { int n = 4722 ; Console . WriteLine ( round ( n ) ) ; } }
Breaking a number such that first part is integral division of second by a power of 10 | C # program to count ways to divide a String in two parts a and b such that b / pow ( 10 , p ) == a ; subString representing int a ; no of digits in a ; consider only most significant l1 characters of remaining String for int b ; if any of a or b contains leading 0 s discard this combination ; if both are equal ; Driver Code
using System ; class GFG { static int calculate ( String N ) { int len = N . Length ; int l = ( len ) / 2 ; int count = 0 ; for ( int i = 1 ; i <= l ; i ++ ) { String s = N . Substring ( 0 , i ) ; int l1 = s . Length ; String t = N . Substring ( i , l1 ) ; if ( s [ 0 ] == '0' t [ 0 ] == '0' ) continue ; if ( s . CompareTo ( t ) == 0 ) count ++ ; } return count ; } public static void Main ( String [ ] args ) { String N = "2202200" ; Console . Write ( calculate ( N ) ) ; } }
Number of subsequences as " ab " in a string repeated K times | C # code to find number of subsequences of " ab " in the string S which is repeated K times . ; Count of ' a ' s ; Count of ' b ' s ; occurrence of " ab " s in string S ; Add following two : 1 ) K * ( Occurrences of " ab " in single string ) 2 ) a is from one string and b is from other . ; Driver code
using System ; class GFG { static int countOccurrences ( string s , int K ) { int n = s . Length ; int C = 0 , c1 = 0 , c2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ' a ' ) c1 ++ ; if ( s [ i ] == ' b ' ) { c2 ++ ; C += c1 ; } } return C * K + ( K * ( K - 1 ) / 2 ) * c1 * c2 ; } public static void Main ( ) { string S = " abcb " ; int k = 2 ; Console . WriteLine ( countOccurrences ( S , k ) ) ; } }
String with k distinct characters and no same characters adjacent | C # program to construct a n length string with k distinct characters such that no two same characters are adjacent . ; Function to find a string of length n with k distinct characters . ; Initialize result with first k Latin letters ; Fill remaining n - k letters by repeating k letters again and again . ; Driver code
using System ; public class GFG { static string findString ( int n , int k ) { string res = " " ; for ( int i = 0 ; i < k ; i ++ ) res = res + ( char ) ( ' a ' + i ) ; int count = 0 ; for ( int i = 0 ; i < n - k ; i ++ ) { res = res + ( char ) ( ' a ' + count ) ; count ++ ; if ( count == k ) count = 0 ; } return res ; } static public void Main ( ) { int n = 5 , k = 2 ; Console . WriteLine ( findString ( n , k ) ) ; } }
Program for credit card number validation | C # program to check if a given credit card is valid or not . ; Main Method ; Return true if the card number is valid ; Get the result from Step 2 ; Return this number if it is a single digit , otherwise , return the sum of the two digits ; Return sum of odd - place digits in number ; Return true if the digit d is a prefix for number ; Return the number of digits in d ; Return the first k number of digits from number . If the number of digits in number is less than k , return number .
using System ; class CreditCard { public static void Main ( ) { long number = 5196081888500645L ; Console . Write ( number + " ▁ is ▁ " + ( isValid ( number ) ? " valid " : " invalid " ) ) ; } public static bool isValid ( long number ) { return ( getSize ( number ) >= 13 && getSize ( number ) <= 16 ) && ( prefixMatched ( number , 4 ) || prefixMatched ( number , 5 ) || prefixMatched ( number , 37 ) || prefixMatched ( number , 6 ) ) && ( ( sumOfDoubleEvenPlace ( number ) + sumOfOddPlace ( number ) ) % 10 == 0 ) ; } public static int sumOfDoubleEvenPlace ( long number ) { int sum = 0 ; String num = number + " " ; for ( int i = getSize ( number ) - 2 ; i >= 0 ; i -= 2 ) sum += getDigit ( int . Parse ( num [ i ] + " " ) * 2 ) ; return sum ; } public static int getDigit ( int number ) { if ( number < 9 ) return number ; return number / 10 + number % 10 ; } public static int sumOfOddPlace ( long number ) { int sum = 0 ; String num = number + " " ; for ( int i = getSize ( number ) - 1 ; i >= 0 ; i -= 2 ) sum += int . Parse ( num [ i ] + " " ) ; return sum ; } public static bool prefixMatched ( long number , int d ) { return getPrefix ( number , getSize ( d ) ) == d ; } public static int getSize ( long d ) { String num = d + " " ; return num . Length ; } public static long getPrefix ( long number , int k ) { if ( getSize ( number ) > k ) { String num = number + " " ; return long . Parse ( num . Substring ( 0 , k ) ) ; } return number ; } }
Find substrings that contain all vowels | c # program to find all substring that contain all vowels ; Returns true if x is vowel . ; Function to check whether a character is vowel or not ; Function to FindSubstrings of string ; To store vowels ; If current character is vowel then insert into hash , ; If all vowels are present in current substring ; Driver Code
using System ; using System . Collections . Generic ; public class GFG { public static bool isVowel ( char x ) { return ( x == ' a ' x == ' e ' x == ' i ' x == ' o ' x == ' u ' ) ; } public static void findSubstring ( string str ) { HashSet < char > hash = new HashSet < char > ( ) ; int start = 0 ; for ( int i = 0 ; i < str . Length ; i ++ ) { if ( isVowel ( str [ i ] ) == true ) { hash . Add ( str [ i ] ) ; if ( hash . Count == 5 ) { Console . Write ( str . Substring ( start , ( i + 1 ) - start ) + " ▁ " ) ; } } else { start = i + 1 ; hash . Clear ( ) ; } } } public static void Main ( string [ ] args ) { string str = " aeoibsddaeiouudb " ; findSubstring ( str ) ; } }
Concatenated string with uncommon characters of two strings | C # program Find concatenated string with uncommon characters of given strings ; Result ; creating a hashMap to add characters in string s2 ; Find characters of s1 that are not present in s2 and append to result ; Find characters of s2 that are not present in s1 . ; Driver code
using System ; using System . Collections . Generic ; class GFG { public static String concatenatedString ( String s1 , String s2 ) { String res = " " ; int i ; Dictionary < char , int > m = new Dictionary < char , int > ( ) ; for ( i = 0 ; i < s2 . Length ; i ++ ) if ( ! m . ContainsKey ( s2 [ i ] ) ) m . Add ( s2 [ i ] , 1 ) ; for ( i = 0 ; i < s1 . Length ; i ++ ) if ( ! m . ContainsKey ( s1 [ i ] ) ) res += s1 [ i ] ; else m [ s1 [ i ] ] = 2 ; for ( i = 0 ; i < s2 . Length ; i ++ ) if ( m [ s2 [ i ] ] == 1 ) res += s2 [ i ] ; return res ; } public static void Main ( String [ ] args ) { String s1 = " abcs " ; String s2 = " cxzca " ; Console . WriteLine ( concatenatedString ( s1 , s2 ) ) ; } }
Count All Palindrome Sub | C # Program to count palindrome substring in a string ; Method which return count palindrome substring ; Iterate the loop twice ; Get each substring ; If length is greater than or equal to two Check for palindrome ; Use StringBuffer class to reverse the string ; Compare substring wih reverse of substring ; return the count ; Swap values of l and r ; Driver Code ; Declare and initialize the string ; Call the method
using System ; class GFG { static int countPS ( String str ) { String temp = " " ; String stf ; int count = 0 ; for ( int i = 0 ; i < str . Length ; i ++ ) { for ( int j = i + 1 ; j <= str . Length ; j ++ ) { temp = str . Substring ( i , j - i ) ; if ( temp . Length >= 2 ) { stf = temp ; stf = reverse ( temp ) ; if ( stf . ToString ( ) . CompareTo ( temp ) == 0 ) count ++ ; } } } return count ; } static String reverse ( String input ) { char [ ] a = input . ToCharArray ( ) ; int l , r = 0 ; r = a . Length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { char temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return String . Join ( " " , a ) ; } public static void Main ( String [ ] args ) { String str = " abbaeae " ; Console . WriteLine ( countPS ( str ) ) ; } }
Print all Subsequences of String which Start with Vowel and End with Consonant . | C # Program to generate all the subsequence starting with vowel and ending with consonant . ; Set to store all the subsequences ; It computes all the possible substring that starts with vowel and end with consonent ; iterate over the entire string ; test ith character for vowel ; if the ith character is vowel iterate from end of the string and check for consonant . ; test jth character for consonant . ; once we get a consonant add it to the hashset ; drop each character of the substring and recur to generate all subsequence of the substring ; Utility method to check vowel ; Utility method to check consonant ; Driver code
using System ; using System . Collections . Generic ; using System . Text ; class Subsequence { static HashSet < String > st = new HashSet < String > ( ) ; static void subsequence ( String str ) { for ( int i = 0 ; i < str . Length ; i ++ ) { if ( isVowel ( str [ i ] ) ) { for ( int j = ( str . Length - 1 ) ; j >= i ; j -- ) { if ( isConsonant ( str [ j ] ) ) { String str_sub = str . Substring ( i , j - i + 1 ) ; st . Add ( str_sub ) ; for ( int k = 1 ; k < str_sub . Length - 1 ; k ++ ) { StringBuilder sb = new StringBuilder ( str_sub ) ; sb . Remove ( k , 1 ) ; subsequence ( sb . ToString ( ) ) ; } } } } } } static bool isVowel ( char c ) { return ( c == ' a ' c == ' e ' c == ' i ' c == ' o ' c == ' u ' ) ; } static bool isConsonant ( char c ) { return ! isVowel ( c ) ; } public static void Main ( String [ ] args ) { String s = " xabcef " ; subsequence ( s ) ; foreach ( String str in st ) Console . Write ( str + " , ▁ " ) ; } }
Null Cipher | A C # program to decode NULL CIPHER ; Function to decode the message . ; Store the decoded string ; found variable is used to tell that the encoded encoded character is found in that particular word . ; Set found variable to false whenever we find whitespace , meaning that encoded character for new word is not found ; Driver Code
using System ; class GFG { static String decode ( String str ) { String res = " " ; Boolean found = false ; for ( int i = 0 ; i < str . Length ; i ++ ) { if ( str [ i ] == ' ▁ ' ) { found = false ; continue ; } if ( ! found ) { if ( str [ i ] >= ' A ' && str [ i ] <= ' Z ' ) { res += ( char ) ( str [ i ] + 32 ) ; found = true ; } else if ( str [ i ] >= ' a ' && str [ i ] <= ' z ' ) { res += ( char ) str [ i ] ; found = true ; } } } return res ; } public static void Main ( String [ ] args ) { String str ; str = " A ▁ Step ▁ by ▁ Step ▁ Guide ▁ for ▁ Placement ▁ Preparation ▁ by ▁ GeeksforGeeks " ; Console . WriteLine ( " Enciphered ▁ Message : ▁ " + decode ( str ) ) ; } }
Program to count vowels in a string ( Iterative and Recursive ) | Recursive C # program to count the total number of vowels using recursion ; Function to check the Vowel ; to count total number of vowel from 0 to n ; Main Calling Function ; string object ; Total numbers of Vowel
using System ; public class GFG { public static int isVowel ( char ch ) { ch = char . ToUpper ( ch ) ; if ( ch == ' A ' ch == ' E ' ch == ' I ' ch == ' O ' ch == ' U ' ) { return 1 ; } else { return 0 ; } } public static int countVowels ( string str , int n ) { if ( n == 1 ) { return isVowel ( str [ n - 1 ] ) ; } return countVowels ( str , n - 1 ) + isVowel ( str [ n - 1 ] ) ; } public static void Main ( string [ ] args ) { string str = " abc ▁ de " ; Console . WriteLine ( countVowels ( str , str . Length ) ) ; } }
Generate all rotations of a given string | A simple C # program to generate all rotations of a given string ; Print all the rotated string . ; Concatenate str with itself ; Print all substrings of size n . Note that size of sb is 2 n ; Driver method
using System ; using System . Text ; class Test { static void printRotatedString ( String str ) { int n = str . Length ; StringBuilder sb = new StringBuilder ( str ) ; sb . Append ( str ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j != n ; j ++ ) Console . Write ( sb [ i + j ] ) ; Console . WriteLine ( ) ; } } public static void Main ( String [ ] args ) { String str = " geeks " ; printRotatedString ( str ) ; } }
Check if frequency of all characters can become same by one removal | C # program to get same frequency character string by removal of at most one char ; Utility method to get index of character ch in lower alphabet characters ; Returns true if all non - zero elements values are same ; get first non - zero element ; check equality of each element with variable same ; Returns true if we can make all character frequencies same ; fill frequency array ; if all frequencies are same , then return true ; Try decreasing frequency of all character by one and then check all equality of all non - zero frequencies ; Check character only if it occurs in str ; Driver code
using System ; class GFG { static int M = 26 ; static int getIdx ( char ch ) { return ( ch - ' a ' ) ; } static bool allSame ( int [ ] freq , int N ) { int same = 0 ; int i ; for ( i = 0 ; i < N ; i ++ ) { if ( freq [ i ] > 0 ) { same = freq [ i ] ; break ; } } for ( int j = i + 1 ; j < N ; j ++ ) if ( freq [ j ] > 0 && freq [ j ] != same ) return false ; return true ; } static bool possibleSameCharFreqByOneRemoval ( string str ) { int l = str . Length ; int [ ] freq = new int [ M ] ; for ( int i = 0 ; i < l ; i ++ ) freq [ getIdx ( str [ i ] ) ] ++ ; if ( allSame ( freq , M ) ) return true ; for ( char c = ' a ' ; c <= ' z ' ; c ++ ) { int i = getIdx ( c ) ; if ( freq [ i ] > 0 ) { freq [ i ] -- ; if ( allSame ( freq , M ) ) return true ; freq [ i ] ++ ; } } return false ; } public static void Main ( ) { string str = " xyyzz " ; if ( possibleSameCharFreqByOneRemoval ( str ) ) Console . Write ( " Yes " ) ; else Console . Write ( " No " ) ; } }
Check if a large number is divisible by 11 or not | C # program to find if a number is divisible by 11 or not ; Function to find that number divisible by 11 or not ; Compute sum of even and odd digit sums ; When i is even , position of digit is odd ; Check its difference is divisible by 11 or not ; main function
using System ; class GFG { static bool check ( string str ) { int n = str . Length ; int oddDigSum = 0 , evenDigSum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) oddDigSum += ( str [ i ] - '0' ) ; else evenDigSum += ( str [ i ] - '0' ) ; } return ( ( oddDigSum - evenDigSum ) % 11 == 0 ) ; } public static void Main ( ) { String str = "76945" ; if ( check ( str ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
Palindrome pair in an array of words ( or strings ) | C # program to check if there is a pair that of above method using Trie ; Alphabet size ( # of symbols ) ; Trie node ; public List < int > pos ; To store palindromic positions in str ; isLeaf is true if the node represents end of a word ; constructor ; Utility function to check if a string is a palindrome ; compare each character from starting with its corresponding character from last ; If not present , inserts reverse of key into Trie . If the key is prefix of a Trie node , just mark leaf node ; Start traversing word from the last ; If it is not available in Trie , then store it ; If current word is palindrome till this level , store index of current word . ; mark last node as leaf ; list to store result ; Returns true if key presents in Trie , else false ; If it is present also check upto which index it is palindrome ; If not present then return ; Function to check if a palindrome pair exists ; Construct trie ; Search for different keys ; Driver code
using System ; using System . Collections . Generic ; class GFG { static readonly int ALPHABET_SIZE = 26 ; class TrieNode { public TrieNode [ ] children = new TrieNode [ ALPHABET_SIZE ] ; public int id ; public Boolean isLeaf ; public TrieNode ( ) { isLeaf = false ; pos = new List < int > ( ) ; for ( int i = 0 ; i < ALPHABET_SIZE ; i ++ ) children [ i ] = null ; } } static Boolean isPalindrome ( String str , int i , int len ) { while ( i < len ) { if ( str [ i ] != str [ len ] ) return false ; i ++ ; len -- ; } return true ; } static void insert ( TrieNode root , String key , int id ) { TrieNode pCrawl = root ; for ( int level = key . Length - 1 ; level >= 0 ; level -- ) { int index = key [ level ] - ' a ' ; if ( pCrawl . children [ index ] == null ) pCrawl . children [ index ] = new TrieNode ( ) ; if ( isPalindrome ( key , 0 , level ) ) ( pCrawl . pos ) . Add ( id ) ; pCrawl = pCrawl . children [ index ] ; } pCrawl . id = id ; pCrawl . pos . Add ( id ) ; pCrawl . isLeaf = true ; } static List < List < int > > result ; static void search ( TrieNode root , String key , int id ) { TrieNode pCrawl = root ; for ( int level = 0 ; level < key . Length ; level ++ ) { int index = key [ level ] - ' a ' ; if ( pCrawl . id >= 0 && pCrawl . id != id && isPalindrome ( key , level , key . Length - 1 ) ) { List < int > l = new List < int > ( ) ; l . Add ( id ) ; l . Add ( pCrawl . id ) ; result . Add ( l ) ; } if ( pCrawl . children [ index ] == null ) return ; pCrawl = pCrawl . children [ index ] ; } foreach ( int i in pCrawl . pos ) { if ( i == id ) continue ; List < int > l = new List < int > ( ) ; l . Add ( id ) ; l . Add ( i ) ; result . Add ( l ) ; } } static Boolean checkPalindromePair ( List < String > vect ) { TrieNode root = new TrieNode ( ) ; for ( int i = 0 ; i < vect . Count ; i ++ ) insert ( root , vect [ i ] , i ) ; result = new List < List < int > > ( ) ; for ( int i = 0 ; i < vect . Count ; i ++ ) { search ( root , vect [ i ] , i ) ; if ( result . Count > 0 ) return true ; } return false ; } public static void Main ( String [ ] args ) { List < String > vect = new List < String > ( ) { " geekf " , " geeks " , " or " , " keeg " , " abc " , " bc " } ; if ( checkPalindromePair ( vect ) == true ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
Hamming Distance between two strings | C # program to find hamming distance b / w two string ; function to calculate Hamming distance ; Driver code ; function call
using System ; class GFG { static int hammingDist ( String str1 , String str2 ) { int i = 0 , count = 0 ; while ( i < str1 . Length ) { if ( str1 [ i ] != str2 [ i ] ) count ++ ; i ++ ; } return count ; } public static void Main ( ) { String str1 = " geekspractice " ; String str2 = " nerdspractise " ; Console . Write ( hammingDist ( str1 , str2 ) ) ; } }
Check if two strings are k | C # program to check if two strings are k anagram or not . ; Function to check that string is k - anagram or not ; If both strings are not of equal length then return false ; Store the occurrence of all characters in a hash_array ; Count number of characters that are different in both strings ; Return true if count is less than or equal to k ; Driver code
using System ; class GFG { static int MAX_CHAR = 26 ; static bool arekAnagrams ( string str1 , string str2 , int k ) { int n = str1 . Length ; if ( str2 . Length != n ) return false ; int [ ] count1 = new int [ MAX_CHAR ] ; int [ ] count2 = new int [ MAX_CHAR ] ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) count1 [ str1 [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < n ; i ++ ) count2 [ str2 [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) if ( count1 [ i ] > count2 [ i ] ) count = count + Math . Abs ( count1 [ i ] - count2 [ i ] ) ; return ( count <= k ) ; } public static void Main ( ) { string str1 = " anagram " ; string str2 = " grammar " ; int k = 2 ; if ( arekAnagrams ( str1 , str2 , k ) ) Console . Write ( " Yes " ) ; else Console . Write ( " No " ) ; } }
Remove spaces from a given string | An efficient C # program to remove all spaces from a string ; Function to remove all spaces from a given string ; To keep track of non - space character count ; Traverse the given string . If current character is not space , then place it at index ' count + + ' ; str [ count ++ ] = str [ i ] ; here count is incremented ; Driver code
using System ; class GFG { static int removeSpaces ( char [ ] str ) { int count = 0 ; for ( int i = 0 ; i < str . Length ; i ++ ) if ( str [ i ] != ' ▁ ' ) return count ; } public static void Main ( String [ ] args ) { char [ ] str = " g ▁ eeks ▁ for ▁ ge ▁ eeks ▁ " . ToCharArray ( ) ; int i = removeSpaces ( str ) ; Console . WriteLine ( String . Join ( " " , str ) . Substring ( 0 , i ) ) ; } }
Given a binary string , count number of substrings that start and end with 1. | A O ( n ) C # program to count number of substrings starting and ending with 1 ; Traverse input string and count of 1 's in it ; Return count of possible pairs among m 1 's ; Driver Code
using System ; class GFG { int countSubStr ( char [ ] str , int n ) { for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == '1' ) m ++ ; } return m * ( m - 1 ) / 2 ; } public static void Main ( String [ ] args ) { GFG count = new GFG ( ) ; String strings = "00100101" ; char [ ] str = strings . ToCharArray ( ) ; int n = str . Length ; Console . Write ( count . countSubStr ( str , n ) ) ; } }
Given a number as a string , find the number of contiguous subsequences which recursively add up to 9 | C # program to count substrings with recursive sum equal to 9 ; To store result ; Consider every character as beginning of substring ; sum of digits in current substring ; One by one choose every character as an ending character ; Add current digit to sum , if sum becomes multiple of 5 then increment count . Let us do modular arithmetic to avoid overflow for big strings ; Driver Code
using System ; class GFG { static int count9s ( String number ) { int count = 0 ; int n = number . Length ; for ( int i = 0 ; i < n ; i ++ ) { int sum = number [ i ] - '0' ; if ( number [ i ] == '9' ) count ++ ; for ( int j = i + 1 ; j < n ; j ++ ) { sum = ( sum + number [ j ] - '0' ) % 9 ; if ( sum == 0 ) count ++ ; } } return count ; } public static void Main ( ) { Console . WriteLine ( count9s ( "4189" ) ) ; Console . WriteLine ( count9s ( "1809" ) ) ; } }
Generate n | C # program to generate n - bit Gray codes ; This function generates all n bit Gray codes and prints the generated codes ; base case ; ' arr ' will store all generated codes ; start with one - bit pattern ; Every iteration of this loop generates 2 * i codes from previously generated i codes . ; Enter the prviously generated codes again in arr [ ] in reverse order . Nor arr [ ] has double number of codes . ; append 0 to the first half ; append 1 to the second half ; print contents of arr [ ] ; Driver program to test above function
using System ; using System . Collections . Generic ; public class GfG { public static void generateGrayarr ( int n ) { if ( n <= 0 ) { return ; } List < string > arr = new List < string > ( ) ; arr . Add ( "0" ) ; arr . Add ( "1" ) ; int i , j ; for ( i = 2 ; i < ( 1 << n ) ; i = i << 1 ) { for ( j = i - 1 ; j >= 0 ; j -- ) { arr . Add ( arr [ j ] ) ; } for ( j = 0 ; j < i ; j ++ ) { arr [ j ] = "0" + arr [ j ] ; } for ( j = i ; j < 2 * i ; j ++ ) { arr [ j ] = "1" + arr [ j ] ; } } for ( i = 0 ; i < arr . Count ; i ++ ) { Console . WriteLine ( arr [ i ] ) ; } } public static void Main ( string [ ] args ) { generateGrayarr ( 3 ) ; } }
Rat in a Maze Problem when movement in all possible directions is allowed | C # implementation of the above approach ; List to store all the possible paths ; Function returns true if the move taken is valid else it will return false . ; Function to print all the possible paths from ( 0 , 0 ) to ( n - 1 , n - 1 ) . ; This will check the initial point ( i . e . ( 0 , 0 ) ) to start the paths . ; If reach the last cell ( n - 1 , n - 1 ) then store the path and return ; Mark the cell as visited ; Check if downward move is valid ; Check if the left move is valid ; Check if the right move is valid ; Check if the upper move is valid ; Mark the cell as unvisited for other possible paths ; Function to store and print all the valid paths ; Call the utility function to find the valid paths ; Print all possible paths ; Driver code
using System ; using System . Collections . Generic ; class GFG { static List < String > possiblePaths = new List < String > ( ) ; static String path = " " ; static readonly int MAX = 5 ; static bool isSafe ( int row , int col , int [ , ] m , int n , bool [ , ] visited ) { if ( row == - 1 row == n col == - 1 col == visited [ row , col ] m [ row , col ] == 0 ) return false ; return true ; } static void printPathUtil ( int row , int col , int [ , ] m , int n , bool [ , ] visited ) { if ( row == - 1 row == n col == - 1 col == visited [ row , col ] m [ row , col ] == 0 ) return ; if ( row == n - 1 && col == n - 1 ) { possiblePaths . Add ( path ) ; return ; } visited [ row , col ] = true ; if ( isSafe ( row + 1 , col , m , n , visited ) ) { path += ' D ' ; printPathUtil ( row + 1 , col , m , n , visited ) ; path = path . Substring ( 0 , path . Length - 1 ) ; } if ( isSafe ( row , col - 1 , m , n , visited ) ) { path += ' L ' ; printPathUtil ( row , col - 1 , m , n , visited ) ; path = path . Substring ( 0 , path . Length - 1 ) ; } if ( isSafe ( row , col + 1 , m , n , visited ) ) { path += ' R ' ; printPathUtil ( row , col + 1 , m , n , visited ) ; path = path . Substring ( 0 , path . Length - 1 ) ; } if ( isSafe ( row - 1 , col , m , n , visited ) ) { path += ' U ' ; printPathUtil ( row - 1 , col , m , n , visited ) ; path = path . Substring ( 0 , path . Length - 1 ) ; } visited [ row , col ] = false ; } static void printPath ( int [ , ] m , int n ) { bool [ , ] visited = new bool [ n , MAX ] ; printPathUtil ( 0 , 0 , m , n , visited ) ; for ( int i = 0 ; i < possiblePaths . Count ; i ++ ) Console . Write ( possiblePaths [ i ] + " ▁ " ) ; } public static void Main ( String [ ] args ) { int [ , ] m = { { 1 , 0 , 0 , 0 , 0 } , { 1 , 1 , 1 , 1 , 1 } , { 1 , 1 , 1 , 0 , 1 } , { 0 , 0 , 0 , 0 , 1 } , { 0 , 0 , 0 , 0 , 1 } } ; int n = m . GetLength ( 0 ) ; printPath ( m , n ) ; } }
N Queen in O ( n ) space | C # code to for n Queen placement ; Function to check queens placement ; Helper Function to check if queen can be placed ; Function to display placed queen ; Driver Code
using System ; class GfG { static void breakLine ( ) { Console . Write ( " -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - " } static int = 10 ; static int [ ] arr = new int [ MAX ] ; static int no ; static void nQueens ( int k , int n ) { for ( int i = 1 ; i <= n ; i ++ ) { if ( canPlace ( k , i ) ) { arr [ k ] = i ; if ( k == n ) { display ( n ) ; } else { nQueens ( k + 1 , n ) ; } } } } static bool canPlace ( int k , int i ) { for ( int j = 1 ; j <= k - 1 ; j ++ ) { if ( arr [ j ] == i || ( Math . Abs ( arr [ j ] - i ) == Math . Abs ( j - k ) ) ) { return false ; } } return true ; } static void display ( int n ) { breakLine ( ) ; Console . Write ( " Arrangement ▁ No . ▁ " + ++ no ) ; breakLine ( ) ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( arr [ i ] != j ) { Console . Write ( " TABSYMBOL _ " ) ; } else { Console . Write ( " TABSYMBOL Q " ) ; } } Console . WriteLine ( " " ) ; } breakLine ( ) ; } public static void Main ( String [ ] args ) { int n = 4 ; nQueens ( 1 , n ) ; } }
Numbers that are bitwise AND of at least one non | C # implementation of the approach ; Set to store all possible AND values . ; Starting index of the sub - array . ; Ending index of the sub - array . ; AND value is added to the set . ; displaying the values
using System ; using System . Collections . Generic ; class CP { public static void Main ( String [ ] args ) { int [ ] A = { 11 , 15 , 7 , 19 } ; int N = A . Length ; HashSet < int > set1 = new HashSet < int > ( ) ; int i , j , res ; for ( i = 0 ; i < N ; ++ i ) { for ( j = i , res = int . MaxValue ; j < N ; ++ j ) { res &= A [ j ] ; set1 . Add ( res ) ; } } foreach ( int m in set1 ) { Console . Write ( m + " ▁ " ) ; } } }
Collect all coins in minimum number of steps | C # Code to Collect all coins in minimum number of steps ; recursive method to collect coins from height array l to r , with height h already collected ; if l is more than r , no steps needed ; loop over heights to get minimum height index ; choose minimum from , 1 ) collecting coins using all vertical lines ( total r - l ) 2 ) collecting coins using lower horizontal lines and recursively on left and right segments ; method returns minimum number of step to collect coin from stack , with height in height [ ] array ; Driver program to test above function
using System ; class GFG { public static int minStepsRecur ( int [ ] height , int l , int r , int h ) { if ( l >= r ) return 0 ; int m = l ; for ( int i = l ; i < r ; i ++ ) if ( height [ i ] < height [ m ] ) m = i ; return Math . Min ( r - l , minStepsRecur ( height , l , m , height [ m ] ) + minStepsRecur ( height , m + 1 , r , height [ m ] ) + height [ m ] - h ) ; } public static int minSteps ( int [ ] height , int N ) { return minStepsRecur ( height , 0 , N , 0 ) ; } public static void Main ( ) { int [ ] height = { 2 , 1 , 2 , 5 , 1 } ; int N = height . Length ; Console . Write ( minSteps ( height , N ) ) ; } }
Count of Unique Direct Path Between N Points On a Plane | C # program for the above approach ; Function to count the total number of direct paths ; Driver Code
using System ; public class GFG { static int countDirectPath ( int N ) { return N + ( N * ( N - 3 ) ) / 2 ; } public static void Main ( string [ ] args ) { int N = 5 ; Console . Write ( countDirectPath ( N ) ) ; } }
Triacontagon Number | C # program for above approach ; Finding the nth triacontagonal number ; Driver code
using System ; class GFG { static int triacontagonalNum ( int n ) { return ( 28 * n * n - 26 * n ) / 2 ; } public static void Main ( ) { int n = 3 ; Console . Write ( "3rd ▁ triacontagonal ▁ Number ▁ is ▁ = ▁ " + triacontagonalNum ( n ) ) ; } }
Hexacontagon Number | C # program for above approach ; Finding the nth hexacontagon number ; Driver code
using System ; class GFG { public static int hexacontagonNum ( int n ) { return ( 58 * n * n - 56 * n ) / 2 ; } public static void Main ( ) { int n = 3 ; Console . Write ( "3rd ▁ hexacontagon ▁ Number ▁ is ▁ = ▁ " + hexacontagonNum ( n ) ) ; } }
Enneacontagon Number | C # program for above approach ; Finding the nth enneacontagon number ; Driver code
using System ; class GFG { public static int enneacontagonNum ( int n ) { return ( 88 * n * n - 86 * n ) / 2 ; } public static void Main ( String [ ] args ) { int n = 3 ; Console . WriteLine ( "3rd ▁ enneacontagon ▁ Number ▁ is ▁ = ▁ " + enneacontagonNum ( n ) ) ; } }
Triacontakaidigon Number | C # program for above approach ; Finding the nth triacontakaidigon number ; Driver code
using System ; class GFG { public static int triacontakaidigonNum ( int n ) { return ( 30 * n * n - 28 * n ) / 2 ; } public static void Main ( String [ ] args ) { int n = 3 ; Console . WriteLine ( "3rd ▁ triacontakaidigon ▁ Number ▁ is ▁ = ▁ " + triacontakaidigonNum ( n ) ) ; } }
Icosihexagonal Number | C # program for above approach ; Finding the nth icosihexagonal number ; Driver code
using System ; class GFG { public static int IcosihexagonalNum ( int n ) { return ( 24 * n * n - 22 * n ) / 2 ; } public static void Main ( String [ ] args ) { int n = 3 ; Console . WriteLine ( "3rd ▁ Icosihexagonal ▁ Number ▁ is ▁ = ▁ " + IcosihexagonalNum ( n ) ) ; } }
Icosikaioctagon or Icosioctagon Number | C # program for above approach ; Finding the nth icosikaioctagonal number ; Driver code
using System ; class GFG { public static int icosikaioctagonalNum ( int n ) { return ( 26 * n * n - 24 * n ) / 2 ; } public static void Main ( ) { int n = 3 ; Console . Write ( "3rd ▁ icosikaioctagonal ▁ Number ▁ is ▁ = ▁ " + icosikaioctagonalNum ( n ) ) ; } }
Octacontagon Number | C # program for above approach ; Finding the nth octacontagon Number ; Driver Code
using System ; class GFG { static int octacontagonNum ( int n ) { return ( 78 * n * n - 76 * n ) / 2 ; } public static void Main ( ) { int n = 3 ; Console . Write ( "3rd ▁ octacontagon ▁ Number ▁ is ▁ = ▁ " + octacontagonNum ( n ) ) ; } }
Hectagon Number | C # program for above approach ; Finding the nth hectagon Number ; Driver Code
using System ; class GFG { static int hectagonNum ( int n ) { return ( 98 * n * n - 96 * n ) / 2 ; } public static void Main ( ) { int n = 3 ; Console . Write ( "3rd ▁ hectagon ▁ Number ▁ is ▁ = ▁ " + hectagonNum ( n ) ) ; } }
Tetracontagon Number | C # program for above approach ; Finding the nth tetracontagon number ; Driver code
using System ; class GFG { static int tetracontagonNum ( int n ) { return ( 38 * n * n - 36 * n ) / 2 ; } public static void Main ( string [ ] args ) { int n = 3 ; Console . Write ( "3rd ▁ tetracontagon ▁ Number ▁ is ▁ = ▁ " + tetracontagonNum ( n ) ) ; } }
Perimeter of an Ellipse | C # program to find perimeter of an Ellipse . ; Function to find perimeter of an ellipse . ; formula to find the Perimeter of an Ellipse . ; Display the result ; Driver code
using System ; class GFG1 { static void Perimeter ( double a , double b ) { double Perimeter ; Perimeter = ( double ) 2 * 3.14 * Math . Sqrt ( ( a * a + b * b ) / ( 2 * 1.0 ) ) ; Console . WriteLine ( " Perimeter : ▁ " + Perimeter ) ; } public static void Main ( String [ ] args ) { double a = 3 , b = 2 ; Perimeter ( a , b ) ; } }
Biggest Reuleaux Triangle within A Square | C # program to find area of the biggest Reuleaux triangle that can be inscribed within a square ; Function to find the area of the reuleaux triangle ; Side cannot be negative ; Area of the reauleaux triangle ; Driver code
using System ; class GFG { static double reuleauxArea ( double a ) { if ( a < 0 ) return - 1 ; double A = 0.70477 * Math . Pow ( a , 2 ) ; return A ; } static public void Main ( ) { double a = 6 ; Console . WriteLine ( reuleauxArea ( a ) ) ; } }
Largest hexagon that can be inscribed within a square | C # Program to find the biggest hexagon which can be inscribed within the given square ; Function to return the side of the hexagon ; Side cannot be negative ; Side of the hexagon ; Driver code
using System ; class GFG { static double hexagonside ( double a ) { if ( a < 0 ) return - 1 ; double x = ( 0.5176 * a ) ; return x ; } public static void Main ( ) { double a = 6 ; Console . WriteLine ( hexagonside ( a ) ) ; } }
Largest hexagon that can be inscribed within an equilateral triangle | C # program to find the side of the largest hexagon which can be inscribed within an equilateral triangle ; Function to find the side of the hexagon ; Side cannot be negative ; Side of the hexagon ; Driver code
using System ; class CLG { static float hexagonside ( float a ) { if ( a < 0 ) return - 1 ; float x = a / 3 ; return x ; } public static void Main ( ) { float a = 6 ; Console . Write ( hexagonside ( a ) ) ; } }
Find middle point segment from given segment lengths | C # implementation of the approach ; Function that returns the segment for the middle point ; the middle point ; stores the segment index ; increment sum by length of the segment ; if the middle is in between two segments ; if sum is greater than middle point ; Driver code
using System ; class GFG { static int findSegment ( int n , int m , int [ ] segment_length ) { double meet_point = ( 1.0 * n ) / 2.0 ; int sum = 0 ; int segment_number = 0 ; for ( int i = 0 ; i < m ; i ++ ) { sum += segment_length [ i ] ; if ( ( double ) sum == meet_point ) { segment_number = - 1 ; break ; } if ( sum > meet_point ) { segment_number = i + 1 ; break ; } } return segment_number ; } public static void Main ( ) { int n = 13 ; int m = 3 ; int [ ] segment_length = new int [ ] { 3 , 2 , 8 } ; int ans = findSegment ( n , m , segment_length ) ; Console . WriteLine ( ans ) ; } }
Maximum points of intersection n lines | C # program to find maximum intersecting points ; nC2 = ( n ) * ( n - 1 ) / 2 ; ; Driver code ; n is number of line
using System ; class GFG { public static long countMaxIntersect ( long n ) { return ( n ) * ( n - 1 ) / 2 ; } public static void Main ( ) { long n = 8 ; Console . WriteLine ( countMaxIntersect ( n ) ) ; } }
Program to find volume and surface area of pentagonal prism | C # program to find surface area and volume of the Pentagonal Prism ; function for surface area ; function for VOlume ; Driver Code
using System ; class GFG { static float surfaceArea ( float a , float b , float h ) { return 5 * a * b + 5 * b * h ; } static float volume ( float b , float h ) { return ( 5 * b * h ) / 2 ; } public static void Main ( ) { float a = 5 ; float b = 3 ; float h = 7 ; Console . WriteLine ( " surface ▁ area ▁ = ▁ " + surfaceArea ( a , b , h ) + " , ▁ " ) ; Console . WriteLine ( " volume ▁ = ▁ " + volume ( b , h ) ) ; } }
Check if a point is inside , outside or on the parabola | C # Program to check if the point lies within the parabola or not ; Function to check the point ; checking the equation of parabola with the given point ; Driver code
using System ; class GFG { public static int checkpoint ( int h , int k , int x , int y , int a ) { int p = ( int ) Math . Pow ( ( y - k ) , 2 ) - 4 * a * ( x - h ) ; return p ; } public static void Main ( string [ ] arr ) { int h = 0 , k = 0 , x = 2 , y = 1 , a = 4 ; if ( checkpoint ( h , k , x , y , a ) > 0 ) { Console . WriteLine ( " Outside " ) ; } else if ( checkpoint ( h , k , x , y , a ) == 0 ) { Console . WriteLine ( " On ▁ the ▁ parabola " ) ; } else { Console . WriteLine ( " Inside " ) ; } } }
Check if a point is inside , outside or on the ellipse | C # Program to check if the point lies within the ellipse or not ; Function to check the point ; checking the equation of ellipse with the given point ; Driver code
using System ; class GFG { static int checkpoint ( int h , int k , int x , int y , int a , int b ) { int p = ( ( int ) Math . Pow ( ( x - h ) , 2 ) / ( int ) Math . Pow ( a , 2 ) ) + ( ( int ) Math . Pow ( ( y - k ) , 2 ) / ( int ) Math . Pow ( b , 2 ) ) ; return p ; } public static void Main ( ) { int h = 0 , k = 0 , x = 2 , y = 1 , a = 4 , b = 5 ; if ( checkpoint ( h , k , x , y , a , b ) > 1 ) Console . WriteLine ( " Outside " ) ; else if ( checkpoint ( h , k , x , y , a , b ) == 1 ) Console . WriteLine ( " On ▁ the ▁ ellipse " ) ; else Console . WriteLine ( " Inside " ) ; } }
Area of circle inscribed within rhombus | C # Program to find the area of the circle which can be inscribed within the rhombus ; Function to find the area of the inscribed circle ; the diagonals cannot be negative ; area of the circle ; Driver code
using System ; public class GFG { public static float circlearea ( double a , double b ) { if ( a < 0 b < 0 ) return - 1 ; float A = ( float ) ( ( 3.14 * Math . Pow ( a , 2 ) * Math . Pow ( b , 2 ) ) / ( 4 * ( Math . Pow ( a , 2 ) + Math . Pow ( b , 2 ) ) ) ) ; return A ; } public static void Main ( ) { float a = 8 , b = 10 ; Console . WriteLine ( circlearea ( a , b ) ) ; } }
The biggest possible circle that can be inscribed in a rectangle | C # Program to find the biggest circle which can be inscribed within the rectangle ; Function to find the area of the biggest circle ; the length and breadth cannot be negative ; area of the circle ; Driver code
using System ; class GFG { static float circlearea ( float l , float b ) { if ( l < 0 b < 0 ) return - 1 ; if ( l < b ) return ( float ) ( 3.14 * Math . Pow ( l / 2 , 2 ) ) ; else return ( float ) ( 3.14 * Math . Pow ( b / 2 , 2 ) ) ; } public static void Main ( ) { float l = 4 , b = 8 ; Console . Write ( circlearea ( l , b ) ) ; } }
Centered cube number | C # Program to find nth Centered cube number ; Function to find Centered cube number ; Formula to calculate nth Centered cube number & return it into main function . ; Driver code
using System ; class GFG { static int centered_cube ( int n ) { return ( 2 * n + 1 ) * ( n * n + n + 1 ) ; } static public void Main ( ) { int n = 3 ; Console . Write ( n + " th ▁ Centered " + " ▁ cube ▁ number : ▁ " ) ; Console . WriteLine ( centered_cube ( n ) ) ; n = 10 ; Console . Write ( n + " th ▁ Centered " + " ▁ cube ▁ number : ▁ " ) ; Console . WriteLine ( centered_cube ( n ) ) ; } }
Find the center of the circle using endpoints of diameter | C # program to find the center of the circle ; function to find the center of the circle ; Driver Program to test above function
using System ; class GFG { static void center ( int x1 , int x2 , int y1 , int y2 ) { Console . WriteLine ( ( float ) ( x1 + x2 ) / 2 + " , ▁ " + ( float ) ( y1 + y2 ) / 2 ) ; } public static void Main ( ) { int x1 = - 9 , y1 = 3 , x2 = 5 , y2 = - 7 ; center ( x1 , x2 , y1 , y2 ) ; } }
Program to calculate volume of Octahedron | C # Program to calculate volume of Octahedron ; Driver Function ; utility Function
using System ; class GFG { public static void Main ( ) { double side = 3 ; Console . Write ( " Volume ▁ of ▁ octahedron ▁ = ▁ " ) ; Console . WriteLine ( vol_of_octahedron ( side ) ) ; } static double vol_of_octahedron ( double side ) { return ( ( side * side * side ) * ( Math . Sqrt ( 2 ) / 3 ) ) ; } }
Program to calculate volume of Ellipsoid | C # program to find the volume of Ellipsoid . ; Function to find the volume ; Driver Code
using System ; class GfG { public static float volumeOfEllipsoid ( float r1 , float r2 , float r3 ) { float pi = ( float ) 3.14 ; return ( float ) 1.33 * pi * r1 * r2 * r3 ; } public static void Main ( ) { float r1 = ( float ) 2.3 , r2 = ( float ) 3.4 , r3 = ( float ) 5.7 ; Console . WriteLine ( " volume ▁ of ▁ ellipsoid ▁ is ▁ : ▁ " + volumeOfEllipsoid ( r1 , r2 , r3 ) ) ; } }
Program to calculate Area Of Octagon | C # Program to find area of Octagon . ; utility function ; Driver code
using System ; class GFG { static double areaOctagon ( double side ) { return ( float ) ( 2 * ( 1 + Math . Sqrt ( 2 ) ) * side * side ) ; } public static void Main ( ) { double side = 4 ; Console . WriteLine ( " Area ▁ of ▁ Regular ▁ Octagon ▁ = ▁ " + areaOctagon ( side ) ) ; } }
Program for Volume and Surface Area of Cube | C # program to find area and total surface area of cube ; utility function ; Driver code
using System ; class GFG { static double areaCube ( double a ) { return ( a * a * a ) ; } static double surfaceCube ( double a ) { return ( 6 * a * a ) ; } public static void Main ( ) { double a = 5 ; Console . WriteLine ( " Area ▁ = ▁ " + areaCube ( a ) ) ; Console . WriteLine ( " Total ▁ surface ▁ area ▁ = ▁ " + surfaceCube ( a ) ) ; } }
Find mirror image of a point in 2 | C # code to find mirror image ; function which finds coordinates of mirror image . This function return a pair of double ; Driver code
using System ; class GFG { class pair { public double first , second ; public pair ( double first , double second ) { this . first = first ; this . second = second ; } } static pair mirrorImage ( double a , double b , double c , double x1 , double y1 ) { double temp = - 2 * ( a * x1 + b * y1 + c ) / ( a * a + b * b ) ; double x = temp * a + x1 ; double y = temp * b + y1 ; return new pair ( x , y ) ; } public static void Main ( String [ ] args ) { double a = - 1.0 ; double b = 1.0 ; double c = 0.0 ; double x1 = 1.0 ; double y1 = 0.0 ; pair image = mirrorImage ( a , b , c , x1 , y1 ) ; Console . Write ( " Image ▁ of ▁ point ▁ ( " + x1 + " , ▁ " + y1 + " ) ▁ " ) ; Console . Write ( " by ▁ mirror ▁ ( " + a + " ) x ▁ + ▁ ( " + b + " ) y ▁ + ▁ ( " + c + " ) ▁ = ▁ 0 , ▁ is ▁ : " ) ; Console . WriteLine ( " ( " + image . first + " , ▁ " + image . second + " ) " ) ; } }
Program for Point of Intersection of Two Lines | C # Implementation . To find the point of intersection of two lines ; Class used to used to store the X and Y coordinates of a point respectively ; Method used to display X and Y coordinates of a point ; Line AB represented as a1x + b1y = c1 ; Line CD represented as a2x + b2y = c2 ; The lines are parallel . This is simplified by returning a pair of FLT_MAX ; Driver method ; NOTE : Further check can be applied in case of line segments . Here , we have considered AB and CD as lines
using System ; public class Point { public double x , y ; public Point ( double x , double y ) { this . x = x ; this . y = y ; } public static void displayPoint ( Point p ) { Console . WriteLine ( " ( " + p . x + " , ▁ " + p . y + " ) " ) ; } } public class Test { public static Point lineLineIntersection ( Point A , Point B , Point C , Point D ) { double a1 = B . y - A . y ; double b1 = A . x - B . x ; double c1 = a1 * ( A . x ) + b1 * ( A . y ) ; double a2 = D . y - C . y ; double b2 = C . x - D . x ; double c2 = a2 * ( C . x ) + b2 * ( C . y ) ; double determinant = a1 * b2 - a2 * b1 ; if ( determinant == 0 ) { return new Point ( double . MaxValue , double . MaxValue ) ; } else { double x = ( b2 * c1 - b1 * c2 ) / determinant ; double y = ( a1 * c2 - a2 * c1 ) / determinant ; return new Point ( x , y ) ; } } public static void Main ( string [ ] args ) { Point A = new Point ( 1 , 1 ) ; Point B = new Point ( 4 , 4 ) ; Point C = new Point ( 1 , 8 ) ; Point D = new Point ( 2 , 4 ) ; Point intersection = lineLineIntersection ( A , B , C , D ) ; if ( intersection . x == double . MaxValue && intersection . y == double . MaxValue ) { Console . WriteLine ( " The ▁ given ▁ lines ▁ AB ▁ and ▁ CD ▁ are ▁ parallel . " ) ; } else { Console . Write ( " The ▁ intersection ▁ of ▁ the ▁ given ▁ lines ▁ AB ▁ " + " and ▁ CD ▁ is : ▁ " ) ; Point . displayPoint ( intersection ) ; } } }
Minimum revolutions to move center of a circle to a target | C # program to find minimum number of revolutions to reach a target center ; Minimum revolutions to move center from ( x1 , y1 ) to ( x2 , y2 ) ; Driver Program to test above function
using System ; class GFG { static double minRevolutions ( double r , int x1 , int y1 , int x2 , int y2 ) { double d = Math . Sqrt ( ( x1 - x2 ) * ( x1 - x2 ) + ( y1 - y2 ) * ( y1 - y2 ) ) ; return Math . Ceiling ( d / ( 2 * r ) ) ; } public static void Main ( ) { int r = 2 , x1 = 0 , y1 = 0 ; int x2 = 0 , y2 = 4 ; Console . Write ( ( int ) minRevolutions ( r , x1 , y1 , x2 , y2 ) ) ; } }
Find all sides of a right angled triangle from given hypotenuse and area | Set 1 | C # program to get right angle triangle , given hypotenuse and area of triangle ; limit for float comparison ; Utility method to get area of right angle triangle , given base and hypotenuse ; Prints base and height of triangle using hypotenuse and area information ; maximum area will be obtained when base and height are equal ( = sqrt ( h * h / 2 ) ) ; if given area itself is larger than maxArea then no solution is possible ; binary search for base ; get height by pythagorean rule ; Driver code to test above methods
using System ; public class GFG { static double eps = ( double ) 1e-6 ; static double getArea ( double base1 , double hypotenuse ) { double height = Math . Sqrt ( hypotenuse * hypotenuse - base1 * base1 ) ; return 0.5 * base1 * height ; } static void printRightAngleTriangle ( int hypotenuse , int area ) { int hsquare = hypotenuse * hypotenuse ; double sideForMaxArea = Math . Sqrt ( hsquare / 2.0 ) ; double maxArea = getArea ( sideForMaxArea , hypotenuse ) ; if ( area > maxArea ) { Console . Write ( " Not ▁ possible " ) ; return ; } double low = 0.0 ; double high = sideForMaxArea ; double base1 = 0 ; while ( Math . Abs ( high - low ) > eps ) { base1 = ( low + high ) / 2.0 ; if ( getArea ( base1 , hypotenuse ) >= area ) { high = base1 ; } else { low = base1 ; } } double height = Math . Sqrt ( hsquare - base1 * base1 ) ; Console . WriteLine ( Math . Round ( base1 ) + " ▁ " + Math . Round ( height ) ) ; } static public void Main ( ) { int hypotenuse = 5 ; int area = 6 ; printRightAngleTriangle ( hypotenuse , area ) ; } }
Circle and Lattice Points | C # program to find countLattice points on a circle ; Function to count Lattice points on a circle ; Initialize result as 4 for ( r , 0 ) , ( - r . 0 ) , ( 0 , r ) and ( 0 , - r ) ; Check every value that can be potential x ; Find a potential y ; checking whether square root is an integer or not . Count increments by 4 for four different quadrant values ; Driver code
using System ; class GFG { static int countLattice ( int r ) { if ( r <= 0 ) return 0 ; int result = 4 ; for ( int x = 1 ; x < r ; x ++ ) { int ySquare = r * r - x * x ; int y = ( int ) Math . Sqrt ( ySquare ) ; if ( y * y == ySquare ) result += 4 ; } return result ; } public static void Main ( ) { int r = 5 ; Console . Write ( countLattice ( r ) ) ; } }
Count of subarrays of size K with average at least M | C # program for the above approach ; Driver Code ; Function to count the subarrays of size K having average at least M ; Stores the resultant count of subarray ; Stores the sum of subarrays of size K ; Add the values of first K elements to the sum ; Increment the count if the current subarray is valid ; Traverse the given array ; Find the updated sum ; Check if current subarray is valid or not ; Return the count of subarrays
using System ; public class GFG { public static void Main ( String [ ] args ) { int [ ] arr = { 3 , 6 , 3 , 2 , 1 , 3 , 9 } ; int K = 2 , M = 4 ; Console . WriteLine ( countSubArrays ( arr , K , M ) ) ; } public static int countSubArrays ( int [ ] arr , int K , int M ) { int count = 0 ; int sum = 0 ; for ( int i = 0 ; i < K ; i ++ ) { sum += arr [ i ] ; } if ( sum >= K * M ) count ++ ; for ( int i = K ; i < arr . Length ; i ++ ) { sum += ( arr [ i ] - arr [ i - K ] ) ; if ( sum >= K * M ) count ++ ; } return count ; } }
Count of Ks in the Array for a given range of indices after array updates for Q queries | C # program for the above approach ; Function to perform all the queries ; Stores the count of 0 s ; Count the number of 0 s for query of type 1 ; Update the array element for query of type 2 ; Driver Code
using System ; public class GFG { static void performQueries ( int n , int q , int k , int [ ] arr , int [ , ] query ) { for ( int i = 1 ; i <= q ; i ++ ) { int count = 0 ; if ( query [ i - 1 , 0 ] == 1 ) { for ( int j = query [ i - 1 , 1 ] ; j <= query [ i - 1 , 2 ] ; j ++ ) { if ( arr [ j ] == k ) count ++ ; } Console . WriteLine ( count ) ; } else { arr [ query [ i - 1 , 1 ] ] = query [ i - 1 , 2 ] ; } } } public static void Main ( string [ ] args ) { int [ ] arr = { 9 , 5 , 7 , 6 , 9 , 0 , 0 , 0 , 0 , 5 , 6 , 7 , 3 , 9 , 0 , 7 , 0 , 9 , 0 } ; int Q = 5 ; int [ , ] query = { { 1 , 5 , 14 } , { 2 , 6 , 1 } , { 1 , 0 , 8 } , { 2 , 13 , 0 } , { 1 , 6 , 18 } } ; int N = arr . Length ; int K = 0 ; performQueries ( N , Q , K , arr , query ) ; } }
Minimum count of consecutive integers till N whose bitwise AND is 0 with N | C # program for the above approach ; Function to count the minimum count of integers such that bitwise AND of that many consecutive elements is equal to 0 ; Stores the binary representation of N ; Stores the MSB bit ; Stores the count of numbers ; Return res ; Driver Code ; Given Input ; Function Call
using System ; using System . Collections . Generic ; public class GFG { static int count ( int N ) { String a = Convert . ToString ( N , 2 ) ; int m = a . Length - 1 ; int res = ( int ) ( N - ( Math . Pow ( 2 , m ) - 1 ) ) ; return res ; } public static void Main ( String [ ] args ) { int N = 18 ; Console . WriteLine ( count ( N ) ) ; } }