"Queries to count array elements from a given range having a single set bit | C # implementation for above approach ; Check if N has only one set bit ; Function to build segment tree ; If se is leaf node ; Update the node ; Stores mid value of segment [ ss , se ] ; Recursive call for left Subtree ; Recursive call for right Subtree ; Update the Current Node ; Function to update a value at Xth index ; If ss is equal to X ; Update the Xth node ; Update the tree ; Stores the mid of segment [ ss , se ] ; Update current node ; Count of numbers having one set bit ; If L > se or R < ss Invalid Range ; If [ ss , se ] lies inside the [ L , R ] ; Stores the mid of segment [ ss , se ] ; Return the sum after recursively traversing left and right subtree ; Function to solve queries ; Initialise Segment tree ; Build segment tree ; Perform queries ; Driver code ; Input ; Function call to solve queries"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static int check ( int N ) { if ( N == 0 || ( N & ( N - 1 ) ) != 0 ) return 0 ; return 1 ; } static void build_seg_tree ( int ss , int se , int si , int [ ] tree , int [ ] arr ) { if ( ss == se ) { tree [ si ] = check ( arr [ ss ] ) ; return ; } int mid = ( ss + se ) / 2 ; build_seg_tree ( ss , mid , 2 * si + 1 , tree , arr ) ; build_seg_tree ( mid + 1 , se , 2 * si + 2 , tree , arr ) ; tree [ si ] = tree [ 2 * si + 1 ] + tree [ 2 * si + 2 ] ; } static void update ( int ss , int se , int si , int X , int V , int [ ] tree , int [ ] arr ) { if ( ss == se ) { if ( ss == X ) { arr [ X ] = V ; tree [ si ] = check ( V ) ; } return ; } int mid = ( ss + se ) / 2 ; if ( X <= mid ) update ( ss , mid , 2 * si + 1 , X , V , tree , arr ) ; else update ( mid + 1 , se , 2 * si + 2 , X , V , tree , arr ) ; tree [ si ] = tree [ 2 * si + 1 ] + tree [ 2 * si + 2 ] ; } static int query ( int l , int r , int ss , int se , int si , int [ ] tree ) { if ( r < ss l > se ) return 0 ; if ( l <= ss && r >= se ) return tree [ si ] ; int mid = ( ss + se ) / 2 ; return query ( l , r , ss , mid , 2 * si + 1 , tree ) + query ( l , r , mid + 1 , se , 2 * si + 2 , tree ) ; } static void Query ( int [ ] arr , int N , List < List < int > > Q ) { int [ ] tree = new int [ 4 * N ] ; build_seg_tree ( 0 , N - 1 , 0 , tree , arr ) ; for ( int i = 0 ; i < ( int ) Q . Count ; i ++ ) { if ( Q [ i ] [ 0 ] == 1 ) Console . Write ( query ( Q [ i ] [ 1 ] , Q [ i ] [ 2 ] , 0 , N - 1 , 0 , tree ) + " ▁ " ) ; else update ( 0 , N - 1 , 0 , Q [ i ] [ 1 ] , Q [ i ] [ 2 ] , tree , arr ) ; } } static void Main ( ) { int [ ] arr = { 12 , 11 , 16 , 2 , 32 } ; List < List < int > > Q = new List < List < int > > ( ) ; Q . Add ( new List < int > ( new int [ ] { 1 , 0 , 2 } ) ) ; Q . Add ( new List < int > ( new int [ ] { 2 , 4 , 24 } ) ) ; Q . Add ( new List < int > ( new int [ ] { 1 , 1 , 4 } ) ) ; int N = arr . Length ; Query ( arr , N , Q ) ; } }


"Queries to count array elements from a given range having a single set bit | C # program for the above approach ; Function to check whether only one bit is set or not ; Function to perform Range - query ; Function to count array elements with a single set bit for each range in a query ; Initialize array for Prefix sum ; Driver code ; Given array ; Size of the array ; Given queries ; Size of queries array"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static int check ( int x ) { if ( ( ( x ) & ( x - 1 ) ) == 0 ) return 1 ; return 0 ; } static int query ( int l , int r , int [ ] pre ) { if ( l == 0 ) return pre [ r ] ; else return pre [ r ] - pre [ l - 1 ] ; } static void countInRange ( int [ ] arr , int N , List < Tuple < int , int > > queries , int Q ) { int [ ] pre = new int [ N ] ; pre [ 0 ] = check ( arr [ 0 ] ) ; for ( int i = 1 ; i < N ; i ++ ) { pre [ i ] = pre [ i - 1 ] + check ( arr [ i ] ) ; } int c = 0 ; int q = 0 ; while ( q < Q ) { int l = queries [ q ] . Item1 ; int r = queries [ q ] . Item2 ; c ++ ; q ++ ; Console . Write ( query ( l , r , pre ) + " ▁ " ) ; } } static void Main ( ) { int [ ] arr = { 12 , 11 , 16 , 8 , 2 , 5 , 1 , 3 , 256 , 1 } ; int N = arr . Length ; List < Tuple < int , int > > queries = new List < Tuple < int , int > > ( ) ; queries . Add ( new Tuple < int , int > ( 0 , 9 ) ) ; queries . Add ( new Tuple < int , int > ( 4 , 9 ) ) ; int Q = queries . Count ; countInRange ( arr , N , queries , Q ) ; } }


"Queries to count characters having odd frequency in a range [ L , R ] | C # program to implement the above problem ; Function to print the number of characters having odd frequencies for each query ; A function to construct the [ ] arr and prefix [ ] ; Stores array length ; Stores the unique powers of 2 associated to each character ; Prefix array to store the XOR values from array elements ;  ; Driver Code"
Solution in C#:

 using System ; class GFG { class pair { public int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static void queryResult ( int [ ] prefix , pair Q ) { int l = Q . first ; int r = Q . second ; if ( l == 0 ) { int xorval = prefix [ r ] ; Console . Write ( countSetBits ( xorval ) + "
 " ) ; } else { int xorval = prefix [ r ] ^ prefix [ l - 1 ] ; Console . Write ( countSetBits ( xorval ) + "
 " ) ; } } static void calculateCount ( String S , pair [ ] Q , int m ) { int n = S . Length ; int [ ] arr = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { arr [ i ] = ( 1 << ( S [ i ] - ' a ' ) ) ; } int [ ] prefix = new int [ n ] ; int x = 0 ; for ( int i = 0 ; i < n ; i ++ ) { x ^= arr [ i ] ; prefix [ i ] = x ; } for ( int i = 0 ; i < m ; i ++ ) { queryResult ( prefix , Q [ i ] ) ; } } static int countSetBits ( long x ) { int setBits = 0 ; while ( x != 0 ) { x = x & ( x - 1 ) ; setBits ++ ; } return setBits ; } public static void Main ( String [ ] args ) { String S = " geeksforgeeks " ; pair [ ] Q = { new pair ( 2 , 4 ) , new pair ( 0 , 3 ) , new pair ( 0 , 12 ) } ; calculateCount ( S , Q , 3 ) ; } }


"Queries to count distinct Binary Strings of all lengths from N to M satisfying given properties | C # program to implement the above approach ; Function to calculate the count of possible Strings ; Initialize dp [ 0 ] ; dp [ i ] represents count of Strings of length i ; Add dp [ i - k ] if i >= k ; Update Prefix Sum Array ; Driver Code"
Solution in C#:

 using System ; class GFG { static int N = ( int ) ( 1e5 + 5 ) ; static int MOD = 1000000007 ; static int [ ] dp = new int [ N ] ; static void countStrings ( int K , int [ , ] Q ) { dp [ 0 ] = 1 ; for ( int i = 1 ; i < N ; i ++ ) { dp [ i ] = dp [ i - 1 ] ; if ( i >= K ) dp [ i ] = ( dp [ i ] + dp [ i - K ] ) % MOD ; } for ( int i = 1 ; i < N ; i ++ ) { dp [ i ] = ( dp [ i ] + dp [ i - 1 ] ) % MOD ; } for ( int i = 0 ; i < Q . GetLength ( 0 ) ; i ++ ) { int ans = dp [ Q [ i , 1 ] ] - dp [ Q [ i , 0 ] - 1 ] ; if ( ans < 0 ) ans = ans + MOD ; Console . Write ( ans + "
 " ) ; } } public static void Main ( String [ ] args ) { int K = 3 ; int [ , ] Q = { { 1 , 4 } , { 3 , 7 } } ; countStrings ( K , Q ) ; } }


"Queries to count frequencies of a given character in a given range of indices | C # program for the above approach ; Function to print count of char y present in the range [ l , r ] ; Length of the string ; Stores the precomputed results ; Iterate the given string ; Increment dp [ i , y - ' a ' ] by 1 ; Pre - compute ; Number of queries ; Traverse each query ; Print the result for each query ; Driver Code ; Given string ; Given Queries ; Function Call"
Solution in C#:

using System ; public class GFG { static void noOfChars ( String s , char [ , ] queries ) { int n = s . Length ; int [ , ] dp = new int [ n + 1 , 26 ] ; for ( int i = 0 ; i < n ; i ++ ) { dp [ i + 1 , s [ i ] - ' a ' ] ++ ; for ( int j = 0 ; j < 26 ; j ++ ) { dp [ i + 1 , j ] += dp [ i , j ] ; } } int q = queries . GetLength ( 0 ) ; for ( int i = 0 ; i < q ; i ++ ) { int l = ( int ) queries [ i , 0 ] ; int r = ( int ) queries [ i , 1 ] ; int c = queries [ i , 2 ] - ' a ' ; Console . Write ( dp [ r , c ] - dp [ l - 1 , c ] + " ▁ " ) ; } } public static void Main ( String [ ] args ) { String S = " aabv " ; char [ , ] queries = new char [ , ] { { ( char ) 1 , ( char ) 2 , ' a ' } , { ( char ) 2 , ( char ) 3 , ' b ' } } ; noOfChars ( S , queries ) ; } }


"Queries to count minimum flips required to fill a binary submatrix with 0 s only | C # program for the above approach ; Function to compute the matrix prefixCnt [ M ] [ N ] from mat [ M ] [ N ] such that prefixCnt [ i ] [ j ] stores the count of 0 's from (0, 0) to (i, j) ; Initialize prefixCnt [ i ] [ j ] with 1 if mat [ i , j ] is 0 ; Otherwise , assign with 0 ; Calculate prefix sum for each row ; Calculate prefix sum for each column ; Function to compute count of 0 's in submatrix from (pi, pj) to (qi, qj) from prefixCnt[M][N] ; Initialize that count of 0 's  in the sub-matrix within  indices (0, 0) to (qi, qj) ; Subtract count of 0 's within  indices (0, 0) and (pi-1, qj) ; Subtract count of 0 's within  indices (0, 0) and (qi, pj-1) ; Add prefixCnt [ pi - 1 ] [ pj - 1 ] because its value has been added ; once but subtracted twice ; Function to count the 0 s in the each given submatrix ; Stores the prefix sum of each row and column ; Compute matrix prefixCnt [ , ] ; Function Call for each query ; Driver Code ; Given matrix ; Function Call"
Solution in C#:

using System ; class GFG { static int M = 6 ; static int N = 7 ; static void preCompute ( int [ , ] mat , int [ , ] prefixCnt ) { for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( mat [ i , j ] == 0 ) { prefixCnt [ i , j ] = 1 ; } else { prefixCnt [ i , j ] = 0 ; } } } for ( int i = 0 ; i < M ; i ++ ) for ( int j = 1 ; j < N ; j ++ ) prefixCnt [ i , j ] += prefixCnt [ i , j - 1 ] ; for ( int i = 1 ; i < M ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) prefixCnt [ i , j ] += prefixCnt [ i - 1 , j ] ; } static int countQuery ( int [ , ] prefixCnt , int pi , int pj , int qi , int qj ) { int cnt = prefixCnt [ qi , qj ] ; if ( pi > 0 ) cnt -= prefixCnt [ pi - 1 , qj ] ; if ( pj > 0 ) cnt -= prefixCnt [ qi , pj - 1 ] ; if ( pi > 0 && pj > 0 ) cnt += prefixCnt [ pi - 1 , pj - 1 ] ; return cnt ; } static void count0s ( int [ , ] mat , int [ , ] Q , int sizeQ ) { int [ , ] prefixCnt = new int [ M , N ] ; preCompute ( mat , prefixCnt ) ; for ( int i = 0 ; i < sizeQ ; i ++ ) { Console . Write ( countQuery ( prefixCnt , Q [ i , 0 ] , Q [ i , 1 ] , Q [ i , 2 ] , Q [ i , 3 ] ) + " ▁ " ) ; } } public static void Main ( string [ ] args ) { int [ , ] mat = { { 0 , 1 , 0 , 1 , 1 , 1 , 0 } , { 1 , 0 , 1 , 1 , 1 , 0 , 1 } , { 1 , 1 , 0 , 0 , 1 , 1 , 0 } , { 1 , 1 , 1 , 1 , 1 , 0 , 1 } , { 0 , 0 , 1 , 0 , 1 , 1 , 1 } , { 1 , 1 , 0 , 1 , 1 , 0 , 1 } } ; int [ , ] Q = { { 0 , 1 , 3 , 2 } , { 2 , 2 , 4 , 5 } , { 4 , 3 , 5 , 6 } } ; int sizeQ = Q . GetLength ( 0 ) ; count0s ( mat , Q , sizeQ ) ; } }


"Queries to count numbers from a given range which are divisible the sum of their digits | C # program for the above approach ; Function to check if the number x is divisible by its sum of digits ; Stores sum of digits of x ; Temporarily store x ; Calculate sum of digits of x ; If x is not divisible by sum ; Otherwise ; Function to perform the precomputation ; Iterate from i equals 1 to 1e5 ; Check if i is divisible by sum of its digits ; Convert [ ] arr to prefix sum array ; Driver Code ; Given queries ; Using inclusion - exclusion principle , calculate the result"
Solution in C#:

using System ; class GFG { static int [ ] arr = new int [ 100005 ] ; static bool isDivisible ( int x ) { int sum = 0 ; int temp = x ; while ( x != 0 ) { sum += x % 10 ; x /= 10 ; } if ( temp % sum != 0 ) return false ; else return true ; } static void precompute ( ) { for ( int i = 1 ; i <= 100000 ; i ++ ) { if ( isDivisible ( i ) ) arr [ i ] = 1 ; else arr [ i ] = 0 ; } for ( int i = 1 ; i <= 100000 ; i ++ ) { arr [ i ] = arr [ i ] + arr [ i - 1 ] ; } } public static int [ ] GetRow ( int [ , ] matrix , int row ) { var rowLength = matrix . GetLength ( 1 ) ; var rowVector = new int [ rowLength ] ; for ( var i = 0 ; i < rowLength ; i ++ ) rowVector [ i ] = matrix [ row , i ] ; return rowVector ; } public static void Main ( String [ ] args ) { int [ , ] Q = { { 5 , 9 } , { 5 , 20 } } ; int [ ] q ; precompute ( ) ; for ( int i = 0 ; i < Q . GetLength ( 0 ) ; i ++ ) { q = GetRow ( Q , i ) ; Console . WriteLine ( arr [ q [ 1 ] ] - arr [ q [ 0 ] - 1 ] ) ; } } }


"Queries to count numbers from a range which does not contain digit K in their decimal or octal representation | C # program for the above approach ; Function to check if the given digit ' K ' is present in the decimal and octal representations of num or not ; Stores if the digit exists or not ; Iterate till nums is non - zero ; Find the remainder ; If the remainder is K ; Function to count the numbers in the range [ 1 , N ] such that it doesn ' t ▁ ▁ contain ▁ the ▁ digit ▁ ' K ' in its decimal  and octal representation ; Stores count of numbers in the range [ 0 , i ] that contains the digit ' K ' in its octal or decimal representation ; Traverse the range [ 0 , 1e6 + 5 ] ; Check if i contains the digit ' K ' in its decimal or octal representation ; Update pref [ i ] ; Print the answer of queries ; Driver code ; Function Call"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static bool contains ( int num , int K , int Base ) { bool isThere = false ; while ( num > 0 ) { int remainder = num % Base ; if ( remainder == K ) { isThere = true ; } num /= Base ; } return isThere ; } static void count ( int n , int k , List < List < int > > v ) { int [ ] pref = new int [ 1000005 ] ; for ( int i = 1 ; i < 1e6 + 5 ; i ++ ) { bool present = contains ( i , k , 10 ) || contains ( i , k , 8 ) ; if ( present ) { pref [ i ] += pref [ i - 1 ] + 1 ; } } Console . Write ( ( v [ 0 ] [ 1 ] - v [ 0 ] [ 0 ] + 1 - ( pref [ v [ 0 ] [ 1 ] ] - pref [ v [ 0 ] [ 0 ] - 1 ] ) ) + " ▁ " ) ; Console . Write ( ( v [ 1 ] [ 1 ] - v [ 1 ] [ 0 ] - ( pref [ v [ 1 ] [ 1 ] ] - pref [ v [ 1 ] [ 0 ] - 1 ] ) ) + " ▁ " ) ; } static void Main ( ) { int K = 7 ; List < List < int > > Q = new List < List < int > > ( ) ; Q . Add ( new List < int > ( ) ) ; Q [ 0 ] . Add ( 2 ) ; Q [ 0 ] . Add ( 5 ) ; Q . Add ( new List < int > ( ) ) ; Q [ 1 ] . Add ( 1 ) ; Q [ 1 ] . Add ( 15 ) ; int N = Q . Count ; count ( N , K , Q ) ; } }


"Queries to count numbers from given range which are divisible by all its digits | C # program to implement the above approach ; Function to check if a number is divisible by all of its non - zero digits or not ; Stores the number ; Iterate over the digits of the numbers ; If digit of number is non - zero ; If number is not divisible by its current digit ; Update n ; Function to count of numbers which are divisible by all of its non - zero digits in the range [ 1 , i ] ; Stores count of numbers which are divisible by all of its non - zero digits in the range [ 1 , i ] ; Iterate over the range [ 1 , Max ] ; Update ; Traverse the array , arr [ ] ; Driver Code"
Solution in C#:

using System ; class GFG { public static int Max = 1000005 ; static bool CheckDivByAllDigits ( int number ) { int n = number ; while ( n > 0 ) { if ( n % 10 != 0 ) if ( number % ( n % 10 ) != 0 ) { return false ; } n /= 10 ; } return true ; } static void cntNumInRang ( int [ , ] arr , int N ) { int [ ] prefCntDiv = new int [ Max + 1 ] ; for ( int i = 1 ; i <= Max ; i ++ ) { int ans = 0 ; if ( CheckDivByAllDigits ( i ) ) ans = 1 ; prefCntDiv [ i ] = prefCntDiv [ i - 1 ] + ans ; } for ( int i = 0 ; i < N ; i ++ ) Console . Write ( ( prefCntDiv [ arr [ i , 1 ] ] - prefCntDiv [ arr [ i , 0 ] - 1 ] ) + " ▁ " ) ; } public static void Main ( string [ ] args ) { int [ , ] arr = { { 1 , 5 } , { 12 , 14 } } ; int N = arr . GetLength ( 0 ) ; cntNumInRang ( arr , N ) ; } }


"Queries to count points lying on or inside an isosceles Triangle with given length of equal sides | C # implementation of above approach ; Function to find answer of each query ; Stores the count of points with sum less than or equal to their indices ; Traverse the array ; If both x and y - coordinate < 0 ; Stores the sum of co - ordinates ; Increment count of sum by 1 ; Prefix array ; Perform queries ; Drivers Code"
Solution in C#:

using System ; public class GFG { static int MAX = ( int ) ( 1e6 + 5 ) ; static void query ( double [ , ] arr , int [ ] Q ) { int [ ] pre = new int [ MAX ] ; for ( int i = 0 ; i < arr . GetLength ( 0 ) ; i ++ ) { if ( arr [ i , 0 ] < 0 arr [ i , 1 ] < 0 ) continue ; int sum = ( int ) Math . Ceiling ( ( arr [ i , 0 ] + arr [ i , 1 ] ) ) ; pre [ sum ] ++ ; } for ( int i = 1 ; i < MAX ; i ++ ) pre [ i ] += pre [ i - 1 ] ; for ( int i = 0 ; i < Q . Length ; i ++ ) { Console . Write ( pre [ Q [ i ] ] + " ▁ " ) ; } Console . WriteLine ( ) ; } public static void Main ( String [ ] args ) { double [ , ] arr = { { 2.1 , 3.0 } , { 3.7 , 1.2 } , { 1.5 , 6.5 } , { 1.2 , 0.0 } } ; int [ ] Q = { 2 , 8 , 5 } ; int N = arr . GetLength ( 0 ) ; int M = Q . Length ; query ( arr , Q ) ; } }


"Queries to count sum of rows and columns of a Matrix present in given ranges |  ; Function to preprocess the matrix to execute the queries ; Stores the sum of each row ; Stores the sum of each col ; Traverse the matrix and calculate sum of each row and column ; Insert all row sums in sum_list ; Insert all column sums in sum_list ; Sort the array in ascending order ; Traverse the array queries [ ] [ ] ; Search the leftmost index of L ; Search the rightmost index of R ; Function to search for the leftmost index of given number ; Initialize low , high and ans ; Stores mid ; If A [ mid ] >= num ; Function to search for the rightmost index of given number ; Initialise low , high and ans ; Stores mid ; If A [ mid ] <= num ; Update ans ; Update mid ; Update high ; driver code ; Given dimensions of matrix ; Given matrix ; Given number of queries ; Given queries ; Function call to count the number row - sums and column - sums present in the given ranges"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static void totalCount ( int [ , ] A , int N , int M , int [ , ] queries , int Q ) { int [ ] row_sum = new int [ N ] ; int [ ] col_sum = new int [ M ] ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { row_sum [ i ] += A [ i , j ] ; col_sum [ j ] += A [ i , j ] ; } } List < int > sum_list = new List < int > ( ) ; for ( int i = 0 ; i < N ; i ++ ) sum_list . Add ( row_sum [ i ] ) ; for ( int i = 0 ; i < M ; i ++ ) sum_list . Add ( col_sum [ i ] ) ; sum_list . Sort ( ) ; for ( int i = 0 ; i < Q ; i ++ ) { int L = queries [ i , 0 ] ; int R = queries [ i , 1 ] ; int l = left_search ( sum_list , L ) ; int r = right_search ( sum_list , R ) ; Console . Write ( r - l + 1 + " ▁ " ) ; } } static int left_search ( List < int > A , int num ) { int low = 0 , high = A . Count - 1 ; int ans = 0 ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( A [ mid ] >= num ) { ans = mid ; high = mid - 1 ; } else { low = mid + 1 ; } } return ans ; } static int right_search ( List < int > A , int num ) { int low = 0 , high = A . Count - 1 ; int ans = high ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( A [ mid ] <= num ) { ans = mid ; low = mid + 1 ; } else { high = mid - 1 ; } } return ans ; } static void Main ( ) { int N = 3 , M = 2 ; int [ , ] A = new int [ , ] { { 13 , 3 } , { 9 , 4 } , { 6 , 10 } } ; int Q = 2 ; int [ , ] queries = new int [ , ] { { 10 , 20 } , { 25 , 35 } } ; totalCount ( A , N , M , queries , Q ) ; } }


"Queries to count the number of unordered co | C # program to find number of unordered coprime pairs of integers from 1 to N ; to store euler 's totient function ; to store required answer ; Computes and prints totient of all numbers smaller than or equal to N . ; Initialise the phi [ ] with 1 ; Compute other Phi values ; If phi [ p ] is not computed already , then number p is prime ; Phi of a prime number p is always equal to p - 1. ; Update phi values of all multiples of p ; Add contribution of p to its multiple i by multiplying with ( 1 - 1 / p ) ; function to compute number coprime pairs ; function call to compute euler totient function ; prefix sum of all euler totient function values ; Driver code ; function call"
Solution in C#:

 using System ; class GFG { static int N = 100005 ; static int [ ] phi ; static int [ ] S ; static void computeTotient ( ) { for ( int i = 1 ; i < N ; i ++ ) phi [ i ] = i ; for ( int p = 2 ; p < N ; p ++ ) { if ( phi [ p ] == p ) { phi [ p ] = p - 1 ; for ( int i = 2 * p ; i < N ; i += p ) { phi [ i ] = ( phi [ i ] / p ) * ( p - 1 ) ; } } } } static void CoPrimes ( ) { computeTotient ( ) ; for ( int i = 1 ; i < N ; i ++ ) S [ i ] = S [ i - 1 ] + phi [ i ] ; } public static void Main ( ) { phi = new int [ N ] ; S = new int [ N ] ; CoPrimes ( ) ; int [ ] q = { 3 , 4 } ; int n = q . Length ; for ( int i = 0 ; i < n ; i ++ ) Console . WriteLine ( " Number ▁ of ▁ unordered ▁ coprime
 " + " pairs ▁ of ▁ integers ▁ from ▁ 1 ▁ to ▁ " + q [ i ] + " ▁ are ▁ " + S [ q [ i ] ] ) ; } }


"Queries to find Kth greatest character in a range [ L , R ] from a string with updates | C # Program to implement the above approach ; Maximum Size of a String ; Fenwick Tree to store the frequencies of 26 alphabets ; Size of the String . ; Function to update Fenwick Tree for char c at index val ; Add val to current node Fenwick Tree ; Move index to parent node in update View ; Function to get sum of frequencies of character c till index ; Stores the sum ; Add current element of Fenwick tree to sum ; Move index to parent node in getSum View ; Function to create the Fenwick tree ; Function to print the kth largest character in the range of l to r ; Stores the count of characters ; Stores the required character ; Calculate frequency of C in the given range ; Increase count ; If count exceeds K ; Required character found ; Function to update character at pos by character s ; 0 based index system ; Driver Code ; Makes the String 1 - based indexed ; Number of queries ; Construct the Fenwick Tree"
Solution in C#:

 using System ; class GFG { static int maxn = 100005 ; static int [ , ] BITree = new int [ 26 , maxn ] ; static int N ; static void update_BITree ( int index , char C , int val ) { while ( index <= N ) { BITree [ C - ' a ' , index ] += val ; index += ( index & - index ) ; } } static int sum_BITree ( int index , char C ) { int s = 0 ; while ( index > 0 ) { s += BITree [ C - ' a ' , index ] ; index -= ( index & - index ) ; } return s ; } static void buildTree ( String str ) { for ( int i = 1 ; i <= N ; i ++ ) { update_BITree ( i , str [ i ] , 1 ) ; } Console . WriteLine ( ) ; } static char printchar ( String str , int l , int r , int k ) { int count = 0 ; char ans = ( char ) 0 ; for ( char C = ' z ' ; C >= ' a ' ; C -- ) { int times = sum_BITree ( r , C ) - sum_BITree ( l - 1 , C ) ; count += times ; if ( count >= k ) { ans = C ; break ; } } return ans ; } static void updateTree ( String str , int pos , char s ) { int index = pos ; update_BITree ( index , str [ index ] , - 1 ) ; str = str . Substring ( 0 , index ) + s + str . Substring ( index + 1 ) ; update_BITree ( index , s , 1 ) ; } public static void Main ( String [ ] args ) { String str = " abcddef " ; N = str . Length ; str = ' / ' + str ; int Q = 3 ; buildTree ( str ) ; Console . Write ( printchar ( str , 1 , 2 , 2 ) + "
 " ) ; updateTree ( str , 4 , ' g ' ) ; Console . Write ( printchar ( str , 1 , 5 , 4 ) + "
 " ) ; } }


"Queries to find Kth greatest character in a range [ L , R ] from a string with updates | C # program to implement the above approach ; Function to find the kth greatest character from the string ; Sorting the String in non - increasing Order ; Function to print the K - th character from the subString S [ l ] . . S [ r ] ; 0 - based indexing ; SubString of str from the indices l to r . ; Extract kth Largest character ; Function to replace character at pos of str by the character s ; Index of S to be updated . ; char to be replaced at index in S ; Driver Code ; Given String ; Queries"
Solution in C#:

 using System ; class GFG { static char find_kth_largest ( char [ ] str , int k ) { Array . Sort ( str ) ; reverse ( str ) ; return str [ k - 1 ] ; } static char [ ] reverse ( char [ ] a ) { int i , n = a . Length ; char t ; for ( i = 0 ; i < n / 2 ; i ++ ) { t = a [ i ] ; a [ i ] = a [ n - i - 1 ] ; a [ n - i - 1 ] = t ; } return a ; } static char printchar ( String str , int l , int r , int k ) { l = l - 1 ; r = r - 1 ; String temp = str . Substring ( l , r - l + 1 ) ; char ans = find_kth_largest ( temp . ToCharArray ( ) , k ) ; return ans ; } static void updateString ( char [ ] str , int pos , char s ) { int index = pos - 1 ; char c = s ; str [ index ] = c ; } public static void Main ( String [ ] args ) { String str = " abcddef " ; Console . Write ( printchar ( str , 1 , 2 , 2 ) + "
 " ) ; updateString ( str . ToCharArray ( ) , 4 , ' g ' ) ; Console . Write ( printchar ( str , 1 , 5 , 4 ) + "
 " ) ; } }


"Queries to find distance between two nodes of a Binary tree | C # program to find distance between two nodes for multiple queries ; A tree node structure ; Array to store level of each node ; Utility Function to store level of all nodes ; queue to hold tree node with level ; let root node be at level 0 ; Do level Order Traversal of tree ; Node p . first is on level p . second ; If left child exits , put it in queue with current_level + 1 ; If right child exists , put it in queue with current_level + 1 ; Stores Euler Tour ; index in Euler array ; Find Euler Tour ; store current node 's data ; If left node exists ; traverse left subtree ; store parent node 's data ; If right node exists ; traverse right subtree ; store parent node 's data ; checks for visited nodes ; Stores level of Euler Tour ; Stores indices of first occurrence of nodes in Euler tour ; Preprocessing Euler Tour for finding LCA ; If node is not visited before ; Add to first occurrence ; Mark it visited ; Stores values and positions ; Utility function to find minimum of pair type values ; Utility function to build segment tree ; Utility function to find LCA ; Function to return distance between two nodes n1 and n2 ; Maintain original Values ; Get First Occurrence of n1 ; Get First Occurrence of n2 ; Swap if low > high ; Get position of minimum value ; Extract value out of Euler tour ; return calculated distance ; Build Tree ; Store Levels ; Find L and H array ; Build segment Tree ; Driver Code ; Number of nodes ; Constructing tree given in the above figure ; Function to do all preprocessing"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static int MAX = 100001 ; public class Node { public int data ; public Node left , right ; public Node ( int data ) { this . data = data ; this . left = this . right = null ; } } class Pair < T , V > { public T first ; public V second ; public Pair ( ) { } public Pair ( T first , V second ) { this . first = first ; this . second = second ; } } static int [ ] level = new int [ MAX ] ; static void findLevels ( Node root ) { if ( root == null ) return ; List < Pair < Node , int > > q = new List < Pair < Node , int > > ( ) ; q . Add ( new Pair < Node , int > ( root , 0 ) ) ; Pair < Node , int > p = new Pair < Node , int > ( ) ; while ( q . Count != 0 ) { p = q [ 0 ] ; q . RemoveAt ( 0 ) ; level [ p . first . data ] = p . second ; if ( p . first . left != null ) q . Add ( new Pair < Node , int > ( p . first . left , p . second + 1 ) ) ; if ( p . first . right != null ) q . Add ( new Pair < Node , int > ( p . first . right , p . second + 1 ) ) ; } } static int [ ] Euler = new int [ MAX ] ; static int idx = 0 ; static void eulerTree ( Node root ) { Euler [ ++ idx ] = root . data ; if ( root . left != null ) { eulerTree ( root . left ) ; Euler [ ++ idx ] = root . data ; } if ( root . right != null ) { eulerTree ( root . right ) ; Euler [ ++ idx ] = root . data ; } } static int [ ] vis = new int [ MAX ] ; static int [ ] L = new int [ MAX ] ; static int [ ] H = new int [ MAX ] ; static void preprocessEuler ( int size ) { for ( int i = 1 ; i <= size ; i ++ ) { L [ i ] = level [ Euler [ i ] ] ; if ( vis [ Euler [ i ] ] == 0 ) { H [ Euler [ i ] ] = i ; vis [ Euler [ i ] ] = 1 ; } } } static Pair < int , int > [ ] seg = new Pair < int , int > [ 4 * MAX ] ; static Pair < int , int > min ( Pair < int , int > a , Pair < int , int > b ) { if ( a . first <= b . first ) return a ; return b ; } static Pair < int , int > buildSegTree ( int low , int high , int pos ) { if ( low == high ) { seg [ pos ] . first = L [ low ] ; seg [ pos ] . second = low ; return seg [...


"Queries to find frequencies of a string within specified substrings | C # program to find frequency of a string K in a substring [ L , R ] in S ; Store the frequency of string for each index ; Compute and store frequencies for every index ; Driver code"
Solution in C#:

using System . IO ; using System ; class GFG { static int max_len = 100005 ; static int [ ] cnt = new int [ max_len ] ; static void precompute ( string s , string K ) { int n = s . Length ; for ( int i = 0 ; i < n - 2 ; i ++ ) { cnt [ i + 1 ] = cnt [ i ] ; if ( s . Substring ( i , K . Length ) . Equals ( K ) ) { cnt [ i + 1 ] += 1 ; } } cnt [ n - 2 + 1 ] = cnt [ n - 2 ] ; } static void Main ( ) { string s = " ABCABCABABC " ; string K = " ABC " ; precompute ( s , K ) ; int [ , ] Q = { { 1 , 6 } , { 5 , 11 } } ; for ( int it = 0 ; it < Q . GetLength ( 0 ) ; it ++ ) { Console . WriteLine ( cnt [ Q [ it , 1 ] - 1 ] - cnt [ Q [ it , 0 ] - 1 ] ) ; } } }


"Queries to find maximum sum contiguous subarrays of given length in a rotating array | C # program for the above approach ; Function to calculate the maximum sum of length k ; Calculating the max sum for the first k elements ; Find subarray with maximum sum ; Update the sum ; Return maximum sum ; Function to calculate gcd of the two numbers n1 and n2 ; Base Case ; Recursively find the GCD ; Function to rotate the array by Y ; For handling k >= N ; Dividing the array into number of sets ; Rotate the array by Y ; Update arr [ j ] ; Return the rotated array ; Function that performs the queries on the given array ; Traverse each query ; If query of type X = 1 ; Print the array ; If query of type X = 2 ; Driver code ; Given array arr [ ] ; Given Queries ; Function call"
Solution in C#:

using System ; class GFG { static int MaxSum ( int [ ] arr , int n , int k ) { int i , max_sum = 0 , sum = 0 ; for ( i = 0 ; i < k ; i ++ ) { sum += arr [ i ] ; } max_sum = sum ; while ( i < n ) { sum = sum - arr [ i - k ] + arr [ i ] ; if ( max_sum < sum ) { max_sum = sum ; } i ++ ; } return max_sum ; } static int gcd ( int n1 , int n2 ) { if ( n2 == 0 ) { return n1 ; } else { return gcd ( n2 , n1 % n2 ) ; } } static int [ ] RotateArr ( int [ ] arr , int n , int d ) { int i = 0 , j = 0 ; d = d % n ; int no_of_sets = gcd ( d , n ) ; for ( i = 0 ; i < no_of_sets ; i ++ ) { int temp = arr [ i ] ; j = i ; while ( true ) { int k = j + d ; if ( k >= n ) k = k - n ; if ( k == i ) break ; arr [ j ] = arr [ k ] ; j = k ; } arr [ j ] = temp ; } return arr ; } static void performQuery ( int [ ] arr , int [ , ] Q , int q ) { int N = arr . Length ; for ( int i = 0 ; i < q ; i ++ ) { if ( Q [ i , 0 ] == 1 ) { arr = RotateArr ( arr , N , Q [ i , 1 ] ) ; for ( int t = 0 ; t < arr . Length ; t ++ ) { Console . Write ( arr [ t ] + " ▁ " ) ; } Console . WriteLine ( ) ; } else { Console . WriteLine ( MaxSum ( arr , N , Q [ i , 1 ] ) ) ; } } } static void Main ( ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 } ; int q = 5 ; int [ , ] Q = { { 1 , 2 } , { 2 , 3 } , { 1 , 3 } , { 1 , 1 } , { 2 , 4 } } ; performQuery ( arr , Q , q ) ; } }


"Queries to find minimum absolute difference between adjacent array elements in given ranges | C # program for the above approach ; Stores the index for the minimum value in the subarray arr [ i , j ] ; Structure for query range ; Function to fill the lookup array lookup [ , ] in the bottom up manner ; Initialize M for the intervals with length 1 ; Find the values from smaller to bigger intervals ; Compute minimum value for all intervals with size 2 ^ j ; For arr [ 2 , 10 ] , compare arr [ lookup [ 0 , 3 ] ] and arr [ lookup [ 3 , 3 ] ] ; Otherwise ; Function find minimum of absolute difference of all adjacent element in subarray arr [ L . . R ] ; For [ 2 , 10 ] , j = 3 ; For [ 2 , 10 ] , compare arr [ lookup [ 0 , 3 ] ] and arr [ lookup [ 3 , 3 ] ] , ; Function to find the minimum of the ranges for M queries ; Fills table lookup [ n , Log n ] ; Compute sum of all queries ; Left and right boundaries of current range ; Print sum of current query range ; Function to find the minimum absolute difference in a range ; diff [ ] is to stores the absolute difference of adjacent elements ; Call Min_difference to get minimum difference of adjacent elements ; Driver Code"
Solution in C#:

using System ; public class GFG { static readonly int MAX = 500 ; static int [ , ] lookup = new int [ MAX , MAX ] ; class Query { public int L , R ; public Query ( int l , int r ) { L = l ; R = r ; } } ; static void preprocess ( int [ ] arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) lookup [ i , 0 ] = i ; for ( int j = 1 ; ( 1 << j ) <= n ; j ++ ) { for ( int i = 0 ; ( i + ( 1 << j ) - 1 ) < n ; i ++ ) { if ( arr [ lookup [ i , j - 1 ] ] < arr [ lookup [ i + ( 1 << ( j - 1 ) ) , j - 1 ] ] ) lookup [ i , j ] = lookup [ i , j - 1 ] ; else lookup [ i , j ] = lookup [ i + ( 1 << ( j - 1 ) ) , j - 1 ] ; } } } static int query ( int [ ] arr , int L , int R ) { int j = ( int ) Math . Log ( R - L + 1 ) ; if ( arr [ lookup [ L , j ] ] <= arr [ lookup [ R - ( 1 << j ) + 1 , j ] ] ) return arr [ lookup [ L , j ] ] ; else return arr [ lookup [ R - ( 1 << j ) + 1 , j ] ] ; } static void Min_difference ( int [ ] arr , int n , Query [ ] q , int m ) { preprocess ( arr , n ) ; for ( int i = 0 ; i < m ; i ++ ) { int L = q [ i ] . L , R = q [ i ] . R ; Console . WriteLine ( query ( arr , L , R - 1 ) ) ; } } static void minimumDifference ( int [ ] arr , Query [ ] q , int N , int m ) { int [ ] diff = new int [ N ] ; for ( int i = 0 ; i < N - 1 ; i ++ ) diff [ i ] = Math . Abs ( arr [ i ] - arr [ i + 1 ] ) ; Min_difference ( diff , N - 1 , q , m ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , 6 , 1 , 8 , 3 , 4 } ; int N = arr . Length ; Query [ ] Q = { new Query ( 0 , 3 ) , new Query ( 1 , 5 ) , new Query ( 4 , 5 ) } ; int M = Q . Length ; minimumDifference ( arr , Q , N , M ) ; } }


"Queries to find minimum absolute difference between adjacent array elements in given ranges | C # program for the above approach ; Structure for query range ; Function to find the minimum difference between adjacent array element over the given range [ L , R ] for Q Queries ; Find the sum of all queries ; Left and right boundaries of current range ; Print the sum of the current query range ; Function to find the minimum absolute difference of adjacent array elements for the given range ; Stores the absolute difference of adjacent elements ; Find the minimum difference of adjacent elements ; Driver Code"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { class Query { public int L , R ; public Query ( int l , int r ) { this . L = l ; this . R = r ; } } ; static int MAX = 5000 ; static void minDifference ( int [ ] arr , int n , Query [ ] q , int m ) { for ( int i = 0 ; i < m ; i ++ ) { int L = q [ i ] . L , R = q [ i ] . R ; int ans = MAX ; for ( int j = L ; j < R ; j ++ ) { ans = Math . Min ( ans , arr [ j ] ) ; } Console . WriteLine ( ans ) ; } } static void minimumDifference ( int [ ] arr , Query [ ] q , int N , int m ) { int [ ] diff = new int [ N ] ; for ( int i = 0 ; i < N - 1 ; i ++ ) diff [ i ] = Math . Abs ( arr [ i ] - arr [ i + 1 ] ) ; minDifference ( diff , N - 1 , q , m ) ; } public static void Main ( ) { int [ ] arr = { 2 , 6 , 1 , 8 , 3 , 4 } ; int N = arr . Length ; Query [ ] Q = { new Query ( 0 , 3 ) , new Query ( 1 , 5 ) , new Query ( 4 , 5 ) } ; int M = Q . Length ; minimumDifference ( arr , Q , N , M ) ; } }


"Queries to find minimum sum of array elements from either end of an array | C # implementation of the above approach ; Function to calculate the minimum sum from either end of the arrays for the given queries ; Traverse the query [ ] array ; Stores sum from start and end of the array ; Calculate distance from start ; Calculate distance from end ; Driver code"
Solution in C#:

using System ; class GFG { static void calculateQuery ( int [ ] arr , int N , int [ ] query , int M ) { for ( int i = 0 ; i < M ; i ++ ) { int X = query [ i ] ; int sum_start = 0 , sum_end = 0 ; for ( int j = 0 ; j < N ; j ++ ) { sum_start += arr [ j ] ; if ( arr [ j ] == X ) break ; } for ( int j = N - 1 ; j >= 0 ; j -- ) { sum_end += arr [ j ] ; if ( arr [ j ] == X ) break ; } Console . Write ( Math . Min ( sum_end , sum_start ) + " ▁ " ) ; } } static void Main ( ) { int [ ] arr = { 2 , 3 , 6 , 7 , 4 , 5 , 30 } ; int [ ] queries = { 6 , 5 } ; int N = arr . Length ; int M = queries . Length ; calculateQuery ( arr , N , queries , M ) ; } }


"Queries to find minimum sum of array elements from either end of an array | C # implementation of the above approach ; Function to find the minimum sum for the given queries ; Stores prefix and suffix sums ; Stores pairs of prefix and suffix sums ; Traverse the array ; Add element to prefix ; Store prefix for each element ; Traverse the array in reverse ; Add element to suffix ; Storing suffix for each element ; Traverse the array queries [ ] ; Minimum of suffix and prefix sums ; Driver code"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static void calculateQuery ( int [ ] arr , int N , int [ ] query , int M ) { int prefix = 0 , suffix = 0 ; Dictionary < int , Tuple < int , int > > mp = new Dictionary < int , Tuple < int , int > > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { prefix += arr [ i ] ; mp [ arr [ i ] ] = new Tuple < int , int > ( prefix , 0 ) ; } for ( int i = N - 1 ; i >= 0 ; i -- ) { suffix += arr [ i ] ; mp [ arr [ i ] ] = new Tuple < int , int > ( mp [ arr [ i ] ] . Item1 , suffix ) ; } for ( int i = 0 ; i < M ; i ++ ) { int X = query [ i ] ; Console . Write ( Math . Min ( mp [ X ] . Item1 , mp [ X ] . Item2 ) + " ▁ " ) ; } } static void Main ( ) { int [ ] arr = { 2 , 3 , 6 , 7 , 4 , 5 , 30 } ; int [ ] queries = { 6 , 5 } ; int N = arr . Length ; int M = queries . Length ; calculateQuery ( arr , N , queries , M ) ; } }


"Queries to find minimum swaps required to sort given array with updates | C # program for the above approach ; Function to return the position of the given value using binary search ; Return 0 if every value is greater than the given value ; Return N - 1 if every value is smaller than the given value ; Perform Binary Search ; Iterate till start < end ; Find the mid ; Update start and end ; Return the position of the given value ; Function to return the number of make the array sorted ; Index x to update ; Increment value by y ; Set newElement equals to x + y ; Compute the new index ; Print the minimum number of swaps ; Driver Code ; Given array [ ] arr ; Given Queries ; Function Call"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static int computePos ( int [ ] arr , int n , int value ) { if ( value < arr [ 0 ] ) return 0 ; if ( value > arr [ n - 1 ] ) return n - 1 ; int start = 0 ; int end = n - 1 ; while ( start < end ) { int mid = ( start + end + 1 ) / 2 ; if ( arr [ mid ] >= value ) end = mid - 1 ; else start = mid ; } return start ; } static void countShift ( int [ ] arr , int n , List < List < int > > queries ) { foreach ( List < int > q in queries ) { int index = q [ 0 ] ; int update = q [ 1 ] ; int newElement = arr [ index ] + update ; int newIndex = computePos ( arr , n , newElement ) ; Console . Write ( Math . Abs ( newIndex - index ) + " ▁ " ) ; } } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , 3 , 4 , 5 , 6 } ; int N = arr . Length ; List < List < int > > queries = new List < List < int > > ( ) ; List < int > v = new List < int > ( ) ; List < int > v1 = new List < int > ( ) ; v . Add ( 0 ) ; v . Add ( - 1 ) ; queries . Add ( v ) ; v1 . Add ( 4 ) ; v1 . Add ( - 11 ) ; queries . Add ( v1 ) ; countShift ( arr , N , queries ) ; } }


"Queries to find number of connected grid components of given sizes in a Matrix | C # implementation for the above approach ; stores information about which cell are already visited in a particular BFS ; Stores the count of cells in the largest connected component ; Function checks if a cell is valid , i . e . it is inside the grid and equal to 1 ; Map to count the frequency of each connected component ; function to calculate the largest connected component ; Iterate over every cell ; Stores the indices of the matrix cells ; Mark the starting cell as visited and push it into the queue ; Iterate while the queue is not empty ; Go to the adjacent cells ; Drivers Code ; Given input array of 1 s and 0 s ; queries array ; sizeof queries array ; Count the frequency of each connected component ; Iterate over the given queries array and And answer the queries"
Solution in C#:

using System ; using System . Collections . Generic ; public class GFG { class pair { public int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static int n = 6 ; static int m = 6 ; static int [ ] dx = { 0 , 1 , - 1 , 0 } ; static int [ ] dy = { 1 , 0 , 0 , - 1 } ; static int [ , ] visited = new int [ n , m ] ; static int COUNT ; static bool is_valid ( int x , int y , int [ , ] matrix ) { if ( x < n && y < m && x >= 0 && y >= 0 ) { if ( visited [ x , y ] == 0 && matrix [ x , y ] == 1 ) return true ; else return false ; } else return false ; } static Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; static void findComponentSize ( int [ , ] matrix ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( visited [ i , j ] == 0 && matrix [ i , j ] == 1 ) { COUNT = 0 ; List < pair > q = new List < pair > ( ) ; q . Add ( new pair ( i , j ) ) ; visited [ i , j ] = 1 ; while ( q . Count > 0 ) { pair p = q [ 0 ] ; q . RemoveAt ( ) ; int x = p . first , y = p . second ; COUNT ++ ; for ( int k = 0 ; k < 4 ; k ++ ) { int newX = x + dx [ k ] ; int newY = y + dy [ k ] ; if ( is_valid ( newX , newY , matrix ) ) { q . Add ( new pair ( newX , newY ) ) ; visited [ newX , newY ] = 1 ; } } } if ( mp . ContainsKey ( COUNT ) ) { mp [ COUNT ] += 1 ; } else { mp . Add ( COUNT , 1 ) ; } } } } } public static void Main ( ) { int [ , ] matrix = new int [ , ] { { 1 , 1 , 1 , 1 , 1 , 1 } , { 1 , 1 , 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 1 , 1 , 1 } , { 0 , 0 , 0 , 1 , 1 , 1 } , { 0 , 0 , 1 , 0 , 0 , 0 } , { 1 , 0 , 0 , 0 , 0 , 0 } } ; int [ ] queries = { 6 , 1 , 8 , 2 } ; int N = queries . Length ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { visited [ i , j ] = 0 ; } } findComponentSize ( matrix ) ; for ( int i = 0 ; i < N ; i ++ ) if ( mp . ContainsKey ( queries [ i ] ) != false ) Console . Write ( mp [ queries [ i ] ] + " ▁ " ) ; } }


"Queries to find sum of distance of a given node to every leaf node in a Weighted Tree | C # program for the above problem ; MAX size ; Graph with { destination , weight } ; For storing the sum for ith node ; Leaves in subtree of ith . ; dfs to find sum of distance of leaves in the subtree of a node ; flag is the node is leaf or not ; Skipping if parent ; Setting flag to false ; Doing dfs call ; Doing calculation in postorder . ; If the node is leaf then we just increment the no . of leaves under the subtree of a node ; Adding num of leaves ; Calculating answer for the sum in the subtree ; dfs function to find the sum of distance of leaves outside the subtree ; Number of leaves other than the leaves in the subtree of i ; Adding the contribution of leaves outside to the ith node ; Adding the leafs outside to ith node 's leaves. ; Calculating the sum of distance of leaves in the subtree of a node assuming the root of the tree is 1 ; Calculating the sum of distance of leaves outside the subtree of node assuming the root of the tree is 1 ; Answering the queries ; 1 ( 4 ) / \ ( 2 ) / \ 4 2 ( 5 ) / \ ( 3 ) / \ 5 3 ; initialising tree ; System . out . println ( v ) ;"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static int N = 100005 ; static List < List < Tuple < int , int > > > v = new List < List < Tuple < int , int > > > ( ) ; static int [ ] dp = new int [ N ] ; static int [ ] leaves = new int [ N ] ; static void dfs ( int a , int par ) { bool leaf = true ; foreach ( Tuple < int , int > i in v [ a ] ) { if ( i . Item1 == par ) continue ; leaf = false ; dfs ( i . Item1 , a ) ; } if ( leaf == true ) { leaves [ a ] += 1 ; } else { foreach ( Tuple < int , int > i in v [ a ] ) { if ( i . Item1 == par ) continue ; leaves [ a ] += leaves [ i . Item1 ] ; dp [ a ] = ( dp [ a ] + dp [ i . Item1 ] + leaves [ i . Item1 ] * i . Item2 ) ; } } } static void dfs2 ( int a , int par ) { foreach ( Tuple < int , int > i in v [ a ] ) { if ( i . Item1 == par ) continue ; int leafOutside = leaves [ a ] - leaves [ i . Item1 ] ; dp [ i . Item1 ] += ( dp [ a ] - dp [ i . Item1 ] ) ; dp [ i . Item1 ] += i . Item2 * ( leafOutside - leaves [ i . Item1 ] ) ; leaves [ i . Item1 ] += leafOutside ; dfs2 ( i . Item1 , a ) ; } } static void answerQueries ( List < int > queries ) { dfs ( 1 , 0 ) ; dfs2 ( 1 , 0 ) ; for ( int i = 0 ; i < queries . Count ; i ++ ) Console . WriteLine ( dp [ queries [ i ] ] ) ; } static void Main ( ) { for ( int i = 0 ; i < N ; i ++ ) { v . Add ( new List < Tuple < int , int > > ( ) ) ; } v [ 1 ] . Add ( new Tuple < int , int > ( 4 , 4 ) ) ; v [ 4 ] . Add ( new Tuple < int , int > ( 1 , 4 ) ) ; v [ 1 ] . Add ( new Tuple < int , int > ( 2 , 2 ) ) ; v [ 2 ] . Add ( new Tuple < int , int > ( 1 , 2 ) ) ; v [ 2 ] . Add ( new Tuple < int , int > ( 3 , 3 ) ) ; v [ 3 ] . Add ( new Tuple < int , int > ( 2 , 3 ) ) ; v [ 2 ] . Add ( new Tuple < int , int > ( 5 , 5 ) ) ; v [ 5 ] . Add ( new Tuple < int , int > ( 2 , 5 ) ) ; List < int > queries = new List < int > { 1 , 3 , 5 } ; answerQueries ( queries ) ; } }


"Queries to find the Lower Bound of K from Prefix Sum Array with updates using Fenwick Tree | C # program to implement the above approach ; Function to calculate and return the sum of arr [ 0. . index ] ; Traverse ancestors of BITree [ index ] ; Update the sum of current element of BIT to ans ; Update index to that of the parent node in getSum ( ) view by subtracting LSB ( Least Significant Bit ) ; Function to update the Binary Index Tree by replacing all ancestors of index by their respective sum with val ; Traverse all ancestors and sum with ' val ' . ; Add ' val ' to current node of BIT ; Update index to that of the parent node in updateBit ( ) view by adding LSB ( Least Significant Bit ) ; Function to construct the Binary Indexed Tree for the given array ; Initialize the Binary Indexed Tree ; Store the actual values in BITree [ ] using update ( ) ; Function to obtain and return the index of lower_bound of k ; Store the Binary Indexed Tree ; Solve each query in Q ; Update the values of all ancestors of idx ; Driver Code"
Solution in C#:

using System ; class GFG { static int getSum ( int [ ] BITree , int index ) { int ans = 0 ; index += 1 ; while ( index > 0 ) { ans += BITree [ index ] ; index -= index & ( - index ) ; } return ans ; } static void updateBIT ( int [ ] BITree , int n , int index , int val ) { index = index + 1 ; while ( index <= n ) { BITree [ index ] += val ; index += index & ( - index ) ; } } static int [ ] constructBITree ( int [ ] arr , int n ) { int [ ] BITree = new int [ n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) BITree [ i ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) updateBIT ( BITree , n , i , arr [ i ] ) ; return BITree ; } static int getLowerBound ( int [ ] BITree , int [ ] arr , int n , int k ) { int lb = - 1 ; int l = 0 , r = n - 1 ; while ( l <= r ) { int mid = l + ( r - l ) / 2 ; if ( getSum ( BITree , mid ) >= k ) { r = mid - 1 ; lb = mid ; } else l = mid + 1 ; } return lb ; } static void performQueries ( int [ ] A , int n , int [ , ] q ) { int [ ] BITree = constructBITree ( A , n ) ; for ( int i = 0 ; i < q . GetLength ( 0 ) ; i ++ ) { int id = q [ i , 0 ] ; if ( id == 1 ) { int idx = q [ i , 1 ] ; int val = q [ i , 2 ] ; A [ idx ] += val ; updateBIT ( BITree , n , idx , val ) ; } else { int k = q [ i , 1 ] ; int lb = getLowerBound ( BITree , A , n , k ) ; Console . WriteLine ( lb ) ; } } } public static void Main ( String [ ] args ) { int [ ] A = { 1 , 2 , 3 , 5 , 8 } ; int n = A . Length ; int [ , ] q = { { 1 , 0 , 2 } , { 2 , 5 , 0 } , { 1 , 3 , 5 } } ; performQueries ( A , n , q ) ; } }


"Queries to find the XOR of an Array after replacing all occurrences of X by Y | C # program to implement the above approach ; Stores the bitwise XOR of array elements ; Function to find the total xor ; Loop to find the xor of all the elements ; Function to find the XOR after replacing all occurrences of X by Y for Q queries ; Remove contribution of X from total_xor ; Adding contribution of Y to total_xor ; Print total_xor ; Driver Code"
Solution in C#:

 using System ; class GFG { static int total_xor ; static void initialize_xor ( int [ ] arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) { total_xor = total_xor ^ arr [ i ] ; } } static void find_xor ( int X , int Y ) { total_xor = total_xor ^ X ; total_xor = total_xor ^ Y ; Console . Write ( total_xor + "
 " ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 5 , 7 , 8 , 9 } ; int n = arr . Length ; initialize_xor ( arr , n ) ; int [ , ] Q = { { 5 , 6 } , { 8 , 1 } } ; for ( int i = 0 ; i < Q . GetLength ( 0 ) ; i ++ ) { find_xor ( Q [ i , 0 ] , Q [ i , 1 ] ) ; } } }


"Queries to find the count of characters preceding the given location | C # implementation of the approach ; Driver Code"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static void Count ( int [ ] temp ) { int [ ] query = { 9 , 3 , 2 } ; int Q = query . Length ; for ( int i = 0 ; i < Q ; i ++ ) { int pos = query [ i ] ; Console . WriteLine ( temp [ pos - 1 ] ) ; } } static int [ ] processing ( String s , int len ) { int [ ] temp = new int [ len ] ; Dictionary < int , int > d = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < len ; i ++ ) { if ( ! d . ContainsKey ( s [ i ] ) ) { d . Add ( s [ i ] , i ) ; } else { temp [ i ] = temp [ d [ s [ i ] ] ] + 1 ; d [ s [ i ] ] = i ; } } return temp ; } public static void Main ( String [ ] args ) { String s = " abacsddaa " ; int n = s . Length ; int [ ] temp = processing ( s , n ) ; Count ( temp ) ; } }


"Queries to find the count of characters preceding the given location | C # implementation of the approach ; returns character at index pos - 1 ; Driver Code"
Solution in C#:

using System ; class GFG { static int Count ( String s , int pos ) { int c = s [ pos - 1 ] ; int counter = 0 ; for ( int i = 0 ; i < pos - 1 ; i ++ ) { if ( s [ i ] == c ) counter = counter + 1 ; } return counter ; } public static void Main ( String [ ] args ) { String s = " abacsddaa " ; int pos ; int n = s . Length ; int [ ] query = { 9 , 3 , 2 } ; int Q = query . Length ; for ( int i = 0 ; i < Q ; i ++ ) { pos = query [ i ] ; Console . WriteLine ( Count ( s , pos ) ) ; } } }


"Queries to find the count of connected Non | C # program to implement the above approach ; Count of connected cells ; Function to return the representative of the Set to which x belongs ; If x is parent of itself ; x is representative of the Set ; Otherwise ; Path Compression ; Unites the set that includes x and the set that includes y ; Find the representatives ( or the root nodes ) for x an y ; If both are in the same set ; Decrement count ; If x ' s ▁ rank ▁ is ▁ less ▁ than ▁ y ' s rank ; Otherwise ; Then move x under y ( doesn 't matter which one goes where) ; And increment the result tree 's  rank by 1 ; Function to count the number of connected cells in the matrix ; Store result for queries ; Store representative of each element ; Initially , all elements are in their own set ; Stores the rank ( depth ) of each node ; If the grid [ x * m + y ] is already set , store the result ; Set grid [ x * m + y ] to 1 ; Increment count . ; Check for all adjacent cells to do a Union with neighbour 's  set if neighbour is also 1 ; Store result . ; Driver Code"
Solution in C#:

using System ; class GFG { static int ctr = 0 ; static int find ( int [ ] parent , int x ) { if ( parent [ x ] == x ) return x ; parent [ x ] = find ( parent , parent [ x ] ) ; return parent [ x ] ; } static void setUnion ( int [ ] parent , int [ ] rank , int x , int y ) { int parentx = find ( parent , x ) ; int parenty = find ( parent , y ) ; if ( parenty == parentx ) return ; ctr -- ; if ( rank [ parentx ] < rank [ parenty ] ) { parent [ parentx ] = parenty ; } else if ( rank [ parentx ] > rank [ parenty ] ) { parent [ parenty ] = parentx ; } else { parent [ parentx ] = parenty ; rank [ parenty ] ++ ; } } static int [ ] solve ( int n , int m , int [ , ] query ) { int [ ] result = new int [ query . Length ] ; int [ ] parent = new int [ n * m ] ; for ( int i = 0 ; i < n * m ; i ++ ) parent [ i ] = i ; int [ ] rank = new int [ n * m ] ; for ( int i = 0 ; i < rank . Length ; i ++ ) rank [ i ] = 1 ; bool [ ] grid = new bool [ n * m ] ; for ( int i = 0 ; i < query . GetLength ( 0 ) ; i ++ ) { int x = query [ i , 0 ] ; int y = query [ i , 1 ] ; if ( grid [ m * x + y ] == true ) { result [ i ] = ctr ; continue ; } grid [ m * x + y ] = true ; ctr ++ ; if ( x > 0 && grid [ m * ( x - 1 ) + y ] == true ) setUnion ( parent , rank , m * x + y , m * ( x - 1 ) + y ) ; if ( y > 0 && grid [ m * ( x ) + y - 1 ] == true ) setUnion ( parent , rank , m * x + y , m * ( x ) + y - 1 ) ; if ( x < n - 1 && grid [ m * ( x + 1 ) + y ] == true ) setUnion ( parent , rank , m * x + y , m * ( x + 1 ) + y ) ; if ( y < m - 1 && grid [ m * ( x ) + y + 1 ] == true ) setUnion ( parent , rank , m * x + y , m * ( x ) + y + 1 ) ; result [ i ] = ctr ; } return result ; } public static void Main ( String [ ] args ) { int N = 3 , M = 3 , K = 4 ; int [ , ] query = { { 0 , 0 } , { 1 , 1 } , { 1 , 0 } , { 1 , 2 } } ; int [ ] result = solve ( N , M , query ) ; for ( int i = 0 ; i < K ; i ++ ) Console . Write ( result [ i ] + " ▁ " ) ; } }


"Queries to find the count of vowels in the substrings of the given string | C # implementation of the approach ; Function that returns true if ch is a vowel ; Function to return the count of vowels in the substring str [ l ... r ] ; To store the count of vowels ; For every character in the index range [ l , r ] ; If the current character is a vowel ; For every query ; Find the count of vowels for the current query ; Driver code"
Solution in C#:

using System ; class GFG { static int N = 2 ; static Boolean isVowel ( char ch ) { return ( ch == ' a ' ch == ' e ' ch == ' i ' ch == ' o ' ch == ' u ' ) ; } static int countVowels ( String str , int l , int r ) { int cnt = 0 ; for ( int i = l ; i <= r ; i ++ ) { if ( isVowel ( str [ i ] ) ) cnt ++ ; } return cnt ; } static void performQueries ( String str , int [ , ] queries , int q ) { for ( int i = 0 ; i < q ; i ++ ) { Console . WriteLine ( countVowels ( str , queries [ i , 0 ] , queries [ i , 1 ] ) ) ; } } public static void Main ( String [ ] args ) { String str = " geeksforgeeks " ; int [ , ] queries = { { 1 , 3 } , { 2 , 4 } , { 1 , 9 } } ; int q = queries . GetLength ( 0 ) ; performQueries ( str , queries , q ) ; } }


"Queries to find the count of vowels in the substrings of the given string | C # implementation of the approach ; Function that returns true if ch is a vowel ; pre [ i ] will store the count of vowels in the subString str [ 0. . . i ] ; Fill the pre [ ] array ; If current character is a vowel ; If its a consonant ; For every query ; Find the count of vowels for the current query ; Driver code"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static readonly int N = 2 ; static Boolean isVowel ( char ch ) { return ( ch == ' a ' ch == ' e ' ch == ' i ' ch == ' o ' ch == ' u ' ) ; } static void performQueries ( String str , int len , int [ , ] queries , int q ) { int [ ] pre = new int [ len ] ; if ( isVowel ( str [ 0 ] ) ) pre [ 0 ] = 1 ; else pre [ 0 ] = 0 ; for ( int i = 1 ; i < len ; i ++ ) { if ( isVowel ( str [ i ] ) ) pre [ i ] = 1 + pre [ i - 1 ] ; else pre [ i ] = pre [ i - 1 ] ; } for ( int i = 0 ; i < q ; i ++ ) { if ( queries [ i , 0 ] == 0 ) { Console . WriteLine ( pre [ queries [ i , 1 ] ] ) ; } else { Console . WriteLine ( ( pre [ queries [ i , 1 ] ] - pre [ queries [ i , 0 ] - 1 ] ) ) ; } } } public static void Main ( String [ ] args ) { String str = " geeksforgeeks " ; int len = str . Length ; int [ , ] queries = { { 1 , 3 } , { 2 , 4 } , { 1 , 9 } } ; int q = queries . GetLength ( 0 ) ; performQueries ( str , len , queries , q ) ; } }


"Queries to find the first non | C # implementation of the approach ; Maximum distinct characters possible ; To store the frequency of the characters ; Function to pre - calculate the frequency array ; Only the first character has frequency 1 till index 0 ; Starting from the second character of the string ; For every possible character ; Current character under consideration ; If it is equal to the character at the current index ; Function to return the frequency of the given character in the sub - string str [ l ... r ] ; Function to return the first non - repeating character in range [ l . . r ] ; Starting from the first character ; Current character ; If frequency of the current character is 1 then return the character ; All the characters of the sub - string are repeating ; Driver code ; Pre - calculate the frequency array"
Solution in C#:

using System ; class GFG { static int MAX = 256 ; static int [ , ] freq ; static void preCalculate ( string str , int n ) { freq [ ( int ) str [ 0 ] , 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { char ch = str [ i ] ; for ( int j = 0 ; j < MAX ; j ++ ) { char charToUpdate = ( char ) j ; if ( charToUpdate == ch ) freq [ j , i ] = freq [ j , i - 1 ] + 1 ; else freq [ j , i ] = freq [ j , i - 1 ] ; } } } static int getFrequency ( char ch , int l , int r ) { if ( l == 0 ) return freq [ ( int ) ch , r ] ; else return ( freq [ ( int ) ch , r ] - freq [ ( int ) ch , l - 1 ] ) ; } static string firstNonRepeating ( string str , int n , int l , int r ) { for ( int i = l ; i < r ; i ++ ) { char ch = str [ i ] ; if ( getFrequency ( ch , l , r ) == 1 ) return ( " " + ch ) ; } return " - 1" ; } public static void Main ( ) { string str = " GeeksForGeeks " ; int n = str . Length ; int [ , ] queries = { { 0 , 3 } , { 2 , 3 } , { 5 , 12 } } ; int q = queries . Length ; freq = new int [ MAX , n ] ; preCalculate ( str , n ) ; for ( int i = 0 ; i < q ; i ++ ) { Console . WriteLine ( firstNonRepeating ( str , n , queries [ i , 0 ] , queries [ i , 1 ] ) ) ; } } }


"Queries to find the last non | C # implementation of the approach ; Maximum distinct characters possible ; To store the frequency of the characters ; Function to pre - calculate the frequency array ; Only the first character has frequency 1 till index 0 ; Starting from the second character of the string ; For every possible character ; Current character under consideration ; If it is equal to the character at the current index ; Function to return the frequency of the given character in the sub - string str [ l ... r ] ; Function to return the last non - repeating character ; Starting from the last character ; Current character ; If frequency of the current character is 1 then return the character ; All the characters of the sub - string are repeating ; Driver code ; Pre - calculate the frequency array"
Solution in C#:

using System ; class GFG { static int MAX = 256 ; static int [ , ] freq ; static void preCalculate ( string str , int n ) { freq [ ( int ) str [ 0 ] , 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { char ch = str [ i ] ; for ( int j = 0 ; j < MAX ; j ++ ) { char charToUpdate = ( char ) j ; if ( charToUpdate == ch ) freq [ j , i ] = freq [ j , i - 1 ] + 1 ; else freq [ j , i ] = freq [ j , i - 1 ] ; } } } static int getFrequency ( char ch , int l , int r ) { if ( l == 0 ) return freq [ ( int ) ch , r ] ; else return ( freq [ ( int ) ch , r ] - freq [ ( int ) ch , l - 1 ] ) ; } static String lastNonRepeating ( string str , int n , int l , int r ) { for ( int i = r ; i >= l ; i -- ) { char ch = str [ i ] ; if ( getFrequency ( ch , l , r ) == 1 ) return ( " " + ch ) ; } return " - 1" ; } public static void Main ( ) { string str = " GeeksForGeeks " ; int n = str . Length ; int [ , ] queries = { { 2 , 9 } , { 2 , 3 } , { 0 , 12 } } ; int q = queries . Length ; freq = new int [ MAX , n ] ; preCalculate ( str , n ) ; for ( int i = 0 ; i < q ; i ++ ) { Console . WriteLine ( lastNonRepeating ( str , n , queries [ i , 0 ] , queries [ i , 1 ] ) ) ; } } }


"Queries to find the maximum Xor value between X and the nodes of a given level of a perfect binary tree | C # implementation of the approach ; Function to solve queries of the maximum xor value between the nodes in a given level L of a perfect binary tree and a given value X ; Initialize result ; Initialize array to store bits ; Initialize a copy of X and size of array ; Storing the bits of X in the array a [ ] ; Filling the array b [ ] ; Initializing variable which gives maximum xor ; Getting the maximum xor value ; Return the result ; Driver code ; Perform queries"
Solution in C#:

using System ; class GFG { static int MAXN = 60 ; static int solveQuery ( int L , int X ) { int res ; int [ ] a = new int [ MAXN ] ; int [ ] b = new int [ L ] ; int refer = X , size_a = 0 ; while ( refer > 0 ) { a [ size_a ] = refer % 2 ; refer /= 2 ; size_a ++ ; } for ( int i = 0 ; i < Math . Min ( size_a , L ) ; i ++ ) { if ( a [ i ] == 1 ) b [ i ] = 0 ; else b [ i ] = 1 ; } for ( int i = Math . Min ( size_a , L ) ; i < L ; i ++ ) b [ i ] = 1 ; b [ L - 1 ] = 1 ; int temp = 0 , p = 1 ; for ( int i = 0 ; i < L ; i ++ ) { temp += b [ i ] * p ; p *= 2 ; } res = temp ^ X ; return res ; } static public void Main ( ) { int [ , ] queries = { { 2 , 5 } , { 3 , 15 } } ; int q = queries . Length ; for ( int i = 0 ; i < q ; i ++ ) Console . WriteLine ( solveQuery ( queries [ i , 0 ] , queries [ i , 1 ] ) ) ; } }


"Queries to find the maximum and minimum array elements excluding elements from a given range | C # program for the above approach ; Function to find the maximum and minimum array elements up to the i - th index ; Traverse the array ; Compare current value with maximum and minimum values up to previous index ; Function to find the maximum and minimum array elements from i - th index ; Traverse the array in reverse ; Compare current value with maximum and minimum values in the next index ; Function to find the maximum and minimum array elements for each query ; If no index remains after excluding the elements in a given range ; Find maximum and minimum from from the range [ R + 1 , N - 1 ] ; Find maximum and minimum from from the range [ 0 , N - 1 ] ; Find maximum and minimum values from the ranges [ 0 , L - 1 ] and [ R + 1 , N - 1 ] ; Print the maximum and minimum value ; Function to perform queries to find the minimum and maximum array elements excluding elements from a given range ; Size of the array ; Size of query array ; prefix [ i ] [ 0 ] : Stores the maximum prefix [ i ] [ 1 ] : Stores the minimum value ; suffix [ i ] [ 0 ] : Stores the maximum suffix [ i ] [ 1 ] : Stores the minimum value ; Function calls to store maximum and minimum values for respective ranges ; Driver Code ; Given array"
Solution in C#:

using System ; public class GFG { static void prefixArr ( int [ ] arr , int [ , ] prefix , int N ) { for ( int i = 0 ; i < N ; i ++ ) { if ( i == 0 ) { prefix [ i , 0 ] = arr [ i ] ; prefix [ i , 1 ] = arr [ i ] ; } else { prefix [ i , 0 ] = Math . Max ( prefix [ i - 1 , 0 ] , arr [ i ] ) ; prefix [ i , 1 ] = Math . Min ( prefix [ i - 1 , 1 ] , arr [ i ] ) ; } } } static void suffixArr ( int [ ] arr , int [ , ] suffix , int N ) { for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( i == N - 1 ) { suffix [ i , 0 ] = arr [ i ] ; suffix [ i , 1 ] = arr [ i ] ; } else { suffix [ i , 0 ] = Math . Max ( suffix [ i + 1 , 0 ] , arr [ i ] ) ; suffix [ i , 1 ] = Math . Min ( suffix [ i + 1 , 1 ] , arr [ i ] ) ; } } } static void maxAndmin ( int [ , ] prefix , int [ , ] suffix , int N , int L , int R ) { int maximum , minimum ; if ( L == 0 && R == N - 1 ) { Console . WriteLine ( " No ▁ maximum ▁ and ▁ minimum ▁ value " ) ; return ; } else if ( L == 0 ) { maximum = suffix [ R + 1 , 0 ] ; minimum = suffix [ R + 1 , 1 ] ; } else if ( R == N - 1 ) { maximum = prefix [ L - 1 , 0 ] ; minimum = prefix [ R - 1 , 1 ] ; } else { maximum = Math . Max ( prefix [ L - 1 , 0 ] , suffix [ R + 1 , 0 ] ) ; minimum = Math . Min ( prefix [ L - 1 , 1 ] , suffix [ R + 1 , 1 ] ) ; } Console . WriteLine ( maximum + " ▁ " + minimum ) ; } static void MinMaxQueries ( int [ ] a , int [ , ] Q ) { int N = a . GetLength ( 0 ) ; int q = Q . GetLength ( 0 ) ; int [ , ] prefix = new int [ N , 2 ] ; int [ , ] suffix = new int [ N , 2 ] ; prefixArr ( a , prefix , N ) ; suffixArr ( a , suffix , N ) ; for ( int i = 0 ; i < q ; i ++ ) { int L = Q [ i , 0 ] ; int R = Q [ i , 1 ] ; maxAndmin ( prefix , suffix , N , L , R ) ; } } static public void Main ( ) { int [ ] arr = { 2 , 3 , 1 , 8 , 3 , 5 , 7 , 4 } ; int [ , ] queries = { { 4 , 6 } , { 0 , 4 } , { 3 , 7 } , { 2 , 5 } } ; MinMaxQueries ( arr , queries ) ; } }


"Queries to find the maximum array element after removing elements from a given range | C # program for the above approach ; Function to find the maximum element after removing elements in range [ l , r ] ; Store prefix maximum element ; Store suffix maximum element ; Prefix max till first index is first index itself ; Traverse the array to fill prefix max array ; Store maximum till index i ; Suffix max till last index is last index itself ; Traverse the array to fill suffix max array ; Store maximum till index i ; Traverse all queries ; Store the starting and the ending index of the query ; Edge Cases ; Otherwise ; Driver Code"
Solution in C#:

 using System ; public class GFG { static void findMaximum ( int [ ] arr , int N , int Q , int [ , ] queries ) { int [ ] prefix_max = new int [ N + 1 ] ; int [ ] suffix_max = new int [ N + 1 ] ; prefix_max [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { prefix_max [ i ] = Math . Max ( prefix_max [ i - 1 ] , arr [ i ] ) ; } suffix_max [ N - 1 ] = arr [ N - 1 ] ; for ( int i = N - 2 ; i >= 0 ; i -- ) { suffix_max [ i ] = Math . Max ( suffix_max [ i + 1 ] , arr [ i ] ) ; } for ( int i = 0 ; i < Q ; i ++ ) { int l = queries [ i , 0 ] ; int r = queries [ i , 1 ] ; if ( l == 0 && r == ( N - 1 ) ) Console . Write ( "0
 " ) ; else if ( l == 0 ) Console . Write ( suffix_max [ r + 1 ] + "
 " ) ; else if ( r == ( N - 1 ) ) Console . Write ( prefix_max [ l - 1 ] + "
 " ) ; else Console . Write ( Math . Max ( prefix_max [ l - 1 ] , suffix_max [ r + 1 ] ) + "
 " ) ; } } static public void Main ( ) { int [ ] arr = { 5 , 6 , 8 , 10 , 15 } ; int N = arr . Length ; int [ , ] queries = { { 0 , 1 } , { 0 , 2 } , { 1 , 4 } } ; int Q = queries . GetLength ( 0 ) ; findMaximum ( arr , N , Q , queries ) ; } }


"Queries to find the minimum array sum possible by removing elements from either end | C # program for the above approach ; Function to find the minimum sum for each query after removing element from either ends till each value Q [ i ] ; Stores the prefix sum from both the ends of the array ; Traverse the array from front ; Insert it into the map m1 ; Traverse the array in reverse ; Insert it into the map m2 ; Traverse the query array ; Print the minimum of the two values as the answer ; Driver Code ; Function Call"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static void minOperations ( int [ ] arr , int N , int [ ] Q , int M ) { Dictionary < int , int > m1 = new Dictionary < int , int > ( ) ; Dictionary < int , int > m2 = new Dictionary < int , int > ( ) ; int front = 0 , rear = 0 ; for ( int i = 0 ; i < N ; i ++ ) { front += arr [ i ] ; m1 [ arr [ i ] ] = front ; } for ( int i = N - 1 ; i >= 0 ; i -- ) { rear += arr [ i ] ; m2 [ arr [ i ] ] = rear ; } for ( int i = 0 ; i < M ; i ++ ) { Console . Write ( Math . Min ( m1 [ Q [ i ] ] , m2 [ Q [ i ] ] ) + " ▁ " ) ; } } public static void Main ( ) { int [ ] arr = { 2 , 3 , 6 , 7 , 4 , 5 , 1 } ; int N = arr . Length ; int [ ] Q = { 7 , 6 } ; int M = Q . Length ; minOperations ( arr , N , Q , M ) ; } }


"Queries to find the minimum array sum possible by removing elements from either end | C # program for the above approach ; Function to find the minimum sum for each query after removing elements from either ends ; Traverse the query array ; Traverse the array from the front ; If element equals val , then break out of loop ; Traverse the array from rear ; If element equals val , break ; Print the minimum of the two as the answer ; Driver Code ; Function Call"
Solution in C#:

using System ; class GFG { static void minSum ( int [ ] arr , int N , int [ ] Q , int M ) { for ( int i = 0 ; i < M ; i ++ ) { int val = Q [ i ] ; int front = 0 , rear = 0 ; for ( int j = 0 ; j < N ; j ++ ) { front += arr [ j ] ; if ( arr [ j ] == val ) { break ; } } for ( int j = N - 1 ; j >= 0 ; j -- ) { rear += arr [ j ] ; if ( arr [ j ] == val ) { break ; } } Console . Write ( Math . Min ( front , rear ) + " ▁ " ) ; } } static public void Main ( ) { int [ ] arr = { 2 , 3 , 6 , 7 , 4 , 5 , 1 } ; int N = arr . Length ; int [ ] Q = { 7 , 6 } ; int M = Q . Length ; minSum ( arr , N , Q , M ) ; } }


"Queries to find the minimum index in a range [ L , R ] having at least value X with updates | C # program to implement the above approach ; Stores nodes value of the Tree ; Function to build segment tree ; Base Case ; Find the value of mid ; Update for left subtree ; Update for right subtree ; Update the value at the current index ; Function for finding the index of the first element at least x ; If current range does not lie in query range ; If current range is inside of query range ; Maximum value in this range is less than x ; Finding index of first value in this range ; Update the value of the minimum index ; Find mid of the current range ; Left subtree ; If it does not lie in left subtree ; Function for updating segment tree ; Update the value , we reached leaf node ; Find the mid ; If pos lies in the left subtree ; pos lies in the right subtree ; Update the maximum value in the range ; Function to print the answer for the given queries ; Build segment tree ; Find index of first value atleast 2 in range [ 0 , n - 1 ] ; Update value at index 2 to 5 ; Find index of first value atleast 4 in range [ 0 , n - 1 ] ; Find index of first value atleast 0 in range [ 0 , n - 1 ] ; Driver code ; Function Call"
Solution in C#:

using System ; class GFG { static int maxN = 100 ; static int [ ] Tree = new int [ 4 * maxN ] ; static void build ( int [ ] arr , int index , int s , int e ) { if ( s == e ) Tree [ index ] = arr [ s ] ; else { int m = ( s + e ) / 2 ; build ( arr , 2 * index , s , m ) ; build ( arr , 2 * index + 1 , m + 1 , e ) ; Tree [ index ] = Math . Max ( Tree [ 2 * index ] , Tree [ 2 * index + 1 ] ) ; } } static int atleast_x ( int index , int s , int e , int ql , int qr , int x ) { if ( ql > e qr < s ) return - 1 ; if ( s <= ql && e <= qr ) { if ( Tree [ index ] < x ) return - 1 ; while ( s != e ) { int m = ( s + e ) / 2 ; if ( Tree [ 2 * index ] >= x ) { e = m ; index = 2 * index ; } else { s = m + 1 ; index = 2 * index + 1 ; } } return s ; } int mm = ( s + e ) / 2 ; int val = atleast_x ( 2 * index , s , mm , ql , qr , x ) ; if ( val != - 1 ) return val ; return atleast_x ( 2 * index + 1 , mm + 1 , e , ql , qr , x ) ; } static void update ( int index , int s , int e , int new_val , int pos ) { if ( s == e ) Tree [ index ] = new_val ; else { int m = ( s + e ) / 2 ; if ( pos <= m ) { update ( 2 * index , s , m , new_val , pos ) ; } else { update ( 2 * index + 1 , m + 1 , e , new_val , pos ) ; } Tree [ index ] = Math . Max ( Tree [ 2 * index ] , Tree [ 2 * index + 1 ] ) ; } } static void printAnswer ( int [ ] arr , int n ) { build ( arr , 1 , 0 , n - 1 ) ; Console . WriteLine ( atleast_x ( 1 , 0 , n - 1 , 0 , n - 1 , 2 ) ) ; arr [ 2 ] = 5 ; update ( 1 , 0 , n - 1 , 5 , 2 ) ; Console . WriteLine ( atleast_x ( 1 , 0 , n - 1 , 0 , n - 1 , 4 ) ) ; Console . WriteLine ( atleast_x ( 1 , 0 , n - 1 , 0 , n - 1 , 0 ) ) ; } static void Main ( ) { int [ ] arr = { 1 , 3 , 2 , 4 , 6 } ; int N = arr . Length ; printAnswer ( arr , N ) ; } }


"Queries to find whether a number has exactly four distinct factors or not | C # program to check whether number has exactly four distinct factors or not ; Initialize global variable according to given condition so that it can be accessible to all function ; Function to calculate all number having four distinct distinct factors ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Initialize prime [ ] array which will contains all the primes from 1 - N ; Iterate over all the prime numbers ; Mark cube root of prime numbers ; Mark product of prime numbers ; Driver Code"
Solution in C#:

using System ; using System . Collections ; class GFG { static int N = ( int ) 1E6 ; static bool [ ] fourDiv = new bool [ N + 1 ] ; static void fourDistinctFactors ( ) { bool [ ] primeAll = new bool [ N + 1 ] ; for ( int p = 2 ; p * p <= N ; p ++ ) { if ( primeAll [ p ] == false ) { for ( int i = p * 2 ; i <= N ; i += p ) primeAll [ i ] = true ; } } ArrayList prime = new ArrayList ( ) ; for ( int p = 2 ; p <= N ; p ++ ) if ( ! primeAll [ p ] ) prime . Add ( p ) ; for ( int i = 0 ; i < prime . Count ; ++ i ) { int p = ( int ) prime [ i ] ; if ( 1L * p * p * p <= N ) fourDiv [ p * p * p ] = true ; for ( int j = i + 1 ; j < prime . Count ; ++ j ) { int q = ( int ) prime [ j ] ; if ( 1L * p * q > N ) break ; fourDiv [ p * q ] = true ; } } } public static void Main ( ) { fourDistinctFactors ( ) ; int num = 10 ; if ( fourDiv [ num ] ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; num = 12 ; if ( fourDiv [ num ] ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }


"Queries to flip characters of a binary string in given range | C # program to implement the above approach ; Function to find the binary String by performing all the given queries ; Stores length of the String ; prefixCnt [ i ] : Stores number of times str [ i ] toggled by performing all the queries ; Update prefixCnt [ Q [ i , 0 ] ] ; Update prefixCnt [ Q [ i , 1 ] + 1 ] ; Calculate prefix sum of prefixCnt [ i ] ; Traverse prefixCnt [ ] array ; If ith element toggled odd number of times ; Toggled i - th element of binary String ; Driver Code"
Solution in C#:

using System ; class GFG { static String toggleQuery ( char [ ] str , int [ , ] Q , int M ) { int N = str . Length ; int [ ] prefixCnt = new int [ N + 1 ] ; for ( int i = 0 ; i < M ; i ++ ) { prefixCnt [ Q [ i , 0 ] ] += 1 ; prefixCnt [ Q [ i , 1 ] + 1 ] -= 1 ; } for ( int i = 1 ; i <= N ; i ++ ) { prefixCnt [ i ] += prefixCnt [ i - 1 ] ; } for ( int i = 0 ; i < N ; i ++ ) { if ( prefixCnt [ i ] % 2 == 1 ) { str [ i ] = ( char ) ( '1' - str [ i ] + '0' ) ; } } return String . Join ( " " , str ) ; } public static void Main ( String [ ] args ) { String str = "101010" ; int [ , ] Q = { { 0 , 1 } , { 2 , 5 } , { 2 , 3 } , { 1 , 4 } , { 0 , 5 } } ; int M = Q . GetLength ( 0 ) ; Console . Write ( toggleQuery ( str . ToCharArray ( ) , Q , M ) ) ; } }


"Queries to replace every array element by its XOR with a given value with updates | C # program of the above approach ; Function to insert an element into the array ; Function to update every array element a [ i ] by a [ i ] ^ x ; Function to compute the final results after the operations ; Driver Code ; Queries ; Function Call"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static List < int > arr = new List < int > ( ) ; static int effect ; static void add ( int x ) { arr . Add ( x ) ; } static void update ( int x ) { effect = effect ^ x ; } static void computeResults ( ) { for ( int i = 0 ; i < arr . Count ; i ++ ) { arr [ i ] = arr [ i ] ^ effect ; Console . Write ( arr [ i ] + " ▁ " ) ; } } public static void Main ( String [ ] args ) { arr = new List < int > ( ) ; arr . Add ( 0 ) ; effect = 0 ; add ( 5 ) ; update ( 2 ) ; computeResults ( ) ; } }


"Queries to update array by adding or multiplying array elements and print the element present at specified index | C # program for the above approach ; Function to modify the array by performing given queries ; Stores the multiplication of all integers of type 1 ; Stores the value obtained after performing queries of type 1 & 2 ; Iterate over the queries ; Query of type 0 ; Update the value of add ; Query of type 1 ; Update the value of mul ; Update the value of add ; Otherwise ; Store the element at index Q [ i ] [ 1 ] ; Print the result for the current query ; Driver Code"
Solution in C#:

using System ; class GFG { static void Query ( int [ ] arr , int N , int [ , ] Q ) { int mul = 1 ; int add = 0 ; for ( int i = 0 ; i < Q . GetLength ( 0 ) ; i ++ ) { if ( Q [ i , 0 ] == 0 ) { add = add + Q [ i , 1 ] ; } else if ( Q [ i , 0 ] == 1 ) { mul = mul * Q [ i , 1 ] ; add = add * Q [ i , 1 ] ; } else { int ans = arr [ Q [ i , 1 ] ] * mul + add ; Console . Write ( ans + " ▁ " ) ; } } } public static void Main ( ) { int [ ] arr = { 3 , 1 , 23 , 45 , 100 } ; int N = arr . Length ; int [ , ] Q = { { 1 , 2 } , { 0 , 10 } , { 2 , 3 } , { 1 , 5 } , { 2 , 4 } } ; Query ( arr , N , Q ) ; } }


"Queries to update array elements in a range [ L , R ] to satisfy given conditions | C # program to implement the above approach ; Function to print the array ; Function to perform the query in range [ L , R ] such that arr [ i ] += i - L + 1 ; Initialize array ; Traverse the query array ; Stores range in 1 - based index ; Update arr1 [ L ] ; Update arr1 [ R + 1 ] ; Update arr2 [ R + 1 ] ; Calculate prefix sum ; Traverse the array , arr2 [ ] ; Copy arr2 [ ] into arr [ ] ; Driver Code ; Given array ; Size of the array ; Stores count of query ; Function Call"
Solution in C#:

using System ; class GFG { static void printArray ( int [ ] arr , int N ) { for ( int i = 0 ; i < N ; i ++ ) { Console . Write ( arr [ i ] + " ▁ " ) ; } } static void modifyArray ( int [ ] arr , int N , int [ , ] Q , int cntQuery ) { int [ ] arr1 = new int [ N + 2 ] ; int [ ] arr2 = new int [ N + 2 ] ; for ( int i = 0 ; i < cntQuery ; i ++ ) { int L = Q [ i , 0 ] + 1 , R = Q [ i , 1 ] + 1 ; arr1 [ L ] ++ ; arr1 [ R + 1 ] -- ; arr2 [ R + 1 ] -= R - L + 1 ; } for ( int i = 1 ; i <= N ; i ++ ) arr1 [ i ] += arr1 [ i - 1 ] ; for ( int i = 1 ; i <= N ; i ++ ) arr2 [ i ] += arr2 [ i - 1 ] + arr1 [ i ] ; for ( int i = 1 ; i <= N ; i ++ ) arr [ i - 1 ] = arr2 [ i ] ; printArray ( arr , N ) ; } public static void Main ( ) { int [ ] arr = { 0 , 0 , 0 , 0 } ; int N = arr . Length ; int [ , ] Q = { { 1 , 3 } , { 0 , 1 } } ; int cntQuery = 2 ; modifyArray ( arr , N , Q , cntQuery ) ; } }


"Query for ancestor | C # program to query whether two node has ancestor - descendant relationship or not ; Utility dfs method to assign in and out time to each node ; Assign In - time to node u ; Call dfs over all neighbors except parent ; Assign Out - time to node u ; Method to preprocess all nodes for assigning time ; Construct array of vector data structure for tree ; Call dfs method from root ; Method returns " yes " if u is a ancestor node of v ; Driver code"
Solution in C#:

 using System ; using System . Collections ; class GFG { static void dfs ( ArrayList [ ] g , int u , int parent , int [ ] timeIn , int [ ] timeOut , ref int cnt ) { timeIn [ u ] = cnt ++ ; for ( int i = 0 ; i < g [ u ] . Count ; i ++ ) { int v = ( int ) g [ u ] [ i ] ; if ( v != parent ) dfs ( g , v , u , timeIn , timeOut , ref cnt ) ; } timeOut [ u ] = cnt ++ ; } static void preProcess ( int [ , ] edges , int V , int [ ] timeIn , int [ ] timeOut ) { ArrayList [ ] g = new ArrayList [ V ] ; for ( int i = 0 ; i < V ; i ++ ) { g [ i ] = new ArrayList ( ) ; } for ( int i = 0 ; i < V - 1 ; i ++ ) { int u = edges [ i , 0 ] ; int v = edges [ i , 1 ] ; g [ u ] . Add ( v ) ; g [ v ] . Add ( u ) ; } int cnt = 0 ; dfs ( g , 0 , - 1 , timeIn , timeOut , ref cnt ) ; } static string isAncestor ( int u , int v , int [ ] timeIn , int [ ] timeOut ) { bool b = ( timeIn [ u ] <= timeIn [ v ] && timeOut [ v ] <= timeOut [ u ] ) ; return ( b ? " yes " : " no " ) ; } static void Main ( ) { int [ , ] edges = { { 0 , 1 } , { 0 , 2 } , { 1 , 3 } , { 1 , 4 } , { 2 , 5 } , { 4 , 6 } , { 5 , 7 } } ; int E = edges . GetLength ( 0 ) ; int V = E + 1 ; int [ ] timeIn = new int [ V ] ; int [ ] timeOut = new int [ V ] ; preProcess ( edges , V , timeIn , timeOut ) ; int u = 1 ; int v = 6 ; Console . Write ( isAncestor ( u , v , timeIn , timeOut ) + "
 " ) ; u = 1 ; v = 7 ; Console . Write ( isAncestor ( u , v , timeIn , timeOut ) + "
 " ) ; } }


"Query to find length of the longest subarray consisting only of 1 s | C # Program for the above approach ; Arrays to store prefix sums , suffix and MAX 's node respectively ; Function to conSegment Tree ; MAX array for node MAX ; Array for prefix sum node ; Array for suffix sum node ; Calculate MAX node ; Function to update Segment Tree ; Update at position ; Update sums from bottom to the top of Segment Tree ; Update MAX tree ; Update pref tree ; Update suf tree ; Function to perform given queries ; Stores count of queries ; Traverse each query ; Print longest length of subarray in [ 1 , N ] ; Flip the character ; Driver Code ; Size of array ; Given array ; Given queries ; Number of queries"
Solution in C#:

using System ; class GFG { static readonly int INF = 1000000 ; static int [ ] pref = new int [ 500005 ] ; static int [ ] suf = new int [ 500005 ] ; static int [ ] MAX = new int [ 500005 ] ; static void build ( int [ ] a , int tl , int tr , int v ) { if ( tl == tr ) { MAX [ v ] = a [ tl ] ; pref [ v ] = a [ tl ] ; suf [ v ] = a [ tl ] ; } else { int tm = ( tl + tr ) / 2 ; build ( a , tl , tm , v * 2 ) ; build ( a , tm + 1 , tr , v * 2 + 1 ) ; MAX [ v ] = Math . Max ( MAX [ v * 2 ] , Math . Max ( MAX [ v * 2 + 1 ] , suf [ v * 2 ] + pref [ v * 2 + 1 ] ) ) ; pref [ v ] = Math . Max ( pref [ v * 2 ] , pref [ 2 * v ] + ( pref [ 2 * v ] == ( tm - tl + 1 ) ? 1 : 0 ) * pref [ v * 2 + 1 ] ) ; suf [ v ] = Math . Max ( suf [ v * 2 + 1 ] , suf [ 2 * v + 1 ] + suf [ v * 2 ] * ( suf [ 2 * v + 1 ] == ( tr - tm ) ? 1 : 0 ) ) ; } } static void update ( int [ ] a , int pos , int tl , int tr , int v ) { if ( tl > pos tr < pos ) { return ; } if ( tl == tr && tl == pos ) { MAX [ v ] = a [ pos ] ; pref [ v ] = a [ pos ] ; suf [ v ] = a [ pos ] ; } else { int tm = ( tl + tr ) / 2 ; update ( a , pos , tl , tm , v * 2 ) ; update ( a , pos , tm + 1 , tr , v * 2 + 1 ) ; MAX [ v ] = Math . Max ( MAX [ v * 2 ] , Math . Max ( MAX [ v * 2 + 1 ] , suf [ v * 2 ] + pref [ v * 2 + 1 ] ) ) ; pref [ v ] = Math . Max ( pref [ v * 2 ] , pref [ 2 * v ] + ( pref [ 2 * v ] == ( tm - tl + 1 ) ? 1 : 0 ) * pref [ v * 2 + 1 ] ) ; suf [ v ] = Math . Max ( suf [ v * 2 + 1 ] , suf [ 2 * v + 1 ] + ( suf [ 2 * v + 1 ] == ( tr - tm ) ? 1 : 0 ) * suf [ v * 2 ] ) ; } } static void solveQueries ( int [ ] arr , int n , int [ , ] Q , int k ) { int cntQuery = Q . GetLength ( 0 ) ; build ( arr , 0 , n - 1 , 1 ) ; for ( int i = 0 ; i < cntQuery ; i ++ ) { if ( Q [ i , 0 ] == 1 ) { Console . Write ( MAX [ 1 ] + " ▁ " ) ; } else { arr [ Q [ i , 1 ] - 1 ] ^= 1 ; update ( arr , Q [ i , 1 ] - 1 , 0 , n - 1 , 1 ) ; } } } public static void Main ( String [ ] args ) { int N = 10 ; int [ ] arr = { 1 , 1 , 0 , 1 , 1 , 1 , 0 , 0 , 1 , 1 } ; int [ , ] Q = { { 1 , 0 } , { 2 , 3 } ,...


"Query to find length of the longest subarray consisting only of 1 s | C # Program for the above approach ; Function to calculate the longest subarray consisting of 1 s only ; Stores the maximum length of subarray containing 1 s only ; Traverse the array ; If current element is '1' ; Increment length ; Otherwise ; Reset length ; Update maximum subarray length ; Function to perform given queries ; Stores count of queries ; Traverse each query ; Flip the character ; Driver code ; Size of array ; Given array ; Given queries ; Number of queries"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static int longestsubarray ( int [ ] a , int N ) { int maxlength = 0 , sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( a [ i ] == 1 ) { sum ++ ; } else { sum = 0 ; } maxlength = Math . Max ( maxlength , sum ) ; } return maxlength ; } static void solveQueries ( int [ ] arr , int n , List < List < int > > Q , int k ) { int cntQuery = Q . Count ; for ( int i = 0 ; i < cntQuery ; i ++ ) { if ( Q [ i ] [ 0 ] == 1 ) { Console . Write ( longestsubarray ( arr , n ) + " ▁ " ) ; } else { arr [ Q [ i ] [ 1 ] - 1 ] ^= 1 ; } } } static void Main ( ) { int N = 10 ; int [ ] arr = { 1 , 1 , 0 , 1 , 1 , 1 , 0 , 0 , 1 , 1 } ; List < List < int > > Q = new List < List < int > > ( ) ; Q . Add ( new List < int > { 1 } ) ; Q . Add ( new List < int > { 2 , 3 } ) ; Q . Add ( new List < int > { 1 } ) ; int K = 3 ; solveQueries ( arr , N , Q , K ) ; } }


"Query to find the maximum and minimum weight between two nodes in the given tree using LCA . | C # Program to find the maximum and minimum weight between two nodes in the given tree using LCA ; Math . Log ( MAX ) ; Array to store the level of each node ; List to store tree ; Array to store weight of nodes ; Pre - Processing to calculate values of lca [ , ] , MinWeight [ , ] and MaxWeight [ , ] ; Using recursion formula to calculate the values of lca [ , ] ; Storing the level of each node ; Using recursion formula to calculate the values of lca [ , ] , MinWeight [ , ] and MaxWeight [ , ] ; Function to find the minimum and maximum weights in the given range ; The node which is present farthest from the root node is taken as v If u is farther from root node then swap the two ; Finding the ancestor of v which is at same level as u ; Calculating Minimum and Maximum Weight of node v till its 2 ^ i - th ancestor ; If u is the ancestor of v then u is the LCA of u and v ; Finding the node closest to the root which is not the common ancestor of u and v i . e . a node x such that x is not the common ancestor of u and v but lca [ x , 0 ] is ; Calculating the minimum of MinWeight of v to its 2 ^ i - th ancestor and MinWeight of u to its 2 ^ i - th ancestor ; Calculating the maximum of MaxWeight of v to its 2 ^ i - th ancestor and MaxWeight of u to its 2 ^ i - th ancestor ; Calculating the Minimum of first ancestor of u and v ; Calculating the maximum of first ancestor of u and v ; Driver Code ; Number of nodes ; Add edges ; Initialising lca values with - 1 Initialising MinWeight values with int . MaxValue Initialising MaxWeight values with int . MinValue ; Perform DFS ; Query 1 : { 1 , 3 } ; Query 2 : { 2 , 4 } ; Query 3 : { 3 , 5 }"
Solution in C#:

 using System ; using System . Collections . Generic ; class GFG { static readonly int MAX = 1000 ; static readonly int log = 10 ; static int [ ] level = new int [ MAX ] ; static int [ , ] lca = new int [ MAX , log ] ; static int [ , ] minWeight = new int [ MAX , log ] ; static int [ , ] maxWeight = new int [ MAX , log ] ; static List < int > [ ] graph = new List < int > [ MAX ] ; static int [ ] weight = new int [ MAX ] ; private static void swap ( int x , int y ) { int temp = x ; x = y ; y = temp ; } static void addEdge ( int u , int v ) { graph [ u ] . Add ( v ) ; graph [ v ] . Add ( u ) ; } static void dfs ( int node , int parent , int h ) { lca [ node , 0 ] = parent ; level [ node ] = h ; if ( parent != - 1 ) { minWeight [ node , 0 ] = Math . Min ( weight [ node ] , weight [ parent ] ) ; maxWeight [ node , 0 ] = Math . Max ( weight [ node ] , weight [ parent ] ) ; } for ( int i = 1 ; i < log ; i ++ ) { if ( lca [ node , i - 1 ] != - 1 ) { lca [ node , i ] = lca [ lca [ node , i - 1 ] , i - 1 ] ; minWeight [ node , i ] = Math . Min ( minWeight [ node , i - 1 ] , minWeight [ lca [ node , i - 1 ] , i - 1 ] ) ; maxWeight [ node , i ] = Math . Max ( maxWeight [ node , i - 1 ] , maxWeight [ lca [ node , i - 1 ] , i - 1 ] ) ; } } foreach ( int i in graph [ node ] ) { if ( i == parent ) continue ; dfs ( i , node , h + 1 ) ; } } static void findMinMaxWeight ( int u , int v ) { int minWei = int . MaxValue ; int maxWei = int . MinValue ; if ( level [ u ] > level [ v ] ) swap ( u , v ) ; for ( int i = log - 1 ; i >= 0 ; i -- ) { if ( lca [ v , i ] != - 1 && level [ lca [ v , i ] ] >= level [ u ] ) { minWei = Math . Min ( minWei , minWeight [ v , i ] ) ; maxWei = Math . Max ( maxWei , maxWeight [ v , i ] ) ; v = lca [ v , i ] ; } } if ( v == u ) { Console . Write ( minWei + " ▁ " + maxWei + "
 " ) ; } else { for ( int i = log - 1 ; i >= 0 ; i -- ) { if ( v == - 1 ) v ++ ; if ( lca [ v , i ] != lca [ u , i ] ) { minWei = Math . Min ( minWei , Math . Min ( minWeight [ v , i ] , minWeight [ u , i ] ) ) ; maxWei = Math ....


"Querying maximum number of divisors that a number in a given range has | C # implementation of the above idea to process queries of finding a number with maximum divisors . ; Finds smallest prime factor of all numbersin range [ 1 , maxn ) and stores them in smallest_prime [ ] , smallest_prime [ i ] should contain the smallest prime that divides i ; Initialize the smallest_prime factors of all to infinity ; to be built like eratosthenes sieve ; prime number will have its smallest_prime equal to itself ; if ' i ' is the first prime number reaching ' j ' ; number of divisors of n = ( p1 ^ k1 ) * ( p2 ^ k2 ) . . . ( pn ^ kn ) are equal to ( k1 + 1 ) * ( k2 + 1 ) . . . ( kn + 1 ) this function finds the number of divisorsof all numbers in range [ 1 , maxn ) and stores it in divisors [ ] divisors [ i ] stores the number of divisors i has ; we can obtain the prime factorization of the number n , n = ( p1 ^ k1 ) * ( p2 ^ k2 ) . . . ( pn ^ kn ) using the smallest_prime [ ] array , we keep dividing n by its smallest_prime until it becomes 1 , whilst we check if we have need to set k zero ; use p ^ k , initialize k to 0 ; builds segment tree for divisors [ ] array ; leaf node ; build left and right subtree ; combine the information from left and right subtree at current node ; returns the maximum number of divisors in [ l , r ] ; If current node 's range is disjoint  with query range ; If the current node stores information for the range that is completely inside the query range ; Returns maximum number of divisors from left or right subtree ; Driver Code ; First find smallest prime divisors for all the numbers ; Then build the divisors [ ] array to store the number of divisors ; Build segment tree for the divisors [ ] array"
Solution in C#:

using System ; class GFG { static int maxn = 10005 ; static int INF = 999999 ; static int [ ] smallest_prime = new int [ maxn ] ; static int [ ] divisors = new int [ maxn ] ; static int [ ] segmentTree = new int [ 4 * maxn ] ; static void findSmallestPrimeFactors ( ) { for ( int i = 0 ; i < maxn ; i ++ ) smallest_prime [ i ] = INF ; for ( int i = 2 ; i < maxn ; i ++ ) { if ( smallest_prime [ i ] == INF ) { smallest_prime [ i ] = i ; for ( int j = i * i ; j < maxn ; j += i ) if ( smallest_prime [ j ] > i ) smallest_prime [ j ] = i ; } } } static void buildDivisorsArray ( ) { for ( int i = 1 ; i < maxn ; i ++ ) { divisors [ i ] = 1 ; int n = i , p = smallest_prime [ i ] , k = 0 ; while ( n > 1 ) { n = n / p ; k ++ ; if ( smallest_prime [ n ] != p ) { divisors [ i ] = divisors [ i ] * ( k + 1 ) ; k = 0 ; } p = smallest_prime [ n ] ; } } } static void buildSegtmentTree ( int node , int a , int b ) { if ( a == b ) { segmentTree [ node ] = divisors [ a ] ; return ; } buildSegtmentTree ( 2 * node , a , ( a + b ) / 2 ) ; buildSegtmentTree ( 2 * node + 1 , ( ( a + b ) / 2 ) + 1 , b ) ; segmentTree [ node ] = Math . Max ( segmentTree [ 2 * node ] , segmentTree [ 2 * node + 1 ] ) ; } static int query ( int node , int a , int b , int l , int r ) { if ( l > b a > r ) return - 1 ; if ( a >= l && b <= r ) return segmentTree [ node ] ; return Math . Max ( query ( 2 * node , a , ( a + b ) / 2 , l , r ) , query ( 2 * node + 1 , ( ( a + b ) / 2 ) + 1 , b , l , r ) ) ; } public static void Main ( String [ ] args ) { findSmallestPrimeFactors ( ) ; buildDivisorsArray ( ) ; buildSegtmentTree ( 1 , 1 , maxn - 1 ) ; Console . WriteLine ( " Maximum ▁ divisors ▁ that ▁ a ▁ number ▁ " + " has ▁ in ▁ [ 1 , ▁ 100 ] ▁ are ▁ " + query ( 1 , 1 , maxn - 1 , 1 , 100 ) ) ; Console . WriteLine ( " Maximum ▁ divisors ▁ that ▁ a ▁ number ▁ " + " has ▁ in ▁ [ 10 , ▁ 48 ] ▁ are ▁ " + query ( 1 , 1 , maxn - 1 , 10 , 48 ) ) ; Console . WriteLine ( " Maximum ▁ divisors ▁ that ▁ a ▁ number ▁ " + " has ▁ in ▁ [ 1 , ▁ 10 ] ▁ are ▁ " + query ( 1 , 1 , maxn...


"Queue using Stacks | C # program to implement Queue using two stacks with costly enQueue ( ) ; Move all elements from s1 to s2 ; Push item into s1 ; Push everything back to s1 ; Dequeue an item from the queue ; if first stack is empty ; Return top of s1 ; Driver code"
Solution in C#:

using System ; using System . Collections ; class GFG { public class Queue { public Stack s1 = new Stack ( ) ; public Stack s2 = new Stack ( ) ; public void enQueue ( int x ) { while ( s1 . Count > 0 ) { s2 . Push ( s1 . Pop ( ) ) ; s1 . Pop ( ) ; } s1 . Push ( x ) ; while ( s2 . Count > 0 ) { s1 . Push ( s2 . Pop ( ) ) ; s2 . Pop ( ) ; } } public int deQueue ( ) { if ( s1 . Count == 0 ) { Console . WriteLine ( " Q ▁ is ▁ Empty " ) ; } int x = ( int ) s1 . Peek ( ) ; s1 . Pop ( ) ; return x ; } } ; public static void Main ( ) { Queue q = new Queue ( ) ; q . enQueue ( 1 ) ; q . enQueue ( 2 ) ; q . enQueue ( 3 ) ; Console . Write ( q . deQueue ( ) + " ▁ " ) ; Console . Write ( q . deQueue ( ) + " ▁ " ) ; Console . Write ( q . deQueue ( ) ) ; } }


"Quick way to check if all the characters of a string are same | C # program for above approach ; Function to check is all the characters in string are or not ; Insert characters in the set ; If all characters are same Size of set will always be 1 ; Driver code"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static void allCharactersSame ( string s ) { HashSet < char > s1 = new HashSet < char > ( ) ; for ( int i = 0 ; i < s . Length ; i ++ ) s1 . Add ( s [ i ] ) ; if ( s1 . Count == 1 ) Console . WriteLine ( " YES " ) ; else Console . WriteLine ( " NO " ) ; } static void Main ( ) { string str = " nnnn " ; allCharactersSame ( str ) ; } }


"QuickSelect ( A Simple Iterative Implementation ) | C # program for iterative implementation of QuickSelect ; Standard Lomuto partition function ; Implementation of QuickSelect ; Partition a [ left . . right ] around a pivot and find the position of the pivot ; If pivot itself is the k - th smallest element ; If there are more than k - 1 elements on left of pivot , then k - th smallest must be on left side . ; Else k - th smallest is on right side . ; Driver Code"
Solution in C#:

using System ; class GFG { static int partition ( int [ ] arr , int low , int high ) { int temp ; int pivot = arr [ high ] ; int i = ( low - 1 ) ; for ( int j = low ; j <= high - 1 ; j ++ ) { if ( arr [ j ] <= pivot ) { i ++ ; temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; } } temp = arr [ i + 1 ] ; arr [ i + 1 ] = arr [ high ] ; arr [ high ] = temp ; return ( i + 1 ) ; } static int kthSmallest ( int [ ] a , int left , int right , int k ) { while ( left <= right ) { int pivotIndex = partition ( a , left , right ) ; if ( pivotIndex == k - 1 ) return a [ pivotIndex ] ; else if ( pivotIndex > k - 1 ) right = pivotIndex - 1 ; else left = pivotIndex + 1 ; } return - 1 ; } public static void Main ( String [ ] args ) { int [ ] arr = { 10 , 4 , 5 , 8 , 11 , 6 , 26 } ; int n = arr . Length ; int k = 5 ; Console . WriteLine ( " K - th ▁ smallest ▁ element ▁ is ▁ " + kthSmallest ( arr , 0 , n - 1 , k ) ) ; } }


"QuickSort Tail Call Optimization ( Reducing worst case space to Log n ) | A Simple implementation of QuickSort that makes two recursive calls . ; pi is partitioning index , arr [ p ] is now at right place ; Separately sort elements before partition and after partition"
Solution in C#:

static void quickSort ( int [ ] arr , int low , int high ) { if ( low < high ) { int pi = partition ( arr , low , high ) ; quickSort ( arr , low , pi - 1 ) ; quickSort ( arr , pi + 1 , high ) ; } }


"Quickly find multiple left rotations of an array | Set 1 | C # implementation of left rotation of an array K number of times ; Fills temp [ ] with two copies of arr [ ] ; Store arr [ ] elements at i and i + n ; Function to left rotate an array k time ; Starting position of array after k rotations in temp [ ] will be k % n ; Print array after k rotations ; Driver program"
Solution in C#:

using System ; class LeftRotate { static void preprocess ( int [ ] arr , int n , int [ ] temp ) { for ( int i = 0 ; i < n ; i ++ ) temp [ i ] = temp [ i + n ] = arr [ i ] ; } static void leftRotate ( int [ ] arr , int n , int k , int [ ] temp ) { int start = k % n ; for ( int i = start ; i < start + n ; i ++ ) Console . Write ( temp [ i ] + " ▁ " ) ; Console . WriteLine ( ) ; } public static void Main ( ) { int [ ] arr = { 1 , 3 , 5 , 7 , 9 } ; int n = arr . Length ; int [ ] temp = new int [ 2 * n ] ; preprocess ( arr , n , temp ) ; int k = 2 ; leftRotate ( arr , n , k , temp ) ; k = 3 ; leftRotate ( arr , n , k , temp ) ; k = 4 ; leftRotate ( arr , n , k , temp ) ; } }


"Quickly find multiple left rotations of an array | Set 1 | C # implementation of left rotation of an array K number of times ; Function to left rotate an array k times ; Print array after k rotations ; Driver Code"
Solution in C#:

using System ; class GFG { static void leftRotate ( int [ ] arr , int n , int k ) { for ( int i = k ; i < k + n ; i ++ ) Console . Write ( arr [ i % n ] + " ▁ " ) ; } static public void Main ( ) { int [ ] arr = { 1 , 3 , 5 , 7 , 9 } ; int n = arr . Length ; int k = 2 ; leftRotate ( arr , n , k ) ; Console . WriteLine ( ) ; k = 3 ; leftRotate ( arr , n , k ) ; Console . WriteLine ( ) ; k = 4 ; leftRotate ( arr , n , k ) ; Console . WriteLine ( ) ; } }