"Detect loop in a linked list | C # program to return first node of loop ; A utility function to print a linked list ; returns distance between first and last node every time * last node moves forwars ; counts no of nodes between first and last ; Function to detect first node of loop in a linked list that may contain loop ; Create a temporary node ; first always points to head ; last pointer initially points to head ; current_length stores no of nodes between current * position of first and last ; current_length stores no of nodes between previous * position of first and last ; set prev_length to current length then update the current length ; distance is calculated ; last node points the next node ; Driver program to test above function ; Create a loop for testing ( 5 is pointing to 3 )"
Solution in C#:

using System ; public class GFG { public class Node { public int key ; public Node next ; } ; static Node newNode ( int key ) { Node temp = new Node ( ) ; temp . key = key ; temp . next = null ; return temp ; } static void printList ( Node head ) { while ( head != null ) { Console . Write ( head . key + " ▁ " ) ; head = head . next ; } Console . WriteLine ( ) ; } static int distance ( Node first , Node last ) { int counter = 0 ; Node curr ; curr = first ; while ( curr != last ) { counter += 1 ; curr = curr . next ; } return counter + 1 ; } static bool detectLoop ( Node head ) { Node temp = new Node ( ) ; Node first , last ; first = head ; last = head ; int current_length = 0 ; int prev_length = - 1 ; while ( current_length > prev_length && last != null ) { prev_length = current_length ; current_length = distance ( first , last ) ; last = last . next ; } if ( last == null ) { return false ; } else { return true ; } } public static void Main ( String [ ] args ) { Node head = newNode ( 1 ) ; head . next = newNode ( 2 ) ; head . next . next = newNode ( 3 ) ; head . next . next . next = newNode ( 4 ) ; head . next . next . next . next = newNode ( 5 ) ; head . next . next . next . next . next = head . next . next ; bool found = detectLoop ( head ) ; if ( found ) Console . Write ( " Loop ▁ Found " ) ; else Console . Write ( " No ▁ Loop ▁ Found " ) ; } }


"Detecting negative cycle using Floyd Warshall | C # Program to check if there is a negative weight cycle using Floyd Warshall Algorithm ; Number of vertices in the graph ; Define Infinite as a large enough value . This value will be used for vertices not connected to each other ; Returns true if graph has negative weight cycle else false . ; dist [ ] [ ] will be the output matrix that will finally have the shortest distances between every pair of vertices ; Initialize the solution matrix same as input graph matrix . Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex . ; Add all vertices one by one to the set of intermediate vertices . -- -> Before start of a iteration , we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set { 0 , 1 , 2 , . . k - 1 } as intermediate vertices . -- -- > After the end of a iteration , vertex no . k is added to the set of intermediate vertices and the set becomes { 0 , 1 , 2 , . . k } ; Pick all vertices as source one by one ; Pick all vertices as destination for the above picked source ; If vertex k is on the shortest path from i to j , then update the value of dist [ i ] [ j ] ; If distance of any verex from itself becomes negative , then there is a negative weight cycle . ; Driver code ; Let us create the following weighted graph 1 ( 0 ) -- -- -- -- -- -> ( 1 ) / | \ | | | - 1 | | - 1 | \ | / ( 3 ) < -- -- -- -- -- - ( 2 ) - 1"
Solution in C#:

using System ; namespace Cycle { public class GFG { static int V = 4 ; static int INF = 99999 ; static bool negCyclefloydWarshall ( int [ , ] graph ) { int [ , ] dist = new int [ V , V ] ; int i , j , k ; for ( i = 0 ; i < V ; i ++ ) for ( j = 0 ; j < V ; j ++ ) dist [ i , j ] = graph [ i , j ] ; for ( k = 0 ; k < V ; k ++ ) { for ( i = 0 ; i < V ; i ++ ) { for ( j = 0 ; j < V ; j ++ ) { if ( dist [ i , k ] + dist [ k , j ] < dist [ i , j ] ) dist [ i , j ] = dist [ i , k ] + dist [ k , j ] ; } } } for ( i = 0 ; i < V ; i ++ ) if ( dist [ i , i ] < 0 ) return true ; return false ; } public static void Main ( ) { int [ , ] graph = { { 0 , 1 , INF , INF } , { INF , 0 , - 1 , INF } , { INF , INF , 0 , - 1 } , { - 1 , INF , INF , 0 } } ; if ( negCyclefloydWarshall ( graph ) ) Console . Write ( " Yes " ) ; else Console . Write ( " No " ) ; } } }


"Determine if a string has all Unique Characters | C # program to illustrate String with unique characters using set data structure ; Inserting character of String into set ; If length of set is equal to len of String then it will have unique characters ; Driver code"
Solution in C#:

 using System ; using System . Collections . Generic ; public class GFG { static bool uniquechars ( String str ) { HashSet < char > char_set = new HashSet < char > ( ) ; for ( int c = 0 ; c < str . Length ; c ++ ) { char_set . Add ( str ) ; } if ( char_set . Count == str . Length ) { return true ; } else { return false ; } } public static void Main ( String [ ] args ) { String str = " GeeksforGeeks " ; if ( uniquechars ( str ) ) { Console . Write ( " The ▁ String ▁ " + str + " ▁ has ▁ all ▁ unique ▁ characters
 " ) ; } else { Console . Write ( " The ▁ String ▁ " + str + " ▁ has ▁ duplicate ▁ characters
 " ) ; } } }


"Determine if a string has all Unique Characters | C # program to illustrate String with unique characters without using any data structure ; Assuming string can have characters a - z this has 32 bits set to 0 ; if that bit is already set in checker , return false ; otherwise update and continue by setting that bit in the checker ; no duplicates encountered , return true ; Driver Code"
Solution in C#:

using System ; class GFG { public virtual bool uniqueCharacters ( string str ) { int checker = 0 ; for ( int i = 0 ; i < str . Length ; i ++ ) { int bitAtIndex = str [ i ] - ' a ' ; if ( ( checker & ( 1 << bitAtIndex ) ) > 0 ) { return false ; } checker = checker | ( 1 << bitAtIndex ) ; } return true ; } public static void Main ( string [ ] args ) { GFG obj = new GFG ( ) ; string input = " geekforgeeks " ; if ( obj . uniqueCharacters ( input ) ) { Console . WriteLine ( " The ▁ String ▁ " + input + " ▁ has ▁ all ▁ unique ▁ characters " ) ; } else { Console . WriteLine ( " The ▁ String ▁ " + input + " ▁ has ▁ duplicate ▁ characters " ) ; } } }


"Determine if a string has all Unique Characters | C # program to illustrate string with unique characters using brute force technique ; If at any time we encounter 2 same characters , return false ; If no duplicate characters encountered , return true ; Driver Code"
Solution in C#:

using System ; public class GFG { static bool uniqueCharacters ( String str ) { for ( int i = 0 ; i < str . Length ; i ++ ) for ( int j = i + 1 ; j < str . Length ; j ++ ) if ( str [ i ] == str [ j ] ) return false ; return true ; } public static void Main ( ) { string input = " GeeksforGeeks " ; if ( uniqueCharacters ( input ) == true ) Console . WriteLine ( " The ▁ String ▁ " + input + " ▁ has ▁ all ▁ unique ▁ characters " ) ; else Console . WriteLine ( " The ▁ String ▁ " + input + " ▁ has ▁ duplicate ▁ characters " ) ; } }


"Determine position of two points with respect to a 3D plane | C # program for the above approach ; Function to check position of two points with respect to a plane in 3D ; Put coordinates in plane equation ; If both values have same sign ; If both values have different sign ; If both values are zero ; If either of the two values is zero ; Driver code ; Given Input ; Coordinates of points ; Function Call"
Solution in C#:

using System ; class GFG { static void check_position ( int a , int b , int c , int d , int x1 , int y1 , int z1 , int x2 , int y2 , int z2 ) { int value_1 = a * x1 + b * y1 + c * z1 + d ; int value_2 = a * x2 + b * y2 + c * z2 + d ; if ( ( value_1 > 0 && value_2 > 0 ) || ( value_1 < 0 && value_2 < 0 ) ) Console . Write ( " On ▁ same ▁ side " ) ; if ( ( value_1 > 0 && value_2 < 0 ) || ( value_1 < 0 && value_2 > 0 ) ) Console . Write ( " On ▁ different ▁ sides " ) ; if ( value_1 == 0 && value_2 == 0 ) Console . Write ( " Both ▁ on ▁ the ▁ plane " ) ; if ( value_1 == 0 && value_2 != 0 ) Console . Write ( " Point ▁ 1 ▁ on ▁ the ▁ plane " ) ; if ( value_1 != 0 && value_2 == 0 ) Console . Write ( " Point ▁ 2 ▁ on ▁ the ▁ plane " ) ; } static void Main ( ) { int a = 1 , b = 2 , c = 3 , d = 4 ; int x1 = - 2 , y1 = - 2 , z1 = 1 ; int x2 = - 4 , y2 = 11 , z2 = - 1 ; check_position ( a , b , c , d , x1 , y1 , z1 , x2 , y2 , z2 ) ; } }


"Determine the count of Leaf nodes in an N | C # program to find number of leaf nodes ; Function to calculate leaf nodes in n - ary tree ; Driver code"
Solution in C#:

using System ; class GFG { static int calcNodes ( int N , int I ) { int result = 0 ; result = I * ( N - 1 ) + 1 ; return result ; } public static void Main ( ) { int N = 5 , I = 2 ; Console . Write ( " Leaf ▁ nodes ▁ = ▁ " + calcNodes ( N , I ) ) ; } }


"Determine the number of squares of unit area that a given line will pass through . | Function to return the required position ;  ; Driver Code"
Solution in C#:

using System ; class GFG { static void noOfSquares ( int x1 , int y1 , int x2 , int y2 ) { int dx = Math . Abs ( x2 - x1 ) ; int dy = Math . Abs ( y2 - y1 ) ; int ans = dx + dy - __gcd ( dx , dy ) ; Console . WriteLine ( ans ) ; } static int __gcd ( int a , int b ) { if ( b == 0 ) return a ; return __gcd ( b , a % b ) ; } static void Main ( ) { int x1 = 1 , y1 = 1 , x2 = 4 , y2 = 3 ; noOfSquares ( x1 , y1 , x2 , y2 ) ; } }


"Determine the position of the third person on regular N sided polygon | C # implementation of the approach ; Function to find out the number of that vertices ; Another person can 't stand on  vertex on which 2 children stand. ; calculating minimum jumps from each vertex . ; Calculate sum of jumps . ; Driver code ; Calling function"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static int vertices ( int N , int A , int B ) { int position = 0 ; int minisum = int . MaxValue ; int sum = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { if ( i == A i == B ) continue ; else { int x = Math . Abs ( i - A ) ; int y = Math . Abs ( i - B ) ; sum = x + y ; if ( sum < minisum ) { minisum = sum ; position = i ; } } } return position ; } public static void Main ( String [ ] args ) { int N = 3 , A = 1 , B = 2 ; Console . WriteLine ( " Vertex ▁ = ▁ " + vertices ( N , A , B ) ) ; } }


"Determine the winner of a game of deleting Characters from a String | C # program for the above approach ; Function to find the winner of the game when both players play optimally ; Stores the frequency of all digit ; Stores the scores of player1 and player2 respectively ; Iterate to store frequencies ; Turn for the player1 ; Add score of player1 ; Add score of player2 ; Check if its a draw ; If score of player 1 is greater ; Otherwise ; Driver code"
Solution in C#:

using System ; class GFG { static void determineWinner ( String str ) { int [ ] A = new int [ 10 ] ; int sum1 = 0 , sum2 = 0 ; for ( int i = 0 ; i < str . Length ; i ++ ) { A [ ( int ) str [ i ] - 48 ] ++ ; } for ( int i = 0 ; i <= 9 ; i ++ ) { if ( i % 2 != 0 ) { sum1 = sum1 + A [ i ] ; } else { sum2 = sum2 + A [ i ] ; } } if ( sum1 == sum2 ) { Console . Write ( " - 1" ) ; } else if ( sum1 > sum2 ) { Console . Write ( " Player ▁ 1" ) ; } else { Console . Write ( " Player ▁ 2" ) ; } } public static void Main ( String [ ] args ) { String str = "78787" ; determineWinner ( str ) ; } }


"Determine whether a given number is a Hyperperfect Number | C # program to check whether a given number is k - hyperperfect ; function to find the sum of all proper divisors ( excluding1 and N ) ; Iterate only until sqrt N as we are going to generate pairs to produce divisors ; As divisors occur in pairs , we can take the values i and N / i as long as i divides N ; Function to check whether the given number is prime ; base and corner cases ; Since integers can be represented as some 6 * k + y where y >= 0 , we can eliminate all integers that can be expressed in this form ; start from 5 as this is the next prime number ; Returns true if N is a K - Hyperperfect number Else returns false . ; Condition from the definition of hyperperfect ; Driver Code ; First two statements test against the condition N = 1 + K * ( sum ( proper divisors ) )"
Solution in C#:

using System ; class GFG { static int divisorSum ( int N , int K ) { int sum = 0 ; for ( int i = 2 ; i <= Math . Ceiling ( Math . Sqrt ( N ) ) ; i ++ ) if ( N % i == 0 ) sum += ( i + N / i ) ; return sum ; } static bool isPrime ( int n ) { if ( n == 1 n == 0 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; return true ; } static bool isHyperPerfect ( int N , int K ) { int sum = divisorSum ( N , K ) ; if ( ( 1 + K * ( sum ) ) == N ) return true ; else return false ; } static public void Main ( ) { int N1 = 1570153 , K1 = 12 ; int N2 = 321 , K2 = 3 ; if ( isHyperPerfect ( N1 , K1 ) ) Console . WriteLine ( N1 + " ▁ is ▁ " + K1 + " - HyperPerfect " ) ; else Console . WriteLine ( N1 + " ▁ is ▁ not ▁ " + K1 + " - HyperPerfect " ) ; if ( isHyperPerfect ( N2 , K2 ) ) Console . WriteLine ( N2 + " ▁ is ▁ " + K2 + " - HyperPerfect " ) ; else Console . WriteLine ( N2 + " ▁ is ▁ not ▁ " + K2 + " - HyperPerfect " ) ; } }


"Determine whether a universal sink exists in a directed graph | C # program to find whether a universal sink exists in a directed graph ; constructor to initialize number of vertices and size of adjacency matrix ; make adjacency_matrix [ i , j ] = 1 if there is an edge from i to j ; if any element in the row i is 1 , it means that there is an edge emanating from the vertex , which means it cannot be a sink ; if any element other than i in the column i is 0 , it means that there is no edge from that vertex to the vertex we are testing and hence it cannot be a sink ; if none of the checks fails , return true ; we will eliminate n - 1 non sink vertices so that we have to check for only one vertex instead of all n vertices ; If the index is 1 , increment the row we are checking by 1 else increment the column ; If i exceeds the number of vertices , it means that there is no valid vertex in the given vertices that can be a sink ; Driver Code ; input set 1 g . insert ( 1 , 6 ) ; g . insert ( 2 , 6 ) ; g . insert ( 3 , 6 ) ; g . insert ( 4 , 6 ) ; g . insert ( 5 , 6 ) ; input set 2 ; returns 0 based indexing of vertex . returns - 1 if no sink exits . returns the vertex number - 1 if sink is found"
Solution in C#:

using System ; using System . Collections . Generic ; class graph { int vertices , itr ; int [ , ] adjacency_matrix ; public graph ( int vertices ) { this . vertices = vertices ; adjacency_matrix = new int [ vertices , vertices ] ; } public void insert ( int source , int destination ) { adjacency_matrix = 1 ; } public bool issink ( int i ) { for ( int j = 0 ; j < vertices ; j ++ ) { if ( adjacency_matrix [ i , j ] == 1 ) return false ; if ( adjacency_matrix [ j , i ] == 0 && j != i ) return false ; } return true ; } public int eliminate ( ) { int i = 0 , j = 0 ; while ( i < vertices && j < vertices ) { if ( adjacency_matrix [ i , j ] == 1 ) i = i + 1 ; else j = j + 1 ; } if ( i > vertices ) return - 1 ; else if ( ! issink ( i ) ) return - 1 ; else return i ; } } public class Sink { public static void Main ( String [ ] args ) { int number_of_vertices = 6 ; graph g = new graph ( number_of_vertices ) ; g . insert ( 1 , 6 ) ; g . insert ( 2 , 3 ) ; g . insert ( 2 , 4 ) ; g . insert ( 4 , 3 ) ; g . insert ( 5 , 3 ) ; int vertex = g . eliminate ( ) ; if ( vertex >= 0 ) Console . WriteLine ( " Sink ▁ found ▁ at ▁ vertex ▁ " + ( vertex + 1 ) ) ; else Console . WriteLine ( " No ▁ Sink " ) ; } }


"Determine whether the given integer N is a Peculiar Number or not | C # implementation to check if the number is peculiar ; Function to find sum of digits of a number ; Function to check if the number is peculiar ; Store a duplicate of n ; Driver code"
Solution in C#:

using System ; class GFG { static int sumDig ( int n ) { int s = 0 ; while ( n != 0 ) { s = s + ( n % 10 ) ; n = n / 10 ; } return s ; } static bool Pec ( int n ) { int dup = n ; int dig = sumDig ( n ) ; if ( dig * 3 == dup ) return true ; else return false ; } public static void Main ( ) { int n = 36 ; if ( Pec ( n ) == true ) Console . Write ( " Yes " ) ; else Console . Write ( " No " ) ; } }


"Determine winner of the Game by arranging balls in a row | C # program for the above approach ; Function to find the winner of the Game by arranging the balls in a row ; Check if small balls are greater or equal to the large ones ; X can place balls therefore scores n - 1 ; Condition if large balls are greater than small ; X can have m - 1 as a score since greater number of balls can only be adjacent ; Compare the score ; Driver Code ; Given number of small balls ( N ) and number of large balls ( M ) ; Function call"
Solution in C#:

using System ; class GFG { static void findWinner ( int n , int m ) { int X = 0 ; int Y = 0 ; if ( n >= m ) { X = n - 1 ; Y = m ; } else { X = m - 1 ; Y = n ; } if ( X > Y ) Console . Write ( " X " ) ; else if ( Y > X ) Console . Write ( " Y " ) ; else Console . Write ( " - 1" ) ; } public static void Main ( String [ ] args ) { int n = 3 , m = 1 ; findWinner ( n , m ) ; } }


"Diagonal Sum of a Binary Tree | C # Program to calculate the sum of diagonal nodes . ; Node Structure ; to map the node with level - index ; Function to create new node ; recursvise function to calculate sum of elements where level - index is same . ; if there is no child then return ; add the element in the group of node whose level - index is equal ; left child call ; right child call ; Function call ; for different values of level - index add te sum of those node to answer ; Driver code ; build binary tree ; Function Call ; print the daigonal sums"
Solution in C#:

using System ; using System . Collections . Generic ; public class GFG { public class Node { public int data ; public Node left , right ; } ; static Dictionary < int , int > grid = new Dictionary < int , int > ( ) ; static Node newNode ( int data ) { Node Node = new Node ( ) ; Node . data = data ; Node . left = Node . right = null ; return Node ; } static void addConsideringGrid ( Node root , int level , int index ) { if ( root == null ) return ; if ( grid . ContainsKey ( level - index ) ) grid [ level - index ] = grid [ level - index ] + ( root . data ) ; else grid . Add ( level - index , root . data ) ; addConsideringGrid ( root . left , level + 1 , index - 1 ) ; addConsideringGrid ( root . right , level + 1 , index + 1 ) ; } static List < int > diagonalSum ( Node root ) { grid . Clear ( ) ; addConsideringGrid ( root , 0 , 0 ) ; List < int > ans = new List < int > ( ) ; foreach ( KeyValuePair < int , int > x in grid ) { ans . Add ( x . Value ) ; } return ans ; } public static void Main ( String [ ] args ) { Node root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 3 ) ; root . left . left = newNode ( 9 ) ; root . left . right = newNode ( 6 ) ; root . right . left = newNode ( 4 ) ; root . right . right = newNode ( 5 ) ; root . right . left . right = newNode ( 7 ) ; root . right . left . left = newNode ( 12 ) ; root . left . right . left = newNode ( 11 ) ; root . left . left . right = newNode ( 10 ) ; List < int > v = diagonalSum ( root ) ; for ( int i = 0 ; i < v . Count ; i ++ ) Console . Write ( v [ i ] + " ▁ " ) ; } }


"Diagonal of a Regular Decagon | C # program to find the diagonal of a regular decdiagonal ; Function to return the diagonal of a regular decdiagonal ; side cannot be negative ; length of the diagonal ; Driver code"
Solution in C#:

using System ; public class GFG { static double decdiagonal ( double a ) { if ( a < 0 ) return - 1 ; double d = 1.902 * a ; return d ; } public static void Main ( ) { int a = 9 ; Console . WriteLine ( decdiagonal ( a ) ) ; } }


"Diagonal of a Regular Heptagon | C # program to find the diagonal of a regular heptagon ; Function to return the diagonal of a regular heptagon ; side cannot be negative ; length of the diagonal ; Driver code"
Solution in C#:

using System ; public class GFG { static double heptdiagonal ( double a ) { if ( a < 0 ) return - 1 ; double d = 1.802 * a ; return d ; } public static void Main ( ) { int a = 6 ; Console . WriteLine ( heptdiagonal ( a ) ) ; }


"Diagonal of a Regular Hexagon | C # Program to find the diagonal of a regular hexagon ; Function to find the diagonal of a regular hexagon ; Side cannot be negative ; Length of the diagonal ; Driver code"
Solution in C#:

using System ; public class GFG { static double hexDiagonal ( float a ) { if ( a < 0 ) return - 1 ; double d = ( double ) 1.73 * a ; return d ; } public static void Main ( ) { float a = 9 ; Console . WriteLine ( hexDiagonal ( a ) ) ; } }


"Diagonal of a Regular Pentagon | C # Program to find the diagonal of a regular pentagon ; Function to find the diagonal of a regular pentagon ; Side cannot be negative ; Length of the diagonal ; Driver code"
Solution in C#:

using System ; public class GFG { static double pentdiagonal ( double a ) { if ( a < 0 ) return - 1 ; double d = 1.22 * a ; return d ; } static public void Main ( ) { double a = 6 ; Console . WriteLine ( pentdiagonal ( a ) ) ; } }


"Diameter of a Binary Tree in O ( n ) [ A new method ] | Simple C # program to find diameter of a binary tree . ; Tree node structure used in the program ; Function to find height of a tree ; update the answer , because diameter of a tree is nothing but maximum value of ( left_height + right_height + 1 ) for each node ; Computes the diameter of binary tree with given root . ; This will store the final answer ; A utility function to create a new Binary Tree Node ; Driver code"
Solution in C#:

using System ; class GfG { class Node { public int data ; public Node left , right ; } class A { public int ans = int . MinValue ; } static int height ( Node root , A a ) { if ( root == null ) return 0 ; int left_height = height ( root . left , a ) ; int right_height = height ( root . right , a ) ; a . ans = Math . Max ( a . ans , 1 + left_height + right_height ) ; return 1 + Math . Max ( left_height , right_height ) ; } static int diameter ( Node root ) { if ( root == null ) return 0 ; A a = new A ( ) ; int height_of_tree = height ( root , a ) ; return a . ans ; } static Node newNode ( int data ) { Node node = new Node ( ) ; node . data = data ; node . left = null ; node . right = null ; return ( node ) ; } public static void Main ( ) { Node root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 3 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 5 ) ; Console . WriteLine ( " Diameter ▁ is ▁ " + diameter ( root ) ) ; } }


"Diameter of a Binary Tree | Class containing left and right child of current node and key value ; Class to print the Diameter ; The function Compute the " height " of a tree . Height is the number of nodes along the longest path from the root node down to the farthest leaf node . ; base case tree is empty ; If tree is not empty then height = 1 + max of left height and right heights ; Function to get diameter of a binary tree ; base case where tree is empty ; get the height of left and right sub - trees ; get the diameter of left and right sub - trees ; Return max of following three 1 ) Diameter of left subtree 2 ) Diameter of right subtree 3 ) Height of left subtree + height of right subtree + 1 ; A wrapper over diameter ( Node root ) ; Driver Code ; creating a binary tree and entering the nodes ; Function Call"
Solution in C#:

using System ; namespace Tree { class Tree < T > { public Tree ( T value ) { this . value = value ; } public T value { get ; set ; } public Tree < T > left { get ; set ; } public Tree < T > right { get ; set ; } } public class TreeDiameter { Tree < int > root ; int Height ( Tree < int > node ) { if ( node == null ) return 0 ; return 1 + Math . Max ( Height ( node . left ) , Height ( node . right ) ) ; } int Diameter ( Tree < int > root ) { if ( root == null ) return 0 ; int lHeight = Height ( root . left ) ; int rHeight = Height ( root . right ) ; int lDiameter = Diameter ( root . left ) ; int rDiameter = Diameter ( root . right ) ; return Math . Max ( lHeight + rHeight + 1 , Math . Max ( lDiameter , rDiameter ) ) ; } int Diameter ( ) { return Diameter ( root ) ; } public static void Main ( string [ ] args ) { TreeDiameter tree = new TreeDiameter ( ) ; tree . root = new Tree < int > ( 1 ) ; tree . root . left = new Tree < int > ( 2 ) ; tree . root . right = new Tree < int > ( 3 ) ; tree . root . left . left = new Tree < int > ( 4 ) ; tree . root . left . right = new Tree < int > ( 5 ) ; Console . WriteLine ( $" The diameter of given binary tree is :  { tree . Diameter ( ) } " ) ; } } }


"Diameter of a Binary Tree | Recursive C # program to find the diameter of a Binary Tree ; Class containing left and right child of current node and key value ; A utility class to pass heigh object ; Class to print the Diameter ; define height = 0 globally and call diameterOpt ( root , height ) from main ; lh -- > Height of left subtree rh -- > Height of right subtree ; base condition - when binary tree is empty ; diameter is also 0 ; ldiameter -- > diameter of left subtree rdiameter -- > Diameter of right subtree Get the heights of left and right subtrees in lh and rh And store the returned values in ldiameter and ldiameter ; Height of current node is max of heights of left and right subtrees plus 1 ; A wrapper over diameter ( Node root ) ; The function Compute the " height " of a tree . Height is the number f nodes along the longest path from the root node down to the farthest leaf node . ; base case tree is empty ; If tree is not empty then height = 1 + max of left height and right heights ; Driver Code ; creating a binary tree and entering the nodes ; Function Call"
Solution in C#:

using System ; using System . Collections . Generic ; class Node { public int data ; public Node left , right ; public Node ( int item ) { data = item ; left = right = null ; } } class Height { public int h ; } class BinaryTree { public Node root ; public int diameterOpt ( Node root , Height height ) { Height lh = new Height ( ) , rh = new Height ( ) ; if ( root == null ) { height . h = 0 ; return 0 ; } int ldiameter = diameterOpt ( root . left , lh ) ; int rdiameter = diameterOpt ( root . right , rh ) ; height . h = Math . Max ( lh . h , rh . h ) + 1 ; return Math . Max ( lh . h + rh . h + 1 , Math . Max ( ldiameter , rdiameter ) ) ; } public int diameter ( ) { Height height = new Height ( ) ; return diameterOpt ( root , height ) ; } public int height ( Node node ) { if ( node == null ) return 0 ; return ( 1 + Math . Max ( height ( node . left ) , height ( node . right ) ) ) ; } static void Main ( ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 1 ) ; tree . root . left = new Node ( 2 ) ; tree . root . right = new Node ( 3 ) ; tree . root . left . left = new Node ( 4 ) ; tree . root . left . right = new Node ( 5 ) ; Console . Write ( " The ▁ diameter ▁ of ▁ given ▁ binary ▁ tree ▁ is ▁ : ▁ " + tree . diameter ( ) ) ; } }


"Diameters for each node of Tree after connecting it with given disconnected component | C # Program to implement the above approach ; Keeps track of the farthest end of the diameter ; Keeps track of the length of the diameter ; Stores the nodes which are at ends of the diameter ; Perform DFS on the given tree ; Update diameter and X ; If current node is an end of diameter ; Traverse its neighbors ; Function to call DFS for the required purposes ; DFS from a random node and find the node farthest from it ; DFS from X to calculate diameter ; DFS from farthest_node to find the farthest node ( s ) from it ; DFS from X ( other end of diameter ) and check the farthest node ( s ) from it ; If node i is the end of a diameter ; Increase diameter by 1 ; Otherwise ; Remains unchanged ; Driver Code ; constructed tree is 1 / \ 2 3 7 / | \ / | \ 4 5 6 ; creating undirected edges"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static int X = 1 ; static int diameter = 0 ; static Dictionary < int , Boolean > mp = new Dictionary < int , Boolean > ( ) ; static void dfs ( int current_node , int prev_node , int len , bool add_to_map , List < int > [ ] adj ) { if ( len > diameter ) { diameter = len ; X = current_node ; } if ( add_to_map && len == diameter ) { mp . Add ( current_node , true ) ; } foreach ( int it in adj [ current_node ] ) { if ( it != prev_node ) dfs ( it , current_node , len + 1 , add_to_map , adj ) ; } } static void dfsUtility ( List < int > [ ] adj ) { dfs ( 1 , - 1 , 0 , false , adj ) ; int farthest_node = X ; dfs ( farthest_node , - 1 , 0 , false , adj ) ; dfs ( farthest_node , - 1 , 0 , true , adj ) ; dfs ( X , - 1 , 0 , true , adj ) ; } static void printDiameters ( List < int > [ ] adj ) { dfsUtility ( adj ) ; for ( int i = 1 ; i <= 6 ; i ++ ) { if ( mp . ContainsKey ( i ) && mp [ i ] == true ) Console . Write ( diameter + 1 + " , ▁ " ) ; else Console . Write ( diameter + " , ▁ " ) ; } } public static void Main ( String [ ] args ) { List < int > [ ] adj = new List < int > [ 7 ] ; for ( int i = 0 ; i < adj . Length ; i ++ ) adj [ i ] = new List < int > ( ) ; adj [ 1 ] . Add ( 2 ) ; adj [ 2 ] . Add ( 1 ) ; adj [ 1 ] . Add ( 3 ) ; adj [ 3 ] . Add ( 1 ) ; adj [ 2 ] . Add ( 4 ) ; adj [ 4 ] . Add ( 2 ) ; adj [ 2 ] . Add ( 5 ) ; adj [ 5 ] . Add ( 2 ) ; adj [ 2 ] . Add ( 6 ) ; adj [ 6 ] . Add ( 2 ) ; printDiameters ( adj ) ; } }


"Dice Throw | DP | C # program The main function that returns number of ways to get sum ' x ' with ' n ' dice and ' m ' with m faces . ; * * Count ways * * @ param f * @ param d * @ param s * @ return ; Create a table to store results of subproblems . One extra row and column are used for simpilicity ( Number of dice is directly used as row index and sum is directly used as column index ) . The entries in 0 th row and 0 th column are never used . ; Table entries for no dices If you do not have any data , then the value must be 0 , so the result is 1 ; Iterate over dices ; Iterate over sum ; The result is obtained in two ways , pin the current dice and spending 1 of the value , so we have mem [ i - 1 , j - 1 ] remaining combinations , to find the remaining combinations we would have to pin the values ? ? above 1 then we use mem [ i , j - 1 ] to sum all combinations that pin the remaining j - 1 's. But there is a way, when "j-f-1> = 0" we would be adding  extra combinations, so we remove the combinations that only pin the extrapolated dice face and  subtract the extrapolated combinations. ; Driver code"
Solution in C#:

using System ; class GFG { public static long findWays ( int f , int d , int s ) { long [ , ] mem = new long [ d + 1 , s + 1 ] ; mem [ 0 , 0 ] = 1 ; for ( int i = 1 ; i <= d ; i ++ ) { for ( int j = i ; j <= s ; j ++ ) { mem [ i , j ] = mem [ i , j - 1 ] + mem [ i - 1 , j - 1 ] ; if ( j - f - 1 >= 0 ) mem [ i , j ] -= mem [ i - 1 , j - f - 1 ] ; } } return mem [ d , s ] ; } public static void Main ( String [ ] args ) { Console . WriteLine ( findWays ( 4 , 2 , 1 ) ) ; Console . WriteLine ( findWays ( 2 , 2 , 3 ) ) ; Console . WriteLine ( findWays ( 6 , 3 , 8 ) ) ; Console . WriteLine ( findWays ( 4 , 2 , 5 ) ) ; Console . WriteLine ( findWays ( 4 , 3 , 5 ) ) ; } }


"Dice Throw | DP | C # program to find number of ways to get sum ' x ' with ' n ' dice where every dice has ' m ' faces ; The main function that returns number of ways to get sum ' x ' with ' n ' dice and ' m ' with m faces . ; Create a table to store results of subproblems . row and column are used for simpilicity ( Number of dice is directly used as row index and sum is directly used as column index ) . The entries in 0 th row and 0 th column are never used . ; Table entries for only one dice ; Fill rest of the entries in table using recursive relation i : number of dice , j : sum ; Return value ; Driver Code"
Solution in C#:

using System ; class GFG { static int findWays ( int m , int n , int x ) { int [ , ] table = new int [ n + 1 , x + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) for ( int j = 0 ; j <= x ; j ++ ) table [ i , j ] = 0 ; for ( int j = 1 ; j <= m && j <= x ; j ++ ) table [ 1 , j ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) for ( int j = 1 ; j <= x ; j ++ ) for ( int k = 1 ; k <= m && k < j ; k ++ ) table [ i , j ] += table [ i - 1 , j - k ] ; return table [ n , x ] ; } public static void Main ( ) { Console . WriteLine ( findWays ( 4 , 2 , 1 ) ) ; Console . WriteLine ( findWays ( 2 , 2 , 3 ) ) ; Console . WriteLine ( findWays ( 6 , 3 , 8 ) ) ; Console . WriteLine ( findWays ( 4 , 2 , 5 ) ) ; Console . WriteLine ( findWays ( 4 , 3 , 5 ) ) ; } }


"Difference Array | Range update query in O ( 1 ) | C # code to demonstrate Difference Array ; Creates a diff array D [ ] for A [ ] and returns it after filling initial values . ; We use one extra space because update ( l , r , x ) updates D [ r + 1 ] ; Does range update ; Prints updated Array ; Note that A [ 0 ] or D [ 0 ] decides values of rest of the elements . ; Driver Code ; Array to be updated ; Create and fill difference Array We use one extra space because update ( l , r , x ) updates D [ r + 1 ] ; After below update ( l , r , x ) , the elements should become 20 , 15 , 20 , 40 ; After below updates , the array should become 30 , 35 , 70 , 60"
Solution in C#:

using System ; class GFG { static void initializeDiffArray ( int [ ] A , int [ ] D ) { int n = A . Length ; D [ 0 ] = A [ 0 ] ; D [ n ] = 0 ; for ( int i = 1 ; i < n ; i ++ ) D [ i ] = A [ i ] - A [ i - 1 ] ; } static void update ( int [ ] D , int l , int r , int x ) { D [ l ] += x ; D [ r + 1 ] -= x ; } static int printArray ( int [ ] A , int [ ] D ) { for ( int i = 0 ; i < A . Length ; i ++ ) { if ( i == 0 ) A [ i ] = D [ i ] ; else A [ i ] = D [ i ] + A [ i - 1 ] ; Console . Write ( A [ i ] + " ▁ " ) ; } Console . WriteLine ( ) ; return 0 ; } public static void Main ( ) { int [ ] A = { 10 , 5 , 20 , 40 } ; int n = A . Length ; int [ ] D = new int [ n + 1 ] ; initializeDiffArray ( A , D ) ; update ( D , 0 , 1 , 10 ) ; printArray ( A , D ) ; update ( D , 1 , 3 , 20 ) ; update ( D , 2 , 2 , 30 ) ; printArray ( A , D ) ; } }


"Difference between Recursion and Iteration | C # program to find factorial of given number ; -- -- - Recursion -- -- - method to find factorial of given number ; recursion call ; -- -- - Iteration -- -- - Method to find the factorial of a given number ; using iteration ; Driver Code"
Solution in C#:

using System ; class GFG { static int factorialUsingRecursion ( int n ) { if ( n == 0 ) return 1 ; return n * factorialUsingRecursion ( n - 1 ) ; } static int factorialUsingIteration ( int n ) { int res = 1 , i ; for ( i = 2 ; i <= n ; i ++ ) res *= i ; return res ; } public static void Main ( String [ ] args ) { int num = 5 ; Console . WriteLine ( " Factorial ▁ of ▁ " + num + " ▁ using ▁ Recursion ▁ is : ▁ " + factorialUsingRecursion ( 5 ) ) ; Console . WriteLine ( " Factorial ▁ of ▁ " + num + " ▁ using ▁ Iteration ▁ is : ▁ " + factorialUsingIteration ( 5 ) ) ; } }


"Difference between Sum of Cubes and Sum of First N Natural Numbers | C # program to find the difference between the sum of the cubes of the first N natural numbers and the sum of the first N natural number ; Sum of first n natural numbers ; Find the required difference ; Driver Code"
Solution in C#:

using System ; class GFG { static int difference ( int n ) { int S , res ; S = ( n * ( n + 1 ) ) / 2 ; res = S * ( S - 1 ) ; return res ; } static public void Main ( ) { int n = 5 ; Console . Write ( difference ( n ) ) ; } }


"Difference between ceil of array sum divided by K and sum of ceil of array elements divided by K | C # approach for the above approach ; Function to find absolute difference between array sum divided by x and sum of ceil of array elements divided by x ; Stores the total sum ; Stores the sum of ceil of array elements divided by x ; Traverse the array ; Adding each array element ; Add the value ceil of arr [ i ] / x ; Find the ceil of the total sum divided by x ; Return absolute difference ; Driver Code"
Solution in C#:

using System ; class GFG { static int ceilDifference ( int [ ] arr , int n , int x ) { int totalSum = 0 ; int perElementSum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { totalSum += arr [ i ] ; perElementSum += ( int ) Math . Ceiling ( ( double ) ( arr [ i ] ) / ( double ) ( x ) ) ; } int totalCeilSum = ( int ) Math . Ceiling ( ( double ) ( totalSum ) / ( double ) ( x ) ) ; return Math . Abs ( perElementSum - totalCeilSum ) ; } public static void Main ( string [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 , 6 } ; int K = 4 ; int N = arr . Length ; Console . Write ( ceilDifference ( arr , N , K ) ) ; } }


"Difference between highest and least frequencies in an array | C # Code for Difference between highest and least frequencies in an array ; sort the array ; checking consecutive elements ; Driver program to test above function"
Solution in C#:

using System ; class GFG { static int findDiff ( int [ ] arr , int n ) { Array . Sort ( arr ) ; int count = 0 , max_count = 0 , min_count = n ; for ( int i = 0 ; i < ( n - 1 ) ; i ++ ) { if ( arr [ i ] == arr [ i + 1 ] ) { count += 1 ; continue ; } else { max_count = Math . Max ( max_count , count ) ; min_count = Math . Min ( min_count , count ) ; count = 0 ; } } return ( max_count - min_count ) ; } public static void Main ( ) { int [ ] arr = { 7 , 8 , 4 , 5 , 4 , 1 , 1 , 7 , 7 , 2 , 5 } ; int n = arr . Length ; Console . WriteLine ( findDiff ( arr , n ) ) ; } }


"Difference between highest and least frequencies in an array | C # code to find the difference between highest and least frequencies ; Put all elements in a hash map ; Find counts of maximum and minimum frequent elements ; Driver code"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static int findDiff ( int [ ] arr , int n ) { Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp . ContainsKey ( arr [ i ] ) ) { var val = mp [ arr [ i ] ] ; mp . Remove ( arr [ i ] ) ; mp . Add ( arr [ i ] , val + 1 ) ; } else { mp . Add ( arr [ i ] , 1 ) ; } } int max_count = 0 , min_count = n ; foreach ( KeyValuePair < int , int > entry in mp ) { max_count = Math . Max ( max_count , entry . Value ) ; min_count = Math . Min ( min_count , entry . Value ) ; } return ( max_count - min_count ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 7 , 8 , 4 , 5 , 4 , 1 , 1 , 7 , 7 , 2 , 5 } ; int n = arr . Length ; Console . WriteLine ( findDiff ( arr , n ) ) ; } }


"Difference between lexicographical ranks of two given permutations | C # program for the above approach ; Function the print the difference between the lexicographical ranks ; Store the permutations in lexicographic order ; Intital permutation ; Initial variables ; Check permutation ; Initialize second permutation ; Check permutation ; Print difference ; Driver Code ; Given array P [ ] ; Given array Q [ ] ; Given size ; Function call"
Solution in C#:

 using System ; class GFG { static void findDifference ( int [ ] p , int [ ] q , int N ) { int [ ] A = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) A [ i ] = i + 1 ; bool IsCorrect ; int a = 1 , b = 1 ; do { IsCorrect = true ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] != p [ i ] ) { IsCorrect = false ; break ; } } if ( IsCorrect ) break ; a ++ ; } while ( next_permutation ( A ) ) ; for ( int i = 0 ; i < N ; i ++ ) A [ i ] = i + 1 ; do { IsCorrect = true ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] != q [ i ] ) { IsCorrect = false ; break ; } } if ( IsCorrect ) break ; b ++ ; } while ( next_permutation ( A ) ) ; Console . Write ( Math . Abs ( a - b ) + "
 " ) ; } static bool next_permutation ( int [ ] p ) { for ( int a = p . Length - 2 ; a >= 0 ; -- a ) if ( p [ a ] < p [ a + 1 ] ) for ( int b = p . Length - 1 ; ; -- b ) if ( p [ b ] > p [ a ] ) { int t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; for ( ++ a , b = p . Length - 1 ; a < b ; ++ a , -- b ) { t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; } return true ; } return false ; } public static void Main ( String [ ] args ) { int [ ] p = { 1 , 3 , 2 } ; int [ ] q = { 3 , 1 , 2 } ; int n = p . Length ; findDifference ( p , q , n ) ; } }


"Difference between maximum and minimum average of all K | C # program for the above approach ; Function to find the difference between averages of the maximum and the minimum subarrays of length k ; Stores min and max sum ; Iterate through starting points ; Sum up next K elements ; Update max and min moving sum ; Return the difference between max and min average ; Driver Code ; Given Input ; Function Call"
Solution in C#:

using System ; class GFG { static double Avgdifference ( double [ ] arr , int N , int K ) { double min = 1000000 , max = - 1 ; for ( int i = 0 ; i <= N - K ; i ++ ) { double sum = 0 ; for ( int j = 0 ; j < K ; j ++ ) { sum += arr [ i + j ] ; } if ( min > sum ) min = sum ; if ( max < sum ) max = sum ; } return ( max - min ) / K ; } public static void Main ( String [ ] args ) { double [ ] arr = { 3 , 8 , 9 , 15 } ; int N = arr . Length ; int K = 2 ; Console . Write ( Avgdifference ( arr , N , K ) ) ; } }


"Difference between maximum and minimum average of all K | C # program for the above approach ; Function to find the difference between the maximum and minimum subarrays of length K ; Stores the sum of subarray over the range [ 0 , K ] ; Iterate over the range [ 0 , K ] ; Store min and max sum ; Iterate over the range [ K , N - K ] ; Increment sum by arr [ i ] - arr [ i - K ] ; Update max and min moving sum ; Return difference between max and min average ; Driver Code ; Given Input ; Function Call"
Solution in C#:

using System ; class GFG { static double Avgdifference ( double [ ] arr , int N , int K ) { double sum = 0 ; for ( int i = 0 ; i < K ; i ++ ) sum += arr [ i ] ; double min = sum ; double max = sum ; for ( int i = K ; i <= N - K + 1 ; i ++ ) { sum += arr [ i ] - arr [ i - K ] ; if ( min > sum ) min = sum ; if ( max < sum ) max = sum ; } return ( max - min ) / K ; } public static void Main ( String [ ] args ) { double [ ] arr = { 3 , 8 , 9 , 15 } ; int N = arr . Length ; int K = 2 ; Console . Write ( Avgdifference ( arr , N , K ) ) ; } }


"Difference between maximum and minimum of a set of anagrams from an array | C # program for the above approach ; Utility function to find the hash value for each element of the given array ; Initialize an array with first 10 prime numbers ; Iterate over digits of N ; Update Hash Value ; Update N ; Function to find the set of anagrams in the array and print the difference between the maximum and minimum of these numbers ; Map to store the hash value and the array elements having that hash value ; Find the hash value for each arr [ i ] by calling hash function ; Iterate over the map ; If size of vector at m [ i ] greater than 1 then it must contain the anagrams ; Find the minimum and maximum element of this anagrams vector ; Display the difference ; If the end of Map is reached , then no anagrams are present ; Driver code ; Given array ; Size of the array"
Solution in C#:

using System ; using System . Collections . Generic ; using System . Linq ; class GFG { static int hashFunction ( int N ) { int [ ] prime = { 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 } ; int value = 1 , r ; while ( N != 0 ) { r = N % 10 ; value = value * prime [ r ] ; N = N / 10 ; } return value ; } static void findDiff ( int [ ] arr , int n ) { Dictionary < int , List < int > > m = new Dictionary < int , List < int > > ( ) ; int h , min , max ; for ( int i = 0 ; i < n ; i ++ ) { h = hashFunction ( arr [ i ] ) ; if ( ! m . ContainsKey ( h ) ) { m [ h ] = new List < int > ( ) ; } m [ h ] . Add ( arr [ i ] ) ; } foreach ( KeyValuePair < int , List < int > > i in m ) { if ( i . Value . Count > 1 ) { min = Int32 . MaxValue ; max = Int32 . MinValue ; for ( int j = 0 ; j < i . Value . Count ; j ++ ) { if ( m [ i . Key ] [ j ] < min ) { min = m [ i . Key ] [ j ] ; } if ( m [ i . Key ] [ j ] > max ) { max = m [ i . Key ] [ j ] ; } } Console . Write ( max - min ) ; break ; } else if ( m [ i . Key ] . Equals ( m . Last ( ) . Value ) ) Console . Write ( - 1 ) ; } } static void Main ( ) { int [ ] arr = { 121 , 312 , 234 , 211 , 112 , 102 } ; int N = arr . Length ; findDiff ( arr , N ) ; } }


"Difference between sum of K maximum even and odd array elements | C # program for the above approach ; Function to find the absolute difference between sum of first K maximum even and odd numbers ; Stores index from where odd number starts ; Segregate even and odd number ; If current element is even ; Sort in decreasing order even part ; Sort in decreasing order odd part ; Calculate sum of k maximum even number ; Calculate sum of k maximum odd number ; Print the absolute difference ; Driver Code ; Given array [ ] arr ; Size of array ; Function Call"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static void evenOddDiff ( int [ ] a , int n , int k ) { int j = - 1 ; List < int > even = new List < int > ( ) ; List < int > odd = new List < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] % 2 == 0 ) { even . Add ( a [ i ] ) ; } else odd . Add ( a [ i ] ) ; } j ++ ; even . Sort ( ) ; even . Reverse ( ) ; odd . Sort ( ) ; odd . Reverse ( ) ; int evenSum = 0 , oddSum = 0 ; for ( int i = 0 ; i < k ; i ++ ) { evenSum += even [ i ] ; } for ( int i = 0 ; i < k ; i ++ ) { oddSum += odd [ i ] ; } Console . Write ( Math . Abs ( evenSum - oddSum ) ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 8 , 3 , 4 , 5 } ; int N = arr . Length ; int K = 2 ; evenOddDiff ( arr , N , K ) ; } }


"Difference between sum of odd and even frequent elements in an Array | C # program to find absolute difference between the sum of all odd frequenct and even frequent elements in an array ; Function to find the sum of all even and odd frequent elements in an array ; Stores the frequency of array elements ; Traverse the array ; Update frequency of current element ; Stores sum of odd and even frequent elements ; Traverse the map ; If frequency is odd ; Add sum of all occurrences of current element to sum_odd ; If frequency is even ; Add sum of all occurrences of current element to sum_even ; Calculate difference between their sum ; Return diff ; Driver code"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static int findSum ( int [ ] arr , int N ) { Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( mp . ContainsKey ( arr [ i ] ) ) { mp [ arr [ i ] ] ++ ; } else { mp [ arr [ i ] ] = 1 ; } } int sum_odd = 0 , sum_even = 0 ; foreach ( KeyValuePair < int , int > itr in mp ) { if ( itr . Value % 2 != 0 ) sum_odd += ( itr . Key ) * ( itr . Value ) ; if ( itr . Value % 2 == 0 ) sum_even += ( itr . Key ) * ( itr . Value ) ; } int diff = sum_even - sum_odd ; return diff ; } static void Main ( ) { int [ ] arr = { 1 , 5 , 5 , 2 , 4 , 3 , 3 } ; int N = arr . Length ; Console . Write ( findSum ( arr , N ) ) ; } }


"Difference between sums of odd level and even level nodes of a Binary Tree | A recursive C # program to find difference between sum of nodes at odd level and sum at even level ; A binary tree node ; The main function that return difference between odd and even level nodes ; Base case ; Difference for root is root 's   data - difference for left subtree  - difference for right subtree  ; Driver program to test above functions"
Solution in C#:

using System ; public class Node { public int data ; public Node left , right ; public Node ( int item ) { data = item ; left = right ; } } public class BinaryTree { public Node root ; public virtual int getLevelDiff ( Node node ) { if ( node == null ) { return 0 ; } return node . data - getLevelDiff ( node . left ) - getLevelDiff ( node . right ) ; } public static void Main ( string [ ] args ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 5 ) ; tree . root . left = new Node ( 2 ) ; tree . root . right = new Node ( 6 ) ; tree . root . left . left = new Node ( 1 ) ; tree . root . left . right = new Node ( 4 ) ; tree . root . left . right . left = new Node ( 3 ) ; tree . root . right . right = new Node ( 8 ) ; tree . root . right . right . right = new Node ( 9 ) ; tree . root . right . right . left = new Node ( 7 ) ; Console . WriteLine ( tree . getLevelDiff ( tree . root ) + " ▁ is ▁ the ▁ required ▁ difference " ) ; } }


"Difference between sums of odd level and even level nodes of a Binary Tree | C # program to find difference between sums of odd level and even level nodes of binary tree ; User defined node class ; Constructor to create a new tree node ; return difference of sums of odd level and even level ; create a queue for level order traversal ; traverse until the queue is empty ; traverse for complete level ; check if level no . is even or odd and accordingly update the evenSum or oddSum ; check for left child ; check for right child ; Driver code ; construct a tree"
Solution in C#:

using System ; using System . Collections . Generic ; public class Node { public int data ; public Node left , right ; public Node ( int key ) { data = key ; left = right = null ; } } public class GFG { static int evenOddLevelDifference ( Node root ) { if ( root == null ) return 0 ; Queue < Node > q = new Queue < Node > ( ) ; q . Enqueue ( root ) ; int level = 0 ; int evenSum = 0 , oddSum = 0 ; while ( q . Count != 0 ) { int size = q . Count ; level ++ ; while ( size > 0 ) { Node temp = q . Dequeue ( ) ; if ( level % 2 == 0 ) evenSum += temp . data ; else oddSum += temp . data ; if ( temp . left != null ) q . Enqueue ( temp . left ) ; if ( temp . right != null ) q . Enqueue ( temp . right ) ; size -- ; } } return ( oddSum - evenSum ) ; } public static void Main ( String [ ] args ) { Node root = new Node ( 5 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 6 ) ; root . left . left = new Node ( 1 ) ; root . left . right = new Node ( 4 ) ; root . left . right . left = new Node ( 3 ) ; root . right . right = new Node ( 8 ) ; root . right . right . right = new Node ( 9 ) ; root . right . right . left = new Node ( 7 ) ; Console . WriteLine ( " diffence ▁ between ▁ sums ▁ is ▁ " + evenOddLevelDifference ( root ) ) ; } }


"Difference of two large numbers | C # program to find difference of two large numbers . ; Returns true if str1 is smaller than str2 , else false . ; Calculate lengths of both string ; Function for finding difference of larger numbers ; Before proceeding further , make sure str1 is not smaller ; Take an empty string for storing result ; Calculate lengths of both string ; Initially take carry zero ; Traverse from end of both strings ; Do school mathematics , compute difference of current digits and carry ; subtract remaining digits of str1 [ ] ; if ( i > 0 sub > 0 ) remove preceding 0 's ; reverse resultant string ; Driver code ; Function call"
Solution in C#:

using System ; class GFG { static bool isSmaller ( string str1 , string str2 ) { int n1 = str1 . Length , n2 = str2 . Length ; if ( n1 < n2 ) return true ; if ( n2 < n1 ) return false ; for ( int i = 0 ; i < n1 ; i ++ ) { if ( str1 [ i ] < str2 [ i ] ) return true ; else if ( str1 [ i ] > str2 [ i ] ) return false ; } return false ; } static string findDiff ( string str1 , string str2 ) { if ( isSmaller ( str1 , str2 ) ) { string t = str1 ; str1 = str2 ; str2 = t ; } String str = " " ; int n1 = str1 . Length , n2 = str2 . Length ; int diff = n1 - n2 ; int carry = 0 ; for ( int i = n2 - 1 ; i >= 0 ; i -- ) { int sub = ( ( ( int ) str1 [ i + diff ] - ( int ) '0' ) - ( ( int ) str2 [ i ] - ( int ) '0' ) - carry ) ; if ( sub < 0 ) { sub = sub + 10 ; carry = 1 ; } else carry = 0 ; str += sub . ToString ( ) ; } for ( int i = n1 - n2 - 1 ; i >= 0 ; i -- ) { if ( str1 [ i ] == '0' && carry > 0 ) { str += "9" ; continue ; } int sub = ( ( ( int ) str1 [ i ] - ( int ) '0' ) - carry ) ; str += sub . ToString ( ) ; carry = 0 ; } char [ ] aa = str . ToCharArray ( ) ; Array . Reverse ( aa ) ; return new string ( aa ) ; } public static void Main ( ) { String str1 = "88" ; String str2 = "1079" ; Console . WriteLine ( findDiff ( str1 , str2 ) ) ; } }


"Different substrings in a string that start and end with given strings | C # program to find number of different sub strings ; function to return number of different sub - strings ; initially our answer is zero . ; find the length of given strings ; currently make array and initially put zero . ; find occurrence of " a " and " b " in string " s " ; We use a hash to make sure that same substring is not counted twice . ; go through all the positions to find occurrence of " a " first . ; if we found occurrence of " a " . ; then go through all the positions to find occurrence of " b " . ; if we do found " b " at index j then add it to already existed substring . ; if we found occurrence of " b " . ; now add string " b " to already existed substring . ; If current substring is not included already . ; put any non negative integer to make this string as already existed . ; make substring null . ; return answer . ; Driver Code"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static int numberOfDifferentSubstrings ( String s , char a , char b ) { int ans = 0 ; int ls = s . Length ; int [ ] x = new int [ ls ] ; int [ ] y = new int [ ls ] ; for ( int i = 0 ; i < ls ; i ++ ) { if ( s [ i ] == a ) x [ i ] = 1 ; if ( s [ i ] == b ) y [ i ] = 1 ; } HashSet < String > hash = new HashSet < String > ( ) ; String curr_substr = " " ; for ( int i = 0 ; i < ls ; i ++ ) { if ( x [ i ] != 0 ) { for ( int j = i ; j < ls ; j ++ ) { if ( y [ j ] == 0 ) curr_substr += s [ i ] ; if ( y [ j ] != 0 ) { curr_substr += s [ j ] ; if ( ! hash . Contains ( curr_substr ) ) ans ++ ; hash . Add ( curr_substr ) ; } } curr_substr = " " ; } } return ans ; } public static void Main ( String [ ] args ) { String s = " codecppforfood " ; char begin = ' c ' ; char end = ' d ' ; Console . WriteLine ( numberOfDifferentSubstrings ( s , begin , end ) ) ; } }


"Different ways to sum n using numbers greater than or equal to m | C # program to find number of ways to which numbers that are greater than given number can be added to get sum . ; Return number of ways to which numbers that are greater than given number can be added to get sum . ; Filling the table . k is for numbers greater than or equal that are allowed . ; i is for sum ; initializing dp [ i ] [ k ] to number ways to get sum using numbers greater than or equal k + 1 ; if i > k ; Driver Program"
Solution in C#:

using System ; class GFG { static int numberofways ( int n , int m ) { int [ , ] dp = new int [ n + 2 , n + 2 ] ; dp [ 0 , n + 1 ] = 1 ; for ( int k = n ; k >= m ; k -- ) { for ( int i = 0 ; i <= n ; i ++ ) { dp [ i , k ] = dp [ i , k + 1 ] ; if ( i - k >= 0 ) dp [ i , k ] = ( dp [ i , k ] + dp [ i - k , k ] ) ; } } return dp [ n , m ] ; } public static void Main ( ) { int n = 3 , m = 1 ; Console . WriteLine ( numberofways ( n , m ) ) ; } }


"Digit | C # program for Digit Product Sequence ; function to produce and print Digit Product Sequence ; Array which store sequence ; Temporary variable to store product ; Initialize first element of the array with 1 ; Run a loop from 1 to N . Check if previous number is single digit or not . If yes then product = 1 else take modulus . Then again check if previous number is single digit or not if yes then store previous number , else store its first value Then for every i store value in the array . ; Print sequence ; Driver Code ; Value of N ; Calling function"
Solution in C#:

using System ; class GFG { public static void digit_product_Sum ( int N ) { int [ ] a = new int [ N + 1 ] ; int product = 1 ; a [ 0 ] = 1 ; for ( int i = 1 ; i <= N ; i ++ ) { product = a [ i - 1 ] / 10 ; if ( product == 0 ) product = 1 ; else product = a [ i - 1 ] % 10 ; int val = a [ i - 1 ] / 10 ; if ( val == 0 ) val = a [ i - 1 ] ; a [ i ] = a [ i - 1 ] + ( val * product ) ; } for ( int i = 0 ; i < N ; i ++ ) Console . Write ( a [ i ] + " ▁ " ) ; } public static void Main ( ) { int N = 10 ; digit_product_Sum ( N ) ; } }


"Digital Root of a given large integer using Recursion | C # program to print the digital root of a given very large number ; Function to convert given sum into String ; Loop to extract digit one by one from the given sum and concatenate into the String ; Type casting for concatenation ; Return converted String ; Function to get individual digit sum from String ; Loop to get individual digit sum ; Function call to convert sum into String ; Function to calculate the digital root of a very large number ; Base condition ; Function call to get individual digit sum ; Recursive function to get digital root of a very large number ; Driver code ; Function to print readonly digit"
Solution in C#:

using System ; class GFG { static String convertToString ( int sum ) { String str = " " ; while ( sum > 0 ) { str = str + ( char ) ( ( sum % 10 ) + '0' ) ; sum = sum / 10 ; } return str ; } static String GetIndividulaDigitSum ( String str , int len ) { int sum = 0 ; for ( int i = 0 ; i < len ; i ++ ) { sum = sum + str [ i ] - '0' ; } return convertToString ( sum ) ; } static int GetDigitalRoot ( String str ) { if ( str . Length == 1 ) { return str [ 0 ] - '0' ; } str = GetIndividulaDigitSum ( str , str . Length ) ; return GetDigitalRoot ( str ) ; } public static void Main ( String [ ] args ) { String str = "675987890789756545689070986776987" ; Console . Write ( GetDigitalRoot ( str ) ) ; } }


"Digitally balanced numbers | C # implementation to check if a number is a digitally balanced number ; Function to check if the digits in the number is the same number of digits ; Loop to iterate over the digits of the number N ; Loop to iterate over the map ; Driver Code ; Function to check"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static bool checkSame ( int n , int b ) { Dictionary < int , int > m = new Dictionary < int , int > ( ) ; while ( n != 0 ) { int r = n % b ; n = n / b ; if ( m . ContainsKey ( r ) ) { m [ r ] = m [ r ] + 1 ; } else { m . Add ( r , 1 ) ; } } int last = - 1 ; foreach ( KeyValuePair < int , int > i in m ) { if ( last != - 1 && i . Value != last ) { return false ; } else { last = i . Value ; } } return true ; } public static void Main ( String [ ] args ) { int n = 9 ; int Base = 2 ; if ( checkSame ( n , Base ) ) Console . Write ( " Yes " ) ; else Console . Write ( " NO " ) ; } }


"Digits whose alphabetic representations are jumbled in a given string | C # program for the above approach ; Function to convert the jumbled string into digits ; Initialize vector ; Initialize answer ; Size of the string ; Traverse the string ; Update the elements of the vector ; Print the digits into their original format ; Return answer ; Driver Code"
Solution in C#:

using System ; public class GFG { static string finddigits ( string s ) { int [ ] arr = new int [ 10 ] ; string ans = " " ; int n = s . Length ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ' z ' ) arr [ 0 ] ++ ; if ( s [ i ] == ' w ' ) arr [ 2 ] ++ ; if ( s [ i ] == ' g ' ) arr [ 8 ] ++ ; if ( s [ i ] == ' x ' ) arr [ 6 ] ++ ; if ( s [ i ] == ' v ' ) arr [ 5 ] ++ ; if ( s [ i ] == ' o ' ) arr [ 1 ] ++ ; if ( s [ i ] == ' s ' ) arr [ 7 ] ++ ; if ( s [ i ] == ' f ' ) arr [ 4 ] ++ ; if ( s [ i ] == ' h ' ) arr [ 3 ] ++ ; if ( s [ i ] == ' i ' ) arr [ 9 ] ++ ; } arr [ 7 ] -= arr [ 6 ] ; arr [ 5 ] -= arr [ 7 ] ; arr [ 4 ] -= arr [ 5 ] ; arr [ 1 ] -= ( arr [ 2 ] + arr [ 4 ] + arr [ 0 ] ) ; arr [ 3 ] -= arr [ 8 ] ; arr [ 9 ] -= ( arr [ 5 ] + arr [ 6 ] + arr [ 8 ] ) ; for ( int i = 0 ; i < 10 ; i ++ ) { for ( int j = 0 ; j < arr [ i ] ; j ++ ) { ans += ( char ) ( i + '0' ) ; } } return ans ; } static public void Main ( ) { string s = " owoftnuoer " ; Console . WriteLine ( finddigits ( s ) ) ; } }


"Direction at last square block | C # program to tell the Current direction in R x C grid ; Function which tells the Current direction ; Driver code"
Solution in C#:

using System ; class GFG { static void direction ( int R , int C ) { if ( R != C && R % 2 == 0 && C % 2 != 0 && R < C ) { Console . WriteLine ( " Left " ) ; return ; } if ( R != C && R % 2 != 0 && C % 2 == 0 && R > C ) { Console . WriteLine ( " Up " ) ; return ; } if ( R == C && R % 2 != 0 && C % 2 != 0 ) { Console . WriteLine ( " Right " ) ; return ; } if ( R == C && R % 2 == 0 && C % 2 == 0 ) { Console . WriteLine ( " Left " ) ; return ; } if ( R != C && R % 2 != 0 && C % 2 != 0 && R < C ) { Console . WriteLine ( " Right " ) ; return ; } if ( R != C && R % 2 != 0 && C % 2 != 0 && R > C ) { Console . WriteLine ( " Down " ) ; return ; } if ( R != C && R % 2 == 0 && C % 2 == 0 && R < C ) { Console . WriteLine ( " Left " ) ; return ; } if ( R != C && R % 2 == 0 && C % 2 == 0 && R > C ) { Console . WriteLine ( " Up " ) ; return ; } if ( R != C && R % 2 == 0 && C % 2 != 0 && R > C ) { Console . WriteLine ( " Down " ) ; return ; } if ( R != C && R % 2 != 0 && C % 2 == 0 && R < C ) { Console . WriteLine ( " Right " ) ; return ; } } static public void Main ( ) { int R = 3 , C = 1 ; direction ( R , C ) ; } }


"Direction of a Point from a Line Segment | C # Program to Determine Direction of Point from line segment ; structure for point in cartesian plane . ; constant integers for directions ; subtracting co - ordinates of point A from B and P , to make A as origin ; Determining cross Product ; return RIGHT if cross product is positive ; return LEFT if cross product is negative ; return ZERO if cross product is zero . ; Driver code ; A . y = 10 ; A ( - 30 , 10 ) ; B . y = - 15 ; B ( 29 , - 15 ) ; P . y = 28 ; P ( 15 , 28 )"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { public class point { public int x , y ; } ; static int RIGHT = 1 , LEFT = - 1 , ZERO = 0 ; static int directionOfPoint ( point A , point B , point P ) { B . x -= A . x ; B . y -= A . y ; P . x -= A . x ; P . y -= A . y ; int cross_product = B . x * P . y - B . y * P . x ; if ( cross_product > 0 ) return RIGHT ; if ( cross_product < 0 ) return LEFT ; return ZERO ; } public static void Main ( String [ ] args ) { point A = new point ( ) , B = new point ( ) , P = new point ( ) ; A . x = - 30 ; B . x = 29 ; P . x = 15 ; int direction = directionOfPoint ( A , B , P ) ; if ( direction == 1 ) Console . WriteLine ( " Right ▁ Direction " ) ; else if ( direction == - 1 ) Console . WriteLine ( " Left ▁ Direction " ) ; else Console . WriteLine ( " Point ▁ is ▁ on ▁ the ▁ Line " ) ; } }


"Discrete Cosine Transform ( Algorithm and Program ) | C # program to perform discrete cosine transform ; Function to find discrete cosine transform and print it ; dct will store the discrete cosine transform ; ci and cj depends on frequency as well as number of row and columns of specified matrix ; sum will temporarily store the sum of cosine signals ; Driver code"
Solution in C#:


"Discrete logarithm ( Find an integer k such that a ^ k is congruent modulo b ) | C # program to calculate discrete logarithm ; Calculate a ^ n ; Store all values of a ^ ( n * i ) of LHS ; Calculate ( a ^ j ) * b and check for collision ; Driver code"
Solution in C#:

using System ; class GFG { static int discreteLogarithm ( int a , int b , int m ) { int n = ( int ) ( Math . Sqrt ( m ) + 1 ) ; int an = 1 ; for ( int i = 0 ; i < n ; ++ i ) an = ( an * a ) % m ; int [ ] value = new int [ m ] ; for ( int i = 1 , cur = an ; i <= n ; ++ i ) { if ( value [ cur ] == 0 ) value [ cur ] = i ; cur = ( cur * an ) % m ; } for ( int i = 0 , cur = b ; i <= n ; ++ i ) { if ( value [ cur ] > 0 ) { int ans = value [ cur ] * n - i ; if ( ans < m ) return ans ; } cur = ( cur * a ) % m ; } return - 1 ; } static void Main ( ) { int a = 2 , b = 3 , m = 5 ; Console . WriteLine ( discreteLogarithm ( a , b , m ) ) ; a = 3 ; b = 7 ; m = 11 ; Console . WriteLine ( discreteLogarithm ( a , b , m ) ) ; } }


"Discrete logarithm ( Find an integer k such that a ^ k is congruent modulo b ) | C # program to calculate discrete logarithm ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; x = x % p ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 ; y = y / 2 ; Function to calculate k for given a , b , m ; Store all values of a ^ ( n * i ) of LHS ; Calculate ( a ^ j ) * b and check for collision ; If collision occurs i . e . , LHS = RHS ; Check whether ans lies below m or not ; Driver code"
Solution in C#:

using System ; class GFG { static int powmod ( int x , int y , int p ) { while ( y > 0 ) { if ( ( y & 1 ) > 0 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return res ; } static int discreteLogarithm ( int a , int b , int m ) { int n = ( int ) ( Math . Sqrt ( m ) + 1 ) ; int [ ] value = new int [ m ] ; for ( int i = n ; i >= 1 ; -- i ) value [ powmod ( a , i * n , m ) ] = i ; for ( int j = 0 ; j < n ; ++ j ) { int cur = ( powmod ( a , j , m ) * b ) % m ; if ( value [ cur ] > 0 ) { int ans = value [ cur ] * n - j ; if ( ans < m ) return ans ; } } return - 1 ; } static void Main ( ) { int a = 2 , b = 3 , m = 5 ; Console . WriteLine ( discreteLogarithm ( a , b , m ) ) ; a = 3 ; b = 7 ; m = 11 ; Console . WriteLine ( discreteLogarithm ( a , b , m ) ) ; } }


"Disjoint Set Union on trees | Set 1 | C # code to find maximum subtree such that all nodes are even in weight ; Structure for Edge ; ' id ' : stores parent of a node . ' sz ' : stores size of a DSU tree . ; Function to assign root ; Function to find Union ; Utility function for Union ; Edge between ' u ' and ' v ' ; 0 - indexed nodes ; If weights of both ' u ' and ' v ' are even then we make union of them . ; Function to find maximum size of DSU tree ; Driver code ; Weights of nodes ; Number of nodes in a tree ; Initializing every node as a tree with single node . ; Find maximum size of DSU tree ."
Solution in C#:

 using System ; class GFG { static int N = 100010 ; public class Edge { public int u , v ; public Edge ( int u , int v ) { this . u = u ; this . v = v ; } } static int [ ] id = new int [ N ] ; static int [ ] sz = new int [ N ] ; static int Root ( int idx ) { int i = idx ; while ( i != id [ i ] ) { id [ i ] = id [ id [ i ] ] ; i = id [ i ] ; } return i ; } static void Union ( int a , int b ) { int i = Root ( a ) , j = Root ( b ) ; if ( i != j ) { if ( sz [ i ] >= sz [ j ] ) { id [ j ] = i ; sz [ i ] += sz [ j ] ; sz [ j ] = 0 ; } else { id [ i ] = j ; sz [ j ] += sz [ i ] ; sz [ i ] = 0 ; } } } static void UnionUtil ( Edge [ ] e , int [ ] W , int q ) { for ( int i = 0 ; i < q ; i ++ ) { int u , v ; u = e [ i ] . u ; v = e [ i ] . v ; u -- ; v -- ; if ( W [ u ] % 2 == 0 && W [ v ] % 2 == 0 ) Union ( u , v ) ; } } static int findMax ( int n , int [ ] W ) { int maxi = 0 ; for ( int i = 1 ; i < n ; i ++ ) if ( W [ i ] % 2 == 0 ) maxi = Math . Max ( maxi , sz [ i ] ) ; return maxi ; } public static void Main ( String [ ] args ) { int [ ] W = { 1 , 2 , 6 , 4 , 2 , 0 , 3 } ; int n = W . Length ; for ( int i = 0 ; i < n ; i ++ ) { id [ i ] = i ; sz [ i ] = 1 ; } Edge [ ] e = { new Edge ( 1 , 2 ) , new Edge ( 1 , 3 ) , new Edge ( 2 , 4 ) , new Edge ( 2 , 5 ) , new Edge ( 4 , 6 ) , new Edge ( 6 , 7 ) } ; int q = e . Length ; UnionUtil ( e , W , q ) ; int maxi = findMax ( n , W ) ; Console . Write ( " Maximum ▁ size ▁ of ▁ the ▁ subtree ▁ with ▁ " ) ; Console . WriteLine ( " even ▁ weighted ▁ nodes ▁ = ▁ { 0 }
 " , maxi ) ; } }


"Displacement from origin after N moves of given distances in specified directions | C # program for the above approach ; Function to find the displacement from the origin and direction after performing the given set of moves ; Stores the distances travelled in the directions North , South , East , and West respectively ; Store the initial position of robot ; Traverse the array B [ ] ; If the current direction is North ; If the current direction is South ; If the current direction is East ; If the current direction is West ; Stores the total vertical displacement ; Stores the total horizontal displacement ; Find the displacement ; Print the displacement and direction after N moves ; Driver Code"
Solution in C#:

using System ; class GFG { static void finalPosition ( char [ ] a , int [ ] b , int M ) { int n = 0 , s = 0 , e = 0 , w = 0 ; char p = ' N ' ; for ( int i = 0 ; i < M ; i ++ ) { if ( p == ' N ' ) { if ( a [ i ] == ' U ' ) { p = ' N ' ; n = n + b [ i ] ; } else if ( a [ i ] == ' D ' ) { p = ' S ' ; s = s + b [ i ] ; } else if ( a [ i ] == ' R ' ) { p = ' E ' ; e = e + b [ i ] ; } else if ( a [ i ] == ' L ' ) { p = ' W ' ; w = w + b [ i ] ; } } else if ( p == ' S ' ) { if ( a [ i ] == ' U ' ) { p = ' S ' ; s = s + b [ i ] ; } else if ( a [ i ] == ' D ' ) { p = ' N ' ; n = n + b [ i ] ; } else if ( a [ i ] == ' R ' ) { p = ' W ' ; w = w + b [ i ] ; } else if ( a [ i ] == ' L ' ) { p = ' E ' ; e = e + b [ i ] ; } } else if ( p == ' E ' ) { if ( a [ i ] == ' U ' ) { p = ' E ' ; e = e + b [ i ] ; } else if ( a [ i ] == ' D ' ) { p = ' W ' ; w = w + b [ i ] ; } else if ( a [ i ] == ' R ' ) { p = ' S ' ; s = s + b [ i ] ; } else if ( a [ i ] == ' L ' ) { p = ' N ' ; n = n + b [ i ] ; } } else if ( p == ' W ' ) { if ( a [ i ] == ' U ' ) { p = ' W ' ; w = w + b [ i ] ; } else if ( a [ i ] == ' D ' ) { p = ' E ' ; e = e + b [ i ] ; } else if ( a [ i ] == ' R ' ) { p = ' N ' ; n = n + b [ i ] ; } else if ( a [ i ] == ' L ' ) { p = ' S ' ; s = s + b [ i ] ; } } } int ver_disp = n - s ; int hor_disp = e - w ; int displacement = ( int ) Math . Ceiling ( Math . Sqrt ( ( ver_disp * ver_disp ) + ( hor_disp * hor_disp ) ) ) ; Console . WriteLine ( displacement + " ▁ " + p ) ; } public static void Main ( ) { char [ ] A = { ' U ' , ' R ' , ' R ' , ' R ' , ' R ' } ; int [ ] B = { 1 , 1 , 1 , 1 , 0 } ; int N = 1 ; finalPosition ( A , B , N ) ; } }


"Distance Traveled by Two Trains together in the same Direction | C # program to find the distance traveled together by the two trains ; Function to find the distance traveled together ; Stores distance travelled by A ; Stpres distance travelled by B ; Stores the total distance travelled together ; Sum of distance travelled ; Condition for traveling together ; Driver Code"
Solution in C#:

using System ; class GFG { static int calc_distance ( int [ ] A , int [ ] B , int n ) { int distance_traveled_A = 0 ; int distance_traveled_B = 0 ; int answer = 0 ; for ( int i = 0 ; i < 5 ; i ++ ) { distance_traveled_A += A [ i ] ; distance_traveled_B += B [ i ] ; if ( ( distance_traveled_A == distance_traveled_B ) && ( A [ i ] == B [ i ] ) ) { answer += A [ i ] ; } } return answer ; } public static void Main ( string [ ] s ) { int [ ] A = { 1 , 2 , 3 , 2 , 4 } ; int [ ] B = { 2 , 1 , 3 , 1 , 4 } ; int N = A . Length ; Console . Write ( calc_distance ( A , B , N ) ) ; } }


"Distance between Incenter and Circumcenter of a triangle using Inradius and Circumradius | C # program for the above approach ; Function returns the required distance ; Driver code ; Length of Inradius ; Length of Circumradius"
Solution in C#:

using System ; class GFG { static double distance ( int r , int R ) { double d = Math . Sqrt ( Math . Pow ( R , 2 ) - ( 2 * r * R ) ) ; return d ; } public static void Main ( string [ ] args ) { int r = 2 ; int R = 5 ; Console . Write ( Math . Round ( distance ( r , R ) * 100.0 ) / 100.0 ) ; } }


"Distance between centers of two intersecting circles if the radii and common chord length is given | C # program to find the distance between centers of two intersecting circles if the radii and common chord length is given ; Driver code"
Solution in C#:

using System ; class GFG { static double distcenter ( int r1 , int r2 , int x ) { double z = ( Math . Sqrt ( ( r1 * r1 ) - ( x / 2 * x / 2 ) ) ) + ( Math . Sqrt ( ( r2 * r2 ) - ( x / 2 * x / 2 ) ) ) ; Console . WriteLine ( " distance ▁ between ▁ the " + " ▁ centers ▁ is ▁ " + ( int ) z ) ; return 0 ; } static public void Main ( ) { int r1 = 24 , r2 = 37 , x = 40 ; distcenter ( r1 , r2 , x ) ; } }


"Distance between end points of Hour and minute hand at given time | C # implementation to find the distance between the end points of the hour and minute hand ; Function to find the angle between Hour hand and minute hand ; Validate the input ; Calculate the angles moved by hour and minute hands with reference to 12 : 00 ; Find the difference between two angles ; Return the smaller angle of two possible angles ; Function to calculate cos value of angle c ; Converting degrees to radian ; Maps the sum along the series ; Holds the actual value of sin ( n ) ; Function to distance between the endpoints of the hour and minute hand ; Driver code ; Time ; Length of hour hand ; Length of minute hand ; Calling Function for finding angle between hour hand and minute hand ; Function for finding distance between end points of minute hand and hour hand"
Solution in C#:

using System ; class GFG { static int calcAngle ( double h , double m ) { if ( h < 0 m < 0 h > 12 m > 60 ) Console . Write ( " Wrong ▁ input " ) ; if ( h == 12 ) h = 0 ; if ( m == 60 ) m = 0 ; int hour_angle = ( int ) ( 0.5 * ( h * 60 + m ) ) ; int minute_angle = ( int ) ( 6 * m ) ; int angle = Math . Abs ( hour_angle - minute_angle ) ; angle = Math . Min ( 360 - angle , angle ) ; return angle ; } static float cal_cos ( float n ) { float accuracy = ( float ) 0.0001 , x1 , denominator , cosx , cosval ; n = ( float ) ( n * ( 3.142 / 180.0 ) ) ; x1 = 1 ; cosx = x1 ; cosval = ( float ) Math . Cos ( n ) ; int i = 1 ; do { denominator = 2 * i * ( 2 * i - 1 ) ; x1 = - x1 * n * n / denominator ; cosx = cosx + x1 ; i = i + 1 ; } while ( accuracy <= Math . Abs ( cosval - cosx ) ) ; return cosx ; } static float distanceEndpoints ( int a , int b , float c ) { float angle = cal_cos ( c ) ; return ( float ) Math . Sqrt ( ( a * a ) + ( b * b ) - 2 * a * b * angle ) ; } public static void Main ( ) { int hour = 3 ; int min = 30 ; int hourHand = 3 ; int minHand = 4 ; double angle = calcAngle ( hour , min ) ; float distance = distanceEndpoints ( minHand , hourHand , ( long ) angle ) ; Console . Write ( distance ) ; } }


"Distance between orthocenter and circumcenter of a right | C # program for the above approach ; Function to calculate Euclidean distance between the points p1 and p2 ; Stores x coordinates of both points ; Stores y coordinates of both points ; Return the Euclid distance using distance formula ; Function to find orthocenter of the right angled triangle ; Find the length of the three sides ; Orthocenter will be the vertex opposite to the largest side ; Function to find the circumcenter of right angle triangle ; Circumcenter will be located at center of hypotenuse ; If AB is the hypotenuse ; If BC is the hypotenuse ; If AC is the hypotenuse ; Function to find distance between orthocenter and circumcenter ; Find circumcenter ; Find orthocenter ; Find the distance between the orthocenter and circumcenter ; Print distance between orthocenter and circumcenter ; Driver Code ; Given coordinates A , B , and C ; Function Call"
Solution in C#:

 using System ; class GFG { public class pair { public double first , second ; public pair ( double first , double second ) { this . first = first ; this . second = second ; } } static double distance ( pair p1 , pair p2 ) { double x1 = p1 . first , x2 = p2 . first ; double y1 = p1 . second , y2 = p2 . second ; return Math . Sqrt ( Math . Pow ( x2 - x1 , 2 ) + Math . Pow ( y2 - y1 , 2 ) * 1.0 ) ; } static pair find_orthocenter ( pair A , pair B , pair C ) { double AB = distance ( A , B ) ; double BC = distance ( B , C ) ; double CA = distance ( C , A ) ; if ( AB > BC && AB > CA ) return C ; if ( BC > AB && BC > CA ) return A ; return B ; } static pair find_circumcenter ( pair A , pair B , pair C ) { double AB = distance ( A , B ) ; double BC = distance ( B , C ) ; double CA = distance ( C , A ) ; if ( AB > BC && AB > CA ) return new pair ( ( A . first + B . first ) / 2 , ( A . second + B . second ) / 2 ) ; if ( BC > AB && BC > CA ) return new pair ( ( B . first + C . first ) / 2 , ( B . second + C . second ) / 2 ) ; return new pair ( ( C . first + A . first ) / 2 , ( C . second + A . second ) / 2 ) ; } static void findDistance ( pair A , pair B , pair C ) { pair circumcenter = find_circumcenter ( A , B , C ) ; pair orthocenter = find_orthocenter ( A , B , C ) ; double distance_between = distance ( circumcenter , orthocenter ) ; Console . Write ( distance_between + "
 " ) ; } public static void Main ( String [ ] args ) { pair A , B , C ; A = new pair ( 0.0 , 0.0 ) ; B = new pair ( 6.0 , 0.0 ) ; C = new pair ( 0.0 , 8.0 ) ; findDistance ( A , B , C ) ; } }


"Distance between two nodes of binary tree with node values from 1 to N | C # program to find minimum distance between two nodes in binary tree ; Function to get minimum path distance ; count bit length of n1 and n2 ; find bit difference and maxBit ; calculate result by formula ; Driver code"
Solution in C#:

using System ; class GFG { static int minDistance ( int n1 , int n2 ) { int bitCount1 = ( int ) Math . Floor ( ( Math . Log ( n1 ) / Math . Log ( 2 ) ) ) + 1 ; int bitCount2 = ( int ) Math . Floor ( ( Math . Log ( n2 ) / Math . Log ( 2 ) ) ) + 1 ; int bitDiff = Math . Abs ( bitCount1 - bitCount2 ) ; int maxBitCount = Math . Max ( bitCount1 , bitCount2 ) ; if ( bitCount1 > bitCount2 ) { n2 = n2 * ( int ) Math . Pow ( 2 , bitDiff ) ; } else { n1 = n1 * ( int ) Math . Pow ( 2 , bitDiff ) ; } int xorValue = n1 ^ n2 ; int bitCountXorValue ; if ( xorValue == 0 ) bitCountXorValue = 1 ; else { bitCountXorValue = ( int ) Math . Floor ( ( Math . Log ( xorValue ) / Math . Log ( 2 ) ) ) + 1 ; } int disSimilarBitPosition = maxBitCount - bitCountXorValue ; int result = bitCount1 + bitCount2 - 2 * disSimilarBitPosition ; return result ; } public static void Main ( String [ ] args ) { int n1 = 12 , n2 = 5 ; Console . WriteLine ( minDistance ( n1 , n2 ) ) ; } }


"Distance between two parallel lines | C # program find the distance between two parallel lines ; Function to find the distance between parallel lines ; Driver Code"
Solution in C#:

using System ; class GFG { static double dist ( double m , double b1 , double b2 ) { double d = Math . Abs ( b2 - b1 ) / ( ( m * m ) - 1 ) ; return d ; } public static void Main ( ) { double m = 2 , b1 = 4 , b2 = 3 ; Console . Write ( dist ( m , b1 , b2 ) ) ; } }


"Distance of chord from center when distance between center and another equal length chord is given | C # program to find the distance of chord from center when distance between center and another equal length chord is given ; Driver code"
Solution in C#:

using System ; class GFG { static void lengequichord ( int z ) { Console . WriteLine ( " The ▁ distance ▁ between ▁ the ▁ " + " chord ▁ and ▁ the ▁ center ▁ is ▁ " + z ) ; } public static void Main ( ) { int z = 48 ; lengequichord ( z ) ; } }


"Distance of nearest cell having 1 in a binary matrix | C # program to find the distance of nearest cell having 1 in a binary matrix . ; Print the distance of nearest cell having 1 for each cell . ; Initialise the answer matrix with int . MaxValue . ; For each cell ; Traversing thewhole matrix to find the minimum distance . ; If cell contain 1 , check for minimum distance . ; Printing the answer . ; Driven Program"
Solution in C#:

using System ; class GFG { static int N = 3 ; static int M = 4 ; static void printDistance ( int [ , ] mat ) { int [ , ] ans = new int [ N , M ] ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < M ; j ++ ) ans [ i , j ] = int . MaxValue ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < M ; j ++ ) { for ( int k = 0 ; k < N ; k ++ ) for ( int l = 0 ; l < M ; l ++ ) { if ( mat [ k , l ] == 1 ) ans [ i , j ] = Math . Min ( ans [ i , j ] , Math . Abs ( i - k ) + Math . Abs ( j - l ) ) ; } } for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) Console . Write ( ans [ i , j ] + " ▁ " ) ; Console . WriteLine ( ) ; } } public static void Main ( ) { int [ , ] mat = { { 0 , 0 , 0 , 1 } , { 0 , 0 , 1 , 1 } , { 0 , 1 , 1 , 0 } } ; printDistance ( mat ) ; } }


"Distinct Prime Factors of an Array | C # implementation of the above approach ; Function to return an array of prime numbers upto n using Sieve of Eratosthenes ; Function to return distinct prime factors from the given array ; Creating an empty array to store distinct prime factors ; Iterating through all the prime numbers and check if any of the prime numbers is a factor of the given input array ; Driver code ; Finding prime numbers upto 10000 using Sieve of Eratosthenes"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static List < int > sieve ( int n ) { List < int > prime = new List < int > ( ) ; for ( int i = 0 ; i < n + 1 ; i ++ ) prime . Add ( 0 ) ; int p = 2 ; while ( p * p <= n ) { if ( prime [ p ] == 0 ) { for ( int i = 2 * p ; i < n + 1 ; i += p ) prime [ i ] = 1 ; } p += 1 ; } List < int > allPrimes = new List < int > ( ) ; for ( int i = 2 ; i < n ; i ++ ) { if ( prime [ i ] == 0 ) allPrimes . Add ( i ) ; } return allPrimes ; } static List < int > distPrime ( List < int > arr , List < int > allPrimes ) { List < int > list1 = new List < int > ( ) ; for ( int i = 0 ; i < allPrimes . Count ; i ++ ) { for ( int j = 0 ; j < arr . Count ; j ++ ) { if ( arr [ j ] % allPrimes [ i ] == 0 ) { list1 . Add ( allPrimes [ i ] ) ; break ; } } } return list1 ; } public static void Main ( string [ ] args ) { List < int > allPrimes = new List < int > ( sieve ( 10000 ) ) ; List < int > arr = new List < int > ( ) ; arr . Add ( 15 ) ; arr . Add ( 30 ) ; arr . Add ( 60 ) ; List < int > ans = new List < int > ( distPrime ( arr , allPrimes ) ) ; Console . Write ( " [ " ) ; for ( int i = 0 ; i < ans . Count ; i ++ ) Console . Write ( ans [ i ] + " ▁ " ) ; Console . Write ( " ] " ) ; } }


"Distinct palindromic sub | C # implementation of the approach ; Function to return the count of distinct palindromic sub - strings of the given string s ; To store the positions of palindromic sub - strings ; Map to store the sub - strings ; Sub - strings of length 1 are palindromes ; Store continuous palindromic sub - strings ; Store palindromes of size 2 ; If str [ i ... ( i + 1 ) ] is not a palindromic then set dp [ i , i + 1 ] = 0 ; Find palindromic sub - strings of length >= 3 ; End of palindromic substring ; If s [ start ] = = s [ end ] and dp [ start + 1 , end - 1 ] is already palindrome then s [ start ... . end ] is also a palindrome ; Set dp [ start , end ] = 1 ; Not a palindrome ; Return the count of distinct palindromes ; Driver Code"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static int palindromeSubStrs ( String s ) { int [ , ] dp = new int [ s . Length , s . Length ] ; int st , end , i , len ; Dictionary < String , Boolean > m = new Dictionary < String , Boolean > ( ) ; for ( i = 0 ; i < s . Length ; i ++ ) { dp [ i , i ] = 1 ; if ( ! m . ContainsKey ( s . Substring ( i , 1 ) ) ) m . Add ( s . Substring ( i , 1 ) , true ) ; } for ( i = 0 ; i < s . Length - 1 ; i ++ ) { if ( s [ i ] == s [ i + 1 ] ) { dp [ i , i + 1 ] = 1 ; if ( ! m . ContainsKey ( s . Substring ( i , 2 ) ) ) m . Add ( s . Substring ( i , 2 ) , true ) ; } else dp [ i , i + 1 ] = 0 ; } for ( len = 3 ; len <= s . Length ; len ++ ) { for ( st = 0 ; st <= s . Length - len ; st ++ ) { end = st + len - 1 ; if ( s [ st ] == s [ end ] && dp [ st + 1 , end - 1 ] == 1 ) { dp [ st , end ] = 1 ; m . Add ( s . Substring ( st , end + 1 - st ) , true ) ; } else dp [ st , end ] = 0 ; } } return m . Count ; } public static void Main ( String [ ] args ) { String s = " abaaa " ; Console . WriteLine ( palindromeSubStrs ( s ) ) ; } }


"Distinct permutations of the string | Set 2 | C # program to distinct permutations of the string ; Returns true if str [ curr ] does not matches with any of the characters after str [ start ] ; Prints all distinct permutations in str [ 0. . n - 1 ] ; Proceed further for str [ i ] only if it doesn 't match with any of  the characters after str[index] ; Driver code"
Solution in C#:

using System ; class GFG { static bool shouldSwap ( char [ ] str , int start , int curr ) { for ( int i = start ; i < curr ; i ++ ) { if ( str [ i ] == str [ curr ] ) { return false ; } } return true ; } static void findPermutations ( char [ ] str , int index , int n ) { if ( index >= n ) { Console . WriteLine ( str ) ; return ; } for ( int i = index ; i < n ; i ++ ) { bool check = shouldSwap ( str , index , i ) ; if ( check ) { swap ( str , index , i ) ; findPermutations ( str , index + 1 , n ) ; swap ( str , index , i ) ; } } } static void swap ( char [ ] str , int i , int j ) { char c = str [ i ] ; str [ i ] = str [ j ] ; str [ j ] = c ; } public static void Main ( ) { char [ ] str = { ' A ' , ' B ' , ' C ' , ' A ' } ; int n = str . Length ; findPermutations ( str , 0 , n ) ; } }


"Distinct state codes that appear in a string as contiguous sub | C # implementation of the above approach . ; Function to return the count of distinct state codes ; Insert every sub - String of length 2 in the set ; Return the size of the set ; Driver code"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static int countDistinctCode ( String str ) { HashSet < String > codes = new HashSet < String > ( ) ; for ( int i = 0 ; i < str . Length - 1 ; i ++ ) codes . Add ( str . Substring ( i , 2 ) ) ; return codes . Count ; } public static void Main ( String [ ] args ) { String str = " UPUP " ; Console . Write ( countDistinctCode ( str ) ) ; } }


"Distinct strings such that they contains given strings as sub | C # implementation of the approach ; Set to store strings and avoid duplicates ; Recursive function to generate the required strings ; If current string is part of the result ; Insert it into the set ; If character from str1 can be chosen ; If character from str2 can be chosen ; Function to print the generated strings from the set ; Driver code"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static HashSet < String > stringSet = new HashSet < String > ( ) ; public static void find_permutation ( String str1 , String str2 , int len1 , int len2 , int i , int j , String res ) { if ( res . Length == len1 + len2 ) { stringSet . Add ( res ) ; return ; } if ( i < len1 ) find_permutation ( str1 , str2 , len1 , len2 , i + 1 , j , res + str1 [ i ] ) ; if ( j < len2 ) find_permutation ( str1 , str2 , len1 , len2 , i , j + 1 , res + str2 [ j ] ) ; } public static void print_set ( ) { foreach ( String s in stringSet ) Console . WriteLine ( s ) ; } public static void Main ( String [ ] args ) { String str1 = " aa " , str2 = " ab " ; int len1 = str1 . Length ; int len2 = str2 . Length ; find_permutation ( str1 , str2 , len1 , len2 , 0 , 0 , " " ) ; print_set ( ) ; } }


"Distribute M objects starting from Sth person such that every ith person gets arr [ i ] objects | C # program for the above approach ; Function to find distribution of M objects among all array elements ; Stores the distribution of M objects ; Stores the indices of distribution ; Stores the remaining objects ; Iterate until rem is positive ; If the number of remaining objects exceeds required the number of objects ; Increase the number of objects for the index ptr by arr [ ptr ] ; Decrease remaining objects by arr [ ptr ] ; Increase the number of objects for the index ptr by rem ; Decrease remaining objects to 0 ; Increase ptr by 1 ; Print the final distribution ; Driver Code"
Solution in C#:

using System ; class GFG { static void distribute ( int N , int K , int M , int [ ] arr ) { int [ ] distribution = new int [ N ] ; int ptr = K - 1 ; int rem = M ; while ( rem > 0 ) { if ( rem >= arr [ ptr ] ) { distribution [ ptr ] += arr [ ptr ] ; rem -= arr [ ptr ] ; } else { distribution [ ptr ] += rem ; rem = 0 ; } ptr = ( ptr + 1 ) % N ; } for ( int i = 0 ; i < N ; i ++ ) { Console . Write ( distribution [ i ] + " ▁ " ) ; } } public static void Main ( string [ ] args ) { int [ ] arr = { 2 , 3 , 2 , 1 , 4 } ; int M = 11 , S = 2 ; int N = arr . Length ; distribute ( N , S , M , arr ) ; } }


"Distribute N candies among K people | C # code for better approach to distribute candies ; Function to find out the number of candies every person received ; Count number of complete turns ; Get the last term ; Stores the number of candies ; Last term of last and current series ; Sum of current and last series ; Sum of current series only ; If sum of current is less than N ; else Individually distribute ; First term ; Distribute candies till there ; Candies available ; Not available ; Count the total candies ; Print the total candies ; Driver Code"
Solution in C#:

using System ; class GFG { static void candies ( int n , int k ) { int count = 0 ; int ind = 1 ; int [ ] arr = new int [ k ] ; for ( int i = 0 ; i < k ; i ++ ) arr [ i ] = 0 ; while ( n > 0 ) { int f1 = ( ind - 1 ) * k ; int f2 = ind * k ; int sum1 = ( f1 * ( f1 + 1 ) ) / 2 ; int sum2 = ( f2 * ( f2 + 1 ) ) / 2 ; int res = sum2 - sum1 ; if ( res <= n ) { count ++ ; n -= res ; ind ++ ; } { int i = 0 ; int term = ( ( ind - 1 ) * k ) + 1 ; while ( n > 0 ) { if ( term <= n ) { arr [ i ++ ] = term ; n -= term ; term ++ ; } else { arr [ i ++ ] = n ; n = 0 ; } } } } for ( int i = 0 ; i < k ; i ++ ) arr [ i ] += ( count * ( i + 1 ) ) + ( k * ( count * ( count - 1 ) ) / 2 ) ; for ( int i = 0 ; i < k ; i ++ ) Console . Write ( arr [ i ] + " ▁ " ) ; } public static void Main ( ) { int n = 10 , k = 3 ; candies ( n , k ) ; } }


"Distribute N candies among K people | C # implementation of the above approach ; Function to find out the number of candies every person received ; Count number of complete turns ; Get the last term ; Stores the number of candies ; Do a binary search to find the number whose sum is less than N . ; Get mide ; If sum is below N ; Find number of complete turns ; Right halve ; Left halve ; Last term of last complete series ; Subtract the sum till ; First term of incomplete series ; Count the total candies ; Print the total candies ; Driver Code"
Solution in C#:

using System ; class GFG { static void candies ( int n , int k ) { int count = 0 ; int ind = 1 ; int [ ] arr = new int [ k ] ; for ( int i = 0 ; i < k ; i ++ ) arr [ i ] = 0 ; int low = 0 , high = n ; while ( low <= high ) { int mid = ( low + high ) >> 1 ; int sum = ( mid * ( mid + 1 ) ) >> 1 ; if ( sum <= n ) { count = mid / k ; low = mid + 1 ; } else { high = mid - 1 ; } } int last = ( count * k ) ; n -= ( last * ( last + 1 ) ) / 2 ; int j = 0 ; int term = ( count * k ) + 1 ; while ( n > 0 ) { if ( term <= n ) { arr [ j ++ ] = term ; n -= term ; term ++ ; } else { arr [ j ] += n ; n = 0 ; } } for ( int i = 0 ; i < k ; i ++ ) arr [ i ] += ( count * ( i + 1 ) ) + ( k * ( count * ( count - 1 ) ) / 2 ) ; for ( int i = 0 ; i < k ; i ++ ) Console . Write ( arr [ i ] + " ▁ " ) ; } public static void Main ( ) { int n = 7 , k = 4 ; candies ( n , k ) ; } }


"Distribute R , B beans such that each packet has at least 1 R and 1 B bean with absolute difference at most D | C # program for the above approach ; Function to check if it is possible to distribute R red and B blue beans in packets such that the difference between the beans in each packet is atmost D ; Check for the condition to distributing beans ; Print the answer ; Distribution is not possible ; Driver code"
Solution in C#:

using System ; class GFG { static void checkDistribution ( int R , int B , int D ) { if ( Math . Max ( R , B ) <= Math . Min ( R , B ) * ( D + 1 ) ) { Console . WriteLine ( " Yes " ) ; } else { Console . WriteLine ( " No " ) ; } } static public void Main ( ) { int R = 1 , B = 1 , D = 0 ; checkDistribution ( R , B , D ) ; } }


"Distribute the white and black objects into maximum groups under certain constraints | C # program for the above approach ; Function to check if it is possible to distribute W and B into maximum groups possible ; If W is greater than B , swap them ; Distribution is not possible ; Distribution is possible ; Driver code ; Input ; Function call"
Solution in C#:

using System ; class GFG { static void isPossible ( int W , int B , int D ) { if ( W > B ) { int temp = W ; W = B ; B = temp ; } if ( B > W * ( D + 1 ) ) Console . WriteLine ( " NO " ) ; else Console . WriteLine ( " YES " ) ; } public static void Main ( ) { int W = 2 ; int B = 5 ; int D = 2 ; isPossible ( W , B , D ) ; } }


"Distributed C candies among N boys such that difference between maximum and minimum candies received is K | C # program for the above approach ; Function to calculate the maximum and minimum number of candies a boy can possess ; All candies will be given to one boy ; All the candies will be given to 1 boy ; Give K candies to 1 st boy initially ; Count remaining candies ; If the last candy of remaining candies is given to the last boy , i . e Nth boy ; Increase minimum count ; Driver code"
Solution in C#:

using System ; class GFG { static void max_min ( int N , int C , int K ) { int maximum , minimum ; if ( N == 1 ) { maximum = minimum = C ; } else if ( K >= C ) { maximum = C ; minimum = 0 ; } else { maximum = K ; minimum = 0 ; int remain_candy = C - K ; maximum += remain_candy / N ; minimum = remain_candy / N ; if ( remain_candy % N == N - 1 ) { minimum ++ ; } } Console . WriteLine ( " Maximum ▁ = ▁ " + maximum ) ; Console . WriteLine ( " Minimum ▁ = ▁ " + minimum ) ; } static void Main ( ) { int N = 4 ; int C = 12 ; int K = 3 ; max_min ( N , C , K ) ; } }


"Distributing M items in a circle of size N starting from K | C # program to find the position where last item is delivered . ; n == > Size of circle m == > Number of items k == > Initial position ; n - k + 1 is number of positions before we reach beginning of circle If m is less than this value , then we can simply return ( m - 1 ) th position ; Let us compute remaining items before we reach beginning . ; We compute m % n to skip all complete rounds . If we reach end , we return n else we return m % n ; Driver Program to test above function"
Solution in C#:

using System ; class GFG { static int lastPosition ( int n , int m , int k ) { if ( m <= n - k + 1 ) return m + k - 1 ; m = m - ( n - k + 1 ) ; return ( m % n == 0 ) ? n : ( m % n ) ; } public static void Main ( ) { int n = 5 ; int m = 8 ; int k = 2 ; Console . WriteLine ( lastPosition ( n , m , k ) ) ; } }


"Distributing all balls without repetition | C # program to find if its possible to distribute balls without repitiion ; function to find if its possible to distribute balls or not ; count array to count how many times each color has occurred ; increasing count of each color every time it appears ; to check if any color appears more than K times if it does we will print NO ; Driver code"
Solution in C#:

using System ; public class GFG { static int MAX_CHAR = 26 ; static bool distributingBalls ( long k , long n , string str ) { int [ ] a = new int [ MAX_CHAR ] ; for ( int i = 0 ; i < n ; i ++ ) { a [ str [ i ] - ' a ' ] ++ ; } for ( int i = 0 ; i < MAX_CHAR ; i ++ ) if ( a [ i ] > k ) return false ; return true ; } static public void Main ( ) { long n = 6 , k = 3 ; string str = " aacaab " ; if ( distributingBalls ( k , n , str ) ) Console . WriteLine ( " YES " ) ; else Console . WriteLine ( " NO " ) ; } }


"Distribution of a Number in Array within a Range | C # implementation of the approach ; Function for the distribution of the number ; Distribute the number among k elements ; If there is some remaining sum to distribute ; If there are elements remaining to distribute i . e . ( n - k ) ; Divide the remaining sum into n - k elements ; Print the distribution ; Driver code"
Solution in C#:

using System ; class GFG { static void distribution ( int n , int k , int l , int r , int S , int Sk ) { int [ ] a = new int [ n ] ; int len = k , temp , rem ; int diff = S - Sk ; for ( int i = 0 ; i < len ; i ++ ) { temp = Sk / k ; rem = Sk % k ; if ( temp + rem >= l && temp + rem <= r ) { a [ i ] = temp ; } else if ( temp + rem > r ) { a [ i ] = r ; } else if ( temp + rem < r ) { Console . Write ( " - 1" ) ; return ; } Sk = Sk - a [ i ] ; k = k - 1 ; } if ( Sk > 0 ) { Console . Write ( " - 1" ) ; return ; } if ( len != 0 ) { k = n - len ; for ( int i = len ; i < n ; i ++ ) { temp = diff / k ; rem = diff % k ; if ( temp + rem >= l && temp + rem <= r ) { a [ i ] = temp ; } else if ( temp + rem > r ) { a [ i ] = r ; } else if ( temp + rem < r ) { Console . Write ( " - 1" ) ; return ; } diff = diff - a [ i ] ; k = k - 1 ; } if ( diff != 0 ) { Console . Write ( " - 1" ) ; return ; } } for ( int i = 0 ; i < n ; i ++ ) { Console . Write ( a [ i ] + " ▁ " ) ; } } public static void Main ( String [ ] args ) { int n = 5 , k = 3 , l = 1 , r = 5 , S = 13 , Sk = 9 ; distribution ( n , k , l , r , S , Sk ) ; } }


"Distribution of candies according to ages of students | C # implementation of the approach ; Function to check The validity of distribution ; Stroring the max age of all students + 1 ; Stroring the max candy + 1 ; Creating the frequency array of the age of students ; Creating the frequency array of the packets of candies ; Pointer to tell whether we have reached the end of candy frequency array ; Flag to tell if distribution is possible or not ; Flag to tell if we can choose some candy packets for the students with age j ; If the quantity of packets is greater than or equal to the number of students of age j , then we can choose these packets for the students ; Start searching from k + 1 in next operation ; If we cannot choose any packets then the answer is NO ; Driver code"
Solution in C#:

using System . IO ; using System ; class GFG { static void check_distribution ( int n , int k , int [ ] age , int [ ] candy ) { int mxage = age [ 0 ] ; for ( int i = 0 ; i < age . Length ; i ++ ) { if ( mxage < age [ i ] ) { mxage = age [ i ] ; } } int mxcandy = candy [ 0 ] ; for ( int i = 0 ; i < candy . Length ; i ++ ) { if ( mxcandy < candy [ i ] ) { mxcandy = candy [ i ] ; } } int [ ] fr1 = new int [ mxage + 1 ] ; Array . Fill ( fr1 , 0 ) ; int [ ] fr2 = new int [ mxcandy + 1 ] ; Array . Fill ( fr2 , 0 ) ; for ( int j = 0 ; j < n ; j ++ ) { fr1 [ age [ j ] ] += 1 ; } for ( int j = 0 ; j < k ; j ++ ) { fr2 [ candy [ j ] ] += 1 ; } k = 0 ; bool Tf = true ; for ( int j = 0 ; j < mxage ; j ++ ) { if ( fr1 [ j ] == 0 ) { continue ; } bool flag = false ; while ( k < mxcandy ) { if ( fr1 [ j ] <= fr2 [ k ] ) { flag = true ; break ; } k += 1 ; } k = k + 1 ; if ( flag == false ) { Tf = false ; break ; } } if ( Tf ) { Console . WriteLine ( " Yes " ) ; } else { Console . WriteLine ( " No " ) ; } } static void Main ( ) { int [ ] age = { 5 , 15 , 10 } ; int [ ] candy = { 2 , 2 , 2 , 3 , 3 , 4 } ; int n = age . Length ; int k = candy . Length ; check_distribution ( n , k , age , candy ) ; } }