"Stein 's Algorithm for finding GCD | Recursive C # program to implement Stein 's Algorithm ; Function to implement Stein 's Algorithm ; GCD ( 0 , b ) == b ; GCD ( a , 0 ) == a , GCD ( 0 , 0 ) == 0 ; look for factors of 2 a is even ; b is odd ; both a and b are even ; a is odd , b is even ; reduce larger number ; Driver code"
Solution in C#:

using System ; class GFG { static int gcd ( int a , int b ) { if ( a == b ) return a ; if ( a == 0 ) return b ; if ( b == 0 ) return a ; if ( ( ~ a & 1 ) == 1 ) { if ( ( b & 1 ) == 1 ) return gcd ( a >> 1 , b ) ; else return gcd ( a >> 1 , b >> 1 ) << 1 ; } if ( ( ~ b & 1 ) == 1 ) return gcd ( a , b >> 1 ) ; if ( a > b ) return gcd ( ( a - b ) >> 1 , b ) ; return gcd ( ( b - a ) >> 1 , a ) ; } public static void Main ( ) { int a = 34 , b = 17 ; Console . Write ( " Gcd ▁ of ▁ given " + " numbers ▁ is ▁ " + gcd ( a , b ) ) ; } }


"Stella Octangula Number | Program to check if a number is Stella Octangula Number ; Returns value of n * ( 2 * n * n - 1 ) ; Finds if a value of f ( n ) is equal to x where n is in interval [ low . . high ] ; Returns true if x is Stella Octangula Number . Else returns false . ; Find ' high ' for binary search by repeated doubling ; If condition is satisfied for a power of 2. ; Call binary search ; Driver code"
Solution in C#:

using System ; class GFG { static int f ( int n ) { return n * ( 2 * n * n - 1 ) ; } static bool binarySearch ( int low , int high , int x ) { while ( low <= high ) { int mid = ( low + high ) / 2 ; if ( f ( mid ) < x ) low = mid + 1 ; else if ( f ( mid ) > x ) high = mid - 1 ; else return true ; } return false ; } static bool isStellaOctangula ( int x ) { if ( x == 0 ) return true ; int i = 1 ; while ( f ( i ) < x ) i = i * 2 ; if ( f ( i ) == x ) return true ; return binarySearch ( i / 2 , i , x ) ; } public static void Main ( ) { int n = 51 ; if ( isStellaOctangula ( n ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }


"Stepping Numbers | A C # program to find all the Stepping Number in [ n , m ] ; This Method checks if an integer n is a Stepping Number ; Initalize prevDigit with - 1 ; Iterate through all digits of n and compare difference between value of previous and current digits ; Get Current digit ; Single digit is considered as a Stepping Number ; Check if absolute difference between prev digit and current digit is 1 ; A brute force approach based function to find all stepping numbers . ; Iterate through all the numbers from [ N , M ] and check if it is a stepping number . ; Driver code ; Display Stepping Numbers in the range [ n , m ]"
Solution in C#:

using System ; class GFG { public static bool isStepNum ( int n ) { int prevDigit = - 1 ; while ( n > 0 ) { int curDigit = n % 10 ; if ( prevDigit != - 1 ) { if ( Math . Abs ( curDigit - prevDigit ) != 1 ) return false ; } n /= 10 ; prevDigit = curDigit ; } return true ; } public static void displaySteppingNumbers ( int n , int m ) { for ( int i = n ; i <= m ; i ++ ) if ( isStepNum ( i ) ) Console . Write ( i + " ▁ " ) ; } public static void Main ( ) { int n = 0 , m = 21 ; displaySteppingNumbers ( n , m ) ; } }


"Stepping Numbers | A C # program to find all the Stepping Number in range [ n , m ] ; Prints all stepping numbers reachable from num and in range [ n , m ] ; Queue will contain all the stepping Numbers ; Get the front element and pop from the queue ; If the Stepping Number is in the range [ n , m ] then display ; If Stepping Number is 0 or greater then m , no need to explore the neighbors ; Get the last digit of the currently visited Stepping Number ; There can be 2 cases either digit to be appended is lastDigit + 1 or lastDigit - 1 ; If lastDigit is 0 then only possible digit after 0 can be 1 for a Stepping Number ; If lastDigit is 9 then only possible digit after 9 can be 8 for a Stepping Number ; Prints all stepping numbers in range [ n , m ] using BFS . ; For every single digit Number ' i ' find all the Stepping Numbers starting with i ; Driver code ; Display Stepping Numbers in the range [ n , m ]"
Solution in C#:

using System ; using System . Collections . Generic ; public class GFG { static void bfs ( int n , int m , int num ) { Queue < int > q = new Queue < int > ( ) ; q . Enqueue ( num ) ; while ( q . Count != 0 ) { int stepNum = q . Dequeue ( ) ; if ( stepNum <= m && stepNum >= n ) { Console . Write ( stepNum + " ▁ " ) ; } if ( stepNum == 0 stepNum > m ) continue ; int lastDigit = stepNum % 10 ; int stepNumA = stepNum * 10 + ( lastDigit - 1 ) ; int stepNumB = stepNum * 10 + ( lastDigit + 1 ) ; if ( lastDigit == 0 ) q . Enqueue ( stepNumB ) ; else if ( lastDigit == 9 ) q . Enqueue ( stepNumA ) ; else { q . Enqueue ( stepNumA ) ; q . Enqueue ( stepNumB ) ; } } } static void displaySteppingNumbers ( int n , int m ) { for ( int i = 0 ; i <= 9 ; i ++ ) bfs ( n , m , i ) ; } static public void Main ( ) { int n = 0 , m = 21 ; displaySteppingNumbers ( n , m ) ; } }


"Stepping Numbers | A C # program to find all the Stepping Numbers in range [ n , m ] using DFS Approach ; Method display 's all the stepping numbers  in range [n, m] ; If Stepping Number is in the range [ n , m ] then display ; If Stepping Number is 0 or greater than m then return ; Get the last digit of the currently visited Stepping Number ; There can be 2 cases either digit to be appended is lastDigit + 1 or lastDigit - 1 ; If lastDigit is 0 then only possible digit after 0 can be 1 for a Stepping Number ; If lastDigit is 9 then only possible digit after 9 can be 8 for a Stepping Number ; Prints all stepping numbers in range [ n , m ] using DFS . ; For every single digit Number ' i ' find all the Stepping Numbers starting with i ; Driver code ; Display Stepping Numbers in the range [ n , m ]"
Solution in C#:

using System ; public class GFG { static void dfs ( int n , int m , int stepNum ) { if ( stepNum <= m && stepNum >= n ) Console . Write ( stepNum + " ▁ " ) ; if ( stepNum == 0 stepNum > m ) return ; int lastDigit = stepNum % 10 ; int stepNumA = stepNum * 10 + ( lastDigit - 1 ) ; int stepNumB = stepNum * 10 + ( lastDigit + 1 ) ; if ( lastDigit == 0 ) dfs ( n , m , stepNumB ) ; else if ( lastDigit == 9 ) dfs ( n , m , stepNumA ) ; else { dfs ( n , m , stepNumA ) ; dfs ( n , m , stepNumB ) ; } } public static void displaySteppingNumbers ( int n , int m ) { for ( int i = 0 ; i <= 9 ; i ++ ) dfs ( n , m , i ) ; } static public void Main ( ) { int n = 0 , m = 21 ; displaySteppingNumbers ( n , m ) ; } }


"Steps required to visit M points in order on a circular ring of N points | C # implementation of the approach ; Function to count the steps required ; Start at 1 ; Initialize steps ; If nxt is greater than cur ; Now we are at a [ i ] ; Driver code"
Solution in C#:

using System ; class GFG { static int findSteps ( int n , int m , int [ ] a ) { int cur = 1 ; int steps = 0 ; for ( int i = 0 ; i < m ; i ++ ) { if ( a [ i ] >= cur ) steps += ( a [ i ] - cur ) ; else steps += ( n - cur + a [ i ] ) ; cur = a [ i ] ; } return steps ; } public static void Main ( ) { int n = 3 , m = 3 ; int [ ] a = { 2 , 1 , 2 } ; Console . WriteLine ( findSteps ( n , m , a ) ) ; } }


"Steps to reduce N to zero by subtracting its most significant digit at every step | C # program to find the count of Steps to reduce N to zero by subtracting its most significant digit at every step ; Function to count the number of digits in a number m ; Function to count the number of steps to reach 0 ; count the total number of stesp ; iterate till we reach 0 ; count the digits in last ; decrease it by 1 ; find the number on whose division , we get the first digit ; first digit in last ; find the first number less than last where the first digit changes ; find the number of numbers with same first digit that are jumped ; count the steps ; the next number with a different first digit ; Driver code"
Solution in C#:

using System ; class GFG { static int countdig ( int m ) { if ( m == 0 ) return 0 ; else return 1 + countdig ( m / 10 ) ; } static int countSteps ( int x ) { int c = 0 ; int last = x ; while ( last > 0 ) { int digits = countdig ( last ) ; digits -= 1 ; int divisor = ( int ) Math . Pow ( 10 , digits ) ; int first = last / divisor ; int lastnumber = first * divisor ; int skipped = ( last - lastnumber ) / first ; skipped += 1 ; c += skipped ; last = last - ( first * skipped ) ; } return c ; } static void Main ( ) { int n = 14 ; Console . WriteLine ( countSteps ( n ) ) ; } }


"Stern | C # program to print Brocot Sequence ; loop to create sequence ; adding sum of considered element and it 's precedent ; adding next considered element ; printing sequence . . ; Driver code ; adding first two element in the sequence"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static void SternSequenceFunc ( List < int > BrocotSequence , int n ) { for ( int i = 1 ; BrocotSequence . Count < n ; i ++ ) { int considered_element = BrocotSequence [ i ] ; int precedent = BrocotSequence [ i - 1 ] ; BrocotSequence . Add ( considered_element + precedent ) ; BrocotSequence . Add ( considered_element ) ; } for ( int i = 0 ; i < 15 ; ++ i ) Console . Write ( BrocotSequence [ i ] + " ▁ " ) ; } static void Main ( ) { int n = 15 ; List < int > BrocotSequence = new List < int > ( ) ; BrocotSequence . Add ( 1 ) ; BrocotSequence . Add ( 1 ) ; SternSequenceFunc ( BrocotSequence , n ) ; } }


"Stooge Sort | C # program to implement stooge sort ; Function to implement stooge sort ; If first element is smaller than last , swap them ; If there are more than 2 elements in the array ; Recursively sort first 2 / 3 elements ; Recursively sort last 2 / 3 elements ; Recursively sort first 2 / 3 elements again to confirm ; Driver Code ; Calling Stooge Sort function to sort the array ; Display the sorted array"
Solution in C#:

using System ; class GFG { static void stoogesort ( int [ ] arr , int l , int h ) { if ( l >= h ) return ; if ( arr [ l ] > arr [ h ] ) { int t = arr [ l ] ; arr [ l ] = arr [ h ] ; arr [ h ] = t ; } if ( h - l + 1 > 2 ) { int t = ( h - l + 1 ) / 3 ; stoogesort ( arr , l , h - t ) ; stoogesort ( arr , l + t , h ) ; stoogesort ( arr , l , h - t ) ; } } public static void Main ( ) { int [ ] arr = { 2 , 4 , 5 , 3 , 1 } ; int n = arr . Length ; stoogesort ( arr , 0 , n - 1 ) ; for ( int i = 0 ; i < n ; i ++ ) Console . Write ( arr [ i ] + " ▁ " ) ; } }


"Straight | C # program for the above approach ; Function to check if N is a Straight Line number or not ; N must be > 99 ; Difference between consecutive digits must be same ; Driver code ; Given Number N ; Function Call"
Solution in C#:

using System ; class GFG { static bool isStraighLineNum ( int N ) { if ( N <= 99 ) return false ; string s = N . ToString ( ) ; int d = s [ 1 ] - s [ 0 ] ; for ( int i = 2 ; i < s . Length ; i ++ ) if ( s [ i ] - s [ i - 1 ] != d ) return false ; return true ; } public static void Main ( ) { int n = 135 ; if ( isStraighLineNum ( n ) ) { Console . Write ( " Yes " ) ; } else { Console . Write ( " No " ) ; } } }


"String formed with middle character of every right substring followed by left sequentially | C # implementation of the above approach ; Function to decrypt and print the new String ; If the whole String has been traversed ; To calculate middle index of the String ; Print the character at middle index ; Recursively call for right - subString ; Recursive call for left - subString ; Driver Code"
Solution in C#:

 using System ; class GFG { static void decrypt ( String Str , int Start , int End ) { if ( Start > End ) { return ; } int mid = ( Start + End ) >> 1 ; Console . Write ( Str [ mid ] ) ; decrypt ( Str , mid + 1 , End ) ; decrypt ( Str , Start , mid - 1 ) ; } public static void Main ( ) { int N = 4 ; String Str = " abcd " ; decrypt ( Str , 0 , N - 1 ) ; Console . Write ( "
 " ) ; N = 6 ; Str = " gyuitp " ; decrypt ( Str , 0 , N - 1 ) ; } }


"String hashing using Polynomial rolling hash function | C # implementation of the Polynomial Rolling Hash Function ; Function to calculate the hash of a String ; P and M ; Loop to calculate the hash value by iterating over the elements of String ; Driver Code ; Given Strings"
Solution in C#:

using System ; class GFG { static long polynomialRollingHash ( String str ) { int p = 31 ; int m = ( int ) ( 1e9 + 9 ) ; long power_of_p = 1 ; long hash_val = 0 ; for ( int i = 0 ; i < str . Length ; i ++ ) { hash_val = ( hash_val + ( str [ i ] - ' a ' + 1 ) * power_of_p ) % m ; power_of_p = ( power_of_p * p ) % m ; } return hash_val ; } public static void Main ( String [ ] args ) { String str1 = " geeksforgeeks " ; String str2 = " geeks " ; Console . Write ( " Hash ▁ of ▁ ' " + str1 + " ' ▁ = ▁ " + polynomialRollingHash ( str1 ) ) ; } }


"String matching with * ( that matches with any ) in any of the two strings | C # program for string matching with ; Function to check if the two strings can be matched or not ; if the string don 't have *  then character at that position  must be same. ; Driver code"
Solution in C#:

using System ; class GfG { public static int doMatch ( String A , String B ) { for ( int i = 0 ; i < A . Length ; i ++ ) { if ( A [ i ] != ' * ' && B [ i ] != ' * ' ) if ( A [ i ] != B [ i ] ) return 0 ; } return 1 ; } public static void Main ( String [ ] args ) { String A = " gee * sforgeeks " ; String B = " geeksforgeeks " ; Console . WriteLine ( doMatch ( A , B ) ) ; } }


"String transformation using XOR and OR | C # program to check if string1 can be converted to string2 using XOR and OR operations ; function to check if conversion is possible or not ; if lengths are different ; iterate to check if both strings have 1 ; to check if there is even one 1 in string s1 ; to check if there is even one 1 in string s2 ; if both strings have only '0' ; if both string do not have a '1' . ; Driver code"
Solution in C#:

using System ; class GFG { static bool solve ( String s1 , String s2 ) { bool flag1 = false , flag2 = false ; if ( s1 . Length != s2 . Length ) return false ; int l = s1 . Length ; for ( int i = 0 ; i < l ; i ++ ) { if ( s1 [ i ] == '1' ) flag1 = true ; if ( s2 [ i ] == '1' ) flag2 = true ; if ( flag1 == true && flag2 == true ) return true ; } if ( ! flag1 && ! flag2 ) return true ; return false ; } public static void Main ( ) { String s1 = "100101" ; String s2 = "100000" ; if ( solve ( s1 , s2 ) == true ) Console . Write ( " Yes " ) ; else Console . Write ( " No " ) ; } }


"String which when repeated exactly K times gives a permutation of S | C # program to find a string which when repeated exactly k times gives a permutation of the given string ; Function to return a string which when repeated exactly k times gives a permutation of s ; size of string ; to frequency of each character ; get frequency of each character ; to store final answer ; check if frequency is divisible by k ; add to answer ; if frequency is not divisible by k ; Driver code ; function call"
Solution in C#:

using System ; class GFG { static String K_String ( String s , int k ) { int n = s . Length ; int [ ] fre = new int [ 26 ] ; for ( int i = 0 ; i < n ; i ++ ) fre [ s [ i ] - ' a ' ] ++ ; String str = " " ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( fre [ i ] % k == 0 ) { int x = fre [ i ] / k ; while ( x != 0 ) { str += ( char ) ( i + ' a ' ) ; x -- ; } } else { return " - 1" ; } } return str ; } public static void Main ( String [ ] args ) { String s = " aabb " ; int k = 2 ; Console . WriteLine ( K_String ( s , k ) ) ; } }


"String with k distinct characters and no same characters adjacent | C # program to construct a n length string with k distinct characters such that no two same characters are adjacent . ; Function to find a string of length n with k distinct characters . ; Initialize result with first k Latin letters ; Fill remaining n - k letters by repeating k letters again and again . ; Driver code"
Solution in C#:

using System ; public class GFG { static string findString ( int n , int k ) { string res = " " ; for ( int i = 0 ; i < k ; i ++ ) res = res + ( char ) ( ' a ' + i ) ; int count = 0 ; for ( int i = 0 ; i < n - k ; i ++ ) { res = res + ( char ) ( ' a ' + count ) ; count ++ ; if ( count == k ) count = 0 ; } return res ; } static public void Main ( ) { int n = 5 , k = 2 ; Console . WriteLine ( findString ( n , k ) ) ; } }


"String with maximum number of unique characters | C # code to find the largest string ; Function to find string with maximum number of unique characters . ; Index of string with maximum unique characters ; iterate through all strings ; array indicating any alphabet included or not included ; count number of unique alphabets in each string ; keep track of maximum number of alphabets ; print result ; Driver code"
Solution in C#:

using System ; class GFG { public static void LargestString ( string [ ] na ) { int N = na . Length ; int [ ] c = new int [ N ] ; int m = 0 ; for ( int j = 0 ; j < N ; j ++ ) { bool [ ] character = new bool [ 26 ] ; for ( int k = 0 ; k < na [ j ] . Length ; k ++ ) { int x = na [ j ] [ k ] - ' A ' ; if ( ( na [ j ] [ k ] != ' ▁ ' ) && ( character [ x ] == false ) ) { c [ j ] ++ ; character [ x ] = true ; } } if ( c [ j ] > c [ m ] ) m = j ; } Console . Write ( na [ m ] ) ; } public static void Main ( ) { string [ ] na = { " BOB " , " A ▁ AB ▁ C ▁ JOHNSON " , " ANJALI " , " ASKRIT " , " ARMAN ▁ MALLIK " } ; LargestString ( na ) ; } }


"Strings formed from given characters without any consecutive repeating characters | C # implementation of the above approach ; Function to print the strings which satisfy the mentioned conditions ; Iterate through all the strings in the array . ; check function to check the conditions for every string ; Function to check whether the string contains any consecutive repetitive characters and any characters other than those in str ; Valid characters check ; Nonrepetitive check ; Driver code"
Solution in C#:

using System ; class GFG { public static void getStrings ( String str , String [ ] arr ) { for ( int i = 0 ; i < arr . Length ; i ++ ) { if ( check ( arr [ i ] , str ) ) { Console . Write ( arr [ i ] + " ▁ " ) ; } } } public static bool check ( String s , String str ) { char [ ] chars = s . ToCharArray ( ) ; foreach ( char c in chars ) { if ( ! str . Contains ( String . Join ( " " , c ) ) ) { return false ; } } for ( int i = 0 ; i < chars . Length - 1 ; i ++ ) { if ( chars [ i ] == chars [ i + 1 ] ) { return false ; } } return true ; } public static void Main ( String [ ] args ) { String str = " ABCD " ; String [ ] arr = { " AABCDA " , " ABCDZADC " , " ABCDBCA " , " ABCDABDCA " } ; getStrings ( str , arr ) ; } }


"Students with maximum average score of three subjects | C # program to find the list of students having maximum average score ; Function to find the list of students having maximum average score Driver code ; Variables to store average score of a student and maximum average score ; List to store names of students having maximum average score ; Traversing the file data ; finding average score of a student ; Clear the list and add name of student having current maximum average score in the list ; Printing the maximum average score and names of students having this maximum average score as per the order in the file . ; Driver code ; Number of elements in string array"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static void getStudentsList ( string [ ] file ) { int avgScore ; int maxAvgScore = Int32 . MinValue ; List < string > names = new List < string > ( ) ; for ( int i = 0 ; i < file . Length ; i += 4 ) { avgScore = ( Int32 . Parse ( file [ i + 1 ] ) + Int32 . Parse ( file [ i + 2 ] ) + Int32 . Parse ( file [ i + 3 ] ) ) / 3 ; if ( avgScore > maxAvgScore ) { maxAvgScore = avgScore ; names . Clear ( ) ; names . Add ( file [ i ] ) ; } else if ( avgScore == maxAvgScore ) names . Add ( file [ i ] ) ; } for ( int i = 0 ; i < names . Count ; i ++ ) { Console . Write ( names [ i ] + " ▁ " ) ; } Console . WriteLine ( maxAvgScore ) ; } public static void Main ( ) { string [ ] file = { " Shrikanth " , "20" , "30" , "10" , " Ram " , "100" , "50" , "10" } ; getStudentsList ( file ) ; } }


"Sub | C # code to find the sub - tree with minimum color difference in a 2 - coloured tree ; Tree traversal to compute minimum difference ; Initial min difference is the color of node ; Traversing its children ; Not traversing the parent ; If the child is Adding positively to difference , we include it in the answer Otherwise , we leave the sub - tree and include 0 ( nothing ) in the answer ; DFS for colour difference : 1 colour - 2 colour ; Minimum colour difference is maximum answer value ; Clearing the current value to check for colour2 as well ; Interchanging the colours ; DFS for colour difference : 2 colour - 1 colour ; Checking if colour2 makes the minimum colour difference ; Driver code ; Nodes ; Adjacency list representation ; Edges ; Index represent the colour of that node There is no Node 0 , so we start from index 1 to N ; Printing the result"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static void dfs ( int node , int parent , List < int > [ ] tree , int [ ] colour , int [ ] answer ) { answer [ node ] = colour [ node ] ; foreach ( int u in tree [ node ] ) { if ( u == parent ) continue ; dfs ( u , node , tree , colour , answer ) ; answer [ node ] += Math . Max ( answer [ u ] , 0 ) ; } } static int maxDiff ( List < int > [ ] tree , int [ ] colour , int N ) { int [ ] answer = new int [ N + 1 ] ; dfs ( 1 , 0 , tree , colour , answer ) ; int high = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { high = Math . Max ( high , answer [ i ] ) ; answer [ i ] = 0 ; } for ( int i = 1 ; i <= N ; i ++ ) { if ( colour [ i ] == - 1 ) colour [ i ] = 1 ; else colour [ i ] = - 1 ; } dfs ( 1 , 0 , tree , colour , answer ) ; for ( int i = 1 ; i < N ; i ++ ) high = Math . Max ( high , answer [ i ] ) ; return high ; } public static void Main ( String [ ] args ) { int N = 5 ; List < int > [ ] tree = new List < int > [ N + 1 ] ; for ( int i = 0 ; i < N + 1 ; i ++ ) tree [ i ] = new List < int > ( ) ; tree [ 1 ] . Add ( 2 ) ; tree [ 2 ] . Add ( 1 ) ; tree [ 1 ] . Add ( 3 ) ; tree [ 3 ] . Add ( 1 ) ; tree [ 2 ] . Add ( 4 ) ; tree [ 4 ] . Add ( 2 ) ; tree [ 3 ] . Add ( 5 ) ; tree [ 5 ] . Add ( 3 ) ; int [ ] colour = { 0 , 1 , 1 , - 1 , - 1 , 1 } ; Console . WriteLine ( maxDiff ( tree , colour , N ) ) ; } }


"Sub | C # implementation of above approach ; Function that counts all the sub - strings of length ' k ' which have all identical characters ; count of sub - strings , length , initial position of sliding window ; map to store the frequency of the characters of sub - string ; increase the frequency of the character and length of the sub - string ; if the length of the sub - string is greater than K ; remove the character from the beginning of sub - string ; if the length of the sub string is equal to k and frequency of one of its characters is equal to the length of the sub - string i . e . all the characters are same increase the count ; display the number of valid sub - strings ; Driver code"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static void solve ( string s , int k ) { int count = 0 , length = 0 , pos = 0 ; 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 [ s [ i ] ] = 1 ; length ++ ; if ( length > k ) { m [ s [ pos ] ] -- ; pos ++ ; length -- ; } if ( length == k && m [ s [ i ] ] == length ) count ++ ; } Console . WriteLine ( count ) ; } public static void Main ( ) { string s = " aaaabbbccdddd " ; int k = 4 ; solve ( s , k ) ; } }


"Sub | C # implementation of the approach ; Function that checks if the String contain exactly K characters having ASCII value greater than p ; if ASCII value is greater than ' p ' ; if count of satisfying characters is equal to ' K ' then return true ; otherwise return false ; function to count sub - Strings ; length of the String ; count of sub - Strings ; ' i ' is the starting index for the sub - String ; ' j ' is the no . of characters to include in the sub - String ; check if the sub - String satisfies the condition ; Driver code"
Solution in C#:

using System ; class GFG { bool isValidSubString ( String r , int K , int p ) { int c = 0 ; for ( int i = 0 ; i < r . Length ; i ++ ) { if ( ( int ) r [ i ] > p ) { c ++ ; } } if ( c == K ) { return true ; } else { return false ; } } void countSubStrings ( String s , int K , int p ) { int l = s . Length ; int count = 0 ; for ( int i = 0 ; i < l ; i ++ ) { for ( int j = K ; ( i + j ) <= l ; j ++ ) { String r = s . Substring ( i , j ) ; if ( isValidSubString ( r , K , p ) ) { count ++ ; } } } Console . WriteLine ( count ) ; } public static void Main ( String [ ] args ) { GFG g = new GFG ( ) ; String s = " abepztydba " ; int K = 4 ; int p = 110 ; g . countSubStrings ( s , K , p ) ; } }


"Sub | C # implementation of the approach ; Function that returns the index of next occurrence of the character c in string str starting from index start ; Starting from start ; If current character = c ; Not found ; Function to return the count of required sub - strings ; Stores running count of ' x ' starting from the end ; Next index of ' x ' starting from index 0 ; Next index of ' y ' starting from index 0 ; To store the count of required sub - strings ; If ' y ' appears before ' x ' it won 't contribute to a valid sub-string ; Find next occurrence of ' y ' ; If ' y ' appears after ' x ' every sub - string ending at an ' x ' appearing after this ' y ' and starting with the current ' x ' is a valid sub - string ; Find next occurrence of ' x ' ; Return the count ; Driver code"
Solution in C#:

using System ; public class GFG { static int nextIndex ( string str , int start , char c ) { for ( int i = start ; i < str . Length ; i ++ ) { if ( str [ i ] == c ) return i ; } return - 1 ; } static int countSubStrings ( string str ) { int i , n = str . Length ; int [ ] countX = new int [ n ] ; int count = 0 ; for ( i = n - 1 ; i >= 0 ; i -- ) { if ( str [ i ] == ' x ' ) count ++ ; countX [ i ] = count ; } int nextIndexX = nextIndex ( str , 0 , ' x ' ) ; int nextIndexY = nextIndex ( str , 0 , ' y ' ) ; count = 0 ; while ( nextIndexX != - 1 && nextIndexY != - 1 ) { if ( nextIndexX > nextIndexY ) { nextIndexY = nextIndex ( str , nextIndexY + 1 , ' y ' ) ; continue ; } else { count += countX [ nextIndexY ] ; nextIndexX = nextIndex ( str , nextIndexX + 1 , ' x ' ) ; } } return count ; } public static void Main ( ) { string s = " xyyxx " ; Console . WriteLine ( countSubStrings ( s ) ) ; } }


"Sub | C # implementation of the approach ; Function that returns true if every lowercase character appears atmost once ; every character frequency must be not greater than one ; Function that returns the modified good string if possible ; If the length of the string is less than n ; To store frequency of each character ; Sub - strings of length 26 ; Get the frequency of each character in the current sub - string ; Check if we can get sub - string containing all the 26 characters ; Find which character is missing ; Fill with missing characters ; Find the next missing character ; Return the modified good string ; Driver code"
Solution in C#:

using System ; class GFG { static bool valid ( int [ ] cnt ) { for ( int i = 0 ; i < 26 ; i ++ ) { if ( cnt [ i ] >= 2 ) return false ; } return true ; } static string getGoodString ( string ss , int n ) { char [ ] s = ss . ToCharArray ( ) ; if ( n < 26 ) return " - 1" ; int [ ] cnt = new int [ 27 ] ; for ( int i = 25 ; i < n ; i ++ ) { for ( int j = i ; j >= i - 25 ; j -- ) { if ( s [ j ] != ' ? ' ) cnt [ ( ( int ) s [ j ] - ( int ) ' a ' ) ] ++ ; } if ( valid ( cnt ) ) { int cur = 0 ; while ( cnt [ cur ] > 0 ) cur ++ ; for ( int j = i - 25 ; j <= i ; j ++ ) { if ( s [ j ] == ' ? ' ) { s [ j ] = ( char ) ( cur + ( int ) ( ' a ' ) ) ; cur ++ ; while ( cnt [ cur ] > 0 ) cur ++ ; } } return new String ( s ) ; } } return " - 1" ; } static void Main ( ) { string s = " abcdefghijkl ? nopqrstuvwxy ? " ; int n = s . Length ; Console . WriteLine ( getGoodString ( s , n ) ) ; } }


"Sub | C # implementation of the approach ; Function to return the count of sub - strings starting from startIndex that are also the prefixes of str ; Function to return the count of all possible sub - strings of str that are also the prefixes of str ; If current character is equal to the starting character of str ; Driver code ; Function Call"
Solution in C#:

using System ; class GFG { static int subStringsStartingHere ( String str , int n , int startIndex ) { int count = 0 , i = startIndex + 1 ; while ( i <= n ) { if ( str . StartsWith ( str . Substring ( startIndex , i - startIndex ) ) ) { count ++ ; } else break ; i ++ ; } return count ; } static int countSubStrings ( String str , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == str [ 0 ] ) count += subStringsStartingHere ( str , n , i ) ; } return count ; } static public void Main ( String [ ] args ) { String str = " ababc " ; int n = str . Length ; Console . WriteLine ( countSubStrings ( str , n ) ) ; } }


"Sub | C # program to answer multiple queries of divisibility by 3 in substrings of a number ; Array to store the sum of digits ; Utility function to evaluate a character 's  integer value ; This function receives the string representation of the number and precomputes the sum array ; This function receives l and r representing the indices and prints the required output ; Driver code"
Solution in C#:

using System ; class GFG { static int [ ] sum = new int [ 1000005 ] ; static int toInt ( char x ) { return x - '0' ; } static void prepareSum ( String s ) { sum [ 0 ] = 0 ; for ( int i = 0 ; i < s . Length ; i ++ ) { sum [ i + 1 ] = sum [ i ] + toInt ( s [ i ] ) ; } } static void query ( int l , int r ) { if ( ( sum [ r + 1 ] - sum [ l ] ) % 3 == 0 ) { Console . WriteLine ( " Divisible ▁ by ▁ 3" ) ; } else { Console . WriteLine ( " Not ▁ divisible ▁ by ▁ 3" ) ; } } public static void Main ( ) { String n = "12468236544" ; prepareSum ( n ) ; query ( 0 , 1 ) ; query ( 1 , 2 ) ; query ( 3 , 6 ) ; query ( 0 , 10 ) ; } }


"Subarray / Substring vs Subsequence and Programs to Generate them | C # code to generate all possible subsequences . Time Complexity O ( n * 2 ^ n ) ; Number of subsequences is ( 2 * * n - 1 ) ; Run from counter 000. . 1 to 111. . 1 ; Check if jth bit in the counter is set If set then print jth element from arr [ ] ; Driver Code"
Solution in C#:

using System ; class GFG { static void printSubsequences ( int [ ] arr , int n ) { int opsize = ( int ) Math . Pow ( 2 , n ) ; for ( int counter = 1 ; counter < opsize ; counter ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( ( counter & ( 1 << j ) ) != 0 ) Console . Write ( arr [ j ] + " ▁ " ) ; } Console . WriteLine ( ) ; } } static void Main ( ) { int [ ] arr = { 1 , 2 , 3 , 4 } ; int n = arr . Length ; Console . WriteLine ( " All ▁ Non - empty ▁ Subsequences " ) ; printSubsequences ( arr , n ) ; } }


"Subarray / Substring vs Subsequence and Programs to Generate them | C # program toto generate all possible subarrays / subArrays Complexity - O ( n ^ 3 ) ; Prints all subarrays in arr [ 0. . n - 1 ] ; Pick starting point ; Pick ending point ; Print subarray between current starting and ending points ; Driver Code"
Solution in C#:

using System ; class GFG { static int [ ] arr = new int [ ] { 1 , 2 , 3 , 4 } ; static void subArray ( int n ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { for ( int k = i ; k <= j ; k ++ ) Console . Write ( arr [ k ] + " ▁ " ) ; Console . WriteLine ( " " ) ; } } } public static void Main ( ) { Console . WriteLine ( " All ▁ Non - empty ▁ Subarrays " ) ; subArray ( arr . Length ) ; } }


"Subarray of size K with prime sum | C # program to implement the above approach ; Generate all prime numbers in the range [ 1 , 1000000 ] ; Set all numbers as prime initially ; Mark 0 and 1 as non - prime ; If current element is prime ; Mark all its multiples as non - prime ; Function to print the subarray whose sum of elements is prime ; Store the current subarray of size K ; Calculate the sum of first K elements ; Check if currSum is prime ; Store the start and last index of subarray of size K ; Iterate over remaining array ; Check if currSum ; Driver Code"
Solution in C#:

using System ; class GFG { static void sieve ( bool [ ] prime ) { for ( int i = 0 ; i < 1000000 ; i ++ ) { prime [ i ] = true ; } prime [ 0 ] = prime [ 1 ] = false ; for ( int i = 2 ; i * i <= 1000000 ; i ++ ) { if ( prime [ i ] ) { for ( int j = i * i ; j < 1000000 ; j += i ) { prime [ j ] = false ; } } } } static void subPrimeSum ( int N , int K , int [ ] arr , bool [ ] prime ) { int currSum = 0 ; for ( int i = 0 ; i < K ; i ++ ) { currSum += arr [ i ] ; } if ( prime [ currSum ] ) { for ( int i = 0 ; i < K ; i ++ ) { Console . Write ( arr [ i ] + " ▁ " ) ; } return ; } int st = 1 , en = K ; while ( en < N ) { currSum += arr [ en ] - arr [ st - 1 ] ; if ( prime [ currSum ] ) { for ( int i = st ; i <= en ; i ++ ) { Console . Write ( arr [ i ] + " ▁ " ) ; } return ; } en ++ ; st ++ ; } } public static void Main ( String [ ] args ) { int [ ] arr = { 20 , 7 , 5 , 4 , 3 , 11 , 99 , 87 , 23 , 45 } ; int K = 4 ; int N = arr . Length ; bool [ ] prime = new bool [ 1000000 ] ; sieve ( prime ) ; subPrimeSum ( N , K , arr , prime ) ; } }


"Subarray permutation that satisfies the given condition | C # implementation of the approach ; Function that returns true if the required subarray exists in the given array ; Map to store the positions of each integer in the original permutation ; To store the address of each entry in arr [ n ] but with 1 - based indexing ; To track minimum position sumcur for sum of aint positions tiint this position ; Summing up addresses ; Tracking minimum address encountered tiint now ; The sum of the addresses if it forms the required subarray ; If current sum of address is equal to val ; Driver code"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static bool subArray ( int [ ] arr , int n , int m ) { int i ; Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; for ( i = 0 ; i < n ; i ++ ) { mp . Add ( arr [ i ] , i + 1 ) ; } int sumcur = 0 ; int p = int . MaxValue ; List < int > ans = new List < int > ( ) ; for ( i = 1 ; i <= m ; i ++ ) { sumcur += mp [ i ] ; p = Math . Min ( p , mp [ i ] ) ; int val = p * i - i + ( i * ( i + 1 ) ) / 2 ; if ( i == m ) { if ( val == sumcur ) { return true ; } else return false ; } } return false ; } public static void Main ( String [ ] args ) { int [ ] arr = { 4 , 5 , 1 , 3 , 2 , 6 } ; int n = arr . Length ; int m = 3 ; if ( subArray ( arr , n , m ) ) Console . Write ( " Yes " ) ; else Console . Write ( " No " ) ; } }


"Subarray whose absolute sum is closest to K | C # code to find sub - array whose sum shows the minimum deviation ; Starting index , ending index , Deviation ; Iterate i and j to get all subarrays ; Found sub - array with less sum ; Exactly same sum ; Driver Code ; Array to store return values"
Solution in C#:

using System ; class GFG { public static int [ ] getSubArray ( int [ ] arr , int n , int K ) { int i = - 1 ; int j = - 1 ; int currSum = 0 ; int [ ] result = { i , j , Math . Abs ( K - Math . Abs ( currSum ) ) } ; for ( i = 0 ; i < n ; i ++ ) { currSum = 0 ; for ( j = i ; j < n ; j ++ ) { currSum += arr [ j ] ; int currDev = Math . Abs ( K - Math . Abs ( currSum ) ) ; if ( currDev < result [ 2 ] ) { result [ 0 ] = i ; result [ 1 ] = j ; result [ 2 ] = currDev ; } if ( currDev == 0 ) return result ; } } return result ; } public static void Main ( string [ ] args ) { int [ ] arr = { 15 , - 3 , 5 , 2 , 7 , 6 , 34 , - 6 } ; int n = arr . Length ; int K = 50 ; int [ ] ans = getSubArray ( arr , n , K ) ; if ( ans [ 0 ] == - 1 ) { Console . Write ( " The ▁ empty ▁ array ▁ " + " shows ▁ minimum ▁ Deviation " ) ; } else { for ( int i = ans [ 0 ] ; i <= ans [ 1 ] ; i ++ ) Console . Write ( arr [ i ] + " ▁ " ) ; } } }


"Subarray with largest sum after excluding its maximum element | C # implementation to find the maximum sum subarray such by excluding the maximum element from the subarray ; Function to find the maximum sum subarray by excluding the maximum element from the array ; Loop to store all the positive elements in the map ; Loop to iterating over the map and considering as the maximum element of the current including subarray ; Make the current element maximum ; Iterate through array and apply kadane 's algorithm ; Condition if current element is greater than mx then make the element - infinity ; Store the indices in some variable ; Driver code ; Function call"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static void maximumSumSubarray ( int [ ] arr , int n ) { Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] >= 0 ) mp . Add ( arr [ i ] , 1 ) ; } int first = 0 ; int last = 0 ; int ans = 0 ; int INF = ( int ) 1e6 ; foreach ( KeyValuePair < int , int > i in mp ) { int mx = i . Key ; int curr = 0 ; int curr_start = - 1 ; for ( int j = 0 ; j < n ; j ++ ) { if ( curr == 0 ) curr_start = j ; int val = arr [ j ] > mx ? - INF : arr [ j ] ; curr += val ; if ( curr < 0 ) curr = 0 ; if ( curr > ans ) { ans = curr ; first = curr_start ; last = j ; } } } Console . Write ( ( first + 1 ) + " ▁ " + ( last + 1 ) ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 5 , - 2 , 10 , - 1 , 4 } ; int size = arr . Length ; maximumSumSubarray ( arr , size ) ; } }


"Subarray with no pair sum divisible by K | C # Program to find the subarray with no pair sum divisible by K ; function to find the subarray with no pair sum divisible by k ; hash table to store the remainders obtained on dividing by K ; s : starting index of the current subarray , e : ending index of the current subarray , maxs : starting index of the maximum size subarray so far , maxe : ending index of the maximum size subarray so far ; insert the first element in the set ; Removing starting elements of current subarray while there is an element in set which makes a pair with mod [ i ] such that the pair sum is divisible . ; include the current element in the current subarray the ending index of the current subarray increments by one ; compare the size of the current subarray with the maximum size so far ; Driver Code"
Solution in C#:

 using System ; using System . Collections ; class GFG { static void subarrayDivisibleByK ( int [ ] arr , int n , int k ) { int [ ] mp = new int [ 1000 ] ; int s = 0 , e = 0 , maxs = 0 , maxe = 0 ; mp [ arr [ 0 ] % k ] ++ ; for ( int i = 1 ; i < n ; i ++ ) { int mod = arr [ i ] % k ; while ( mp [ k - mod ] != 0 || ( mod == 0 && mp [ mod ] != 0 ) ) { mp [ arr [ s ] % k ] -- ; s ++ ; } mp [ mod ] ++ ; e ++ ; if ( ( e - s ) > ( maxe - maxs ) ) { maxe = e ; maxs = s ; } } Console . Write ( " The ▁ maximum ▁ size ▁ is ▁ " + ( maxe - maxs + 1 ) + " ▁ and ▁ the ▁ subarray ▁ is ▁ as ▁ follows
 " ) ; for ( int i = maxs ; i <= maxe ; i ++ ) Console . Write ( arr [ i ] + " ▁ " ) ; } public static void Main ( ) { int k = 3 ; int [ ] arr = { 5 , 10 , 15 , 20 , 25 } ; int n = arr . Length ; subarrayDivisibleByK ( arr , n , k ) ; } }


"Subarrays whose sum is a perfect square | C # program to implement the above approach ; Function to print the start and end indices of all subarrays whose sum is a perfect square ; Stores the current subarray sum ; Update current subarray sum ; Stores the square root of currSubSum ; Check if currSubSum is a perfect square or not ; Driver code"
Solution in C#:

using System ; class GFG { static void PrintIndexes ( int [ ] arr , int N ) { for ( int i = 0 ; i < N ; i ++ ) { int currSubSum = 0 ; for ( int j = i ; j < N ; j ++ ) { currSubSum += arr [ j ] ; int sq = ( int ) Math . Sqrt ( currSubSum ) ; if ( sq * sq == currSubSum ) { Console . Write ( " ( " + i + " , " + j + " ) " + " ▁ " ) ; } } } } public static void Main ( String [ ] args ) { int [ ] arr = { 65 , 79 , 81 } ; PrintIndexes ( arr , arr . Length ) ; } }


"Subarrays with distinct elements | C # program to calculate sum of lengths of subarrays of distinct elements ; Returns sum of lengths of all subarrays with distinct elements . ; For maintaining distinct elements . ; Initialize ending point and result ; Fix starting point ; Calculating and adding all possible length subarrays in arr [ i . . j ] ; Remove arr [ i ] as we pick new stating point from next ; Driver Code"
Solution in C#:

using System ; using System . Collections . Generic ; public class geeks { public static int sumoflength ( int [ ] arr , int n ) { HashSet < int > s = new HashSet < int > ( ) ; int j = 0 , ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { while ( j < n && ! s . Contains ( arr [ j ] ) ) { s . Add ( arr [ i ] ) ; j ++ ; } ans += ( ( j - i ) * ( j - i + 1 ) ) / 2 ; s . Remove ( arr [ i ] ) ; } return ans ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 } ; int n = arr . Length ; Console . WriteLine ( sumoflength ( arr , n ) ) ; } }


"Submatrix Sum Queries | C # program to compute submatrix query sum in O ( 1 ) time ; Function to preprcess input mat [ M ] [ N ] . This function mainly fills aux [ M ] [ N ] such that aux [ i ] [ j ] stores sum of elements from ( 0 , 0 ) to ( i , j ) ; Copy first row of mat [ ] [ ] to aux [ ] [ ] ; Do column wise sum ; Do row wise sum ; A O ( 1 ) time function to compute sum of submatrix between ( tli , tlj ) and ( rbi , rbj ) using aux [ ] [ ] which is built by the preprocess function ; result is now sum of elements between ( 0 , 0 ) and ( rbi , rbj ) ; Remove elements between ( 0 , 0 ) and ( tli - 1 , rbj ) ; Remove elements between ( 0 , 0 ) and ( rbi , tlj - 1 ) ; Add aux [ tli - 1 ] [ tlj - 1 ] as elements between ( 0 , 0 ) and ( tli - 1 , tlj - 1 ) are subtracted twice ; Driver code"
Solution in C#:

using System ; class GFG { static int M = 4 ; static int N = 5 ; static int preProcess ( int [ , ] mat , int [ , ] aux ) { for ( int i = 0 ; i < N ; i ++ ) aux [ 0 , i ] = mat [ 0 , i ] ; for ( int i = 1 ; i < M ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) aux [ i , j ] = mat [ i , j ] + aux [ i - 1 , j ] ; for ( int i = 0 ; i < M ; i ++ ) for ( int j = 1 ; j < N ; j ++ ) aux [ i , j ] += aux [ i , j - 1 ] ; return 0 ; } static int sumQuery ( int [ , ] aux , int tli , int tlj , int rbi , int rbj ) { int res = aux [ rbi , rbj ] ; if ( tli > 0 ) res = res - aux [ tli - 1 , rbj ] ; if ( tlj > 0 ) res = res - aux [ rbi , tlj - 1 ] ; if ( tli > 0 && tlj > 0 ) res = res + aux [ tli - 1 , tlj - 1 ] ; return res ; } public static void Main ( ) { int [ , ] mat = { { 1 , 2 , 3 , 4 , 6 } , { 5 , 3 , 8 , 1 , 2 } , { 4 , 6 , 7 , 5 , 5 } , { 2 , 4 , 8 , 9 , 4 } } ; int [ , ] aux = new int [ M , N ] ; preProcess ( mat , aux ) ; int tli = 2 , tlj = 2 , rbi = 3 , rbj = 4 ; Console . Write ( " Query1 : " sumQuery ( aux , tli , tlj , rbi , rbj ) ) ; tli = 0 ; tlj = 0 ; rbi = 1 ; rbj = 1 ; Console . Write ( " Query2 : " sumQuery ( aux , tli , tlj , rbi , rbj ) ) ; tli = 1 ; tlj = 2 ; rbi = 3 ; rbj = 3 ; Console . Write ( " Query3 : " sumQuery ( aux , tli , tlj , rbi , rbj ) ) ; } }


"Subsequence X of length K such that gcd ( X [ 0 ] , X [ 1 ] ) + ( X [ 2 ] , X [ 3 ] ) + ... is maximized | C # program to find the sum of the addition of all possible subsets ; Recursive function to find the maximum value of the given recurrence ; If we get K elements ; If we have reached the end and K elements are not there ; If the state has been visited ; Iterate for every element as the next possible element and take the element which gives the maximum answer ; If this element is the first element in the individual pair in the subsequence then simply recurrence with the last element as i - th index ; If this element is the second element in the individual pair , the find gcd with the previous element and add to the answer and recur for the next element ; Driver Code"
Solution in C#:

using System ; class GFG { static int MAX = 100 ; static int recur ( int ind , int cnt , int last , int [ ] a , int n , int k , int [ , ] dp ) { if ( cnt == k ) return 0 ; if ( ind == n ) return ( int ) - 1e9 ; if ( dp [ ind , cnt ] != - 1 ) return dp [ ind , cnt ] ; int ans = 0 ; for ( int i = ind ; i < n ; i ++ ) { if ( cnt % 2 == 0 ) ans = Math . Max ( ans , recur ( i + 1 , cnt + 1 , i , a , n , k , dp ) ) ; else ans = Math . Max ( ans , __gcd ( a [ last ] , a [ i ] ) + recur ( i + 1 , cnt + 1 , 0 , a , n , k , dp ) ) ; } return dp [ ind , cnt ] = ans ; } static int __gcd ( int a , int b ) { if ( b == 0 ) return a ; return __gcd ( b , a % b ) ; } public static void Main ( String [ ] args ) { int [ ] a = { 4 , 5 , 3 , 7 , 8 , 10 , 9 , 8 } ; int n = a . Length ; int k = 4 ; int [ , ] dp = new int [ n , MAX ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < MAX ; j ++ ) { dp [ i , j ] = - 1 ; } } Console . WriteLine ( recur ( 0 , 0 , 0 , a , n , k , dp ) ) ; } }


"Subsequence of size k with maximum possible GCD | C # program to find subsequence of size k with maximum possible GCD ; function to find GCD of sub sequence of size k with max GCD in the array ; Computing highest element ; Array to store the count of divisors i . e . Potential GCDs ; Iterating over every element ; Calculating all the divisors ; Divisor found ; Incrementing count for divisor ; Element / divisor is also a divisor Checking if both divisors are not same ; Checking the highest potential GCD ; If this divisor can divide at least k numbers , it is a GCD of at least one sub sequence of size k ; Driver code ; Array in which sub sequence with size k with max GCD is to be found"
Solution in C#:

using System ; using System . Linq ; public class GFG { static int findMaxGCD ( int [ ] arr , int n , int k ) { int high = arr . Max ( ) ; int [ ] divisors = new int [ high + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 1 ; j <= Math . Sqrt ( arr [ i ] ) ; j ++ ) { if ( arr [ i ] % j == 0 ) { divisors [ j ] ++ ; if ( j != arr [ i ] / j ) divisors [ arr [ i ] / j ] ++ ; } } } for ( int i = high ; i >= 1 ; i -- ) if ( divisors [ i ] >= k ) return i ; return 0 ; } static public void Main ( ) { int [ ] arr = { 1 , 2 , 4 , 8 , 8 , 12 } ; int k = 3 ; int n = arr . Length ; Console . WriteLine ( findMaxGCD ( arr , n , k ) ) ; } }


"Subsequence pair from given Array having all unique and all same elements respectively | C # program for the above approach ; Function to find the maximum length of subsequences with given property ; To store the frequency ; Traverse the array to store the frequency ; M . Count given count of distinct element in [ ] arr ; Traverse map to find max frequency ; Find the maximum length on the basis of two cases in the approach ; Driver Code ; Function call"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static void maximumSubsequence ( int [ ] arr , int N ) { Dictionary < int , int > M = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( M . ContainsKey ( arr [ i ] ) ) { M [ arr [ i ] ] = M [ arr [ i ] ] + 1 ; } else { M . Add ( arr [ i ] , 1 ) ; } } int distinct_size = M . Count ; int maxFreq = 1 ; foreach ( KeyValuePair < int , int > m in M ) { maxFreq = Math . Max ( maxFreq , m . Value ) ; } Console . Write ( Math . Max ( Math . Min ( distinct_size , maxFreq - 1 ) , Math . Min ( distinct_size - 1 , maxFreq ) ) ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 , 4 , 4 , 4 , 4 , 5 } ; int N = arr . Length ; maximumSubsequence ( arr , N ) ; } }


"Subsequence queries after removing substrings | C # program for answering queries to check whether a string subsequence or not after removing a substring . ; arrays to store results of preprocessing ; function to preprocess the strings ; initialize it as 0. ; store subsequence count in forward direction ; store number of matches till now ; store subsequence count in backward direction ; store number of matches till now ; function that gives the output ; length of remaining string A is less than B 's length ; Driver Code ; two queries"
Solution in C#:

 using System ; class GFG { static int [ ] fwd = new int [ 100 ] ; static int [ ] bwd = new int [ 100 ] ; static void preProcess ( string a , string b ) { int n = a . Length ; int j = 0 ; for ( int i = 1 ; i <= a . Length ; i ++ ) { if ( j < b . Length && a [ i - 1 ] == b [ j ] ) j ++ ; fwd [ i ] = j ; } j = 0 ; for ( int i = a . Length ; i >= 1 ; i -- ) { if ( j < b . Length && a [ i - 1 ] == b [ b . Length - j - 1 ] ) j ++ ; bwd [ i ] = j ; } } static void query ( string a , string b , int x , int y ) { if ( ( x - 1 + a . Length - y ) < b . Length ) { Console . Write ( " No
 " ) ; return ; } if ( fwd [ x - 1 ] + bwd [ y + 1 ] >= b . Length ) Console . Write ( " Yes
 " ) ; else Console . Write ( " No
 " ) ; } static void Main ( ) { string a = " abcabcxy " , b = " acy " ; preProcess ( a , b ) ; int x = 2 , y = 5 ; query ( a , b , x , y ) ; x = 3 ; y = 6 ; query ( a , b , x , y ) ; } }


"Subsequence with maximum pairwise absolute difference and minimum size | C # program for the above approach ; Function to find the subsequence with maximum absolute difference ; To store the resultant subsequence ; First element should be included in the subsequence ; Traverse the given array [ ] arr ; If current element is greater than the previous element ; If the current element is not the local maxima then continue ; Else push it in subsequence ; If the current element is less then the previous element ; If the current element is not the local minima then continue ; Else push it in subsequence ; Last element should also be included in subsequence ; Print the element ; Driver Code ; Given array ; Function Call"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static void getSubsequence ( int [ ] ar ) { int N = ar . Length ; List < int > ans = new List < int > ( ) ; ans . Add ( ar [ 0 ] ) ; for ( int i = 1 ; i < N - 1 ; i ++ ) { if ( ar [ i ] > ar [ i - 1 ] ) { if ( i < N - 1 && ar [ i ] <= ar [ i + 1 ] ) { continue ; } else { ans . Add ( ar [ i ] ) ; } } else { if ( i < N - 1 && ar [ i + 1 ] < ar [ i ] ) { continue ; } else { ans . Add ( ar [ i ] ) ; } } } ans . Add ( ar [ N - 1 ] ) ; foreach ( int it in ans ) Console . Write ( it + " ▁ " ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 4 , 3 , 5 } ; getSubsequence ( arr ) ; } }


"Subsequences generated by including characters or ASCII value of characters of given string | C # program to implement the above approach ; Function to print subsequences containing ASCII value of the characters or the the characters of the given string ; Base Case ; If length of the subsequence exceeds 0 ; Print the subsequence ; Stores character present at i - th index of str ; If the i - th character is not included in the subsequence ; Including the i - th character in the subsequence ; Include the ASCII value of the ith character in the subsequence ; Driver Code ; Stores length of str"
Solution in C#:

using System ; class GFG { static void FindSub ( string str , string res , int i ) { if ( i == str . Length ) { if ( res . Length > 0 ) { Console . Write ( res + " ▁ " ) ; } return ; } char ch = str [ i ] ; FindSub ( str , res , i + 1 ) ; FindSub ( str , res + ch , i + 1 ) ; FindSub ( str , res + ( int ) ch , i + 1 ) ; } public static void Main ( String [ ] args ) { string str = " ab " ; string res = " " ; int N = str . Length ; FindSub ( str , res , 0 ) ; } }


"Subsequences of given string consisting of non | C # program to implement the above approach ; Function to find all the subsequences of the string with non - repeating characters ; Base case ; Insert current subsequence ; If str [ i ] is not present in the current subsequence ; Insert str [ i ] into the set ; Insert str [ i ] into the current subsequence ; Remove str [ i ] from the set ; Not including str [ i ] from the current subsequence ; Utility function to print all subsequences of string with non - repeating characters ; Stores all possible subsequences with non - repeating characters ; Stores subsequence with non - repeating characters ; Traverse all possible subsequences containing non - repeating characters ; Print subsequence ; Driver Code"
Solution in C#:

using System ; using System . Collections . Generic ; public class GFG { public static void FindSub ( HashSet < String > sub , HashSet < char > ch , String str , String res , int i ) { if ( i == str . Length ) { sub . Add ( res ) ; return ; } if ( ! ch . Contains ( str [ i ] ) ) { ch . Add ( str [ i ] ) ; FindSub ( sub , ch , str , res + str [ i ] , i + 1 ) ; ch . Remove ( str [ i ] ) ; } FindSub ( sub , ch , str , res , i + 1 ) ; } public static void printSubwithUniqueChar ( String str , int N ) { HashSet < String > sub = new HashSet < String > ( ) ; HashSet < char > ch = new HashSet < char > ( ) ; FindSub ( sub , ch , str , " " , 0 ) ; foreach ( String subString in sub ) { Console . Write ( subString + " ▁ " ) ; } } public static void Main ( String [ ] args ) { String str = " abac " ; int N = str . Length ; printSubwithUniqueChar ( str , N ) ; } }


"Subsequences of size three in an array whose sum is divisible by m | C # program to find count of subsequences of size three divisible by M . ; Storing frequencies of all remainders when divided by M . ; including i and j in the sum rem calculate the remainder required to make the sum divisible by M ; if the required number is less than j , we skip as we have already calculated for that value before . As j here starts with i and rem is less than j . ; if satisfies the first case . ; if satisfies the second case ; if satisfies the third case ; Driver code"
Solution in C#:

using System ; class GFG { static int countSubSeq ( int [ ] A , int N , int M ) { int ans = 0 ; int [ ] h = new int [ M ] ; for ( int i = 0 ; i < N ; i ++ ) { A [ i ] = A [ i ] % M ; h [ A [ i ] ] ++ ; } for ( int i = 0 ; i < M ; i ++ ) { for ( int j = i ; j < M ; j ++ ) { int rem = ( M - ( i + j ) % M ) % M ; if ( rem < j ) continue ; if ( i == j && rem == j ) ans += h [ i ] * ( h [ i ] - 1 ) * ( h [ i ] - 2 ) / 6 ; else if ( i == j ) ans += h [ i ] * ( h [ i ] - 1 ) * h [ rem ] / 2 ; else if ( i == rem ) ans += h [ i ] * ( h [ i ] - 1 ) * h [ j ] / 2 ; else if ( rem == j ) ans += h [ j ] * ( h [ j ] - 1 ) * h [ i ] / 2 ; else ans = ans + h [ i ] * h [ j ] * h [ rem ] ; } } return ans ; } public static void Main ( ) { int M = 3 ; int [ ] A = { 1 , 2 , 4 , 3 } ; int N = A . Length ; Console . WriteLine ( countSubSeq ( A , N , M ) ) ; } }


"Subsequences of size three in an array whose sum is divisible by m | C # program to find count of subsequences of size three divisible by M . ; Three nested loop to find all the sub sequences of length three in the given array A [ ] . ; checking if the sum of the chosen three number is divisible by m . ; Driver code"
Solution in C#:

using System ; class GFG { static int coutSubSeq ( int [ ] A , int N , int M ) { int sum = 0 ; int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { for ( int k = j + 1 ; k < N ; k ++ ) { sum = A [ i ] + A [ j ] + A [ k ] ; if ( sum % M == 0 ) ans ++ ; } } } return ans ; } public static void Main ( ) { int M = 3 ; int [ ] A = { 1 , 2 , 4 , 3 } ; int N = A . Length ; Console . WriteLine ( coutSubSeq ( A , N , M ) ) ; } }


"Subset with sum closest to zero | C # Program for above approach ; Variable to store states of dp ; Function to return the number closer to integer s ; To find the sum closest to zero Since sum can be negative , we will add MAX to it to make it positive ; Base cases ; Checks if a state is already solved ; Recurrence relation ; Returning the value ; Function to calculate the closest sum value ; Calculate the Closest value for every subarray arr [ i - 1 : n ] ; Driver Code ; Input array"
Solution in C#:

using System ; class GFG { static int arrSize = 51 ; static int maxSum = 201 ; static int MAX = 100 ; static int inf = 999999 ; static int [ , ] dp = new int [ arrSize , maxSum ] ; static int [ , ] visit = new int [ arrSize , maxSum ] ; static int RetClose ( int a , int b , int s ) { if ( Math . Abs ( a - s ) < Math . Abs ( b - s ) ) return a ; else return b ; } static int MinDiff ( int i , int sum , int [ ] arr , int n ) { if ( i == n ) return 0 ; if ( visit [ i , sum + MAX ] > 0 ) return dp [ i , sum + MAX ] ; visit [ i , sum + MAX ] = 1 ; dp [ i , sum + MAX ] = RetClose ( arr [ i ] + MinDiff ( i + 1 , sum + arr [ i ] , arr , n ) , MinDiff ( i + 1 , sum , arr , n ) , - 1 * sum ) ; return dp [ i , sum + MAX ] ; } static void FindClose ( int [ ] arr , int n ) { int ans = inf ; for ( int i = 1 ; i <= n ; i ++ ) ans = RetClose ( arr [ i - 1 ] + MinDiff ( i , arr [ i - 1 ] , arr , n ) , ans , 0 ) ; Console . WriteLine ( ans ) ; } public static void Main ( ) { int [ ] arr = { 25 , - 9 , - 10 , - 4 , - 7 , - 33 } ; int n = arr . Length ; FindClose ( arr , n ) ; } }


"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"
Solution in C#:

 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
 " ) ; else Console . Write ( " NO
 " ) ; } }


"Substring Reverse Pattern | C # program to print the required pattern ; Function to print the required pattern ; Print the unmodified string ; Reverse the string ; Replace the first and last character by ' * ' then second and second last character and so on until the string has characters remaining ; Driver Code"
Solution in C#:

using System ; class GFG { static void printPattern ( char [ ] s , int n ) { Console . WriteLine ( s ) ; int i = 0 , j = n - 1 ; while ( i < j ) { char c = s [ i ] ; s [ i ] = s [ j ] ; s [ j ] = c ; i ++ ; j -- ; } i = 0 ; j = n - 1 ; while ( j - i > 1 ) { s [ i ] = s [ j ] = ' * ' ; Console . WriteLine ( s ) ; i ++ ; j -- ; } } public static void Main ( String [ ] args ) { char [ ] s = " geeks " . ToCharArray ( ) ; int n = s . Length ; printPattern ( s , n ) ; } }


"Substring Sort | C # Program to sort substrings ; sort the input array ; repeated length should be the same string ; two different strings with the same length input array cannot be sorted ; validate that each string is a substring of the following one ; get first element ; The array is valid and sorted print the strings in order ; Test 1 ; Test 2"
Solution in C#:

using System ; class GFG { public static void substringSort ( String [ ] arr , int n , int maxLen ) { int [ ] count = new int [ maxLen ] ; String [ ] sortedArr = new String [ maxLen ] ; for ( int i = 0 ; i < maxLen ; i ++ ) { count [ i ] = 0 ; sortedArr [ i ] = " " ; } for ( int i = 0 ; i < n ; i ++ ) { String s = arr [ i ] ; int len = s . Length ; if ( count [ len - 1 ] == 0 ) { sortedArr [ len - 1 ] = s ; count [ len - 1 ] = 1 ; } else if ( ReferenceEquals ( s , sortedArr [ len - 1 ] ) ) { count [ len - 1 ] ++ ; } else { Console . WriteLine ( " Cannot ▁ be ▁ sorted " ) ; return ; } } int index = 0 ; while ( count [ index ] == 0 ) index ++ ; int prev = index ; String prevString = sortedArr [ prev ] ; index ++ ; for ( ; index < maxLen ; index ++ ) { if ( count [ index ] != 0 ) { String current = sortedArr [ index ] ; if ( current . Contains ( prevString ) ) { prev = index ; prevString = current ; } else { Console . WriteLine ( " Cannot ▁ be ▁ sorted " ) ; return ; } } } for ( int i = 0 ; i < maxLen ; i ++ ) { String s = sortedArr [ i ] ; for ( int j = 0 ; j < count [ i ] ; j ++ ) { Console . WriteLine ( s ) ; } } } public static void Main ( String [ ] args ) { int maxLen = 100 ; String [ ] arr1 = { " d " , " zddsaaz " , " ds " , " ddsaa " , " dds " , " dds " } ; substringSort ( arr1 , arr1 . Length , maxLen ) ; String [ ] arr2 = { " for " , " rof " } ; substringSort ( arr2 , arr2 . Length , maxLen ) ; } }


"Substrings starting with vowel and ending with consonants and vice versa | C # program to count special strings ; Returns true if ch is vowel ; function to check consonant ; in case of empty string , we can 't fullfill the  required condition, hence we return ans as 0. ; co [ i ] is going to store counts of consonants from str [ len - 1 ] to str [ i ] . vo [ i ] is going to store counts of vowels from str [ len - 1 ] to str [ i ] . ; Counting consonants and vowels from end of string . ; Now we traverse string from beginning ; If vowel , then count of substrings starting with str [ i ] is equal to count of consonants after it . ; If consonant , then count of substrings starting with str [ i ] is equal to count of vowels after it . ; Driver program"
Solution in C#:

using System ; class GFG { static Boolean isVowel ( char ch ) { return ( ch == ' a ' ch == ' e ' ch == ' i ' ch == ' o ' ch == ' u ' ) ; } static Boolean isCons ( char ch ) { return ( ch != ' a ' && ch != ' e ' && ch != ' i ' && ch != ' o ' && ch != ' u ' ) ; } static int countSpecial ( char [ ] str ) { int len = str . Length ; if ( len == 0 ) return 0 ; int [ ] co = new int [ len + 1 ] ; int [ ] vo = new int [ len + 1 ] ; if ( isCons ( str [ len - 1 ] ) == true ) co [ len - 1 ] = 1 ; else vo [ len - 1 ] = 1 ; for ( int i = len - 2 ; i >= 0 ; i -- ) { if ( isCons ( str [ i ] ) == true ) { co [ i ] = co [ i + 1 ] + 1 ; vo [ i ] = vo [ i + 1 ] ; } else { co [ i ] = co [ i + 1 ] ; vo [ i ] = vo [ i + 1 ] + 1 ; } } long ans = 0 ; for ( int i = 0 ; i < len ; i ++ ) { if ( isVowel ( str [ i ] ) ) ans = ans + co [ i + 1 ] ; else ans = ans + vo [ i + 1 ] ; } return ( int ) ans ; } public static void Main ( String [ ] args ) { String str = " adceba " ; Console . WriteLine ( countSpecial ( str . ToCharArray ( ) ) ) ; } }


"Subtraction in the Array | C # implementation of the approach ; Function to perform the given operation on arr [ ] ; Skip elements which are 0 ; Pick smallest non - zero element ; If all the elements of arr [ ] are 0 ; Driver code"
Solution in C#:

using System ; class GFG { static void operations ( int [ ] arr , int n , int k ) { Array . Sort ( arr ) ; int i = 0 , sum = 0 ; while ( k -- > 0 ) { while ( i < n && arr [ i ] - sum == 0 ) i ++ ; if ( i < n && arr [ i ] - sum > 0 ) { Console . Write ( arr [ i ] - sum + " ▁ " ) ; sum = arr [ i ] ; } else Console . WriteLine ( "0" ) ; } } public static void Main ( String [ ] args ) { int k = 5 ; int [ ] arr = { 3 , 6 , 4 , 2 } ; int n = arr . Length ; operations ( arr , n , k ) ; } }


"Succinct Encoding of Binary Tree | C # program to demonstrate Succinct Tree Encoding and decoding ; A Binary Tree Node ; Utility function to create new Node ; This function fills lists ' struc ' and ' data ' . ' struc ' list stores structure information . ' data ' list stores tree data ; If root is null , put 0 in structure array and return ; Else place 1 in structure array , key in ' data ' array and recur for left and right children ; Constructs tree from ' struc ' and ' data ' ; Remove one item from structure list ; If removed bit is 1 , ; Remove an item from data list ; Create a tree node with the removed data ; And recur to create left and right subtrees ; A utility function to print tree ; Driver code ; Let us conthe Tree shown in the above figure ; Structure iterator ; Data iterator"
Solution in C#:

 using System ; using System . Collections . Generic ; class GFG { public class Node { public int key ; public Node left , right ; } ; static Node newNode ( int key ) { Node temp = new Node ( ) ; temp . key = key ; temp . left = temp . right = null ; return ( temp ) ; } static List < Boolean > struc ; static List < int > data ; static Node root ; static void EncodeSuccinct ( Node root ) { if ( root == null ) { struc . Add ( false ) ; return ; } struc . Add ( true ) ; data . Add ( root . key ) ; EncodeSuccinct ( root . left ) ; EncodeSuccinct ( root . right ) ; } static Node DecodeSuccinct ( ) { if ( struc . Count <= 0 ) return null ; bool b = struc [ 0 ] ; struc . RemoveAt ( 0 ) ; if ( b == true ) { int key = data [ 0 ] ; data . Remove ( 0 ) ; Node root = newNode ( key ) ; root . left = DecodeSuccinct ( ) ; root . right = DecodeSuccinct ( ) ; return root ; } return null ; } static void preorder ( Node root ) { if ( root != null ) { Console . Write ( " key : ▁ " + root . key ) ; if ( root . left != null ) Console . Write ( " ▁ left ▁ child : ▁ " + root . left . key ) ; if ( root . right != null ) Console . Write ( " ▁ right ▁ child : ▁ " + root . right . key ) ; Console . WriteLine ( ) ; preorder ( root . left ) ; preorder ( root . right ) ; } } public static void Main ( String [ ] args ) { Node root = newNode ( 10 ) ; root . left = newNode ( 20 ) ; root . right = newNode ( 30 ) ; root . left . left = newNode ( 40 ) ; root . left . right = newNode ( 50 ) ; root . right . right = newNode ( 70 ) ; Console . Write ( " Given ▁ Tree
 " ) ; preorder ( root ) ; struc = new List < Boolean > ( ) ; data = new List < int > ( ) ; EncodeSuccinct ( root ) ; Console . Write ( "
 Encoded ▁ Tree
 " ) ; Console . Write ( " Structure ▁ List
 " ) ; foreach ( bool si in struc ) { if ( si == true ) Console . Write ( 1 + " ▁ " ) ; else Console . Write ( 0 + " ▁ " ) ; } Console . Write ( "
 Data ▁ List
 " ) ; foreach ( int di in data ) Console . Write ( di + " ▁ " ) ; Node newroot = DecodeSuccinct ( ) ; Console . Write ( "

...


"Sudo Placement [ 1.5 ] | Wolfish | C # program for SP - Wolfish ; Function to find the maxCost of path from ( n - 1 , n - 1 ) to ( 0 , 0 ) ; base condition ; reaches the point ; if the state has been visited previously ; i + j ; check if it is a power of 2 , then only move diagonally ; if not a power of 2 then move side - wise ; Function to return the maximum cost ; calling dp function to get the answer ; Driver Code ; Function calling to get the answer"
Solution in C#:

using System ; class GFG { static int size = 1000 ; static int maxCost ( int [ , ] a , int m , int n , int [ , ] dp ) { if ( n < 0 m < 0 ) return ( int ) - 1e9 ; else if ( m == 0 && n == 0 ) return 0 ; else if ( dp [ m , n ] != - 1 ) return dp [ m , n ] ; else { int num = m + n ; if ( ( num & ( num - 1 ) ) == 0 ) return dp [ m , n ] = a [ m , n ] + maxCost ( a , m - 1 , n - 1 , dp ) ; else return dp [ m , n ] = ( a [ m , n ] + Math . Max ( maxCost ( a , m - 1 , n , dp ) , maxCost ( a , m , n - 1 , dp ) ) ) ; } } static int answer ( int [ , ] a , int n ) { int [ , ] dp = new int [ size , size ] ; for ( int i = 0 ; i < size ; i ++ ) { for ( int j = 0 ; j < size ; j ++ ) { dp [ i , j ] = - 1 ; } } return maxCost ( a , n - 1 , n - 1 , dp ) ; } public static void Main ( String [ ] args ) { int [ , ] a = { { 1 , 2 , 3 , 1 } , { 4 , 5 , 6 , 1 } , { 7 , 8 , 9 , 1 } , { 1 , 1 , 1 , 1 } } ; int n = 4 ; Console . WriteLine ( answer ( a , n ) ) ; } }


"Sudo Placement [ 1.5 ] | Wolfish | C # program for SP - Wolfish ; Function to find the maxCost of path from ( n - 1 , n - 1 ) to ( 0 , 0 ) | recursive approach ; base condition ; reaches the point ; i + j ; check if it is a power of 2 , then only move diagonally ; if not a power of 2 then move side - wise ; Function to return the maximum cost ; calling dp function to get the answer ; Driver Code ; Function calling to get the answer"
Solution in C#:

using System ; class GFG { static int size = 1000 ; public static int maxCost ( int [ , ] a , int m , int n ) { if ( n < 0 m < 0 ) return - 1 ; else if ( m == 0 && n == 0 ) return 0 ; else { int num = m + n ; if ( ( num & ( num - 1 ) ) == 0 ) return a [ m , n ] + maxCost ( a , m - 1 , n - 1 ) ; else return a [ m , n ] + Math . Max ( maxCost ( a , m - 1 , n ) , maxCost ( a , m , n - 1 ) ) ; } } public static int answer ( int [ , ] a , int n ) { return maxCost ( a , n - 1 , n - 1 ) ; } static void Main ( ) { int [ , ] a = new int [ , ] { { 1 , 2 , 3 , 1 } , { 4 , 5 , 6 , 1 } , { 7 , 8 , 9 , 1 } , { 1 , 1 , 1 , 1 } } ; int n = 4 ; Console . Write ( answer ( a , n ) ) ; } }


"Sudo Placement [ 1.7 ] | Greatest Digital Root | C # program to print the digital roots of a number ; Function to return dig - sum ; Function to print the Digital Roots ; store the largest digital roots ; Iterate till sqrt ( n ) ; if i is a factor ; get the digit sum of both factors i and n / i ; if digit sum is greater then previous maximum ; if digit sum is greater then previous maximum ; if digit sum is same as then previous maximum , then check for larger divisor ; if digit sum is same as then previous maximum , then check for larger divisor ; Print the digital roots ; Driver Code ; Function call to print digital roots"
Solution in C#:

using System ; class GFG { static int summ ( int n ) { if ( n == 0 ) return 0 ; return ( n % 9 == 0 ) ? 9 : ( n % 9 ) ; } static void printDigitalRoot ( int n ) { int maxi = 1 ; int dig = 1 ; for ( int i = 1 ; i <= Math . Sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { int d1 = summ ( n / i ) ; int d2 = summ ( i ) ; if ( d1 > maxi ) { dig = n / i ; maxi = d1 ; } if ( d2 > maxi ) { dig = i ; maxi = d2 ; } if ( d1 == maxi ) { if ( dig < ( n / i ) ) { dig = n / i ; maxi = d1 ; } } if ( d2 == maxi ) { if ( dig < i ) { dig = i ; maxi = d2 ; } } } } Console . WriteLine ( dig + " ▁ " + maxi ) ; } public static void Main ( ) { int n = 10 ; printDigitalRoot ( n ) ; } }


"Sudo Placement | Beautiful Pairs | C # code for finding required pairs ; The function to check if beautiful pair exists ; Set for hashing ; Traversing the first array ; Traversing the second array to check for every j corresponding to single i ; x + y = z = > x = y - z ; if such x exists then we return true ; hash to make use of it next time ; no pair exists ; Driver Code ; If pair exists then 1 else 0 2 nd argument as size of first array fourth argument as sizeof 2 nd array"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static bool pairExists ( int [ ] arr1 , int m , int [ ] arr2 , int n ) { HashSet < int > s = new HashSet < int > ( ) ; for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( s . Contains ( arr2 [ j ] - arr1 [ i ] ) ) return true ; } s . Add ( arr1 [ i ] ) ; } return false ; } public static void Main ( ) { int [ ] arr1 = { 1 , 5 , 10 , 8 } ; int [ ] arr2 = { 2 , 20 , 13 } ; if ( pairExists ( arr1 , 4 , arr2 , 3 ) ) Console . WriteLine ( 1 ) ; else Console . WriteLine ( 0 ) ; } }


"Sudo Placement | Placement Tour | C # Program to find the optimal number of elements such that the cumulative value should be less than given number ; This function returns true if the value cumulative according to received integer K is less than budget B , otherwise returns false ; Initialize a temporary array which stores the cumulative value of the original array ; Sort the array to find the smallest K values ; Check if the value is less than budget ; This function prints the optimal number of elements and respective cumulative value which is less than the given number ; Initialize answer as zero as optimal value may not exists ; If the current Mid Value is an optimal value , then try to maximize it ; Call Again to set the corresponding cumulative value for the optimal ans ; Driver Code ; Budget"
Solution in C#:

 using System ; class GFG { static int value ; static bool canBeOptimalValue ( int K , int [ ] arr , int N , int B ) { int [ ] tmp = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) tmp [ i ] = ( arr [ i ] + K * ( i + 1 ) ) ; Array . Sort ( tmp ) ; value = 0 ; for ( int i = 0 ; i < K ; i ++ ) value += tmp [ i ] ; return value <= B ; } static void findNoOfElementsandValue ( int [ ] arr , int N , int B ) { int ans = 0 ; value = 0 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; if ( canBeOptimalValue ( mid , arr , N , B ) ) { ans = mid ; start = mid + 1 ; } else end = mid - 1 ; } canBeOptimalValue ( ans , arr , N , B ) ; Console . Write ( ans + " ▁ " + value + "
 " ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 5 , 6 , 3 } ; int N = arr . Length ; int B = 90 ; findNoOfElementsandValue ( arr , N , B ) ; } }


"Sudoku | Backtracking | C # program for above approach ; N is the size of the 2D matrix N * N ; A utility function to print grid ; Check whether it will be legal to assign num to the given row , col ; Check if we find the same num in the similar row , we return false ; Check if we find the same num in the similar column , we return false ; Check if we find the same num in the particular 3 * 3 matrix , we return false ; Takes a partially filled - in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution ( non - duplication across rows , columns , and boxes ) ; if we have reached the 8 th row and 9 th column ( 0 indexed matrix ) , we are returning true to avoid further backtracking ; Check if column value becomes 9 , we move to next row and column start from 0 ; Check if the current position of the grid already contains value > 0 , we iterate for next column ; Check if it is safe to place the num ( 1 - 9 ) in the given row , col -> we move to next column ; assigning the num in the current ( row , col ) position of the grid and assuming our assigned num in the position is correct ; Checking for next possibility with next column ; removing the assigned num , since our assumption was wrong , and we go for next assumption with diff num value ; Driver code ; 0 means unassigned cells"
Solution in C#:

using System ; class GFG { static int N = 9 ; static void print ( int [ , ] grid ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) Console . Write ( grid [ i , j ] + " ▁ " ) ; Console . WriteLine ( ) ; } } static bool isSafe ( int [ , ] grid , int row , int col , int num ) { for ( int x = 0 ; x <= 8 ; x ++ ) if ( grid [ row , x ] == num ) return false ; for ( int x = 0 ; x <= 8 ; x ++ ) if ( grid [ x , col ] == num ) return false ; int startRow = row - row % 3 , startCol = col - col % 3 ; for ( int i = 0 ; i < 3 ; i ++ ) for ( int j = 0 ; j < 3 ; j ++ ) if ( grid [ i + startRow , j + startCol ] == num ) return false ; return true ; } static bool solveSuduko ( int [ , ] grid , int row , int col ) { if ( row == N - 1 && col == N ) return true ; if ( col == N ) { row ++ ; col = 0 ; } if ( grid [ row , col ] != 0 ) return solveSuduko ( grid , row , col + 1 ) ; for ( int num = 1 ; num < 10 ; num ++ ) { if ( isSafe ( grid , row , col , num ) ) { grid [ row , col ] = num ; if ( solveSuduko ( grid , row , col + 1 ) ) return true ; } grid [ row , col ] = 0 ; } return false ; } static void Main ( ) { int [ , ] grid = { { 3 , 0 , 6 , 5 , 0 , 8 , 4 , 0 , 0 } , { 5 , 2 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 8 , 7 , 0 , 0 , 0 , 0 , 3 , 1 } , { 0 , 0 , 3 , 0 , 1 , 0 , 0 , 8 , 0 } , { 9 , 0 , 0 , 8 , 6 , 3 , 0 , 0 , 5 } , { 0 , 5 , 0 , 0 , 9 , 0 , 6 , 0 , 0 } , { 1 , 3 , 0 , 0 , 0 , 0 , 2 , 5 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 7 , 4 } , { 0 , 0 , 5 , 2 , 0 , 6 , 3 , 0 , 0 } } ; if ( solveSuduko ( grid , 0 , 0 ) ) print ( grid ) ; else Console . WriteLine ( " No ▁ Solution ▁ exists " ) ; } }


"Sudoku | Backtracking | C # program for above approach ; N is the size of the 2D matrix N * N ; A utility function to print grid ; Check whether it will be legal to assign num to the given row , col ; Check if we find the same num in the similar row , we return false ; Check if we find the same num in the similar column , we return false ; Check if we find the same num in the particular 3 * 3 matrix , we return false ; Takes a partially filled - in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution ( non - duplication across rows , columns , and boxes ) ; if we have reached the 8 th row and 9 th column ( 0 indexed matrix ) , we are returning true to avoid further backtracking ; Check if column value becomes 9 , we move to next row and column start from 0 ; Check if the current position of the grid already contains value > 0 , we iterate for next column ; Check if it is safe to place the num ( 1 - 9 ) in the given row , col -> we move to next column ; assigning the num in the current ( row , col ) position of the grid and assuming our assined num in the position is correct ; Checking for next possibility with next column ; removing the assigned num , since our assumption was wrong , and we go for next assumption with diff num value ; Driver code"
Solution in C#:


"Sum and Product of all Fibonacci Nodes of a Singly Linked List | C # implementation to find the sum and product of all of the Fibonacci nodes in a singly linked list ; Node of the singly linked list ; Function to insert a node at the beginning of the singly Linked List ; Allocate new node ; Insert the data ; Link the old list to the new node ; Move the head to point the new node ; Function that returns the largest element from the linked list . ; Declare a max variable and initialize with int . MinValue ; Check loop while head not equal to null ; If max is less then head . data then assign value of head . data to max otherwise node points to next node . ; Function to create a hash table to check Fibonacci numbers ; Inserting the first two numbers in the hash ; Loop to add Fibonacci numbers upto the maximum element present in the linked list ; Function to find the required sum and product ; Find the largest node value in Singly Linked List ; Creating a set containing all the fibonacci numbers upto the maximum data value in the Singly Linked List ; Traverse the linked list ; If current node is fibonacci ; Find the sum and the product ; Driver code ; Create the linked list 15.16 . 8.6 .13"
Solution in C#:

 using System ; using System . Collections . Generic ; class GFG { class Node { public int data ; public Node next ; } ; static Node push ( Node head_ref , int new_data ) { Node new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = head_ref ; head_ref = new_node ; return head_ref ; } static int largestElement ( Node head_ref ) { int max = int . MinValue ; Node head = head_ref ; while ( head != null ) { if ( max < head . data ) max = head . data ; head = head . next ; } return max ; } static void createHash ( HashSet < int > hash , int maxElement ) { int prev = 0 , curr = 1 ; hash . Add ( prev ) ; hash . Add ( curr ) ; while ( curr <= maxElement ) { int temp = curr + prev ; hash . Add ( temp ) ; prev = curr ; curr = temp ; } } static void sumAndProduct ( Node head_ref ) { int maxEle = largestElement ( head_ref ) ; HashSet < int > hash = new HashSet < int > ( ) ; createHash ( hash , maxEle ) ; int prod = 1 ; int sum = 0 ; Node ptr = head_ref ; while ( ptr != null ) { if ( hash . Contains ( ptr . data ) ) { prod *= ptr . data ; sum += ptr . data ; } ptr = ptr . next ; } Console . Write ( " Sum ▁ = ▁ " + sum + "
 " ) ; Console . Write ( " Product ▁ = ▁ " + prod ) ; } public static void Main ( String [ ] args ) { Node head = null ; head = push ( head , 13 ) ; head = push ( head , 6 ) ; head = push ( head , 8 ) ; head = push ( head , 16 ) ; head = push ( head , 15 ) ; sumAndProduct ( head ) ; } }


"Sum and Product of all even digit sum Nodes of a Singly Linked List | C # program for the above approach ; Node of Linked List ; Function to insert a node at the beginning of the singly Linked List ; Allocate new node ; Insert the data ; Link old list to the new node ; Move head to point the new node ; Function to find the digit sum for a number ; Return the sum ; Function to find the required sum and product ; Initialise the sum and product to 0 and 1 respectively ; Traverse the given linked list ; If current node has even digit sum then include it in resultant sum and product ; Find the sum and the product ; Print the readonly Sum and Product ; Driver Code ; Head of the linked list ; Create the linked list 15.16 . 8.6 .13 ; Function call"
Solution in C#:

 using System ; class GFG { class Node { public int data ; public Node next ; } ; static Node push ( Node head_ref , int new_data ) { Node new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = head_ref ; head_ref = new_node ; return head_ref ; } static int digitSum ( int num ) { int sum = 0 ; while ( num > 0 ) { sum += ( num % 10 ) ; num /= 10 ; } return sum ; } static void sumAndProduct ( Node head_ref ) { int prod = 1 ; int sum = 0 ; Node ptr = head_ref ; while ( ptr != null ) { if ( ( digitSum ( ptr . data ) % 2 != 1 ) ) { prod *= ptr . data ; sum += ptr . data ; } ptr = ptr . next ; } Console . Write ( " Sum ▁ = ▁ " + sum + "
 " ) ; Console . Write ( " Product ▁ = ▁ " + prod ) ; } public static void Main ( String [ ] args ) { Node head = null ; head = push ( head , 13 ) ; head = push ( head , 6 ) ; head = push ( head , 8 ) ; head = push ( head , 16 ) ; head = push ( head , 15 ) ; sumAndProduct ( head ) ; } }


"Sum and Product of digits in a number that divide the number | C # implementation of the above approach ; Print the sum and product of digits that divides the number . ; Fetching each digit of the number ; Checking if digit is greater than 0 and can divides n . ; Driver code"
Solution in C#:

using System ; class GFG { static void countDigit ( int n ) { int temp = n , sum = 0 , product = 1 ; while ( temp != 0 ) { int d = temp % 10 ; temp /= 10 ; if ( d > 0 && n % d == 0 ) { sum += d ; product *= d ; } } Console . Write ( " Sum ▁ = ▁ " + sum ) ; Console . Write ( " Product = " } public static void Main ( ) { int n = 1012 ; countDigit ( n ) ; } }


"Sum and Product of minimum and maximum element of an Array | C # program for the above approach ; Function to get sum ; Function to get product ; Driver code ; sorting the array ; min element would be the element at 0 th index of array after sorting ; max element would be the element at ( n - 1 ) th index of array after sorting"
Solution in C#:

using System ; class GFG { static int findSum ( int minEle , int maxEle ) { return minEle + maxEle ; } static int findProduct ( int minEle , int maxEle ) { return minEle * maxEle ; } public static void Main ( ) { int [ ] arr = { 12 , 1234 , 45 , 67 , 1 } ; int n = arr . Length ; Array . Sort ( arr ) ; int minEle = arr [ 0 ] ; int maxEle = arr [ n - 1 ] ; Console . WriteLine ( " Sum ▁ = ▁ " + findSum ( minEle , maxEle ) ) ; Console . WriteLine ( " Product ▁ = ▁ " + findProduct ( minEle , maxEle ) ) ; } }


"Sum and Product of minimum and maximum element of an Array | C # program to find the sum and product of minimum and maximum element in an array ; Function to find minimum element ; Function to find maximum element ; Function to get Sum ; Function to get product ; Driver Code ; Sum of min and max element ; Product of min and max element"
Solution in C#:

using System ; class GFG { static int getMin ( int [ ] arr , int n ) { int res = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) res = Math . Min ( res , arr [ i ] ) ; return res ; } static int getMax ( int [ ] arr , int n ) { int res = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) res = Math . Max ( res , arr [ i ] ) ; return res ; } static int findSum ( int [ ] arr , int n ) { int min = getMin ( arr , n ) ; int max = getMax ( arr , n ) ; return min + max ; } static int findProduct ( int [ ] arr , int n ) { int min = getMin ( arr , n ) ; int max = getMax ( arr , n ) ; return min * max ; } public static void Main ( ) { int [ ] arr = { 12 , 1234 , 45 , 67 , 1 } ; int n = arr . Length ; Console . WriteLine ( " Sum ▁ = ▁ " + findSum ( arr , n ) ) ; Console . WriteLine ( " Product ▁ = ▁ " + findProduct ( arr , n ) ) ; } }


"Sum of ( maximum element | C # implementation of the above approach ; Function to return a ^ n % mod ; Compute sum of max ( A ) - min ( A ) for all subsets ; Sort the array . ; Maxs = 2 ^ i - 1 ; Mins = 2 ^ ( n - 1 - i ) - 1 ; Driver code"
Solution in C#:

using System ; using System . Collections ; class GFG { static int mod = 1000000007 ; static long power ( long a , long n ) { if ( n == 0 ) { return 1 ; } long p = power ( a , n / 2 ) % mod ; p = ( p * p ) % mod ; if ( n == 1 ) { p = ( p * a ) % mod ; } return p ; } static long computeSum ( int [ ] arr , int n ) { Array . Sort ( arr ) ; long sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { long maxs = ( power ( 2 , i ) - 1 + mod ) % mod ; maxs = ( maxs * arr [ i ] ) % mod ; long mins = ( power ( 2 , n - 1 - i ) - 1 + mod ) % mod ; mins = ( mins * arr [ i ] ) % mod ; long V = ( maxs - mins + mod ) % mod ; sum = ( sum + V ) % mod ; } return sum ; } public static void Main ( ) { int [ ] arr = { 4 , 3 , 1 } ; int n = arr . Length ; Console . WriteLine ( computeSum ( arr , n ) ) ; } }


"Sum of Areas of Rectangles possible for an array | C # code to find sum of all area rectangle possible ; Function to find area of rectangles ; sorting the array in descending order ; store the final sum of all the rectangles area possible ; temporary variable to store the length of rectangle ; Selecting the length of rectangle so that difference between any two number is 1 only . Here length is selected so flag is set ; flag is set means we have got length of rectangle ; length is set to a [ i + 1 ] so that if a [ i ] a [ i + 1 ] is less than by 1 then also we have the correct choice for length ; incrementing the counter one time more as we have considered a [ i + 1 ] element also so . ; Selecting the width of rectangle so that difference between any two number is 1 only . Here width is selected so now flag is again unset for next rectangle ; area is calculated for rectangle ; flag is set false for another rectangle which we can get from elements in array ; incrementing the counter one time more as we have considered a [ i + 1 ] element also so . ; Driver code"
Solution in C#:

using System ; class GFG { static int MaxTotalRectangleArea ( int [ ] a , int n ) { Array . Sort ( a ) ; Array . Reverse ( a ) ; int sum = 0 ; bool flag = false ; int len = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( a [ i ] == a [ i + 1 ] a [ i ] - a [ i + 1 ] == 1 ) && ( ! flag ) ) { flag = true ; len = a [ i + 1 ] ; i ++ ; } else if ( ( a [ i ] == a [ i + 1 ] a [ i ] - a [ i + 1 ] == 1 ) && ( flag ) ) { sum = sum + a [ i + 1 ] * len ; flag = false ; i ++ ; } } return sum ; } static public void Main ( ) { int [ ] a = { 10 , 10 , 10 , 10 , 11 , 10 , 11 , 10 , 9 , 9 , 8 , 8 } ; int n = a . Length ; Console . WriteLine ( MaxTotalRectangleArea ( a , n ) ) ; } }


"Sum of Arithmetic Geometric Sequence | C # Program to find the sum of first n terms . ; Return the sum of first n term of AGP ; Finding the each term of AGP and adding it to sum . ; Driver Code"
Solution in C#:

using System ; class GFG { static int sumofNterm ( int a , int d , int b , int r , int n ) { int sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) sum += ( int ) ( ( a + ( i - 1 ) * d ) * ( b * Math . Pow ( r , i - 1 ) ) ) ; return sum ; } public static void Main ( ) { int a = 1 , d = 1 , b = 2 , r = 2 , n = 3 ; Console . Write ( sumofNterm ( a , d , b , r , n ) ) ; } }


"Sum of Binomial coefficients | C # Program to find sum of Binomial Coefficient . ; Returns value of Binomial Coefficient Sum which is 2 raised to power n . ; Driver program to test above function"
Solution in C#:

using System ; class GFG { static int binomialCoeffSum ( int n ) { return ( 1 << n ) ; } static public void Main ( ) { int n = 4 ; Console . WriteLine ( binomialCoeffSum ( n ) ) ; } }


"Sum of Bitwise AND of all unordered triplets of an array | C # program for the above approach ; Function to calculate sum of Bitwise AND of all unordered triplets from a given array such that ( i < j < k ) ; Stores the resultant sum of Bitwise AND of all triplets ; Generate all triplets of ( arr [ i ] , arr [ j ] , arr [ k ] ) ; Add Bitwise AND to ans ; Print the result ; Driver code"
Solution in C#:

using System ; class GFG { public static void tripletAndSum ( int [ ] arr , int n ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { for ( int k = j + 1 ; k < n ; k ++ ) { ans += arr [ i ] & arr [ j ] & arr [ k ] ; } } } Console . WriteLine ( ans ) ; } static public void Main ( ) { int [ ] arr = { 3 , 5 , 4 , 7 } ; int N = arr . Length ; tripletAndSum ( arr , N ) ; } }


"Sum of Bitwise AND of all unordered triplets of an array | C # program for the above approach ; Function to calculate sum of Bitwise AND of all unordered triplets from a given array such that ( i < j < k ) ; Stores the resultant sum of Bitwise AND of all triplets ; Traverse over all the bits ; Count number of elements with the current bit set ; There are ( cnt ) C ( 3 ) numbers with the current bit set and each triplet contributes 2 ^ bit to the result ; Return the resultant sum ; Driver Code"
Solution in C#:

using System ; class GFG { static int tripletAndSum ( int [ ] arr , int n ) { int ans = 0 ; for ( int bit = 0 ; bit < 32 ; bit ++ ) { int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( arr [ i ] & ( 1 << bit ) ) != 0 ) cnt ++ ; } ans += ( 1 << bit ) * cnt * ( cnt - 1 ) * ( cnt - 2 ) / 6 ; } return ans ; } public static void Main ( ) { int [ ] arr = { 3 , 5 , 4 , 7 } ; int N = arr . Length ; Console . Write ( tripletAndSum ( arr , N ) ) ; } }


"Sum of Bitwise AND of the sum of all leaf and non | C # program for given approach ; Structure of a Binary tree node ; Helper function to allocate a new node with the given data and left and right pointers as None ; Function to calculate the sum of bitwise AND of the sum of all leaf nodes and non - leaf nodes for each level ; Initialize a queue and append root to it ; Store the required answer ; Stores the sum of leaf nodes at the current level ; Stores the sum of non - leaf nodes at the current level ; Get the size of the queue ; Iterate for all the nodes in the queue currently ; Dequeue a node from queue ; Check if the node is a leaf node ; If true , update the leaf node sum ; Otherwise , update the non - leaf node sum ; Enqueue left and right children of removed node ; Update the answer ; Return the answer ; Driver Code ; Given Tree ; Function Call"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { class TreeNode { public int val ; public TreeNode left , right ; } ; static TreeNode newNode ( int x ) { TreeNode temp = new TreeNode ( ) ; temp . val = x ; temp . left = null ; temp . right = null ; return temp ; } static int findSum ( TreeNode root ) { Queue < TreeNode > que = new Queue < TreeNode > ( ) ; que . Enqueue ( root ) ; int ans = 0 ; while ( que . Count > 0 ) { int leaf = 0 ; int nonleaf = 0 ; int length = que . Count ; while ( length > 0 ) { TreeNode temp = que . Peek ( ) ; que . Dequeue ( ) ; if ( temp . left == null && temp . right == null ) leaf += temp . val ; else nonleaf += temp . val ; if ( temp . left != null ) que . Enqueue ( temp . left ) ; if ( temp . right != null ) que . Enqueue ( temp . right ) ; length -= 1 ; } ans += ( leaf & nonleaf ) ; } return ans ; } public static void Main ( ) { TreeNode root = newNode ( 5 ) ; root . left = newNode ( 3 ) ; root . right = newNode ( 9 ) ; root . left . left = newNode ( 6 ) ; root . left . right = newNode ( 4 ) ; root . left . left . right = newNode ( 7 ) ; Console . WriteLine ( findSum ( root ) ) ; } }


"Sum of Bitwise And of all pairs in a given array | A Simple C # program to compute sum of bitwise AND of all pairs ; Returns value of " arr [ 0 ] ▁ & ▁ arr [ 1 ] ▁ + ▁ ▁ arr [ 0 ] ▁ & ▁ arr [ 2 ] ▁ + ▁ . . . ▁ arr [ i ] ▁ & ▁ arr [ j ] ▁ + ▁ ▁ . . . . . ▁ arr [ n - 2 ] ▁ & ▁ arr [ n - 1 ] " ; Consider all pairs ( arr [ i ] , arr [ j ) such that i < j ; Driver program to test above function"
Solution in C#:

using System ; class GFG { static int pairAndSum ( int [ ] arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) ans += arr [ i ] & arr [ j ] ; return ans ; } public static void Main ( ) { int [ ] arr = { 5 , 10 , 15 } ; int n = arr . Length ; Console . Write ( pairAndSum ( arr , n ) ) ; } }


"Sum of Bitwise And of all pairs in a given array | An efficient C # program to compute sum of bitwise AND of all pairs ; Returns value of " arr [ 0 ] ▁ & ▁ arr [ 1 ] ▁ + ▁ ▁ arr [ 0 ] ▁ & ▁ arr [ 2 ] ▁ + ▁ . . . ▁ arr [ i ] ▁ & ▁ arr [ j ] ▁ + ▁ ▁ . . . . . ▁ arr [ n - 2 ] ▁ & ▁ arr [ n - 1 ] " ; Traverse over all bits ; Count number of elements with i 'th bit set Initialize the count ; There are k set bits , means k ( k - 1 ) / 2 pairs . Every pair adds 2 ^ i to the answer . Therefore , we add "2 ^ i ▁ * ▁ ▁ [ k * ( k - 1 ) / 2 ] " to the answer . ; Driver program to test above function"
Solution in C#:

using System ; class GFG { static int pairAndSum ( int [ ] arr , int n ) { for ( int i = 0 ; i < 32 ; i ++ ) { int k = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( arr [ j ] & ( 1 << i ) ) != 0 ) k ++ ; } ans += ( 1 << i ) * ( k * ( k - 1 ) / 2 ) ; } return ans ; } public static void Main ( ) { int [ ] arr = new int [ ] { 5 , 10 , 15 } ; int n = arr . Length ; Console . Write ( pairAndSum ( arr , n ) ) ; } }


"Sum of Bitwise OR of all pairs in a given array | A Simple C # program to compute sum of bitwise OR of all pairs ; Returns value of " arr [ 0 ] ▁ | ▁ arr [ 1 ] ▁ + ▁ ▁ arr [ 0 ] ▁ | ▁ arr [ 2 ] ▁ + ▁ . . . ▁ arr [ i ] ▁ | ▁ arr [ j ] ▁ + ▁ ▁ . . . . . ▁ arr [ n - 2 ] ▁ | ▁ arr [ n - 1 ] " ; Consider all pairs ( arr [ i ] , arr [ j ) such that i < j ; Driver program to test above function"
Solution in C#:

using System ; class GFG { static int pairORSum ( int [ ] arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) ans += arr [ i ] | arr [ j ] ; return ans ; } public static void Main ( ) { int [ ] arr = { 1 , 2 , 3 , 4 } ; int n = arr . Length ; Console . Write ( pairORSum ( arr , n ) ) ; } }


"Sum of Bitwise OR of each array element of an array with all elements of another array | C # program for the above approach ; Function to compute sum of Bitwise OR of each element in arr1 [ ] with all elements of the array arr2 [ ] ; Declaring an array of size 32 to store the count of each bit ; Traverse the array arr1 [ ] ; Current bit position ; While num exceeds 0 ; Checks if i - th bit is set or not ; Increment the count at bit_position by one ; Increment bit_position ; Right shift the num by one ; Traverse in the arr2 [ ] ; Store the ith bit value ; Total required sum ; Traverse in the range [ 0 , 31 ] ; Check if current bit is set ; Increment the Bitwise sum by N * ( 2 ^ i ) ; Right shift num by one ; Left shift valee_at_that_bit by one ; Print the sum obtained for ith number in arr1 [ ] ; Driver Code ; Given arr1 [ ] ; Given arr2 [ ] ; Size of arr1 [ ] ; Size of arr2 [ ] ; Function Call"
Solution in C#:

using System ; class GFG { static void Bitwise_OR_sum_i ( int [ ] arr1 , int [ ] arr2 , int M , int N ) { int [ ] frequency = new int [ 32 ] ; for ( int i = 0 ; i < 32 ; i ++ ) { frequency [ i ] = 0 ; } for ( int i = 0 ; i < N ; i ++ ) { int bit_position = 0 ; int num = arr1 [ i ] ; while ( num != 0 ) { if ( ( num & 1 ) != 0 ) { frequency [ bit_position ] += 1 ; } bit_position += 1 ; num >>= 1 ; } } for ( int i = 0 ; i < M ; i ++ ) { int num = arr2 [ i ] ; int value_at_that_bit = 1 ; int bitwise_OR_sum = 0 ; for ( int bit_position = 0 ; bit_position < 32 ; bit_position ++ ) { if ( ( num & 1 ) != 0 ) { bitwise_OR_sum += N * value_at_that_bit ; } else { bitwise_OR_sum += frequency [ bit_position ] * value_at_that_bit ; } num >>= 1 ; value_at_that_bit <<= 1 ; } Console . Write ( bitwise_OR_sum + " ▁ " ) ; } return ; } public static void Main ( ) { int [ ] arr1 = { 1 , 2 , 3 } ; int [ ] arr2 = { 1 , 2 , 3 } ; int N = arr1 . Length ; int M = arr2 . Length ; Bitwise_OR_sum_i ( arr1 , arr2 , M , N ) ; } }


"Sum of Bitwise OR of every array element paired with all other array elements | C # program for the above approach ; Function to print required sum for every valid index i ; Store the required sum for current array element ; Generate all possible pairs ( arr [ i ] , arr [ j ] ) ; Update the value of req_sum ; Print the required sum ; Driver Code ; Given array ; Size of the array ; Function Call"
Solution in C#:

using System ; public class GFG { static void printORSumforEachElement ( int [ ] arr , int N ) { for ( int i = 0 ; i < N ; i ++ ) { int req_sum = 0 ; for ( int j = 0 ; j < N ; j ++ ) { req_sum += ( arr [ i ] arr [ j ] ) ; } Console . Write ( req_sum + " ▁ " ) ; } } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 } ; int N = arr . Length ; printORSumforEachElement ( arr , N ) ; } }


"Sum of Bitwise XOR of each array element with all other array elements | C # program for the above approach ; Function to calculate for each array element , sum of its Bitwise XOR with all other array elements ; Declare an array of size 64 to store count of each bit ; Traversing the array ; Check if bit is present of not ; Increase the bit position ; Reduce the number to half ; Traverse the array ; Stores the bit position ; Stores the sum of Bitwise XOR ; Check if bit is present of not ; Reduce the number to its half ; Print the sum for A [ i ] ; Driver Code ; Given array ; Given N ; Function Call"
Solution in C#:

using System ; class GFG { static void XOR_for_every_i ( int [ ] A , int N ) { int [ ] frequency_of_bits = new int [ 32 ] ; for ( int i = 0 ; i < N ; i ++ ) { int bit_position = 0 ; int M = A [ i ] ; while ( M != 0 ) { if ( ( M & 1 ) != 0 ) { frequency_of_bits [ bit_position ] += 1 ; } bit_position += 1 ; M >>= 1 ; } } for ( int i = 0 ; i < N ; i ++ ) { int M = A [ i ] ; int value_at_that_bit = 1 ; int XOR_sum = 0 ; for ( int bit_position = 0 ; bit_position < 32 ; bit_position ++ ) { if ( ( M & 1 ) != 0 ) { XOR_sum += ( N - frequency_of_bits [ bit_position ] ) * value_at_that_bit ; } else { XOR_sum += ( frequency_of_bits [ bit_position ] ) * value_at_that_bit ; } M >>= 1 ; value_at_that_bit <<= 1 ; } Console . Write ( XOR_sum + " ▁ " ) ; } return ; } public static void Main ( ) { int [ ] A = { 1 , 2 , 3 } ; int N = A . Length ; XOR_for_every_i ( A , N ) ; } }