text
stringlengths 17
3.65k
| code
stringlengths 60
5.26k
|
---|---|
Given a large number , check if a subsequence of digits is divisible by 8 | C # program to check if given String has a subsequence divisible by 8 ; Driver code ; Map key will be tens place digit of number that is divisible by 8 and value will be units place digit ; For filling the map let start with initial value 8 ; Key is digit at tens place and value is digit at units place mp . Add ( { key , value } ) ; Create a hash to check if we visited a number ; Iterate from last index to 0 th index ; If 8 is present in String then 8 divided 8 hence print yes ; Considering present character as the second digit of two digits no we check if the value of this key is marked in hash or not If marked then we a have a number divisible by 8 ; If no subsequence divisible by 8
|
using System ; using System . Collections . Generic ; class GFG { public static void Main ( String [ ] args ) { String str = "129365" ; Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; int no = 8 ; while ( no < 100 ) { no = no + 8 ; if ( mp . ContainsKey ( ( no / 10 ) % 10 ) ) mp [ ( no / 10 ) % 10 ] = no % 10 ; else mp . Add ( ( no / 10 ) % 10 , no % 10 ) ; } bool [ ] visited = new bool [ 10 ] ; int i ; for ( i = str . Length - 1 ; i >= 0 ; i -- ) { if ( str [ i ] == '8' ) { Console . Write ( " Yes " ) ; break ; } if ( visited [ mp [ str [ i ] - '0' ] ] ) { Console . Write ( " Yes " ) ; break ; } visited [ str [ i ] - '0' ] = true ; } if ( i == - 1 ) Console . Write ( " No " ) ; } }
|
Length of Longest Balanced Subsequence | C # program to find length of the longest balanced subsequence . ; Considering all balanced substrings of length 2 ; Considering all other substrings ; Driver Code
|
using System ; class GFG { static int maxLength ( String s , int n ) { int [ , ] dp = new int [ n , n ] ; for ( int i = 0 ; i < n - 1 ; i ++ ) if ( s [ i ] == ' ( ' && s [ i + 1 ] == ' ) ' ) dp [ i , i + 1 ] = 2 ; for ( int l = 2 ; l < n ; l ++ ) { for ( int i = 0 , j = l ; j < n ; i ++ , j ++ ) { if ( s [ i ] == ' ( ' && s [ j ] == ' ) ' ) dp [ i , j ] = 2 + dp [ i + 1 , j - 1 ] ; for ( int k = i ; k < j ; k ++ ) dp [ i , j ] = Math . Max ( dp [ i , j ] , dp [ i , k ] + dp [ k + 1 , j ] ) ; } } return dp [ 0 , n - 1 ] ; } public static void Main ( ) { string s = " ( ) ( ( ( ( ( ( ) " ; int n = s . Length ; Console . WriteLine ( maxLength ( s , n ) ) ; } }
|
Maximum sum bitonic subarray | C # implementation to find the maximum sum bitonic subarray ; Function to find the maximum sum bitonic subarray . ; To store the maximum sum bitonic subarray ; Find the longest increasing subarray starting at i . ; Now we know that a [ i . . j ] is an increasing subarray . Remove non - positive elements from the left side as much as possible . ; Find the longest decreasing subarray starting at j . ; Now we know that a [ j . . k ] is a decreasing subarray . Remove non - positive elements from the right side as much as possible . last is needed to keep the last seen element . ; Compute the max sum of the increasing part . ; Compute the max sum of the decreasing part . ; The overall max sum is the sum of both parts minus the peak element , because it was counted twice . ; If the next element is equal to the current , i . e . arr [ i + 1 ] == arr [ i ] , last == i . To ensure the algorithm has progress , get the max of last and i + 1. ; Required maximum sum ; Driver code ; The example from the article , the answer is 19. ; Always increasing , the answer is 15. ; Always decreasing , the answer is 15. ; All are equal , the answer is 5. ; The whole array is bitonic , but the answer is 7. ; The answer is 4 ( the tail ) .
|
using System ; class GFG { static int find_partial_sum ( int [ ] arr , int start , int end ) { int sum = 0 ; for ( int i = start ; i < end ; i ++ ) sum += arr [ i ] ; return sum ; } static int maxSumBitonicSubArr ( int [ ] arr , int n ) { int max_sum = - 1000000 ; int i = 0 ; while ( i < n ) { int j = i ; while ( j + 1 < n && arr [ j ] < arr [ j + 1 ] ) j ++ ; while ( i < j && arr [ i ] <= 0 ) i ++ ; int k = j ; while ( k + 1 < n && arr [ k ] > arr [ k + 1 ] ) k ++ ; int last = k ; while ( k > j && arr [ k ] <= 0 ) k -- ; int sum_inc = find_partial_sum ( arr , i , j + 1 ) ; int sum_dec = find_partial_sum ( arr , j , k + 1 ) ; int sum_all = sum_inc + sum_dec - arr [ j ] ; max_sum = Math . Max ( Math . Max ( max_sum , sum_inc ) , Math . Max ( sum_dec , sum_all ) ) ; i = Math . Max ( last , i + 1 ) ; } return max_sum ; } public static void Main ( ) { int [ ] arr = { 5 , 3 , 9 , 2 , 7 , 6 , 4 } ; int n = arr . Length ; Console . WriteLine ( " Maximum β sum β = β " + maxSumBitonicSubArr ( arr , n ) ) ; int [ ] arr2 = { 1 , 2 , 3 , 4 , 5 } ; int n2 = arr2 . Length ; Console . WriteLine ( " Maximum β sum β = β " + maxSumBitonicSubArr ( arr2 , n2 ) ) ; int [ ] arr3 = { 5 , 4 , 3 , 2 , 1 } ; int n3 = arr3 . Length ; Console . WriteLine ( " Maximum β sum β = β " + maxSumBitonicSubArr ( arr3 , n3 ) ) ; int [ ] arr4 = { 5 , 5 , 5 , 5 } ; int n4 = arr4 . Length ; Console . WriteLine ( " Maximum β sum β = β " + maxSumBitonicSubArr ( arr4 , n4 ) ) ; int [ ] arr5 = { - 1 , 0 , 1 , 2 , 3 , 1 , 0 , - 1 , - 10 } ; int n5 = arr5 . Length ; Console . WriteLine ( " Maximum β sum β = β " + maxSumBitonicSubArr ( arr5 , n5 ) ) ; int [ ] arr6 = { - 1 , 0 , 1 , 2 , 0 , - 1 , - 2 , 0 , 1 , 3 } ; int n6 = arr6 . Length ; Console . WriteLine ( " Maximum β sum β = β " + maxSumBitonicSubArr ( arr6 , n6 ) ) ; } }
|
Smallest sum contiguous subarray | C # implementation to find the smallest sum contiguous subarray ; function to find the smallest sum contiguous subarray ; to store the minimum value that is ending up to the current index ; to store the minimum value encountered so far ; traverse the array elements ; if min_ending_here > 0 , then it could not possibly contribute to the minimum sum further ; else add the value arr [ i ] to min_ending_here ; update min_so_far ; required smallest sum contiguous subarray value ; Driver method
|
using System ; class GFG { static int smallestSumSubarr ( int [ ] arr , int n ) { int min_ending_here = 2147483647 ; int min_so_far = 2147483647 ; for ( int i = 0 ; i < n ; i ++ ) { if ( min_ending_here > 0 ) min_ending_here = arr [ i ] ; else min_ending_here += arr [ i ] ; min_so_far = Math . Min ( min_so_far , min_ending_here ) ; } return min_so_far ; } public static void Main ( ) { int [ ] arr = { 3 , - 4 , 2 , - 3 , - 1 , 7 , - 5 } ; int n = arr . Length ; Console . Write ( " Smallest β sum : β " + smallestSumSubarr ( arr , n ) ) ; } }
|
n | C # code to find nth number with digits 0 , 1 , 2 , 3 , 4 , 5 ; If the Number is less than 6 return the number as it is . ; Call the function again and again the get the desired result . And convert the number to base 6. ; Decrease the Number by 1 and Call ans function to convert N to base 6 ; Driver code
|
using System ; public class GFG { static int ans ( int n ) { if ( n < 6 ) { return n ; } return n % 6 + 10 * ( ans ( n / 6 ) ) ; } static int getSpecialNumber ( int N ) { return ans ( -- N ) ; } public static void Main ( String [ ] args ) { int N = 17 ; int answer = getSpecialNumber ( N ) ; Console . WriteLine ( answer ) ; } }
|
Paper Cut into Minimum Number of Squares | Set 2 | C # program to find minimum number of squares to cut a paper using Dynamic Programming ; Returns min number of squares needed ; Initializing max values to vertical_min and horizontal_min ; N = 11 & M = 13 is a special case ; If the given rectangle is already a square ; If the answer for the given rectangle is previously calculated return that answer ; The rectangle is cut horizontally and vertically into two parts and the cut with minimum value is found for every recursive call . ; Calculating the minimum answer for the rectangles with width equal to n and length less than m for finding the cut point for the minimum answer ; Calculating the minimum answer for the rectangles with width less than n and length equal to m for finding the cut point for the minimum answer ; Minimum of the vertical cut or horizontal cut to form a square is the answer ; Driver code ; Function call
|
using System ; class GFG { static int [ , ] dp = new int [ 300 , 300 ] ; static int minimumSquare ( int m , int n ) { int vertical_min = int . MaxValue ; int horizontal_min = int . MaxValue ; if ( n == 13 && m == 11 ) return 6 ; if ( m == 13 && n == 11 ) return 6 ; if ( m == n ) return 1 ; if ( dp [ m , n ] != 0 ) return dp [ m , n ] ; for ( int i = 1 ; i <= m / 2 ; i ++ ) { horizontal_min = Math . Min ( minimumSquare ( i , n ) + minimumSquare ( m - i , n ) , horizontal_min ) ; } for ( int j = 1 ; j <= n / 2 ; j ++ ) { vertical_min = Math . Min ( minimumSquare ( m , j ) + minimumSquare ( m , n - j ) , vertical_min ) ; } dp [ m , n ] = Math . Min ( vertical_min , horizontal_min ) ; return dp [ m , n ] ; } public static void Main ( ) { int m = 30 , n = 35 ; Console . WriteLine ( minimumSquare ( m , n ) ) ; } }
|
Number of n | C # program To calculate Number of n - digits non - decreasing integers ; Returns factorial of n ; returns nCr ; Driver code
|
using System ; class GFG { static long fact ( int n ) { long res = 1 ; for ( int i = 2 ; i <= n ; i ++ ) res = res * i ; return res ; } static long nCr ( int n , int r ) { return fact ( n ) / ( fact ( r ) * fact ( n - r ) ) ; } public static void Main ( String [ ] args ) { int n = 2 ; Console . Write ( " Number β of β Non - Decreasing β digits : β " + nCr ( n + 9 , 9 ) ) ; } }
|
Painting Fence Algorithm | C # program for Painting Fence Algorithm ; Returns count of ways to color k posts using k colors ; There are k ways to color first post ; There are 0 ways for single post to violate ( same color_ and k ways to not violate ( different color ) ; Fill for 2 posts onwards ; Current same is same as previous diff ; We always have k - 1 choices for next post ; Total choices till i . ; Driver code
|
using System ; class GFG { static long countWays ( int n , int k ) { long total = k ; int mod = 1000000007 ; long same = 0 , diff = k ; for ( int i = 2 ; i <= n ; i ++ ) { same = diff ; diff = total * ( k - 1 ) ; diff = diff % mod ; total = ( same + diff ) % mod ; } return total ; } static void Main ( ) { int n = 3 , k = 2 ; Console . Write ( countWays ( n , k ) ) ; } }
|
Sum of all substrings of a string representing a number | Set 2 ( Constant Extra Space ) | C # program to print sum of all substring of a number represented as a string ; Returns sum of all substring of num ; Initialize result ; Here traversing the array in reverse order . Initializing loop from last element . mf is multiplying factor . ; Each time sum is added to its previous sum . Multiplying the three factors as explained above . s [ i ] - '0' is done to convert char to int . ; Making new multiplying factor as explained above . ; Driver code to test above methods
|
using System ; public class GFG { public static long sumOfSubstrings ( string num ) { long sum = 0 ; long mf = 1 ; for ( int i = num . Length - 1 ; i >= 0 ; i -- ) { sum += ( num [ i ] - '0' ) * ( i + 1 ) * mf ; mf = mf * 10 + 1 ; } return sum ; } public static void Main ( ) { string num = "6759" ; Console . WriteLine ( sumOfSubstrings ( num ) ) ; } }
|
Largest sum subarray with at | C # program to find largest subarray sum with at - least k elements in it . ; Returns maximum sum of a subarray with at - least k elements . ; maxSum [ i ] is going to store maximum sum till index i such that a [ i ] is part of the sum . ; We use Kadane 's algorithm to fill maxSum[] Below code is taken from method 3 of https:www.geeksforgeeks.org/largest-sum-contiguous-subarray/ ; Sum of first k elements ; Use the concept of sliding window ; Compute sum of k elements ending with a [ i ] . ; Update result if required ; Include maximum sum till [ i - k ] also if it increases overall max . ; Driver method
|
using System ; class Test { static int maxSumWithK ( int [ ] a , int n , int k ) { int [ ] maxSum = new int [ n ] ; maxSum [ 0 ] = a [ 0 ] ; int curr_max = a [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { curr_max = Math . Max ( a [ i ] , curr_max + a [ i ] ) ; maxSum [ i ] = curr_max ; } int sum = 0 ; for ( int i = 0 ; i < k ; i ++ ) sum += a [ i ] ; int result = sum ; for ( int i = k ; i < n ; i ++ ) { sum = sum + a [ i ] - a [ i - k ] ; result = Math . Max ( result , sum ) ; result = Math . Max ( result , sum + maxSum [ i - k ] ) ; } return result ; } public static void Main ( ) { int [ ] arr = { 1 , 2 , 3 , - 10 , - 3 } ; int k = 4 ; Console . Write ( maxSumWithK ( arr , arr . Length , k ) ) ; ; } }
|
Ways to sum to N using array elements with repetition allowed | C # implementation to count ways to sum up to a given value N ; method to count the total number of ways to sum up to ' N ' ; base case ; count ways for all values up to ' N ' and store the result ; if i >= arr [ j ] then accumulate count for value ' i ' as ways to form value ' i - arr [ j ] ' ; required number of ways ; Driver code
|
using System ; class Gfg { static int [ ] arr = { 1 , 5 , 6 } ; static int countWays ( int N ) { int [ ] count = new int [ N + 1 ] ; count [ 0 ] = 1 ; for ( int i = 1 ; i <= N ; i ++ ) for ( int j = 0 ; j < arr . Length ; j ++ ) if ( i >= arr [ j ] ) count [ i ] += count [ i - arr [ j ] ] ; return count [ N ] ; } public static void Main ( ) { int N = 7 ; Console . Write ( " Total β number β of β ways β = β " + countWays ( N ) ) ; } }
|
Sequences of given length where every element is more than or equal to twice of previous | C # program to count total number of special sequences of length n where every element is more than or equal to twice of previous ; Recursive function to find the number of special sequences ; A special sequence cannot exist if length n is more than the maximum value m . ; If n is 0 , found an empty special sequence ; There can be two possibilities : ( 1 ) Reduce last element value ( 2 ) Consider last element as m and reduce number of terms ; Driver code
|
using System ; class GFG { static int getTotalNumberOfSequences ( int m , int n ) { if ( m < n ) return 0 ; if ( n == 0 ) return 1 ; return getTotalNumberOfSequences ( m - 1 , n ) + getTotalNumberOfSequences ( m / 2 , n - 1 ) ; } public static void Main ( ) { int m = 10 ; int n = 4 ; Console . Write ( " Total β number β of β possible β sequences β " + getTotalNumberOfSequences ( m , n ) ) ; } }
|
Sequences of given length where every element is more than or equal to twice of previous | Efficient C # program to count total number of special sequences of length n where ; DP based function to find the number of special sequences ; define T and build in bottom manner to store number of special sequences of length n and maximum value m ; Base case : If length of sequence is 0 or maximum value is 0 , there cannot exist any special sequence ; if length of sequence is more than the maximum value , special sequence cannot exist ; If length of sequence is 1 then the number of special sequences is equal to the maximum value For example with maximum value 2 and length 1 , there can be 2 special sequences { 1 } , { 2 } ; otherwise calculate ; Driver Code
|
using System ; class Sequences { static int getTotalNumberOfSequences ( int m , int n ) { int [ , ] T = new int [ m + 1 , n + 1 ] ; for ( int i = 0 ; i < m + 1 ; i ++ ) { for ( int j = 0 ; j < n + 1 ; j ++ ) { if ( i == 0 j == 0 ) T [ i , j ] = 0 ; else if ( i < j ) T [ i , j ] = 0 ; else if ( j == 1 ) T [ i , j ] = i ; else T [ i , j ] = T [ i - 1 , j ] + T [ i / 2 , j - 1 ] ; } } return T [ m , n ] ; } public static void Main ( ) { int m = 10 ; int n = 4 ; Console . WriteLine ( " Total β number β of β possible β sequences β " + getTotalNumberOfSequences ( m , n ) ) ; } }
|
Minimum number of deletions and insertions to transform one string into another | Dynamic Programming C # implementation to find minimum number of deletions and insertions ; Returns length of length common subsequence for str1 [ 0. . m - 1 ] , str2 [ 0. . n - 1 ] ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains length of LCS of str1 [ 0. . i - 1 ] and str2 [ 0. . j - 1 ] ; L [ m ] [ n ] contains length of LCS for X [ 0. . n - 1 ] and Y [ 0. . m - 1 ] ; function to find minimum number of deletions and insertions ; Driver code ; Function Call
|
using System ; class GFG { static int lcs ( string str1 , string str2 , int m , int n ) { int [ , ] L = new int [ m + 1 , n + 1 ] ; int i , j ; for ( i = 0 ; i <= m ; i ++ ) { for ( j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) L [ i , j ] = 0 ; else if ( str1 [ i - 1 ] == str2 [ j - 1 ] ) L [ i , j ] = L [ i - 1 , j - 1 ] + 1 ; else L [ i , j ] = Math . Max ( L [ i - 1 , j ] , L [ i , j - 1 ] ) ; } } return L [ m , n ] ; } static void printMinDelAndInsert ( string str1 , string str2 ) { int m = str1 . Length ; int n = str2 . Length ; int len = lcs ( str1 , str2 , m , n ) ; Console . Write ( " Minimum β number β of β " + " deletions β = β " ) ; Console . WriteLine ( m - len ) ; Console . Write ( " Minimum β number β of β " + " insertions β = β " ) ; Console . Write ( n - len ) ; } public static void Main ( ) { string str1 = new string ( " heap " ) ; string str2 = new string ( " pea " ) ; printMinDelAndInsert ( str1 , str2 ) ; } }
|
Minimum number of deletions to make a sorted sequence | C # implementation to find minimum number of deletions to make a sorted sequence ; lis ( ) returns the length of the longest increasing subsequence in arr [ ] of size n ; Initialize LIS values for all indexes ; Compute optimized LIS values in bottom up manner ; Pick resultimum of all LIS values ; function to calculate minimum number of deletions ; Find longest increasing subsequence ; After removing elements other than the lis , we get sorted sequence . ; Driver Code
|
using System ; class GfG { static int lis ( int [ ] arr , int n ) { int result = 0 ; int [ ] lis = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) lis [ i ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) for ( int j = 0 ; j < i ; j ++ ) if ( arr [ i ] > arr [ j ] && lis [ i ] < lis [ j ] + 1 ) lis [ i ] = lis [ j ] + 1 ; for ( int i = 0 ; i < n ; i ++ ) if ( result < lis [ i ] ) result = lis [ i ] ; return result ; } static int minimumNumberOfDeletions ( int [ ] arr , int n ) { int len = lis ( arr , n ) ; return ( n - len ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 30 , 40 , 2 , 5 , 1 , 7 , 45 , 50 , 8 } ; int n = arr . Length ; Console . Write ( " Minimum β number β of " + " β deletions β = β " + minimumNumberOfDeletions ( arr , n ) ) ; } }
|
Clustering / Partitioning an array such that sum of square differences is minimum | C # program to find minimum cost k partitions of array . ; Returns minimum cost of partitioning a [ ] in k clusters . ; Create a dp [ ] [ ] table and initialize all values as infinite . dp [ i ] [ j ] is going to store optimal partition cost for arr [ 0. . i - 1 ] and j partitions ; Fill dp [ ] [ ] in bottom up manner ; Current ending position ( After i - th iteration result for a [ 0. . i - 1 ] is computed . ; j is number of partitions ; Picking previous partition for current i . ; Driver code
|
using System ; class GFG { static int inf = 1000000000 ; static int minCost ( int [ ] a , int n , int k ) { int [ , ] dp = new int [ n + 1 , k + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) for ( int j = 0 ; j <= k ; j ++ ) dp [ i , j ] = inf ; dp [ 0 , 0 ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) for ( int j = 1 ; j <= k ; j ++ ) for ( int m = i - 1 ; m >= 0 ; m -- ) dp [ i , j ] = Math . Min ( dp [ i , j ] , dp [ m , j - 1 ] + ( a [ i - 1 ] - a [ m ] ) * ( a [ i - 1 ] - a [ m ] ) ) ; return dp [ n , k ] ; } public static void Main ( ) { int k = 2 ; int [ ] a = { 1 , 5 , 8 , 10 } ; int n = a . Length ; Console . Write ( minCost ( a , n , k ) ) ; } }
|
Minimum number of deletions to make a string palindrome | C # implementation to find minimum number of deletions to make a string palindromic ; Returns the length of the longest palindromic subsequence in ' str ' ; Create a table to store results of subproblems ; Strings of length 1 are palindrome of length 1 ; Build the table . Note that the lower diagonal values of table are useless and not filled in the process . c1 is length of substring ; length of longest palindromic subsequence ; function to calculate minimum number of deletions ; Find longest palindromic subsequence ; After removing characters other than the lps , we get palindrome . ; Driver Code
|
using System ; class GFG { static int lps ( String str ) { int n = str . Length ; int [ , ] L = new int [ n , n ] ; for ( int i = 0 ; i < n ; i ++ ) L [ i , i ] = 1 ; for ( int cl = 2 ; cl <= n ; cl ++ ) { for ( int i = 0 ; i < n - cl + 1 ; i ++ ) { int j = i + cl - 1 ; if ( str [ i ] == str [ j ] && cl == 2 ) L [ i , j ] = 2 ; else if ( str [ i ] == str [ j ] ) L [ i , j ] = L [ i + 1 , j - 1 ] + 2 ; else L [ i , j ] = Math . Max ( L [ i , j - 1 ] , L [ i + 1 , j ] ) ; } } return L [ 0 , n - 1 ] ; } static int minimumNumberOfDeletions ( string str ) { int n = str . Length ; int len = lps ( str ) ; return ( n - len ) ; } public static void Main ( ) { string str = " geeksforgeeks " ; Console . Write ( " Minimum β number β of " + " β deletions β = β " + minimumNumberOfDeletions ( str ) ) ; } }
|
Temple Offerings | Program to find minimum total offerings required ; Returns minimum offerings required ; Go through all temples one by one ; Go to left while height keeps increasing ; Go to right while height keeps increasing ; This temple should offer maximum of two values to follow the rule . ; Driver code
|
using System ; class GFG { static int offeringNumber ( int n , int [ ] templeHeight ) { for ( int i = 0 ; i < n ; ++ i ) { int left = 0 , right = 0 ; for ( int j = i - 1 ; j >= 0 ; -- j ) { if ( templeHeight [ j ] < templeHeight [ j + 1 ] ) ++ left ; else break ; } for ( int j = i + 1 ; j < n ; ++ j ) { if ( templeHeight [ j ] < templeHeight [ j - 1 ] ) ++ right ; else break ; } sum += Math . Max ( right , left ) + 1 ; } return sum ; } static public void Main ( ) { int [ ] arr1 = { 1 , 2 , 2 } ; Console . WriteLine ( offeringNumber ( 3 , arr1 ) ) ; int [ ] arr2 = { 1 , 4 , 3 , 6 , 2 , 1 } ; Console . WriteLine ( offeringNumber ( 6 , arr2 ) ) ; } }
|
Subset with sum divisible by m | C # program to check if there is a subset with sum divisible by m . ; Returns true if there is a subset of arr [ ] with sum divisible by m ; This array will keep track of all the possible sum ( after modulo m ) which can be made using subsets of arr [ ] initialising boolean array with all false ; we 'll loop through all the elements of arr[] ; anytime we encounter a sum divisible by m , we are done ; To store all the new encountered sum ( after modulo ) . It is used to make sure that arr [ i ] is added only to those entries for which DP [ j ] was true before current iteration . ; For each element of arr [ ] , we loop through all elements of DP table from 1 to m and we add current element i . e . , arr [ i ] to all those elements which are true in DP table ; if an element is true in DP table ; We update it in temp and update to DP once loop of j is over ; Updating all the elements of temp to DP table since iteration over j is over ; Also since arr [ i ] is a single element subset , arr [ i ] % m is one of the possible sum ; driver code
|
using System ; class GFG { static bool modularSum ( int [ ] arr , int n , int m ) { if ( n > m ) return true ; bool [ ] DP = new bool [ m ] ; for ( int l = 0 ; l < DP . Length ; l ++ ) DP [ l ] = false ; for ( int i = 0 ; i < n ; i ++ ) { if ( DP [ 0 ] ) return true ; bool [ ] temp = new bool [ m ] ; for ( int l = 0 ; l < temp . Length ; l ++ ) temp [ l ] = false ; for ( int j = 0 ; j < m ; j ++ ) { if ( DP [ j ] == true ) { if ( DP [ ( j + arr [ i ] ) % m ] == false ) temp [ ( j + arr [ i ] ) % m ] = true ; } } for ( int j = 0 ; j < m ; j ++ ) if ( temp [ j ] ) DP [ j ] = true ; DP [ arr [ i ] % m ] = true ; } return DP [ 0 ] ; } public static void Main ( ) { int [ ] arr = { 1 , 7 } ; int n = arr . Length ; int m = 5 ; if ( modularSum ( arr , n , m ) ) Console . Write ( " YES STRNEWLINE " ) ; else Console . Write ( " NO STRNEWLINE " ) ; } }
|
Maximum sum of a path in a Right Number Triangle | C # program to print maximum sum in a right triangle of numbers ; function to find maximum sum path ; Adding the element of row 1 to both the elements of row 2 to reduce a step from the loop ; Traverse remaining rows ; Loop to traverse columns ; tri [ i ] would store the possible combinations of sum of the paths ; array at n - 1 index ( tri [ i ] ) stores all possible adding combination , finding the maximum one out of them ; Driver Code
|
using System ; class GFG { static int maxSum ( int [ , ] tri , int n ) { if ( n > 1 ) tri [ 1 , 1 ] = tri [ 1 , 1 ] + tri [ 0 , 0 ] ; tri [ 1 , 0 ] = tri [ 1 , 0 ] + tri [ 0 , 0 ] ; for ( int i = 2 ; i < n ; i ++ ) { tri [ i , 0 ] = tri [ i , 0 ] + tri [ i - 1 , 0 ] ; tri [ i , i ] = tri [ i , i ] + tri [ i - 1 , i - 1 ] ; for ( int j = 1 ; j < i ; j ++ ) { if ( tri [ i , j ] + tri [ i - 1 , j - 1 ] >= tri [ i , j ] + tri [ i - 1 , j ] ) tri [ i , j ] = tri [ i , j ] + tri [ i - 1 , j - 1 ] ; else tri [ i , j ] = tri [ i , j ] + tri [ i - 1 , j ] ; } } int max = tri [ n - 1 , 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { if ( max < tri [ n - 1 , i ] ) max = tri [ n - 1 , i ] ; } return max ; } public static void Main ( ) { int [ , ] tri = { { 1 , 0 , 0 } , { 2 , 1 , 0 } , { 3 , 3 , 2 } } ; Console . Write ( maxSum ( tri , 3 ) ) ; } }
|
Modify array to maximize sum of adjacent differences | C # program to get maximum consecutive element difference sum ; Returns maximum - difference - sum with array modifications allowed . ; Initialize dp [ ] [ ] with 0 values . ; for [ i + 1 ] [ 0 ] ( i . e . current modified value is 1 ) , choose maximum from dp [ i ] [ 0 ] + abs ( 1 - 1 ) = dp [ i ] [ 0 ] and dp [ i ] [ 1 ] + abs ( 1 - arr [ i ] ) ; for [ i + 1 ] [ 1 ] ( i . e . current modified value is arr [ i + 1 ] ) , choose maximum from dp [ i ] [ 0 ] + abs ( arr [ i + 1 ] - 1 ) and dp [ i ] [ 1 ] + abs ( arr [ i + 1 ] - arr [ i ] ) ; Driver code
|
using System ; class GFG { static int maximumDifferenceSum ( int [ ] arr , int N ) { int [ , ] dp = new int [ N , 2 ] ; for ( int i = 0 ; i < N ; i ++ ) dp [ i , 0 ] = dp [ i , 1 ] = 0 ; for ( int i = 0 ; i < ( N - 1 ) ; i ++ ) { dp [ i + 1 , 0 ] = Math . Max ( dp [ i , 0 ] , dp [ i , 1 ] + Math . Abs ( 1 - arr [ i ] ) ) ; dp [ i + 1 , 1 ] = Math . Max ( dp [ i , 0 ] + Math . Abs ( arr [ i + 1 ] - 1 ) , dp [ i , 1 ] + Math . Abs ( arr [ i + 1 ] - arr [ i ] ) ) ; } return Math . Max ( dp [ N - 1 , 0 ] , dp [ N - 1 , 1 ] ) ; } public static void Main ( ) { int [ ] arr = { 3 , 2 , 1 , 4 , 5 } ; int N = arr . Length ; Console . Write ( maximumDifferenceSum ( arr , N ) ) ; } }
|
Count of strings that can be formed using a , b and c under given constraints | C # program to count number of strings of n characters with ; n is total number of characters . bCount and cCount are counts of ' b ' and ' c ' respectively . ; Base cases ; if we had saw this combination previously ; Three cases , we choose , a or b or c In all three cases n decreases by 1. ; A wrapper over countStrUtil ( ) ; Driver code ; Total number of characters
|
using System ; class GFG { static int countStrUtil ( int [ , , ] dp , int n , int bCount = 1 , int cCount = 2 ) { if ( bCount < 0 cCount < 0 ) return 0 ; if ( n == 0 ) return 1 ; if ( bCount == 0 && cCount == 0 ) return 1 ; if ( dp [ n , bCount , cCount ] != - 1 ) return dp [ n , bCount , cCount ] ; int res = countStrUtil ( dp , n - 1 , bCount , cCount ) ; res += countStrUtil ( dp , n - 1 , bCount - 1 , cCount ) ; res += countStrUtil ( dp , n - 1 , bCount , cCount - 1 ) ; return ( dp [ n , bCount , cCount ] = res ) ; } static int countStr ( int n ) { int [ , , ] dp = new int [ n + 1 , 2 , 3 ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) for ( int j = 0 ; j < 2 ; j ++ ) for ( int k = 0 ; k < 3 ; k ++ ) dp [ i , j , k ] = - 1 ; return countStrUtil ( dp , n ) ; } static void Main ( ) { int n = 3 ; Console . Write ( countStr ( n ) ) ; } }
|
Probability of Knight to remain in the chessboard | C # program to find the probability of the Knight to remain inside the chessboard after taking exactly K number of steps ; size of the chessboard ; direction vector for the Knight ; returns true if the knight is inside the chessboard ; Bottom up approach for finding the probability to go out of chessboard . ; dp array ; for 0 number of steps , each position will have probability 1 ; for every number of steps s ; for every position ( x , y ) after s number of steps ; for every position reachable from ( x , y ) ; if this position lie inside the board ; store the result ; return the result ; Driver code ; number of steps ; Function Call
|
using System ; class GFG { static int N = 8 ; static int [ ] dx = { 1 , 2 , 2 , 1 , - 1 , - 2 , - 2 , - 1 } ; static int [ ] dy = { 2 , 1 , - 1 , - 2 , - 2 , - 1 , 1 , 2 } ; static bool inside ( int x , int y ) { return ( x >= 0 && x < N && y >= 0 && y < N ) ; } static double findProb ( int start_x , int start_y , int steps ) { double [ , , ] dp1 = new double [ N , N , steps + 1 ] ; for ( int i = 0 ; i < N ; ++ i ) for ( int j = 0 ; j < N ; ++ j ) dp1 [ i , j , 0 ] = 1 ; for ( int s = 1 ; s <= steps ; ++ s ) { for ( int x = 0 ; x < N ; ++ x ) { for ( int y = 0 ; y < N ; ++ y ) { double prob = 0.0 ; for ( int i = 0 ; i < 8 ; ++ i ) { int nx = x + dx [ i ] ; int ny = y + dy [ i ] ; if ( inside ( nx , ny ) ) prob += dp1 [ nx , ny , s - 1 ] / 8.0 ; } dp1 [ x , y , s ] = prob ; } } } return dp1 [ start_x , start_y , steps ] ; } static void Main ( ) { int K = 3 ; Console . WriteLine ( findProb ( 0 , 0 , K ) ) ; } }
|
Count of subarrays whose maximum element is greater than k | C # program to count number of subarrays whose maximum element is greater than K . ; Return number of subarrays whose maximum element is less than or equal to K . ; To store count of subarrays with all elements less than or equal to k . ; Traversing the array . ; If element is greater than k , ignore . ; Counting the subarray length whose each element is less than equal to k . ; Suming number of subarray whose maximum element is less than equal to k . ; Driver code
|
using System ; class GFG { static int countSubarray ( int [ ] arr , int n , int k ) { int s = 0 ; int i = 0 ; while ( i < n ) { if ( arr [ i ] > k ) { i ++ ; continue ; } int count = 0 ; while ( i < n && arr [ i ] <= k ) { i ++ ; count ++ ; } s += ( ( count * ( count + 1 ) ) / 2 ) ; } return ( n * ( n + 1 ) / 2 - s ) ; } public static void Main ( ) { int [ ] arr = { 1 , 2 , 3 } ; int k = 2 ; int n = arr . Length ; Console . WriteLine ( countSubarray ( arr , n , k ) ) ; } }
|
Sum of average of all subsets | C # program to get sum of average of all subsets ; Returns value of Binomial Coefficient C ( n , k ) ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; method returns sum of average of all subsets ; Initialize result ; Find sum of elements ; looping once for all subset of same size ; each element occurs nCr ( N - 1 , n - 1 ) times while considering subset of size n ; Driver code to test above methods
|
using System ; class GFG { static int nCr ( int n , int k ) { int [ , ] C = new int [ n + 1 , k + 1 ] ; int i , j ; for ( i = 0 ; i <= n ; i ++ ) { for ( j = 0 ; j <= Math . Min ( i , k ) ; j ++ ) { if ( j == 0 j == i ) C [ i , j ] = 1 ; else C [ i , j ] = C [ i - 1 , j - 1 ] + C [ i - 1 , j ] ; } } return C [ n , k ] ; } static double resultOfAllSubsets ( int [ ] arr , int N ) { double result = 0.0 ; int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) sum += arr [ i ] ; for ( int n = 1 ; n <= N ; n ++ ) result += ( double ) ( sum * ( nCr ( N - 1 , n - 1 ) ) ) / n ; return result ; } public static void Main ( ) { int [ ] arr = { 2 , 3 , 5 , 7 } ; int N = arr . Length ; Console . WriteLine ( resultOfAllSubsets ( arr , N ) ) ; } }
|
Maximum subsequence sum such that no three are consecutive | C # program to find the maximum sum such that no three are consecutive using recursion . ; Returns maximum subsequence sum such that no three elements are consecutive ; Base cases ( process first three elements ) ; Process rest of the elements We have three cases ; Driver code
|
using System ; class GFG { static int [ ] arr = { 100 , 1000 , 100 , 1000 , 1 } ; static int [ ] sum = new int [ 10000 ] ; static int maxSumWO3Consec ( int n ) { if ( sum [ n ] != - 1 ) return sum [ n ] ; if ( n == 0 ) return sum [ n ] = 0 ; if ( n == 1 ) return sum [ n ] = arr [ 0 ] ; if ( n == 2 ) return sum [ n ] = arr [ 1 ] + arr [ 0 ] ; return sum [ n ] = Math . Max ( Math . Max ( maxSumWO3Consec ( n - 1 ) , maxSumWO3Consec ( n - 2 ) + arr [ n ] ) , arr [ n ] + arr [ n - 1 ] + maxSumWO3Consec ( n - 3 ) ) ; } public static void Main ( String [ ] args ) { int n = arr . Length ; for ( int i = 0 ; i < sum . Length ; i ++ ) sum [ i ] = - 1 ; Console . WriteLine ( maxSumWO3Consec ( n ) ) ; } }
|
Maximum sum of pairs with specific difference | C # program to find maximum pair sum whose difference is less than K ; Method to return maximum sum we can get by finding less than K difference pairs ; Sort elements to ensure every i and i - 1 is closest possible pair ; To get maximum possible sum , iterate from largest to smallest , giving larger numbers priority over smaller numbers . ; Case I : Diff of arr [ i ] and arr [ i - 1 ] is less then K , add to maxSum Case II : Diff between arr [ i ] and arr [ i - 1 ] is not less then K , move to next i since with sorting we know , arr [ i ] - arr [ i - 1 ] < arr [ i ] - arr [ i - 2 ] and so on . ; Assuming only positive numbers . ; When a match is found skip this pair ; Driver Code
|
using System ; class GFG { static int maxSumPairWithDifferenceLessThanK ( int [ ] arr , int N , int k ) { int maxSum = 0 ; Array . Sort ( arr ) ; for ( int i = N - 1 ; i > 0 ; -- i ) { if ( arr [ i ] - arr [ i - 1 ] < k ) { maxSum += arr [ i ] ; maxSum += arr [ i - 1 ] ; -- i ; } } return maxSum ; } public static void Main ( ) { int [ ] arr = { 3 , 5 , 10 , 15 , 17 , 12 , 9 } ; int N = arr . Length ; int K = 4 ; Console . Write ( maxSumPairWithDifferenceLessThanK ( arr , N , K ) ) ; } }
|
Count digit groupings of a number with given constraints | C # program to count number of ways to group digits of a number such that sum of digits in every subgroup is less than or equal to its immediate right subgroup . ; Function to find the subgroups ; Terminating Condition ; sum of digits ; Traverse all digits from current position to rest of the length of string ; If forward_sum is greater than the previous sum , then call the method again ; Note : We pass current sum as previous sum ; Total number of subgroups till current position ; Driver Code
|
using System ; class GFG { static int countGroups ( int position , int previous_sum , int length , String num ) { if ( position == length ) return 1 ; int res = 0 ; int sum = 0 ; for ( int i = position ; i < length ; i ++ ) { sum += ( num [ i ] - '0' ) ; if ( sum >= previous_sum ) res += countGroups ( i + 1 , sum , length , num ) ; } return res ; } public static void Main ( ) { String num = "1119" ; int len = num . Length ; Console . Write ( countGroups ( 0 , 0 , len , num ) ) ; } }
|
Count digit groupings of a number with given constraints | C # program to count number of ways to group digits of a number such that sum of digits in every subgroup is less than or equal to its immediate right subgroup . ; Maximum length of input number string ; A memoization table to store results of subproblems length of string is 40 and maximum sum will be 9 * 40 = 360. ; Function to find the count of splits with given condition ; Terminating Condition ; If already evaluated for a given sub problem then return the value ; countGroups for current sub - group is 0 ; sum of digits ; Traverse all digits from current position to rest of the length of string ; If forward_sum is greater than the previous sum , then call the method again ; Note : We pass current sum as previous sum ; total number of subgroups till current position ; Driver Code ; Initialize dp table
|
using System ; class GFG { static int MAX = 40 ; static int [ , ] dp = new int [ MAX , 9 * MAX + 1 ] ; static int countGroups ( int position , int previous_sum , int length , char [ ] num ) { if ( position == length ) return 1 ; if ( dp [ position , previous_sum ] != - 1 ) return dp [ position , previous_sum ] ; dp [ position , previous_sum ] = 0 ; int res = 0 ; int sum = 0 ; for ( int i = position ; i < length ; i ++ ) { sum += ( num [ i ] - '0' ) ; if ( sum >= previous_sum ) res += countGroups ( i + 1 , sum , length , num ) ; } dp [ position , previous_sum ] = res ; return res ; } static void Main ( ) { char [ ] num = { '1' , '1' , '1' , '9' } ; int len = num . Length ; for ( int i = 0 ; i < MAX ; i ++ ) for ( int j = 0 ; j < 9 * MAX + 1 ; j ++ ) dp [ i , j ] = - 1 ; Console . Write ( countGroups ( 0 , 0 , len , num ) ) ; } }
|
A Space Optimized DP solution for 0 | C # program of a space optimized DP solution for 0 - 1 knapsack problem . ; val [ ] is for storing maximum profit for each weight wt [ ] is for storing weights n number of item W maximum capacity of bag dp [ W + 1 ] to store final result ; array to store final result dp [ i ] stores the profit with KnapSack capacity " i " ; initially profit with 0 to W KnapSack capacity is 0 ; iterate through all items ; traverse dp array from right to left ; above line finds out maximum of dp [ j ] ( excluding ith element value ) and val [ i ] + dp [ j - wt [ i ] ] ( including ith element value and the profit with " KnapSack β capacity β - β ith β element β weight " ) ; Driver code
|
using System ; class GFG { static int KnapSack ( int [ ] val , int [ ] wt , int n , int W ) { int [ ] dp = new int [ W + 1 ] ; for ( int i = 0 ; i < W + 1 ; i ++ ) dp [ i ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = W ; j >= wt [ i ] ; j -- ) dp [ j ] = Math . Max ( dp [ j ] , val [ i ] + dp [ j - wt [ i ] ] ) ; return dp [ W ] ; } public static void Main ( String [ ] args ) { int [ ] val = { 7 , 8 , 4 } ; int [ ] wt = { 3 , 8 , 6 } ; int W = 10 , n = 3 ; Console . WriteLine ( KnapSack ( val , wt , n , W ) ) ; } }
|
Find number of times a string occurs as a subsequence in given string | A Dynamic Programming based C # program to find the number of times the second string occurs in the first string , whether continuous or discontinuous ; Iterative DP function to find the number of times the second string occurs in the first string , whether continuous or discontinuous ; Create a table to store results of sub - problems ; If first string is empty ; If second string is empty ; Fill lookup [ ] [ ] in bottom up manner ; If last characters are same , we have two options - 1. consider last characters of both strings in solution 2. ignore last character of first string ; If last character are different , ignore last character of first string ; Driver Code
|
using System ; class GFG { static int count ( String a , String b ) { int m = a . Length ; int n = b . Length ; int [ , ] lookup = new int [ m + 1 , n + 1 ] ; for ( int i = 0 ; i <= n ; ++ i ) lookup [ 0 , i ] = 0 ; for ( int i = 0 ; i <= m ; ++ i ) lookup [ i , 0 ] = 1 ; for ( int i = 1 ; i <= m ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( a [ i - 1 ] == b [ j - 1 ] ) lookup [ i , j ] = lookup [ i - 1 , j - 1 ] + lookup [ i - 1 , j ] ; else lookup [ i , j ] = lookup [ i - 1 , j ] ; } } return lookup [ m , n ] ; } public static void Main ( ) { String a = " GeeksforGeeks " ; String b = " Gks " ; Console . WriteLine ( count ( a , b ) ) ; } }
|
Longest Geometric Progression | C # program to find length of the longest geometric progression in a given Set ; Returns length of the longest GP subset of Set [ ] ; Base cases ; Let us sort the Set first ; An entry L [ i , j ] in this table stores LLGP with Set [ i ] and Set [ j ] as first two elements of GP and j > i . ; Initialize result ( A single element is always a GP ) ; Initialize values of last column ; Consider every element as second element of GP ; Search for i and k for j ; Two cases when i , j and k don 't form a GP. ; i , j and k form GP , LLGP with i and j as first two elements is equal to LLGP with j and k as first two elements plus 1. L [ j , k ] must have been filled before as we run the loop from right side ; Update overall LLGP ; Change i and k to fill more L [ i , j ] values for current j ; If the loop was stopped due to k becoming more than n - 1 , set the remaining entries in column j as 1 or 2 based on divisibility of Set [ j ] by Set [ i ] ; Return result ; Driver code
|
using System ; class GFG { static int lenOfLongestGP ( int [ ] Set , int n ) { if ( n < 2 ) { return n ; } if ( n == 2 ) { return ( Set [ 1 ] % Set [ 0 ] == 0 ? 2 : 1 ) ; } Array . Sort ( Set ) ; int [ , ] L = new int [ n , n ] ; int llgp = 1 ; for ( int i = 0 ; i < n - 1 ; ++ i ) { if ( Set [ n - 1 ] % Set [ i ] == 0 ) { L [ i , n - 1 ] = 2 ; if ( 2 > llgp ) llgp = 2 ; } else { L [ i , n - 1 ] = 1 ; } } L [ n - 1 , n - 1 ] = 1 ; for ( int j = n - 2 ; j >= 1 ; -- j ) { int i = j - 1 , k = j + 1 ; while ( i >= 0 && k <= n - 1 ) { if ( Set [ i ] * Set [ k ] < Set [ j ] * Set [ j ] ) { ++ k ; } else if ( Set [ i ] * Set [ k ] > Set [ j ] * Set [ j ] ) { if ( Set [ j ] % Set [ i ] == 0 ) { L [ i , j ] = 2 ; if ( 2 > llgp ) llgp = 2 ; } else { L [ i , j ] = 1 ; } -- i ; } else { if ( Set [ j ] % Set [ i ] == 0 ) { L [ i , j ] = L [ j , k ] + 1 ; if ( L [ i , j ] > llgp ) { llgp = L [ i , j ] ; } } else { L [ i , j ] = 1 ; } -- i ; ++ k ; } } while ( i >= 0 ) { if ( Set [ j ] % Set [ i ] == 0 ) { L [ i , j ] = 2 ; if ( 2 > llgp ) llgp = 2 ; } else { L [ i , j ] = 1 ; } -- i ; } } return llgp ; } public static void Main ( String [ ] args ) { int [ ] set1 = { 1 , 3 , 9 , 27 , 81 , 243 } ; int n1 = set1 . Length ; Console . Write ( lenOfLongestGP ( set1 , n1 ) + " STRNEWLINE " ) ; int [ ] set2 = { 1 , 3 , 4 , 9 , 7 , 27 } ; int n2 = set2 . Length ; Console . Write ( lenOfLongestGP ( set2 , n2 ) + " STRNEWLINE " ) ; int [ ] set3 = { 2 , 3 , 5 , 7 , 11 , 13 } ; int n3 = set3 . Length ; Console . Write ( lenOfLongestGP ( set3 , n3 ) + " STRNEWLINE " ) ; } }
|
Printing Longest Bitonic Subsequence | Dynamic Programming solution to print longest Bitonic Subsequence ; Utility function to print longest Bitonic Subsequence ; Function to construct and print longest Bitonic Subsequence ; LIS [ i ] stores the length of the longest increasing subsequence ending with arr [ i ] ; initialize LIS [ 0 ] to arr [ 0 ] ; Compute LIS values from left to right ; for every j less than i ; LDS [ i ] stores the length of the longest decreasing subsequence starting with arr [ i ] ; initialize LDS [ n - 1 ] to arr [ n - 1 ] ; Compute LDS values from right to left ; for every j greater than i ; reverse as vector as we 're inserting at end ; * LDS [ i ] now stores Maximum Decreasing Subsequence * of arr [ i . . n ] that starts with arr [ i ] ; Find maximum value of size of LIS [ i ] + size of LDS [ i ] - 1 ; print all but last element of LIS [ maxIndex ] vector ; print all elements of LDS [ maxIndex ] vector ; Driver Code
|
using System ; using System . Linq ; using System . Collections . Generic ; class GFG { static void print ( List < int > arr , int size ) { for ( int i = 0 ; i < size ; i ++ ) Console . Write ( arr [ i ] + " β " ) ; } static void printLBS ( int [ ] arr , int n ) { List < int > [ ] LIS = new List < int > [ n ] ; for ( int i = 0 ; i < n ; i ++ ) LIS [ i ] = new List < int > ( ) ; LIS [ 0 ] . Add ( arr [ 0 ] ) ; for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { if ( ( arr [ i ] > arr [ j ] ) && LIS [ j ] . Count > LIS [ i ] . Count ) { foreach ( int k in LIS [ j ] ) if ( ! LIS [ i ] . Contains ( k ) ) LIS [ i ] . Add ( k ) ; } } LIS [ i ] . Add ( arr [ i ] ) ; } List < int > [ ] LDS = new List < int > [ n ] ; for ( int i = 0 ; i < n ; i ++ ) LDS [ i ] = new List < int > ( ) ; LDS [ n - 1 ] . Add ( arr [ n - 1 ] ) ; for ( int i = n - 2 ; i >= 0 ; i -- ) { for ( int j = n - 1 ; j > i ; j -- ) { if ( arr [ j ] < arr [ i ] && LDS [ j ] . Count > LDS [ i ] . Count ) foreach ( int k in LDS [ j ] ) if ( ! LDS [ i ] . Contains ( k ) ) LDS [ i ] . Add ( k ) ; } LDS [ i ] . Add ( arr [ i ] ) ; } for ( int i = 0 ; i < n ; i ++ ) LDS [ i ] . Reverse ( ) ; int max = 0 ; int maxIndex = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( LIS [ i ] . Count + LDS [ i ] . Count - 1 > max ) { max = LIS [ i ] . Count + LDS [ i ] . Count - 1 ; maxIndex = i ; } } print ( LIS [ maxIndex ] , LIS [ maxIndex ] . Count - 1 ) ; print ( LDS [ maxIndex ] , LDS [ maxIndex ] . Count ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 11 , 2 , 10 , 4 , 5 , 2 , 1 } ; int n = arr . Length ; printLBS ( arr , n ) ; } }
|
Find if string is K | C # program to find if given string is K - Palindrome or not ; find if given string is K - Palindrome or not ; Create a table to store results of subproblems ; Fill dp [ ] [ ] in bottom up manner ; If first string is empty , only option is to remove all characters of second string ; Min . operations = j ; If second string is empty , only option is to remove all characters of first string ; Min . operations = i ; If last characters are same , ignore last character and recur for remaining string ; If last character are different , remove it and find minimum ; Remove from str1 Remove from str2 ; Returns true if str is k palindrome . ; ; Driver program
|
using System ; class GFG { static int isKPalDP ( string str1 , string str2 , int m , int n ) { int [ , ] dp = new int [ m + 1 , n + 1 ] ; for ( int i = 0 ; i <= m ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { if ( i == 0 ) { dp [ i , j ] = j ; } else if ( j == 0 ) { dp [ i , j ] = i ; } else if ( str1 [ i - 1 ] == str2 [ j - 1 ] ) { dp [ i , j ] = dp [ i - 1 , j - 1 ] ; } else { dp [ i , j ] = 1 + Math . Min ( dp [ i - 1 , j ] , dp [ i , j - 1 ] ) ; } } } return dp [ m , n ] ; } static bool isKPal ( string str , int k ) { string revStr = str ; revStr = reverse ( revStr ) ; int len = str . Length ; return ( isKPalDP ( str , revStr , len , len ) <= k * 2 ) ; } static string reverse ( string str ) { char [ ] sb = str . ToCharArray ( ) ; Array . Reverse ( sb ) ; return new string ( sb ) ; } static void Main ( ) { string str = " acdcb " ; int k = 2 ; if ( isKPal ( str , k ) ) { Console . WriteLine ( " Yes " ) ; } else { Console . WriteLine ( " No " ) ; } } }
|
A Space Optimized Solution of LCS | C # Code for A Space Optimized Solution of LCS ; Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Find lengths of two strings ; Binary index , used to index current row and previous row . ; Compute current binary index ; Last filled entry contains length of LCS for X [ 0. . n - 1 ] and Y [ 0. . m - 1 ] ; Driver Code
|
using System ; class GFG { public static int lcs ( string X , string Y ) { int m = X . Length , n = Y . Length ; int [ , ] L = new int [ 2 , n + 1 ] ; int bi = 0 ; for ( int i = 0 ; i <= m ; i ++ ) { bi = i & 1 ; for ( int j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) L [ bi , j ] = 0 ; else if ( X [ i - 1 ] == Y [ j - 1 ] ) L [ bi , j ] = L [ 1 - bi , j - 1 ] + 1 ; else L [ bi , j ] = Math . Max ( L [ 1 - bi , j ] , L [ bi , j - 1 ] ) ; } } return L [ bi , n ] ; } public static void Main ( ) { string X = " AGGTAB " ; string Y = " GXTXAYB " ; Console . Write ( " Length β of β LCS β is β " + lcs ( X , Y ) ) ; } }
|
Count number of subsets having a particular XOR value | C # dynamic programming solution to finding the number of subsets having xor of their elements as k ; Returns count of subsets of arr [ ] with XOR value equals to k . ; Find maximum element in arr [ ] ; Maximum possible XOR value ; The value of dp [ i ] [ j ] is the number of subsets having XOR of their elements as j from the set arr [ 0. . . i - 1 ] ; Initializing all the values of dp [ i ] [ j ] as 0 ; The xor of empty subset is 0 ; Fill the dp table ; The answer is the number of subset from set arr [ 0. . n - 1 ] having XOR of elements as k ; Driver code
|
using System ; class GFG { static int subsetXOR ( int [ ] arr , int n , int k ) { int max_ele = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] > max_ele ) max_ele = arr [ i ] ; int m = ( 1 << ( int ) ( Math . Log ( max_ele , 2 ) + 1 ) ) - 1 ; if ( k > m ) { return 0 ; } int [ , ] dp = new int [ n + 1 , m + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) for ( int j = 0 ; j <= m ; j ++ ) dp [ i , j ] = 0 ; dp [ 0 , 0 ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) for ( int j = 0 ; j <= m ; j ++ ) dp [ i , j ] = dp [ i - 1 , j ] + dp [ i - 1 , j ^ arr [ i - 1 ] ] ; return dp [ n , k ] ; } static public void Main ( ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 } ; int k = 4 ; int n = arr . Length ; Console . WriteLine ( " Count β of β subsets β is β " + subsetXOR ( arr , n , k ) ) ; } }
|
Partition a set into two subsets such that the difference of subset sums is minimum | A Recursive C # program to solve minimum sum partition problem . ; Returns the minimum value of the difference of the two sets . ; Calculate sum of all elements ; Create an array to store results of subproblems ; Initialize first column as true . 0 sum is possible with all elements . ; Initialize top row , except dp [ 0 , 0 ] , as false . With 0 elements , no other sum except 0 is possible ; Fill the partition table in bottom up manner ; If i 'th element is excluded ; If i 'th element is included ; Initialize difference of two sums . ; Find the largest j such that dp [ n , j ] is true where j loops from sum / 2 t0 0 ; Driver code
|
using System ; class GFG { static int findMin ( int [ ] arr , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; bool [ , ] dp = new bool [ n + 1 , sum + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) dp [ i , 0 ] = true ; for ( int i = 1 ; i <= sum ; i ++ ) dp [ 0 , i ] = false ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= sum ; j ++ ) { dp [ i , j ] = dp [ i - 1 , j ] ; if ( arr [ i - 1 ] <= j ) dp [ i , j ] |= dp [ i - 1 , j - arr [ i - 1 ] ] ; } } int diff = int . MaxValue ; for ( int j = sum / 2 ; j >= 0 ; j -- ) { if ( dp [ n , j ] == true ) { diff = sum - 2 * j ; break ; } } return diff ; } public static void Main ( String [ ] args ) { int [ ] arr = { 3 , 1 , 4 , 2 , 2 , 1 } ; int n = arr . Length ; Console . WriteLine ( " The β minimum β difference β " + " between β 2 β sets β is β " + findMin ( arr , n ) ) ; } }
|
Count number of paths with at | C # program to count number of paths with maximum k turns allowed ; table to store to store results of subproblems ; Returns count of paths to reach ( i , j ) from ( 0 , 0 ) using at - most k turns . d is current direction d = 0 indicates along row , d = 1 indicates along column . ; If invalid row or column indexes ; If current cell is top left itself ; If 0 turns left ; If direction is row , then we can reach here only if direction is row and row is 0. ; If direction is column , then we can reach here only if direction is column and column is 0. ; If this subproblem is already evaluated ; If current direction is row , then count paths for two cases 1 ) We reach here through previous row . 2 ) We reach here through previous column , so number of turns k reduce by 1. ; Similar to above if direction is column ; This function mainly initializes ' dp ' array as - 1 and calls countPathsUtil ( ) ; If ( 0 , 0 ) is target itself ; Initialize ' dp ' array ; Recur for two cases : moving along row and along column return countPathsUtil ( i - 1 , j , k , 1 ) + Moving along row countPathsUtil ( i , j - 1 , k , 0 ) ; Moving along column ; Driver Code
|
using System ; class GFG { static int MAX = 100 ; static int [ , , , ] dp = new int [ MAX , MAX , MAX , 2 ] ; static int countPathsUtil ( int i , int j , int k , int d ) { if ( i < 0 j < 0 ) return 0 ; if ( i == 0 && j == 0 ) return 1 ; if ( k == 0 ) { if ( d == 0 && i == 0 ) return 1 ; if ( d == 1 && j == 0 ) return 1 ; return 0 ; } if ( dp [ i , j , k , d ] != - 1 ) return dp [ i , j , k , d ] ; if ( d == 0 ) return dp [ i , j , k , d ] = countPathsUtil ( i , j - 1 , k , d ) + countPathsUtil ( i - 1 , j , k - 1 , d == 1 ? 0 : 1 ) ; return dp [ i , j , k , d ] = countPathsUtil ( i - 1 , j , k , d ) + countPathsUtil ( i , j - 1 , k - 1 , d == 1 ? 0 : 1 ) ; } static int countPaths ( int i , int j , int k ) { if ( i == 0 && j == 0 ) return 1 ; for ( int p = 0 ; p < MAX ; p ++ ) { for ( int q = 0 ; q < MAX ; q ++ ) { for ( int r = 0 ; r < MAX ; r ++ ) for ( int s = 0 ; s < 2 ; s ++ ) dp [ p , q , r , s ] = - 1 ; } } } public static void Main ( String [ ] args ) { int m = 3 , n = 3 , k = 2 ; Console . WriteLine ( " Number β of β paths β is β " + countPaths ( m - 1 , n - 1 , k ) ) ; } }
|
Find minimum possible size of array with given rules for removing elements | C # program to find size of minimum possible array after removing elements according to given rules ; dp [ i , j ] denotes the minimum number of elements left in the subarray arr [ i . . j ] . ; If already evaluated ; If size of array is less than 3 ; Initialize result as the case when first element is separated ( not removed using given rules ) ; Now consider all cases when first element forms a triplet and removed . Check for all possible triplets ( low , i , j ) ; Check if this triplet follows the given rules of removal . And elements between ' low ' and ' i ' , and between ' i ' and ' j ' can be recursively removed . ; Insert value in table and return result ; This function mainly initializes dp table and calls recursive function minSizeRec ; Driver code
|
using System ; class GFG { static int MAX = 1000 ; static int [ , ] dp = new int [ MAX , MAX ] ; static int minSizeRec ( int [ ] arr , int low , int high , int k ) { if ( dp [ low , high ] != - 1 ) { return dp [ low , high ] ; } if ( ( high - low + 1 ) < 3 ) { return high - low + 1 ; } int res = 1 + minSizeRec ( arr , low + 1 , high , k ) ; for ( int i = low + 1 ; i <= high - 1 ; i ++ ) { for ( int j = i + 1 ; j <= high ; j ++ ) { if ( arr [ i ] == ( arr [ low ] + k ) && arr [ j ] == ( arr [ low ] + 2 * k ) && minSizeRec ( arr , low + 1 , i - 1 , k ) == 0 && minSizeRec ( arr , i + 1 , j - 1 , k ) == 0 ) { res = Math . Min ( res , minSizeRec ( arr , j + 1 , high , k ) ) ; } } } return ( dp [ low , high ] = res ) ; } static int minSize ( int [ ] arr , int n , int k ) { for ( int i = 0 ; i < MAX ; i ++ ) { for ( int j = 0 ; j < MAX ; j ++ ) { dp [ i , j ] = - 1 ; } } return minSizeRec ( arr , 0 , n - 1 , k ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , 3 , 4 , 5 , 6 , 4 } ; int n = arr . Length ; int k = 1 ; Console . WriteLine ( minSize ( arr , n , k ) ) ; } }
|
Find number of solutions of a linear equation of n variables | A naive recursive C # program to find number of non - negative solutions for a given linear equation ; Recursive function that returns count of solutions for given RHS value and coefficients coeff [ start . . end ] ; Base case ; Initialize count of solutions ; One by subtract all smaller or equal coefficiants and recur ; Driver Code
|
using System ; class GFG { static int countSol ( int [ ] coeff , int start , int end , int rhs ) { if ( rhs == 0 ) return 1 ; int result = 0 ; for ( int i = start ; i <= end ; i ++ ) if ( coeff [ i ] <= rhs ) result += countSol ( coeff , i , end , rhs - coeff [ i ] ) ; return result ; } public static void Main ( ) { int [ ] coeff = { 2 , 2 , 5 } ; int rhs = 4 ; int n = coeff . Length ; Console . Write ( countSol ( coeff , 0 , n - 1 , rhs ) ) ; } }
|
Maximum weight transformation of a given string | C # program to find maximum weight transformation of a given string ; Returns weight of the maximum weight transformation ; Base case ; If this subproblem is already solved ; Don 't make pair, so weight gained is 1 ; If we can make pair ; If elements are dissimilar , weight gained is 4 ; if elements are similar so for making a pair we toggle any of them . Since toggle cost is 1 so overall weight gain becomes 3 ; save and return maximum of above cases ; Initializes lookup table and calls getMaxRec ( ) ; Create and initialize lookup table ; Call recursive function ; Driver Code
|
using System ; class GFG { static int getMaxRec ( string str , int i , int n , int [ ] lookup ) { if ( i >= n ) return 0 ; if ( lookup [ i ] != - 1 ) return lookup [ i ] ; int ans = 1 + getMaxRec ( str , i + 1 , n , lookup ) ; if ( i + 1 < n ) { if ( str [ i ] != str [ i + 1 ] ) ans = Math . Max ( 4 + getMaxRec ( str , i + 2 , n , lookup ) , ans ) ; else ans = Math . Max ( 3 + getMaxRec ( str , i + 2 , n , lookup ) , ans ) ; } return lookup [ i ] = ans ; } static int getMaxWeight ( string str ) { int n = str . Length ; int [ ] lookup = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) lookup [ i ] = - 1 ; return getMaxRec ( str , 0 , str . Length , lookup ) ; } public static void Main ( ) { string str = " AAAAABB " ; Console . Write ( " Maximum β weight β of β a " + " β transformation β of β " + str + " β is β " + getMaxWeight ( str ) ) ; } }
|
Minimum steps to reach a destination | C # program to count number of steps to reach a point ; source -> source vertex step -> value of last step taken dest -> destination vertex ; base cases ; if we go on positive side ; if we go on negative side ; minimum of both cases ; Driver Code
|
using System ; class GFG { static int steps ( int source , int step , int dest ) { if ( Math . Abs ( source ) > ( dest ) ) return int . MaxValue ; if ( source == dest ) return step ; int pos = steps ( source + step + 1 , step + 1 , dest ) ; int neg = steps ( source - step - 1 , step + 1 , dest ) ; return Math . Min ( pos , neg ) ; } public static void Main ( ) { int dest = 11 ; Console . WriteLine ( " No . β of β steps β required " + " β to β reach β " + dest + " β is β " + steps ( 0 , 0 , dest ) ) ; } }
|
Longest Common Substring | DP | C # implementation of the above approach ; Function to find the length of the longest LCS ; Create DP table ; Driver Code ; Function call
|
using System ; public class GFG { static int LCSubStr ( string s , string t , int n , int m ) { int [ , ] dp = new int [ 2 , m + 1 ] ; int res = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { if ( s [ i - 1 ] == t [ j - 1 ] ) { dp [ i % 2 , j ] = dp [ ( i - 1 ) % 2 , j - 1 ] + 1 ; if ( dp [ i % 2 , j ] > res ) res = dp [ i % 2 , j ] ; } else dp [ i % 2 , j ] = 0 ; } } return res ; } static public void Main ( ) { string X = " OldSite : GeeksforGeeks . org " ; string Y = " NewSite : GeeksQuiz . com " ; int m = X . Length ; int n = Y . Length ; Console . WriteLine ( LCSubStr ( X , Y , m , n ) ) ; } }
|
Longest Common Substring | DP | C # program using to find length of the longest common substring recursion ; Returns length of function for longest common substring of X [ 0. . m - 1 ] and Y [ 0. . n - 1 ] ; Driver code
|
using System ; class GFG { static String X , Y ; static int lcs ( int i , int j , int count ) { if ( i == 0 j == 0 ) { return count ; } if ( X [ i - 1 ] == Y [ j - 1 ] ) { count = lcs ( i - 1 , j - 1 , count + 1 ) ; } count = Math . Max ( count , Math . Max ( lcs ( i , j - 1 , 0 ) , lcs ( i - 1 , j , 0 ) ) ) ; return count ; } public static void Main ( ) { int n , m ; X = " abcdxyz " ; Y = " xyzabcd " ; n = X . Length ; m = Y . Length ; Console . Write ( lcs ( n , m , 0 ) ) ; } }
|
Make Array elements equal by replacing adjacent elements with their XOR | C # Program of the above approach ; Function to check if it is possible to make all the array elements equal using the given operation ; Stores the XOR of all elements of array A [ ] ; Case 1 , check if the XOR of the array A [ ] is 0 ; Maintains the XOR till the current element ; Iterate over the array ; If the current XOR is equal to the total XOR increment the count and initialize current XOR as 0 ; Print Answer ; Driver Code ; Function Call
|
using System ; class GFG { static void possibleEqualArray ( int [ ] A , int N ) { int tot_XOR = 0 ; for ( int i = 0 ; i < N ; i ++ ) { tot_XOR ^= A [ i ] ; } if ( tot_XOR == 0 ) { Console . Write ( " YES " ) ; return ; } int cur_XOR = 0 ; int cnt = 0 ; for ( int i = 0 ; i < N ; i ++ ) { cur_XOR ^= A [ i ] ; if ( cur_XOR == tot_XOR ) { cnt ++ ; cur_XOR = 0 ; } } if ( cnt > 2 ) { Console . Write ( " YES " ) ; } else { Console . Write ( " NO " ) ; } } public static void Main ( String [ ] args ) { int [ ] A = { 0 , 2 , 2 } ; int N = ( A . Length ) ; possibleEqualArray ( A , N ) ; } }
|
Count of palindromes that can be obtained by concatenating equal length prefix and substrings | C # program for the above approach ; Function to calculate the number of palindromes ; Calculation of Z - array ; Calculation of sigma ( Z [ i ] + 1 ) ; Return the count ; Driver Code ; Given String
|
using System ; public class GFG { static int countPalindromes ( String S ) { int N = ( int ) S . Length ; int [ ] Z = new int [ ( N ) ] ; int l = 0 , r = 0 ; for ( int i = 1 ; 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 ; } } int sum = 0 ; for ( int i = 0 ; i < Z . Length ; i ++ ) { sum += Z [ i ] + 1 ; } return sum ; } public static void Main ( String [ ] args ) { String S = " abab " ; Console . WriteLine ( countPalindromes ( S ) ) ; } }
|
Extract substrings between any pair of delimiters | C # program to implement the above approach ; Function to print strings present between any pair of delimeters ; Stores the indices of ; If opening delimeter is encountered ; If closing delimeter is encountered ; Extract the position of opening delimeter ; Length of substring ; Extract the substring ; Driver Code
|
using System ; using System . Collections ; class GFG { static void printSubsInDelimeters ( string str ) { Stack dels = new Stack ( ) ; for ( int i = 0 ; i < str . Length ; i ++ ) { if ( str [ i ] == ' [ ' ) { dels . Push ( i ) ; } else if ( str [ i ] == ' ] ' && dels . Count > 0 ) { int pos = ( int ) dels . Peek ( ) ; dels . Pop ( ) ; int len = i - 1 - pos ; string ans = str . Substring ( pos + 1 , len ) ; Console . WriteLine ( ans ) ; } } } static void Main ( ) { string str = " [ This β is β first ] β ignored β text β [ This β is β second ] " ; printSubsInDelimeters ( str ) ; } }
|
Print matrix elements from top | C # program for the above approach ; Function to traverse the matrix diagonally upwards ; Store the number of rows ; Initialize queue ; Push the index of first element i . e . , ( 0 , 0 ) ; Get the front element ; Pop the element at the front ; Insert the element below if the current element is in first column ; Insert the right neighbour if it exists ; Driver Code ; Given vector of vectors arr ; Function call
|
using System ; using System . Collections . Generic ; public class GFG { class pair { public int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static void printDiagonalTraversal ( int [ , ] nums ) { int m = nums . GetLength ( 0 ) ; Queue < pair > q = new Queue < pair > ( ) ; q . Enqueue ( new pair ( 0 , 0 ) ) ; while ( q . Count != 0 ) { pair p = q . Peek ( ) ; q . Dequeue ( ) ; Console . Write ( nums [ p . first , p . second ] + " β " ) ; if ( p . second == 0 && p . first + 1 < m ) { q . Enqueue ( new pair ( p . first + 1 , p . second ) ) ; } if ( p . second + 1 < nums . GetLength ( 1 ) ) q . Enqueue ( new pair ( p . first , p . second + 1 ) ) ; } } public static void Main ( String [ ] args ) { int [ , ] arr = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; printDiagonalTraversal ( arr ) ; } }
|
Find original sequence from Array containing the sequence merged many times in order | C # program for the above approach ; Function that returns the restored permutation ; List to store the result ; Map to mark the elements which are taken in result ; Check if the element is coming first time ; Push in result vector ; Mark it in the map ; Return the answer ; Function to print the result ; Driver Code ; Given Array ; Function call
|
using System ; using System . Collections . Generic ; class GFG { static List < int > restore ( int [ ] arr , int N ) { List < int > result = new List < int > ( ) ; Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( mp . ContainsKey ( arr [ i ] ) && mp [ arr [ i ] ] == 0 ) { result . Add ( arr [ i ] ) ; if ( mp . ContainsKey ( arr [ i ] ) ) { mp [ arr [ i ] ] = mp [ arr [ i ] ] + 1 ; } else { mp . Add ( arr [ i ] , 1 ) ; } } else mp . Add ( arr [ i ] , 0 ) ; } return result ; } static void print_result ( List < int > result ) { for ( int i = 0 ; i < result . Count ; i ++ ) Console . Write ( result [ i ] + " β " ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 13 , 1 , 24 , 13 , 24 , 2 , 2 } ; int N = arr . Length ; print_result ( restore ( arr , N ) ) ; } }
|
Find original sequence from Array containing the sequence merged many times in order | C # program for the above approach ; Function that returns the restored permutation ; List to store the result ; Set to insert unique elements ; Check if the element is coming first time ; Push in result vector ; Function to print the result ; Driver Code ; Given Array ; Function call
|
using System ; using System . Collections . Generic ; class GFG { static List < int > restore ( int [ ] arr , int N ) { List < int > result = new List < int > ( ) ; int count1 = 1 ; HashSet < int > s = new HashSet < int > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { s . Add ( arr [ i ] ) ; if ( s . Count == count1 ) { result . Add ( arr [ i ] ) ; count1 ++ ; } } return result ; } static void print_result ( List < int > result ) { for ( int i = 0 ; i < result . Count ; i ++ ) Console . Write ( result [ i ] + " β " ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 13 , 1 , 24 , 13 , 24 , 2 , 2 } ; int N = arr . Length ; print_result ( restore ( arr , N ) ) ; } }
|
Program to print the pattern 1020304017018019020 * * 50607014015016 * * * * 809012013 * * * * * * 10011. . . | C # implementation to print the given pattern ; Function to find the sum of N integers from 1 to N ; Function to print the given pattern ; Iterate over [ 0 , N - 1 ] ; Sub - Pattern - 1 ; Sub - Pattern - 2 ; Count the number of element in rows and sub - pattern 2 and 3 will have same rows ; Increment Val to print the series 1 , 2 , 3 , 4 , 5 ... ; Finally , add the ( N - 1 ) th element i . e . , 5 and increment it by 1 ; Initial is used to give the initial value of the row in Sub - Pattern 3 ; Sub - Pattern 3 ; Skip printing zero at the last ; Driver code ; Given N ; Function call
|
using System ; class GFG { static int sum ( int n ) { return n * ( n - 1 ) / 2 ; } static void BSpattern ( int N ) { int Val = 0 , Pthree = 0 , cnt = 0 , initial = - 1 ; String s = " * * " ; for ( int i = 0 ; i < N ; i ++ ) { cnt = 0 ; if ( i > 0 ) { Console . Write ( s ) ; s += " * * " ; } for ( int j = i ; j < N ; j ++ ) { if ( i > 0 ) { cnt ++ ; } Console . Write ( ++ Val ) ; Console . Write ( "0" ) ; } if ( i == 0 ) { int Sumbeforelast = sum ( Val ) * 2 ; Pthree = Val + Sumbeforelast + 1 ; initial = Pthree ; } initial = initial - cnt ; Pthree = initial ; for ( int k = i ; k < N ; k ++ ) { Console . Write ( Pthree ++ ) ; if ( k != N - 1 ) { Console . Write ( "0" ) ; } } Console . WriteLine ( ) ; } } public static void Main ( String [ ] args ) { int N = 5 ; BSpattern ( N ) ; } }
|
Check if a number starts with another number or not | C # program for the above approach ; Function to check if B is a prefix of A or not ; Convert numbers into Strings ; Find the lengths of Strings s1 and s2 ; Base Case ; Traverse the Strings s1 & s2 ; If at any index characters are unequals then return false ; Return true ; Driver Code ; Given numbers ; Function call ; If B is a prefix of A , then print " Yes "
|
using System ; class GFG { static bool checkprefix ( int A , int B ) { String s1 = A . ToString ( ) ; String s2 = B . ToString ( ) ; int n1 = s1 . Length ; int n2 = s2 . Length ; if ( n1 < n2 ) { return false ; } for ( int i = 0 ; i < n2 ; i ++ ) { if ( s1 [ i ] != s2 [ i ] ) { return false ; } } return true ; } static public void Main ( ) { int A = 12345 , B = 12 ; bool result = checkprefix ( A , B ) ; if ( result ) { Console . Write ( " Yes " ) ; } else { Console . Write ( " No " ) ; } } }
|
Check if it is possible to reach ( x , y ) from origin in exactly Z steps using only plus movements | C # program for the above approach ; Function to check if it is possible to reach ( x , y ) from origin in exactly z steps ; Condition if we can 't reach in Z steps ; Driver Code ; Destination point coordinate ; Number of steps allowed ; Function Call
|
using System ; class GFG { static void possibleToReach ( int x , int y , int z ) { if ( z < Math . Abs ( x ) + Math . Abs ( y ) || ( z - Math . Abs ( x ) - Math . Abs ( y ) ) % 2 == 1 ) { Console . Write ( " Not β Possible " + " STRNEWLINE " ) ; } else Console . Write ( " Possible " + " STRNEWLINE " ) ; } public static void Main ( String [ ] args ) { int x = 5 , y = 5 ; int z = 11 ; possibleToReach ( x , y , z ) ; } }
|
Number of cycles in a Polygon with lines from Centroid to Vertices | C # program to find number of cycles in a Polygon with lines from Centroid to Vertices ; Function to find the Number of Cycles ; Driver code
|
using System ; class GFG { static int nCycle ( int N ) { return ( N ) * ( N - 1 ) + 1 ; } public static void Main ( String [ ] args ) { int N = 4 ; Console . Write ( nCycle ( N ) ) ; } }
|
Sum of consecutive bit differences of first N non | C # program for the above problem ; Recursive function to count the sum of bit differences of numbers from 1 to pow ( 2 , ( i + 1 ) ) - 1 ; base cases ; Recursion call if the sum of bit difference of numbers around i are not calculated ; return the sum of bit differences if already calculated ; Function to calculate the sum of bit differences up to N ; nearest smaller power of 2 ; remaining numbers ; calculate the count of bit diff ; Driver code
|
using System ; class GFG { static int [ ] a = new int [ 65 ] ; static int Count ( int i ) { if ( i == 0 ) return 1 ; else if ( i < 0 ) return 0 ; if ( a [ i ] == 0 ) { a [ i ] = ( i + 1 ) + 2 * Count ( i - 1 ) ; return a [ i ] ; } else return a [ i ] ; } static int solve ( int n ) { int i , sum = 0 ; while ( n > 0 ) { i = ( int ) ( Math . Log ( n ) / Math . Log ( 2 ) ) ; n = n - ( int ) Math . Pow ( 2 , i ) ; sum = sum + ( i + 1 ) + Count ( i - 1 ) ; } return sum ; } public static void Main ( String [ ] args ) { int n = 7 ; Console . Write ( solve ( n ) ) ; } }
|
Count of total Heads and Tails after N flips in a coin | C # program to count total heads and tails after N flips in a coin ; Function to find count of head and tail ; Check if initially all the coins are facing towards head ; Check if initially all the coins are facing towards tail ; Driver Code
|
using System ; class GFG { public static Tuple < int , int > count_ht ( char s , int N ) { Tuple < int , int > p = Tuple . Create ( 0 , 0 ) ; if ( s == ' H ' ) { p = Tuple . Create ( ( int ) Math . Floor ( N / 2.0 ) , ( int ) Math . Ceiling ( N / 2.0 ) ) ; } else if ( s == ' T ' ) { p = Tuple . Create ( ( int ) Math . Ceiling ( N / 2.0 ) , ( int ) Math . Floor ( N / 2.0 ) ) ; } return p ; } static void Main ( ) { char C = ' H ' ; int N = 5 ; Tuple < int , int > p = count_ht ( C , N ) ; Console . WriteLine ( " Head β = β " + p . Item1 ) ; Console . WriteLine ( " Tail β = β " + p . Item2 ) ; } }
|
Longest palindromic string possible after removal of a substring | C # Implementation of the above approach ; Function to find the longest palindrome from the start of the String using KMP match ; Append S ( reverse of C ) to C ; Use KMP algorithm ; Function to return longest palindromic String possible from the given String after removal of any subString ; Initialize three Strings A , B AND F ; Loop to find longest subStrings from both ends which are reverse of each other ; Proceed to third step of our approach ; Remove the subStrings A and B ; Find the longest palindromic subString from beginning of C ; Find the longest palindromic subString from end of C ; Store the maximum of D and E in F ; Find the readonly answer ; Driver Code
|
using System ; class GFG { static String findPalindrome ( String C ) { String S = C ; S = reverse ( S ) ; C = C + " & " + S ; int n = C . Length ; int [ ] longestPalindrome = new int [ n ] ; longestPalindrome [ 0 ] = 0 ; int len = 0 ; int i = 1 ; while ( i < n ) { if ( C [ i ] == C [ len ] ) { len ++ ; longestPalindrome [ i ] = len ; i ++ ; } else { if ( len != 0 ) { len = longestPalindrome [ len - 1 ] ; } else { longestPalindrome [ i ] = 0 ; i ++ ; } } } String ans = C . Substring ( 0 , longestPalindrome [ n - 1 ] ) ; return ans ; } static String findAns ( String s ) { String A = " " ; String B = " " ; String F = " " ; int i = 0 ; int j = s . Length - 1 ; int len = s . Length ; while ( i < j && s [ i ] == s [ j ] ) { i = i + 1 ; j = j - 1 ; } if ( i > 0 ) { A = s . Substring ( 0 , i ) ; B = s . Substring ( len - i , i ) ; } if ( len > 2 * i ) { String C = s . Substring ( i , ( s . Length - 2 * i ) ) ; String D = findPalindrome ( C ) ; C = reverse ( C ) ; String E = findPalindrome ( C ) ; if ( D . Length > E . Length ) { F = D ; } else { F = E ; } } String answer = A + F + B ; return answer ; } static String reverse ( String input ) { char [ ] a = input . ToCharArray ( ) ; int l , r = a . Length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { char temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return String . Join ( " " , a ) ; } public static void Main ( String [ ] args ) { String str = " abcdefghiedcba " ; Console . Write ( findAns ( str ) + " STRNEWLINE " ) ; } }
|
Find Nth term of the series 2 , 3 , 10 , 15 , 26. ... | C # program to find Nth term of the series 2 , 3 , 10 , 15 , 26. ... ; Function to find Nth term ; Nth term ; Driver code
|
using System ; class GFG { static int nthTerm ( int N ) { int nth = 0 ; if ( N % 2 == 1 ) nth = ( N * N ) + 1 ; else nth = ( N * N ) - 1 ; return nth ; } public static void Main ( String [ ] args ) { int N = 5 ; Console . Write ( nthTerm ( N ) + " STRNEWLINE " ) ; } }
|
Find the Nth term in series 12 , 35 , 81 , 173 , 357 , ... | C # program to find the Nth term in series 12 , 35 , 81 , 173 , 357 , ... ; Function to find Nth term ; Nth term ; Driver code
|
using System ; class GFG { static int nthTerm ( int N ) { int nth = 0 , first_term = 12 ; nth = ( int ) ( ( first_term * ( Math . Pow ( 2 , N - 1 ) ) ) + 11 * ( ( Math . Pow ( 2 , N - 1 ) ) - 1 ) ) ; return nth ; } public static void Main ( String [ ] args ) { int N = 5 ; Console . Write ( nthTerm ( N ) + " STRNEWLINE " ) ; } }
|
Find Nth term of the series 4 , 2 , 2 , 3 , 6 , ... | C # program to find Nth term of the series 4 , 2 , 2 , 3 , 6 , ... ; Function to find Nth term ; Nth term ; Driver code
|
using System ; class GFG { static int nthTerm ( int N ) { int nth = 0 , first_term = 4 ; int pi = 1 , po = 1 ; int n = N ; while ( n > 1 ) { pi *= n - 1 ; n -- ; po *= 2 ; } nth = ( first_term * pi ) / po ; return nth ; } public static void Main ( String [ ] args ) { int N = 5 ; Console . Write ( nthTerm ( N ) + " STRNEWLINE " ) ; } }
|
Find the final number obtained after performing the given operation | C # implementation of the approach ; Function to return the readonly number obtained after performing the given operation ; Find the gcd of the array elements ; Driver code
|
using System ; class GFG { static int finalNum ( int [ ] arr , int n ) { int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) { result = __gcd ( result , arr [ i ] ) ; } return result ; } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 3 , 9 , 6 , 36 } ; int n = arr . Length ; Console . Write ( finalNum ( arr , n ) ) ; } }
|
Check whether all the substrings have number of vowels atleast as that of consonants | C # implementation of the approach ; Function that returns true if character ch is a vowel ; Compares two integers according to their digit sum ; Check if there are two consecutive consonants ; Check if there is any vowel surrounded by two consonants ; Driver code
|
using System ; class GFG { static bool isVowel ( char ch ) { switch ( ch ) { case ' a ' : case ' e ' : case ' i ' : case ' o ' : case ' u ' : return true ; } return false ; } static bool isSatisfied ( char [ ] str , int n ) { for ( int i = 1 ; i < n ; i ++ ) { if ( ! isVowel ( str [ i ] ) && ! isVowel ( str [ i - 1 ] ) ) { return false ; } } for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( isVowel ( str [ i ] ) && ! isVowel ( str [ i - 1 ] ) && ! isVowel ( str [ i + 1 ] ) ) { return false ; } } return true ; } public static void Main ( String [ ] args ) { String str = " acaba " ; int n = str . Length ; if ( isSatisfied ( str . ToCharArray ( ) , n ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
|
Print the longest prefix of the given string which is also the suffix of the same string | C # implementation of the approach ; Returns length of the longest prefix which is also suffix and the two do not overlap . This function mainly is copy of computeLPSArray ( ) in KMP Algorithm ; lps [ 0 ] is always 0 ; Length of the previous longest prefix suffix ; Loop to calculate lps [ i ] for i = 1 to n - 1 ; This is tricky . Consider the example . AAACAAAA and i = 7. The idea is similar to search step . ; Also , note that we do not increment i here ; If len = 0 ; Since we are looking for non overlapping parts ; Function that returns the prefix ; Get the length of the longest prefix ; Stores the prefix ; Traverse and add characters ; Returns the prefix ; Driver code
|
using System ; class GfG { static int LengthlongestPrefixSuffix ( string s ) { int n = s . Length ; int [ ] lps = new int [ n ] ; lps [ 0 ] = 0 ; int len = 0 ; int i = 1 ; while ( i < n ) { if ( s [ i ] == s [ len ] ) { len ++ ; lps [ i ] = len ; i ++ ; } else { if ( len != 0 ) { len = lps [ len - 1 ] ; } else { lps [ i ] = 0 ; i ++ ; } } } int res = lps [ n - 1 ] ; return ( res > n / 2 ) ? n / 2 : res ; } static String longestPrefixSuffix ( string s ) { int len = LengthlongestPrefixSuffix ( s ) ; string prefix = " " ; for ( int i = 0 ; i < len ; i ++ ) prefix += s [ i ] ; return prefix ; } public static void Main ( ) { string s = " abcab " ; string ans = longestPrefixSuffix ( s ) ; if ( ans == " " ) Console . WriteLine ( " - 1" ) ; else Console . WriteLine ( ans ) ; } }
|
Print a number as string of ' A ' and ' B ' in lexicographic order | C # implementation of the approach ; Function to calculate number of characters in corresponding string of ' A ' and ' B ' ; Since the minimum number of characters will be 1 ; Calculating number of characters ; Since k length string can represent at most pow ( 2 , k + 1 ) - 2 that is if k = 4 , it can represent at most pow ( 2 , 4 + 1 ) - 2 = 30 so we have to calculate the length of the corresponding string ; return the length of the corresponding string ; Function to print corresponding string of ' A ' and ' B ' ; Find length of string ; Since the first number that can be represented by k length string will be ( pow ( 2 , k ) - 2 ) + 1 and it will be AAA ... A , k times , therefore , N will store that how much we have to print ; At a particular time , we have to decide whether we have to print ' A ' or ' B ' , this can be check by calculating the value of pow ( 2 , k - 1 ) ; Print new line ; Driver code
|
using System ; class GFG { static int no_of_characters ( int M ) { int k = 1 ; while ( true ) { if ( ( int ) Math . Pow ( 2 , k + 1 ) - 2 < M ) k ++ ; else break ; } return k ; } static void print_string ( int M ) { int k , num , N ; k = no_of_characters ( M ) ; N = M - ( ( int ) Math . Pow ( 2 , k ) - 2 ) ; while ( k > 0 ) { num = ( int ) Math . Pow ( 2 , k - 1 ) ; if ( num >= N ) Console . Write ( " A " ) ; else { Console . Write ( " B " ) ; N -= num ; } k -- ; } Console . WriteLine ( ) ; } public static void Main ( ) { int M ; M = 30 ; print_string ( M ) ; M = 55 ; print_string ( M ) ; M = 100 ; print_string ( M ) ; } }
|
Replace two substrings ( of a string ) with each other | C # implementation of the approach ; Function to return the resultant string ; Iterate through all positions i ; Current sub - string of length = len ( A ) = len ( B ) ; If current sub - string gets equal to A or B ; Update S after replacing A ; Update S after replacing B ; Return the updated string ; Driver code
|
using System ; class GFG { static string updateString ( string S , string A , string B ) { int l = A . Length ; for ( int i = 0 ; i + l <= S . Length ; i ++ ) { string curr = S . Substring ( i , l ) ; if ( curr . Equals ( A ) ) { string new_string = S . Substring ( 0 , i ) + B + S . Substring ( i + l ) ; S = new_string ; i += l - 1 ; } else { string new_string = S . Substring ( 0 , i ) + A + S . Substring ( i + l ) ; S = new_string ; i += l - 1 ; } } return S ; } public static void Main ( ) { string S = " aab " ; string A = " aa " ; string B = " bb " ; Console . WriteLine ( updateString ( S , A , B ) ) ; } }
|
Print n 0 s and m 1 s such that no two 0 s and no three 1 s are together | C # implementation of the above approach ; Function to print the required pattern ; When condition fails ; When m = n - 1 ; Driver code
|
using System ; class GFG { static void printPattern ( int n , int m ) { if ( m > 2 * ( n + 1 ) m < n - 1 ) { Console . Write ( " - 1" ) ; } else if ( Math . Abs ( n - m ) <= 1 ) { while ( n > 0 && m > 0 ) { Console . Write ( "01" ) ; n -- ; m -- ; } if ( n != 0 ) { Console . Write ( "0" ) ; } if ( m != 0 ) { Console . Write ( "1" ) ; } } else { while ( m - n > 1 && n > 0 ) { Console . Write ( "110" ) ; m = m - 2 ; n = n - 1 ; } while ( n > 0 ) { Console . Write ( "10" ) ; n -- ; m -- ; } while ( m > 0 ) { Console . Write ( "1" ) ; m -- ; } } } public static void Main ( ) { int n = 4 , m = 8 ; printPattern ( n , m ) ; } }
|
Find the count of Strictly decreasing Subarrays | C # program to count number of strictly decreasing subarrays in O ( n ) time . ; Function to count the number of strictly decreasing subarrays ; Initialize length of current decreasing subarray ; Traverse through the array ; If arr [ i + 1 ] is less than arr [ i ] , then increment length ; Else Update count and reset length ; If last length is more than 1 ; Driver code
|
using System ; class GFG { static int countDecreasing ( int [ ] A , int n ) { int len = 1 ; for ( int i = 0 ; i < n - 1 ; ++ i ) { if ( A [ i + 1 ] < A [ i ] ) len ++ ; else { cnt += ( ( ( len - 1 ) * len ) / 2 ) ; len = 1 ; } } if ( len > 1 ) cnt += ( ( ( len - 1 ) * len ) / 2 ) ; return cnt ; } static void Main ( ) { int [ ] A = { 100 , 3 , 1 , 13 } ; int n = A . Length ; Console . WriteLine ( countDecreasing ( A , n ) ) ; } }
|
Minimum changes required to make first string substring of second string | C # program to find the minimum number of characters to be replaced in string S2 , such that S1 is a substring of S2 ; Function to find the minimum number of characters to be replaced in string S2 , such that S1 is a substring of S2 ; Get the sizes of both strings ; Traverse the string S2 ; From every index in S2 , check the number of mis - matching characters in substring of length of S1 ; Take minimum of prev and current mis - match ; return answer ; Driver Code
|
using System ; class GFG { static int minimumChar ( String S1 , String S2 ) { int n = S1 . Length ; int m = S2 . Length ; int ans = Int32 . MaxValue ; for ( int i = 0 ; i < m - n + 1 ; i ++ ) { int minRemovedChar = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( S1 [ j ] != S2 [ i + j ] ) { minRemovedChar ++ ; } } ans = Math . Min ( minRemovedChar , ans ) ; } return ans ; } public static void Main ( ) { String S1 = " abc " ; String S2 = " paxzk " ; Console . WriteLine ( minimumChar ( S1 , S2 ) ) ; } }
|
Frequency of a substring in a string | Simple C # program to count occurrences of pat in txt . ; A loop to slide pat [ ] one by one ; For current index i , check for pattern match ; if pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; Driver program to test above function
|
using System ; public class GFG { static int countFreq ( String pat , String txt ) { int M = pat . Length ; int N = txt . Length ; int res = 0 ; for ( int i = 0 ; i <= N - M ; i ++ ) { int j ; for ( j = 0 ; j < M ; j ++ ) { if ( txt [ i + j ] != pat [ j ] ) { break ; } } if ( j == M ) { res ++ ; j = 0 ; } } return res ; } static public void Main ( ) { String txt = " dhimanman " ; String pat = " man " ; Console . Write ( countFreq ( pat , txt ) ) ; } }
|
Optimized Naive Algorithm for Pattern Searching | C # program for A modified Naive Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different ; A modified Naive Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different ; For current index i , check for pattern match ; if ( j == M ) if pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; slide the pattern by j ; Driver code
|
using System ; class GFG { static void search ( string pat , string txt ) { int M = pat . Length ; int N = txt . Length ; int i = 0 ; while ( i <= N - M ) { int j ; for ( j = 0 ; j < M ; j ++ ) if ( txt [ i + j ] != pat [ j ] ) break ; { Console . WriteLine ( " Pattern β found β at β index β " + i ) ; i = i + M ; } else if ( j = = 0 ) i = i + 1 ; else i = i + j ; } } static void Main ( ) { string txt = " ABCEABCDABCEABCD " ; string pat = " ABCD " ; search ( pat , txt ) ; } }
|
Find the missing digit in given product of large positive integers | C # program for the above approach ; Function to find the replaced digit in the product of a * b ; Keeps track of the sign of the current digit ; Stores the value of a % 11 ; Find the value of a mod 11 for large value of a as per the derived formula ; Stores the value of b % 11 ; Find the value of b mod 11 for large value of a as per the derived formula ; Stores the value of c % 11 ; Keeps track of the sign of x ; If the current digit is the missing digit , then keep the track of its sign ; Find the value of x using the derived equation ; Check if x has a negative sign ; Return positive equivaluent of x mod 11 ; Driver Code
|
using System ; using System . Collections . Generic ; class GFG { static int findMissingDigit ( string a , string b , string c ) { int w = 1 ; int a_mod_11 = 0 ; for ( int i = a . Length - 1 ; i >= 0 ; i -- ) { a_mod_11 = ( a_mod_11 + w * ( ( int ) a [ i ] - 48 ) ) % 11 ; w = w * - 1 ; } int b_mod_11 = 0 ; w = 1 ; for ( int i = b . Length - 1 ; i >= 0 ; i -- ) { b_mod_11 = ( b_mod_11 + w * ( ( int ) b [ i ] - 48 ) ) % 11 ; w = w * - 1 ; } int c_mod_11 = 0 ; bool xSignIsPositive = true ; w = 1 ; for ( int i = c . Length - 1 ; i >= 0 ; i -- ) { if ( c [ i ] == ' x ' ) { xSignIsPositive = ( w == 1 ) ; } else { c_mod_11 = ( c_mod_11 + w * ( ( int ) c [ i ] - '0' ) ) % 11 ; } w = w * - 1 ; } int x = ( ( a_mod_11 * b_mod_11 ) - c_mod_11 ) % 11 ; if ( xSignIsPositive == false ) { x = - x ; } return ( x % 11 + 11 ) % 11 ; } public static void Main ( ) { string A = "123456789" ; string B = "987654321" ; string C = "12193263111x635269" ; Console . Write ( findMissingDigit ( A , B , C ) ) ; } }
|
Check if a string can be made empty by repeatedly removing given subsequence | C # program for the above approach ; Function to check if a string can be made empty by removing all subsequences of the form " GFG " or not ; Driver Code
|
using System ; using System . Collections . Generic ; class GFG { static void findIfPossible ( int N , string str ) { int countG = 0 , countF = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( str [ i ] == ' G ' ) countG ++ ; else countF ++ ; } if ( 2 * countF != countG ) { Console . WriteLine ( " NO " ) ; } else { int id = 0 ; bool flag = true ; for ( int i = 0 ; i < N ; i ++ ) { if ( str [ i ] == ' G ' ) { countG -- ; id ++ ; } else { countF -- ; id -- ; } if ( id < 0 ) { flag = false ; break ; } if ( countG < countF ) { flag = false ; break ; } } if ( flag ) { Console . WriteLine ( " YES " ) ; } else { Console . WriteLine ( " NO " ) ; } } } public static void Main ( ) { int n = 6 ; string str = " GFGFGG " ; findIfPossible ( n , str ) ; } }
|
Check whether second string can be formed from characters of first string used any number of times | C # implementation of the above approach ; Function to check if str2 can be made by characters of str1 or not ; To store the occurrence of every character ; Length of the two strings ; Assume that it is possible to compose the string str2 from str1 ; Iterate over str1 ; Store the presence of every character ; Iterate over str2 ; Ignore the spaces ; Check for the presence of character in str1 ; If it is possible to make str2 from str1 ; Driver Code ; Given strings ; Function Call
|
using System ; using System . Collections . Generic ; class GFG { static void isPossible ( string str1 , string str2 ) { int [ ] arr = new int [ 256 ] ; Array . Clear ( arr , 0 , 256 ) ; int l1 = str1 . Length ; int l2 = str2 . Length ; int i ; bool possible = true ; for ( i = 0 ; i < l1 ; i ++ ) { arr [ str1 [ i ] ] = 1 ; } for ( i = 0 ; i < l2 ; i ++ ) { if ( str2 [ i ] != ' β ' ) { if ( arr [ str2 [ i ] ] == 1 ) continue ; else { possible = false ; break ; } } } if ( possible ) { Console . Write ( " Yes " ) ; } else { Console . Write ( " No " ) ; } } public static void Main ( ) { string str1 = " we β all β love β geeksforgeeks " ; string str2 = " we β all β love β geeks " ; isPossible ( str1 , str2 ) ; } }
|
Longest subsequence with consecutive English alphabets | C # program for the above approach ; Function to find the length of subsequence starting with character ch ; Length of the string ; Stores the maximum length ; Traverse the given string ; If s [ i ] is required character ch ; Increment ans by 1 ; Increment character ch ; Return the current maximum length with character ch ; Function to find the maximum length of subsequence of consecutive characters ; Stores the maximum length of consecutive characters ; Update ans ; Return the maximum length of subsequence ; Driver Code ; Input ; Function Call
|
using System ; using System . Collections . Generic ; class GFG { static int findSubsequence ( string S , char ch ) { int N = S . Length ; int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] == ch ) { ans ++ ; ch ++ ; } } return ans ; } static int findMaxSubsequence ( string S ) { int ans = 0 ; for ( char ch = ' a ' ; ch <= ' z ' ; ch ++ ) { ans = Math . Max ( ans , findSubsequence ( S , ch ) ) ; } return ans ; } public static void Main ( ) { string S = " abcabefghijk " ; Console . Write ( findMaxSubsequence ( S ) ) ; } }
|
Minimum number of alternate subsequences required to be removed to empty a Binary String | C # program for the above approach ; Function to find the minimum number of operations to empty a binary string ; Stores the resultant number of operations ; Stores the number of 0 s ; Stores the number of 1 s ; Traverse the given string ; To balance 0 with 1 if possible ; Increment the value of cn0 by 1 ; To balance 1 with 0 if possible ; Increment the value of cn1 ; Update the maximum number of unused 0 s and 1 s ; Print the resultant count ; Driver Code
|
using System ; using System . Collections . Generic ; class GFG { static void minOpsToEmptyString ( string s ) { int ans = 0 ; int cn0 = 0 ; int cn1 = 0 ; for ( int i = 0 ; i < s . Length ; i ++ ) { if ( s [ i ] == '0' ) { if ( cn1 > 0 ) cn1 -- ; cn0 ++ ; } else { if ( cn0 > 0 ) cn0 -- ; cn1 ++ ; } ans = Math . Max ( ans , Math . Max ( cn0 , cn1 ) ) ; } Console . Write ( ans ) ; } public static void Main ( ) { string S = "010101" ; minOpsToEmptyString ( S ) ; } }
|
Smallest string obtained by removing all occurrences of 01 and 11 from Binary String | Set 2 | C # program for the above approach ; Function to find the length of the smallest string possible by removing substrings "01" and "11" ; Stores the length of the smallest string ; Traverse the string S ; If st is greater than 0 and S [ i ] is '1' ; Delete the last character and decrement st by 1 ; Otherwise ; Increment st by 1 ; Return the answer in st ; Driver code ; Input ; Function call
|
using System ; public class GFG_JAVA { static int shortestString ( string S , int N ) { int st = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( st > 0 && S [ i ] == '1' ) { st -- ; } else { st ++ ; } } return st ; } public static void Main ( string [ ] args ) { string S = "1010" ; int N = S . Length ; Console . WriteLine ( shortestString ( S , N ) ) ; } }
|
Longest Non | C # program for the above approach ; Function to find the length of the longest non - increasing subsequence ; Stores the prefix and suffix count of 1 s and 0 s respectively ; Initialize the array ; Store the number of '1' s up to current index i in pre ; Find the prefix sum ; If the current element is '1' , update the pre [ i ] ; Store the number of '0' s over the range [ i , N - 1 ] ; Find the suffix sum ; If the current element is '0' , update post [ i ] ; Stores the maximum length ; Find the maximum value of pre [ i ] + post [ i ] ; Return the answer ; Driver Code
|
using System ; class GFG { static int findLength ( String str , int n ) { int [ ] pre = new int [ n ] ; int [ ] post = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { pre [ i ] = 0 ; post [ i ] = 0 ; } for ( int i = 0 ; i < n ; i ++ ) { if ( i != 0 ) { pre [ i ] += pre [ i - 1 ] ; } if ( str [ i ] == '1' ) { pre [ i ] += 1 ; } } for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( i != n - 1 ) post [ i ] += post [ i + 1 ] ; if ( str [ i ] == '0' ) post [ i ] += 1 ; } int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { ans = Math . Max ( ans , pre [ i ] + post [ i ] ) ; } return ans ; } public static void Main ( String [ ] args ) { String S = "0101110110100001011" ; Console . WriteLine ( findLength ( S , S . Length ) ) ; } }
|
Number of substrings having an equal number of lowercase and uppercase letters | C # program for the above approach ; Function to find the count of substrings having an equal number of uppercase and lowercase characters ; Stores the count of prefixes having sum S considering uppercase and lowercase characters as 1 and - 1 ; Stores the count of substrings having equal number of lowercase and uppercase characters ; Stores the sum obtained so far ; If the character is uppercase ; Otherwise ; If currsum is 0 ; If the current sum exists in the Dictionary prevSum ; Increment the resultant count by 1 ; Update the frequency of the current sum by 1 ; Return the resultant count of the subarrays ; Driver Code
|
using System ; using System . Collections . Generic ; class GFG { static int countSubstring ( String S , int N ) { Dictionary < int , int > prevSum = new Dictionary < int , int > ( ) ; int res = 0 ; int currentSum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] >= ' A ' && S [ i ] <= ' Z ' ) { currentSum ++ ; } else currentSum -- ; if ( currentSum == 0 ) res ++ ; if ( prevSum . ContainsKey ( currentSum ) ) { res += prevSum [ currentSum ] ; prevSum [ currentSum ] = prevSum [ currentSum ] + 1 ; } else prevSum . Add ( currentSum , 1 ) ; } return res ; } public static void Main ( String [ ] args ) { String S = " gEEk " ; Console . WriteLine ( countSubstring ( S , S . Length ) ) ; } }
|
Number of substrings with each character occurring even times | C # program for the above approach ; Function to count substrings having even frequency of each character ; Stores the total count of substrings ; Traverse the range [ 0 , N ] : ; Traverse the range [ i + 1 , N ] ; Stores the substring over the range of indices [ i , len ] ; Stores the frequency of characters ; Count frequency of each character ; Traverse the dictionary ; If any of the keys have odd count ; Otherwise ; Return count ; Driver Code
|
using System ; using System . Collections . Generic ; public class GFG { static int subString ( string s , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int len = i + 1 ; len <= n ; len ++ ) { string test_str = s . Substring ( i , len - i ) ; Dictionary < char , int > res = new Dictionary < char , int > ( ) ; foreach ( char keys in test_str . ToCharArray ( ) ) { if ( ! res . ContainsKey ( keys ) ) res . Add ( keys , 0 ) ; res [ keys ] ++ ; } int flag = 0 ; foreach ( KeyValuePair < char , int > keys in res ) { if ( keys . Value % 2 != 0 ) { flag = 1 ; break ; } } if ( flag == 0 ) count += 1 ; } } return count ; } static public void Main ( ) { string S = " abbaa " ; int N = S . Length ; Console . WriteLine ( subString ( S , N ) ) ; } }
|
Count new pairs of strings that can be obtained by swapping first characters of pairs of strings from given array | C # program for the above approach ; Function to count new pairs of strings that can be obtained by swapping first characters of any pair of strings ; Stores the count of pairs ; Generate all possible pairs of strings from the array arr [ ] ; Stores the current pair of strings ; Swap the first characters ; Check if they are already present in the array or not ; If both the strings are not present ; Increment the ans by 1 ; Print the resultant count ; Driver Code
|
using System ; class GFG { static void countStringPairs ( string [ ] a , int n ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { char [ ] p = a [ i ] . ToCharArray ( ) ; char [ ] q = a [ j ] . ToCharArray ( ) ; if ( p [ 0 ] != q [ 0 ] ) { char temp = p [ 0 ] ; p [ 0 ] = q [ 0 ] ; q [ 0 ] = temp ; int flag1 = 0 ; int flag2 = 0 ; for ( int k = 0 ; k < n ; k ++ ) { if ( a [ k ] . Equals ( new string ( p ) ) ) { flag1 = 1 ; } if ( a [ k ] . Equals ( new string ( q ) ) ) { flag2 = 1 ; } } if ( flag1 == 0 && flag2 == 0 ) { ans = ans + 1 ; } } } } Console . WriteLine ( ans ) ; } public static void Main ( string [ ] args ) { string [ ] arr = { " good " , " bad " , " food " } ; int N = arr . Length ; countStringPairs ( arr , N ) ; } }
|
Modify string by replacing characters by alphabets whose distance from that character is equal to its frequency | C # program for the above approach ; Function to modify string by replacing characters by the alphabet present at distance equal to frequency of the string ; Stores frequency of characters ; Stores length of the string ; Traverse the given string S ; Increment frequency of current character by 1 ; Traverse the string ; Store the value to be added to the current character ; Check if after adding the frequency , the character is less than ' z ' or not ; Otherwise , update the value of add so that s [ i ] doesn ' t β exceed β ' z ' ; Print the modified string ; Driver Code
|
using System ; class GFG { static void addFrequencyToCharacter ( char [ ] s ) { int [ ] frequency = new int [ 26 ] ; int n = s . Length ; for ( int i = 0 ; i < n ; i ++ ) { frequency [ s [ i ] - ' a ' ] += 1 ; } for ( int i = 0 ; i < n ; i ++ ) { int add = frequency [ s [ i ] - ' a ' ] % 26 ; if ( ( int ) ( s [ i ] ) + add <= ( int ) ( ' z ' ) ) s [ i ] = ( char ) ( ( int ) ( s [ i ] ) + add ) ; else { add = ( ( int ) ( s [ i ] ) + add ) - ( ( int ) ( ' z ' ) ) ; s [ i ] = ( char ) ( ( int ) ( ' a ' ) + add - 1 ) ; } } Console . WriteLine ( s ) ; } public static void Main ( string [ ] args ) { string str = " geeks " ; addFrequencyToCharacter ( str . ToCharArray ( ) ) ; } }
|
Check if it is possible to reach any point on the circumference of a given circle from origin | C # program for the above approach ; Function to check if it is possible to reach any point on circumference of the given circle from ( 0 , 0 ) ; Stores the count of ' L ' , ' R ' ; Stores the count of ' U ' , ' D ' ; Traverse the string S ; Update the count of L ; Update the count of R ; Update the count of U ; Update the count of D ; Condition 1 for reaching the circumference ; Store the the value of ( i * i ) in the Map ; Check if ( r_square - i * i ) already present in HashMap ; If it is possible to reach the point ( mp [ r_square - i * i ] , i ) ; If it is possible to reach the point ( i , mp [ r_square - i * i ] ) ; If it is impossible to reach ; Driver Code
|
using System ; using System . Collections . Generic ; public class GFG { static string isPossible ( string S , int R , int N ) { int cntl = 0 , cntr = 0 ; int cntu = 0 , cntd = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] == ' L ' ) cntl ++ ; else if ( S [ i ] == ' R ' ) cntr ++ ; else if ( S [ i ] == ' U ' ) cntu ++ ; else cntd ++ ; } if ( Math . Max ( Math . Max ( cntl , cntr ) , Math . Max ( cntu , cntd ) ) >= R ) return " Yes " ; Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; int r_square = R * R ; for ( int i = 1 ; i * i <= r_square ; i ++ ) { mp . Add ( i * i , i ) ; if ( mp . ContainsKey ( r_square - i * i ) ) { if ( Math . Max ( cntl , cntr ) >= mp [ r_square - i * i ] && Math . Max ( cntu , cntd ) >= i ) return " Yes " ; if ( Math . Max ( cntl , cntr ) >= i && Math . Max ( cntu , cntd ) >= mp [ r_square - i * i ] ) return " Yes " ; } } return " No " ; } static public void Main ( ) { string S = " RDLLDDLDU " ; int R = 5 ; int N = S . Length ; Console . WriteLine ( isPossible ( S , R , N ) ) ; } }
|
Modify characters of a string by adding integer values of same | C # program for the above approach ; Function to modify a given String by adding ASCII value of characters from a String S to integer values of same indexed characters in String N ; Traverse the String ; Stores integer value of character in String N ; Stores ASCII value of character in String S ; If b exceeds 122 ; Replace the character ; Print resultant String ; Driver Code ; Given Strings ; Function call to modify String S by given operations
|
using System ; public class GFG { static void addASCII ( char [ ] S , char [ ] N ) { for ( int i = 0 ; i < S . Length ; i ++ ) { int a = ( int ) ( N [ i ] ) - '0' ; int b = ( int ) ( S [ i ] ) + a ; if ( b > 122 ) b -= 26 ; S [ i ] = ( char ) ( b ) ; } Console . Write ( S ) ; } public static void Main ( String [ ] args ) { String S = " sun " , N = "966" ; addASCII ( S . ToCharArray ( ) , N . ToCharArray ( ) ) ; } }
|
Minimum number of chairs required to ensure that every worker is seated at any instant | C # program to implement the above approach ; Function to find the minimum number of chairs required to ensure that every worker is seated at any time ; Stores the number of chairs required ; Pointer to iterate ; Stores minimum number of chairs required ; Iterate over every character ; If character is ' E ' ; Increase the count ; Otherwise ; Update maximum value of count obtained at any given time ; Return mini ; Driver code ; Given String ; Function call to find the minimum number of chairs
|
using System ; using System . Collections . Generic ; class GFG { static int findMinimumChairs ( string s ) { int count = 0 ; int i = 0 ; int mini = Int32 . MinValue ; while ( i < s . Length ) { if ( s [ i ] == ' E ' ) count ++ ; else count -- ; mini = Math . Max ( count , mini ) ; i ++ ; } return mini ; } public static void Main ( ) { string s = " EELEE " ; Console . WriteLine ( findMinimumChairs ( s ) ) ; } }
|
Modify string by inserting characters such that every K | C # program for the above approach ; Function to replace all ' ? ' characters in a string such that the given conditions are satisfied ; Traverse the string to Map the characters with respective positions ; Traverse the string again and replace all unknown characters ; If i % k is not found in the Map M , then return - 1 ; Update S [ i ] ; Print the string S ; Driver code
|
using System ; using System . Collections . Generic ; class GFG { static void fillString ( string str , int k ) { char [ ] s = str . ToCharArray ( ) ; Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < s . Length ; i ++ ) { if ( s [ i ] != ' ? ' ) { mp [ i % k ] = s [ i ] ; } } for ( int i = 0 ; i < s . Length ; i ++ ) { if ( ! mp . ContainsKey ( i % k ) ) { Console . WriteLine ( - 1 ) ; return ; } s [ i ] = ( char ) mp [ i % k ] ; } Console . WriteLine ( new string ( s ) ) ; } static void Main ( ) { string S = " ? ? ? ? abcd " ; int K = 4 ; fillString ( S , K ) ; } }
|
Rearrange a string S1 such that another given string S2 is not its subsequence | C # program for the above approach ; Function to rearrange characters in string S1 such that S2 is not a subsequence of it ; Store the frequencies of characters of string s2 ; Traverse the string s2 ; Update the frequency ; Find the number of unique characters in s2 ; Increment unique by 1 if the condition satisfies ; Check if the number of unique characters in string s2 is 1 ; Store the unique character frequency ; Store occurence of it in s1 ; Find count of that character in the string s1 ; Increment count by 1 if that unique character is same as current character ; If count count_in_s1 is less than count_in_s2 , then print s1 and return ; Otherwise , there is no possible arrangement ; Checks if any character in s2 is less than its next character ; Iterate the string , s2 ; If s [ i ] is greater than the s [ i + 1 ] ; Set inc to 0 ; If inc = 1 , print s1 in decreasing order ; Otherwise , print s1 in increasing order ; Driver code
|
using System ; class GFG { static void rearrangeString ( char [ ] s1 , char [ ] s2 ) { int [ ] cnt = new int [ 26 ] ; for ( int i = 0 ; i < s2 . Length ; i ++ ) cnt [ s2 [ i ] - ' a ' ] ++ ; int unique = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) if ( cnt [ i ] != 0 ) unique ++ ; if ( unique == 1 ) { int count_in_s2 = s2 . Length ; int count_in_s1 = 0 ; for ( int i = 0 ; i < s1 . Length ; i ++ ) if ( s1 [ i ] == s2 [ 0 ] ) count_in_s1 ++ ; if ( count_in_s1 < count_in_s2 ) { Console . Write ( new string ( s1 ) ) ; return ; } Console . Write ( - 1 ) ; } else { int inc = 1 ; for ( int i = 0 ; i < s2 . Length - 1 ; i ++ ) if ( s2 [ i ] > s2 [ i + 1 ] ) inc = 0 ; if ( inc == 1 ) { Array . Sort ( s1 ) ; Array . Reverse ( s1 ) ; Console . Write ( new string ( s1 ) ) ; } else { Array . Sort ( s1 ) ; Console . Write ( new string ( s1 ) ) ; } } } static void Main ( ) { char [ ] s1 = " abcd " . ToCharArray ( ) ; char [ ] s2 = " ab " . ToCharArray ( ) ; rearrangeString ( s1 , s2 ) ; } }
|
Check if a string can be emptied by removing all subsequences of the form "10" | C # program for the above approach ; Function to find if string is reducible to NULL ; Length of string ; Stack to store all 1 s ; Iterate over the characters of the string ; If current character is 1 ; Push it into the stack ; Pop from the stack ; If the stack is empty ; Driver code
|
using System ; using System . Collections . Generic ; class GFG { static bool isReducible ( string str ) { int N = str . Length ; List < char > s = new List < char > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( str [ i ] == '1' ) s . Add ( str [ i ] ) ; else if ( s . Count > 0 ) s . RemoveAt ( s . Count - 1 ) ; else return false ; } if ( s . Count == 0 ) { return true ; } else { return false ; } } static void Main ( ) { string str = "11011000" ; if ( isReducible ( str ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
|
Minimize flips required such that string does not any pair of consecutive 0 s | C # program for the above approach ; Function to find minimum flips required such that a String does not contain any pair of consecutive 0 s ; Stores minimum count of flips ; Iterate over the characters of the String ; If two consecutive characters are equal to '0' ; Update S [ i + 1 ] ; Update cntOp ; Driver Code
|
using System ; class GFG { static int cntMinOperation ( char [ ] S , int N ) { int cntOp = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( S [ i ] == '0' && S [ i + 1 ] == '0' ) { S [ i + 1 ] = '1' ; cntOp += 1 ; } } return cntOp ; } public static void Main ( string [ ] args ) { string S = "10001" ; int N = S . Length ; Console . WriteLine ( cntMinOperation ( S . ToCharArray ( ) , N ) ) ; } }
|
Rearrange a string to maximize the minimum distance between any pair of vowels | C # program for the above approach ; Function to rearrange the String such that the minimum distance between any of vowels is maximum . ; Store vowels and consonants ; Iterate over the characters of String ; If current character is a vowel ; If current character is a consonant ; Stores count of vowels and consonants respectively ; Stores the resultant String ; Stores count of consonants appended into ans ; Append vowel to ans ; Append consonants ; Append consonant to ans ; Update temp ; Remove the taken elements of consonant ; Return final ans ; Driver Code ; Function Call
|
using System ; using System . Collections . Generic ; class GFG { static String solution ( string s ) { List < char > vowel = new List < char > ( ) ; List < char > consonant = new List < char > ( ) ; foreach ( char i in s . ToCharArray ( ) ) { if ( i == ' a ' i == ' e ' i == ' i ' i == ' o ' i == ' u ' ) { vowel . Add ( i ) ; } else { consonant . Add ( i ) ; } } int Nc , Nv ; Nv = vowel . Count ; Nc = consonant . Count ; int M = Nc / ( Nv - 1 ) ; string ans = " " ; int consotnant_till = 0 ; foreach ( char i in vowel ) { ans += i ; int temp = 0 ; for ( int j = consotnant_till ; j < Math . Min ( Nc , consotnant_till + M ) ; j ++ ) { ans += consonant [ j ] ; temp ++ ; } consotnant_till += temp ; } return ans ; } static public void Main ( ) { String str = " aaaabbbcc " ; Console . WriteLine ( solution ( str ) ) ; } }
|
Lexicographically smallest string possible by performing K operations on a given string | C # program to implement the above approach ; Function to find the lexicographically smallest possible string by performing K operations on string S ; Store the size of string , s ; Check if k >= n , if true , convert every character to ' a ' ; Iterate in range [ 0 , n - 1 ] using i ; When k reaches 0 , break the loop ; If current character is ' a ' , continue ; Otherwise , iterate in the range [ i + 1 , n - 1 ] using j ; Check if s [ j ] > s [ i ] ; If true , set s [ j ] = s [ i ] and break out of the loop ; Check if j reaches the last index ; Update S [ i ] ; Decrement k by 1 ; Print string ; Driver code ; Given String , s ; Given k ; Function Call
|
using System ; using System . Collections . Generic ; class GFG { static void smallestlexicographicstring ( char [ ] s , int k ) { int n = s . Length ; if ( k >= n ) { for ( int i = 0 ; i < n ; i ++ ) { s [ i ] = ' a ' ; } Console . Write ( s ) ; return ; } for ( int i = 0 ; i < n ; i ++ ) { if ( k == 0 ) { break ; } if ( s [ i ] == ' a ' ) continue ; for ( int j = i + 1 ; j < n ; j ++ ) { if ( s [ j ] > s [ i ] ) { s [ j ] = s [ i ] ; break ; } else if ( j == n - 1 ) s [ j ] = s [ i ] ; } s [ i ] = ' a ' ; k -- ; } Console . Write ( s ) ; } static void Main ( ) { char [ ] s = ( " geeksforgeeks " ) . ToCharArray ( ) ; int k = 6 ; smallestlexicographicstring ( s , k ) ; } }
|
Minimize removal of non | C # program for the above approach ; Function to find minimum count of steps required ot make String S an empty String ; Stores count of occurences ' ( ' ; Stores count of occurences ' ) ' ; Traverse the String , str ; If current character is ' ( ' ; Update count_1 ; Update count_2 ; If all the characters are same , then print - 1 ; If the count of occurence of ' ) ' and ' ( ' are same then print 0 ; If length of String is Odd ; Driver Code ; Given String ; Size of the String ; Function Call
|
using System ; class GFG { static void canReduceString ( String S , int N ) { int count_1 = 0 ; int count_2 = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] == ' ( ' ) { count_1 ++ ; } else { count_2 ++ ; } } if ( count_1 == 0 count_2 == 0 ) { Console . Write ( " - 1" + " STRNEWLINE " ) ; } else if ( count_1 == count_2 ) { Console . Write ( "0" + " STRNEWLINE " ) ; } else if ( N % 2 != 0 ) { Console . Write ( " - 1" ) ; } else { Console . Write ( Math . Abs ( count_1 - count_2 ) / 2 ) ; } } public static void Main ( String [ ] args ) { String S = " ) ) ) ( ( ( " ; int N = S . Length ; canReduceString ( S , N ) ; } }
|
Program to construct a DFA which accepts the language L = { aN | N Γ’ β°Β₯ 1 } | C # program for the above approach ; Function to check whether the String S satisfy the given DFA or not ; Stores the count of characters ; Iterate over the range [ 0 , N ] ; Count and check every element for ' a ' ; If String matches with DFA ; If not matches ; Driver Code ; Function Call
|
using System ; class GFG { static void isAcceptedDFA ( String s , int N ) { int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( s [ i ] == ' a ' ) count ++ ; } if ( count == N && count != 0 ) { Console . Write ( " Accepted " ) ; } else { Console . Write ( " Not β Accepted " ) ; } } public static void Main ( String [ ] args ) { String S = " aaaaa " ; isAcceptedDFA ( S , S . Length ) ; } }
|
Maximize palindromic strings of length 3 possible from given count of alphabets | C # program for the above approach ; Function to count maximum number of palindromic String of length 3 ; Stores the readonly count of palindromic Strings ; Traverse the array ; Increment res by arr [ i ] / 3 , i . e forming String of only i + ' a ' character ; Store remainder ; Increment c1 by one , if current frequency is 1 ; Increment c2 by one , if current frequency is 2 ; Count palindromic Strings of length 3 having the character at the ends different from that present in the middle ; Update c1 and c2 ; Increment res by 2 * c2 / 3 ; Finally print the result ; Driver Code ; Given array ; Function Call
|
using System ; public class GFG { static void maximum_pallindromic ( int [ ] arr ) { int res = 0 ; int c1 = 0 , c2 = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) { res += arr [ i ] / 3 ; arr [ i ] = arr [ i ] % 3 ; if ( arr [ i ] == 1 ) c1 ++ ; else if ( arr [ i ] == 2 ) c2 ++ ; } res += Math . Min ( c1 , c2 ) ; int t = Math . Min ( c1 , c2 ) ; c1 -= t ; c2 -= t ; res += 2 * ( c2 / 3 ) ; c2 %= 3 ; res += c2 / 2 ; Console . Write ( res ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 4 , 5 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } ; maximum_pallindromic ( arr ) ; } }
|
Find the winner of game of repeatedly removing the first character to empty given string | C # program to implement the above approach ; Function to find the winner of a game of repeatedly removing the first character to empty a String ; Store characters of each String of the array [ ] arr ; Stores count of Strings in [ ] arr ; Traverse the array [ ] arr ; Stores length of current String ; Traverse the String ; Insert arr [ i , j ] ; 1 st Player starts the game ; Stores the player number for the next turn ; Remove 1 st character of current String ; Update player number for the next turn ; Driver Code
|
using System ; using System . Collections . Generic ; class GFG { static void find_Winner ( String [ ] arr , int N ) { List < char > [ ] Q = new List < char > [ N ] ; for ( int i = 0 ; i < Q . Length ; i ++ ) Q [ i ] = new List < char > ( ) ; int M = arr . Length ; for ( int i = 0 ; i < M ; i ++ ) { int len = arr [ i ] . Length ; for ( int j = 0 ; j < len ; j ++ ) { Q [ i ] . Add ( arr [ i ] [ j ] ) ; } } int player = 0 ; while ( Q [ player ] . Count > 0 ) { int nextPlayer = Q [ player ] [ 0 ] - '0' - 1 ; Q [ player ] . RemoveAt ( 0 ) ; player = nextPlayer ; } Console . Write ( " Player β " + ( player + 1 ) ) ; } public static void Main ( String [ ] args ) { int N = 3 ; String [ ] arr = { "323" , "2" , "2" } ; find_Winner ( arr , N ) ; } }
|
Longest Substring that can be made a palindrome by swapping of characters | C # program for the above approach ; Function to find the Longest substring that can be made a palindrome by swapping of characters ; Initialize dp array of size 1024 ; Initializeing dp array with length of s ; Initializing mask and res ; Traverse the string ; Find the mask of the current character ; Finding the length of the longest substring in s which is a palindrome for even count ; Finding the length of the longest substring in s which is a palindrome for one odd count ; Finding maximum length of substring having one odd count ; dp [ mask ] is minimum of current i and dp [ mask ] ; Return longest length of the substring which forms a palindrome with swaps ; Driver Code ; Input String ; Function Call
|
using System ; class GFG { public static int longestSubstring ( string s ) { int [ ] dp = new int [ 1024 ] ; for ( int i = 0 ; i < 1024 ; ++ i ) { dp [ i ] = s . Length ; } int res = 0 , mask = 0 ; dp [ 0 ] = - 1 ; for ( int i = 0 ; i < s . Length ; i ++ ) { mask = mask ^ ( 1 << ( s [ i ] - '0' ) ) ; res = Math . Max ( res , i - dp [ mask ] ) ; for ( int j = 0 ; j < 10 ; j ++ ) { res = Math . Max ( res , i - dp [ mask ^ ( 1 << j ) ] ) ; } dp [ mask ] = Math . Min ( dp [ mask ] , i ) ; } return res ; } public static void Main ( string [ ] args ) { string s = "3242415" ; Console . WriteLine ( longestSubstring ( s ) ) ; } }
|
Convert given string to a valid mobile number | C # program for the above approach ; Function to print the valid and formatted phone number ; Length of given String ; Store digits in temp ; Iterate given M ; If any digit , append it to temp ; Find new length of String ; If length is not equal to 10 ; Store final result ; Make groups of 3 digits and enclose them within ( ) and separate them with " - " 0 to 2 index 1 st group ; 3 to 5 index 2 nd group ; 6 to 8 index 3 rd group ; 9 to 9 index last group ; Print final result ; Driver Code ; Given String ; Function Call
|
using System ; class GFG { static void Validate ( string M ) { int len = M . Length ; string temp = " " ; for ( int i = 0 ; i < len ; i ++ ) { if ( Char . IsDigit ( M [ i ] ) ) temp += M [ i ] ; } int nwlen = temp . Length ; if ( nwlen != 10 ) { Console . Write ( " Invalid STRNEWLINE " ) ; return ; } string res = " " ; string x = temp . Substring ( 0 , 3 ) ; res += " ( " + x + " ) - " ; x = temp . Substring ( 3 , 3 ) ; res += " ( " + x + " ) - " ; x = temp . Substring ( 6 , 3 ) ; res += " ( " + x + " ) - " ; x = temp . Substring ( 9 , 1 ) ; res += " ( " + x + " ) " ; Console . WriteLine ( res ) ; } public static void Main ( string [ ] args ) { string M = "91 β 234rt5%34*0 β 3" ; Validate ( M ) ; } }
|
Modulus of two Hexadecimal Numbers | C # program to implement the above approach ; Function to calculate modulus of two Hexadecimal numbers ; Store all possible hexadecimal digits ; Iterate over the range [ '0' , '9' ] ; Convert given string to long ; Base to get 16 power ; Store N % K ; Iterate over the digits of N ; Stores i - th digit of N ; Update ans ; Update base ; Print the answer converting into hexadecimal ; Driver Code ; Given string N and K ; Function Call
|
using System ; using System . Collections . Generic ; class GFG { static void hexaModK ( String N , String k ) { Dictionary < char , int > map = new Dictionary < char , int > ( ) ; for ( char i = '0' ; i <= '9' ; i ++ ) { map . Add ( i , i - '0' ) ; } map . Add ( ' A ' , 10 ) ; map . Add ( ' B ' , 11 ) ; map . Add ( ' C ' , 12 ) ; map . Add ( ' D ' , 13 ) ; map . Add ( ' E ' , 14 ) ; map . Add ( ' F ' , 15 ) ; long m = long . Parse ( k ) ; long Base = 1 ; long ans = 0 ; for ( int i = N . Length - 1 ; i >= 0 ; i -- ) { long n = map [ N [ i ] ] % m ; ans = ( ans + ( Base % m * n % m ) % m ) % m ; Base = ( Base % m * 16 % m ) % m ; } Console . WriteLine ( ans . ToString ( " X " ) ) ; } public static void Main ( String [ ] args ) { String n = "3E8" ; String k = "13" ; hexaModK ( n , k ) ; } }
|
Print all combinations generated by characters of a numeric string which does not exceed N | C # program for the above approach ; Store the current sequence of s ; Store the all the required sequences ; Function to print all sequences of S satisfying the required condition ; Print all Strings in the set ; Function to generate all sequences of String S that are at most N ; Iterate over String s ; Push ith character to combination ; Convert the String to number ; Check if the condition is true ; Push the current String to the readonly set of sequences ; Recursively call function ; Backtrack to its previous state ; Driver Code ; Function Call ; Print required sequences
|
using System ; using System . Collections . Generic ; class GFG { static String combination = " " ; static SortedSet < String > combinations = new SortedSet < String > ( ) ; static void printSequences ( SortedSet < String > combinations ) { foreach ( String s in combinations ) { Console . Write ( s + " β " ) ; } } static void generateCombinations ( String s , int n ) { for ( int i = 0 ; i < s . Length ; i ++ ) { combination += ( s [ i ] ) ; long x = Int32 . Parse ( combination ) ; if ( x <= n ) { combinations . Add ( combination ) ; generateCombinations ( s , n ) ; } combination = combination . Substring ( 0 , combination . Length - 1 ) ; } } public static void Main ( String [ ] args ) { String S = "124" ; int N = 100 ; generateCombinations ( S , N ) ; printSequences ( combinations ) ; } }
|
Count Distinct Strings present in an array using Polynomial rolling hash function | C # program to implement the above approach ; Function to find the hash value of a string ; Traverse the string ; Update hash_val ; Update mul ; Return hash_val of str ; Function to find the count of distinct strings present in the given array ; Store the hash values of the strings ; Traverse the array ; Stores hash value of arr [ i ] ; Sort hash [ ] array ; Stores count of distinct strings in the array ; Traverse hash [ ] array ; Update cntElem ; Driver Code
|
using System ; class GFG { static int compute_hash ( string str ) { int p = 31 ; int MOD = ( int ) 1e9 + 7 ; int hash_val = 0 ; int mul = 1 ; for ( int i = 0 ; i < str . Length ; i ++ ) { char ch = str [ i ] ; hash_val = ( hash_val + ( ch - ' a ' + 1 ) * mul ) % MOD ; mul = ( mul * p ) % MOD ; } return hash_val ; } static int distinct_str ( string [ ] arr , int n ) { int [ ] hash = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { hash [ i ] = compute_hash ( arr [ i ] ) ; } Array . Sort ( hash ) ; int cntElem = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( hash [ i ] != hash [ i - 1 ] ) { cntElem ++ ; } } return cntElem ; } public static void Main ( String [ ] args ) { string [ ] arr = { " abcde " , " abcce " , " abcdf " , " abcde " } ; int N = arr . Length ; Console . WriteLine ( distinct_str ( arr , N ) ) ; } }
|
Remove characters from given string whose frequencies are a Prime Number | C # program for the above approach ; Function to perform the seive of eratosthenes algorithm ; Initialize all entries in prime [ ] as true ; Initialize 0 and 1 as non prime ; Traversing the prime array ; If i is prime ; All multiples of i must be marked false as they are non prime ; Function to remove characters which have prime frequency in the String ; Length of the String ; Create a bool array prime ; Sieve of Eratosthenes ; Stores the frequency of character ; Storing the frequencies ; New String that will be formed ; Removing the characters which have prime frequencies ; If the character has prime frequency then skip ; Else concatenate the character to the new String ; Print the modified String ; Driver Code ; Function Call
|
using System ; using System . Collections . Generic ; class GFG { static void SieveOfEratosthenes ( bool [ ] prime , int n ) { for ( int i = 0 ; i <= n ; i ++ ) { prime [ i ] = true ; } prime [ 0 ] = prime [ 1 ] = false ; for ( int i = 2 ; i * i <= n ; i ++ ) { if ( prime [ i ] == true ) { for ( int j = 2 ; i * j <= n ; j ++ ) { prime [ i * j ] = false ; } } } } static void removePrimeFrequencies ( char [ ] s ) { int n = s . Length ; bool [ ] prime = new bool [ n + 1 ] ; SieveOfEratosthenes ( prime , n ) ; Dictionary < char , int > m = new Dictionary < char , int > ( ) ; for ( int i = 0 ; i < s . Length ; i ++ ) { if ( m . ContainsKey ( s [ i ] ) ) { m [ s [ i ] ] ++ ; } else { m . Add ( s [ i ] , 1 ) ; } } String new_String = " " ; for ( int i = 0 ; i < s . Length ; i ++ ) { if ( prime [ m [ s [ i ] ] ] ) continue ; new_String += s [ i ] ; } Console . Write ( new_String ) ; } public static void Main ( String [ ] args ) { String str = " geeksforgeeks " ; removePrimeFrequencies ( str . ToCharArray ( ) ) ; } }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.