text
stringlengths
17
3.65k
code
stringlengths
60
5.26k
Minimum characters to be replaced to make a string concatenation of a K | C # program for the above approach ; Function to add an edge to graph ; Function to perform DFS traversal on the graph recursively from a given vertex u ; Visit the current vertex ; Total number of nodes in this component ; Increment the frequency of u ; Function for finding the minimum number changes required in given String ; Form the edges according to the given conditions ; Find minimum number of operations ; Frequency array for finding the most frequent character ; Frequency array for finding the most frequent character ; Finding most frequent character ; Change rest of the characters to most frequent one ; Print total number of changes ; Driver Code ; Function Call
using System ; using System . Collections . Generic ; class GFG { static void addEdge ( List < int > [ ] adj , int u , int v ) { adj [ u ] . Add ( v ) ; adj [ v ] . Add ( u ) ; } static int cnt = 0 ; static bool [ ] visited ; static void DFS ( int u , List < int > [ ] adj , int [ ] fre , String S ) { visited [ u ] = true ; cnt ++ ; fre [ S [ u ] - ' a ' ] ++ ; for ( int i = 0 ; i < adj [ u ] . Count ; i ++ ) { if ( ! visited [ adj [ u ] [ i ] ] ) { DFS ( adj [ u ] [ i ] , adj , fre , S ) ; } } } static void minimumOperations ( String S , int m ) { int V = 100 ; List < int > [ ] adj = new List < int > [ V ] ; int total = 0 , N = S . Length ; for ( int i = 0 ; i < adj . Length ; i ++ ) adj [ i ] = new List < int > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { addEdge ( adj , i , N - i - 1 ) ; addEdge ( adj , N - i - 1 , i ) ; } for ( int i = 0 ; i < N - m ; i ++ ) { addEdge ( adj , i , i + m ) ; addEdge ( adj , i + m , i ) ; } visited = new bool [ V ] ; for ( int i = 0 ; i < N ; i ++ ) { if ( ! visited [ i ] ) { int [ ] fre = new int [ 26 ] ; cnt = 0 ; int maxx = - 1 ; DFS ( i , adj , fre , S ) ; for ( int j = 0 ; j < 26 ; j ++ ) maxx = Math . Max ( maxx , fre [ j ] ) ; total += cnt - maxx ; } } Console . Write ( total ) ; } public static void Main ( String [ ] args ) { String S = " abaaba " ; int K = 2 ; minimumOperations ( S , K ) ; } }
Replace specified matrix elements such that no two adjacent elements are equal | C # program for the above approach ; Function to display the valid matrix ; Traverse the matrix ; If the current cell is a free space and is even - indexed ; If the current cell is a free space and is odd - indexed ; Print the matrix ; Driver Code ; Given N and M ; Given matrix ; Function call
using System ; class GFG { public static void print ( char [ , ] arr , int n , int m ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { char a = arr [ i , j ] ; if ( ( i + j ) % 2 == 0 && a == ' F ' ) { arr [ i , j ] = '1' ; } else if ( a == ' F ' ) { arr [ i , j ] = '2' ; } } } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { Console . Write ( arr [ i , j ] ) ; } Console . WriteLine ( ) ; } } public static void Main ( ) { int n = 4 , m = 4 ; char [ , ] arr = { { ' F ' , ' F ' , ' F ' , ' F ' } , { ' F ' , ' O ' , ' F ' , ' F ' } , { ' F ' , ' F ' , ' O ' , ' F ' } , { ' F ' , ' F ' , ' F ' , ' F ' } } ; print ( arr , n , m ) ; } }
Lexicographically smallest string formed by removing duplicates | C # program for the above approach ; Function that finds lexicographically smallest string after removing the duplicates from the given string ; Stores the frequency of characters ; Mark visited characters ; Stores count of each character ; Stores the resultant string ; Decrease the count of current character ; If character is not already in answer ; Last character > S [ i ] and its count > 0 ; Mark letter unvisited ; Add s [ i ] in res and mark it visited ; Return the resultant string ; Driver Code ; Given string S ; Function Call
using System ; class GFG { static string removeDuplicateLetters ( string s ) { int [ ] cnt = new int [ 26 ] ; int [ ] vis = new int [ 26 ] ; int n = s . Length ; for ( int i = 0 ; i < n ; i ++ ) cnt [ s [ i ] - ' a ' ] ++ ; String res = " " ; for ( int i = 0 ; i < n ; i ++ ) { cnt [ s [ i ] - ' a ' ] -- ; if ( vis [ s [ i ] - ' a ' ] == 0 ) { int size = res . Length ; while ( size > 0 && res [ size - 1 ] > s [ i ] && cnt [ res [ size - 1 ] - ' a ' ] > 0 ) { vis [ res [ size - 1 ] - ' a ' ] = 0 ; res = res . Substring ( 0 , size - 1 ) ; size -- ; } res += s [ i ] ; vis [ s [ i ] - ' a ' ] = 1 ; } } return res ; } public static void Main ( ) { string S = " acbc " ; Console . WriteLine ( removeDuplicateLetters ( S ) ) ; } }
Number of pairs whose product is a power of 2 | C # program for the above approach ; Function to count pairs having product equal to a power of 2 ; Stores count of array elements which are power of 2 ; If array element contains only one set bit ; Increase count of powers of 2 ; Count required number of pairs ; Print the required number of pairs ; Driver Code ; Given array ; Size of the array ; Function call
using System ; using System . Linq ; class GFG { static void countPairs ( int [ ] arr , int N ) { int countPowerof2 = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( ( Convert . ToString ( arr [ i ] , 2 ) ) . Count ( f => ( f == '1' ) ) == 1 ) countPowerof2 ++ ; } int desiredPairs = ( countPowerof2 * ( countPowerof2 - 1 ) ) / 2 ; Console . WriteLine ( desiredPairs + " ▁ " ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , 4 , 7 , 2 } ; int N = arr . Length ; countPairs ( arr , N ) ; } }
Count ways to split N ! into two distinct co | C # program for the above approach ; Maximum value of N ; Stores at each indices if given number is prime or not ; Stores count_of_primes ; Function to generate primes using Sieve of Eratsothenes ; Assume all odds are primes ; If a prime is encountered ; MArk all its multiples as non - prime ; Count all primes upto MAXN ; Function to calculate ( x ^ y ) % p in O ( log y ) ; Utility function to count the number of ways N ! can be split into two co - prime factors ; Driver Code ; Calling sieve function ; Given N ; Function call
using System ; class GFG { static int MAXN = 1000000 ; static int [ ] is_prime ; static int [ ] count_of_primes ; static void sieve ( ) { is_prime = new int [ MAXN ] ; count_of_primes = new int [ MAXN ] ; Array . Fill ( is_prime , 0 ) ; Array . Fill ( count_of_primes , 0 ) ; for ( int i = 3 ; i < MAXN ; i += 2 ) { is_prime [ i ] = 1 ; } for ( int i = 3 ; i * i < MAXN ; i += 2 ) { if ( is_prime [ i ] == 1 ) { for ( int j = i * i ; j < MAXN ; j += i ) { is_prime [ j ] = 0 ; } } } is_prime [ 2 ] = 1 ; for ( int i = 1 ; i < MAXN ; i ++ ) count_of_primes [ i ] = count_of_primes [ i - 1 ] + is_prime [ i ] ; } static long power ( long x , long y , long p ) { long result = 1 ; while ( y > 0 ) { if ( ( y & 1 ) == 1 ) result = ( result * x ) % p ; x = ( x * x ) % p ; y >>= 1 ; } return result ; } static void numberOfWays ( int N ) { long count = count_of_primes [ N ] - 1 ; long mod = 1000000007 ; long answer = power ( 2 , count , mod ) ; if ( N == 1 ) answer = 0 ; long ans = answer ; Console . Write ( ans ) ; } public static void Main ( ) { sieve ( ) ; int N = 7 ; numberOfWays ( N ) ; } }
Maximum possible sum of squares of stack elements satisfying the given properties | C # program to implement the above approach ; Function to find the maximum sum of squares of stack elements ; Stores the sum ofsquares of stack elements ; Check if sum is valid ; Initialize all stack elements with 1 ; Stores the count the number of stack elements not equal to 1 ; Add the sum of squares of stack elements not equal to 1 ; Add 1 * 1 to res as the remaining stack elements are 1 ; Print the result ; Driver Code ; Function call
using System ; class GFG { public static void maxSumOfSquares ( int N , int S ) { int res = 0 ; if ( S < N S > 9 * N ) { Console . WriteLine ( - 1 ) ; return ; } S = S - N ; int c = 0 ; while ( S > 0 ) { c ++ ; if ( S / 8 > 0 ) { res += 9 * 9 ; S -= 8 ; } else { res += ( S + 1 ) * ( S + 1 ) ; break ; } } res = res + ( N - c ) ; Console . WriteLine ( res ) ; } public static void Main ( String [ ] args ) { int N = 3 ; int S = 12 ; maxSumOfSquares ( N , S ) ; } }
Unset least significant K bits of a given number | C # program for the above approach ; Function to return the value after unsetting K LSBs ; Create a mask ; Bitwise AND operation with the number and the mask ; Driver Code ; Given N and K ; Function Call
using System ; class GFG { static int clearLastBit ( int N , int K ) { int mask = ( - 1 << K + 1 ) ; return N = N & mask ; } public static void Main ( String [ ] args ) { int N = 730 , K = 3 ; Console . Write ( clearLastBit ( N , K ) ) ; } }
Check if quantities of 3 distinct colors can be converted to a single color by given merge | C # program for the above approach ; Function to check whether it is possible to do the operation or not ; Calculate modulo 3 of all the colors ; Check for any equal pair ; Otherwise ; Driver Code ; Given colors ; Function Call
using System ; class GFG { static bool isPossible ( int r , int b , int g ) { r = r % 3 ; b = b % 3 ; g = g % 3 ; if ( r == b b == g g == r ) { return true ; } else { return false ; } } public static void Main ( String [ ] args ) { int R = 1 , B = 3 , G = 6 ; if ( isPossible ( R , B , G ) ) { Console . Write ( " Yes " + " STRNEWLINE " ) ; } else { Console . Write ( " No " + " STRNEWLINE " ) ; } } }
Minimize steps required to make all array elements same by adding 1 , 2 or 5 | C # program for the above approach ; Function to calculate the minimum number of steps ; count stores number of operations required to make all elements equal to minimum value ; Remark , the array should remain unchanged for further calculations with different minimum ; Storing the current value of arr [ i ] in val ; Finds how much extra amount is to be removed ; Subtract the maximum number of 5 and stores remaining ; Subtract the maximum number of 2 and stores remaining ; Restores the actual value of arr [ i ] ; Return the count ; Function to find the minimum number of steps to make array elements same ; Sort the array in descending order ; Stores the minimum array element ; Stores the operations required to make array elements equal to minimum ; Stores the operations required to make array elements equal to minimum - 1 ; Stores the operations required to make array elements equal to minimum - 2 ; Return minimum of the three counts ; Driver Code
using System ; public class GFG { static int calculate_steps ( int [ ] arr , int n , int minimum ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int val = arr [ i ] ; if ( arr [ i ] > minimum ) { arr [ i ] = arr [ i ] - minimum ; count += arr [ i ] / 5 ; arr [ i ] = arr [ i ] % 5 ; count += arr [ i ] / 2 ; arr [ i ] = arr [ i ] % 2 ; if ( arr [ i ] > 0 ) { count ++ ; } } arr [ i ] = val ; } return count ; } static int solve ( int [ ] arr , int n ) { Array . Sort ( arr ) ; Array . Reverse ( arr ) ; int minimum = arr [ n - 1 ] ; int count1 = 0 , count2 = 0 , count3 = 0 ; count1 = calculate_steps ( arr , n , minimum ) ; count2 = calculate_steps ( arr , n , minimum - 1 ) ; count3 = calculate_steps ( arr , n , minimum - 2 ) ; return Math . Min ( count1 , Math . Min ( count2 , count3 ) ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 3 , 6 , 6 } ; int N = arr . Length ; Console . Write ( solve ( arr , N ) ) ; } }
Largest palindromic string possible from given strings by rearranging the characters | C # program for the above approach ; Function to find largest palindrome possible from S and P after rearranging characters to make palindromic string T ; Using unordered_map to store frequency of elements mapT will have freq of elements of T ; Size of both the strings ; Take all character in mapT which occur even number of times in respective strings & simultaneously update number of characters left in map ; Check if a unique character is present in both string S and P ; Making string T in two halves half1 - first half half2 - second half ; Reverse the half2 to attach with half1 to make palindrome T ; If same unique element is present in both S and P , then taking that only which is already taken through mapT ; If same unique element is not present in S and P , then take characters that make string T lexicographically smallest ; If no unique element is present in both string S and P ; Driver Code ; Given two strings S and P ; Function call
using System ; using System . Collections . Generic ; using System . Text ; class GFG { static string mergePalindromes ( string S , string P ) { Dictionary < char , int > mapS = new Dictionary < char , int > ( ) ; Dictionary < char , int > mapP = new Dictionary < char , int > ( ) ; Dictionary < char , int > mapT = new Dictionary < char , int > ( ) ; int n = S . Length , m = P . Length ; for ( char i = ' a ' ; i <= ' z ' ; i ++ ) { mapS [ i ] = 0 ; mapP [ i ] = 0 ; mapT [ i ] = 0 ; } for ( int i = 0 ; i < n ; i ++ ) { mapS [ S [ i ] ] ++ ; } for ( int i = 0 ; i < m ; i ++ ) { mapP [ P [ i ] ] ++ ; } for ( char i = ' a ' ; i <= ' z ' ; i ++ ) { if ( mapS [ i ] % 2 == 0 ) { mapT [ i ] += mapS [ i ] ; mapS [ i ] = 0 ; } else { mapT [ i ] += mapS [ i ] - 1 ; mapS [ i ] = 1 ; } if ( mapP [ i ] % 2 == 0 ) { mapT [ i ] += mapP [ i ] ; mapP [ i ] = 0 ; } else { mapT [ i ] += mapP [ i ] - 1 ; mapP [ i ] = 1 ; } } int check = 0 ; for ( char i = ' a ' ; i <= ' z ' ; i ++ ) { if ( mapS [ i ] > 0 && mapP [ i ] > 0 ) { mapT [ i ] += 2 ; check = 1 ; break ; } } string half1 = " " , half2 = " " ; for ( char i = ' a ' ; i <= ' z ' ; i ++ ) { for ( int j = 0 ; ( 2 * j ) < mapT [ i ] ; j ++ ) { half1 += i ; half2 += i ; } } char [ ] tmp = half2 . ToCharArray ( ) ; Array . Reverse ( tmp ) ; half2 = new string ( tmp ) ; if ( check != 0 ) { return half1 + half2 ; } for ( char i = ' a ' ; i <= ' z ' ; i ++ ) { if ( mapS [ i ] > 0 mapP [ i ] > 0 ) { half1 += i ; return half1 + half2 ; } } return half1 + half2 ; } public static void Main ( string [ ] args ) { string S = " aeabb " ; string P = " dfedf " ; Console . Write ( mergePalindromes ( S , P ) ) ; } }
Count of subarrays having sum equal to its length | C # program for the above approach ; Function that counts the subarrays with sum of its elements as its length ; Decrementing all the elements of the array by 1 ; Making prefix sum array ; Declare map to store count of elements upto current element ; To count all the subarrays whose prefix sum is 0 ; Iterate the array ; Increment answer by count of current element of prefix array ; Return the answer ; Driver Code ; Given array [ ] arr ; Function call
using System ; using System . Collections . Generic ; class GFG { static int countOfSubarray ( int [ ] arr , int N ) { for ( int i = 0 ; i < N ; i ++ ) arr [ i ] -- ; int [ ] pref = new int [ N ] ; pref [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) pref [ i ] = pref [ i - 1 ] + arr [ i ] ; Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; int answer = 0 ; mp . Add ( 0 , 1 ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( mp . ContainsKey ( pref [ i ] ) ) { answer += mp [ pref [ i ] ] ; mp [ pref [ i ] ] = mp [ pref [ i ] ] + 1 ; } else { mp . Add ( pref [ i ] , 1 ) ; } } return answer ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 1 , 0 } ; int N = arr . Length ; Console . Write ( countOfSubarray ( arr , N ) ) ; } }
Nth Subset of the Sequence consisting of powers of K in increasing order of their Sum | C # program to print subset at the nth position ordered by the sum of the elements ; Function to print the elements of the subset at pos n ; Initialize count = 0 and x = 0 ; Create a vector for storing the elements of subsets ; Doing until all the set bits of n are used ; This part is executed only when the last bit is set ; Right shift the bit by one position ; Increasing the count each time by one ; Printing the values os elements ; Driver code
using System . Collections . Generic ; using System ; class GFG { static void printsubset ( int n , int k ) { int count = 0 , x = 0 ; List < int > vec = new List < int > ( ) ; while ( n != 0 ) { x = n & 1 ; if ( x != 0 ) { vec . Add ( ( int ) Math . Pow ( k , count ) ) ; } n = n >> 1 ; count ++ ; } for ( int i = 0 ; i < vec . Count ; i ++ ) Console . Write ( vec [ i ] + " ▁ " ) ; } public static void Main ( ) { int n = 7 , k = 4 ; printsubset ( n , k ) ; } }
Minimum digits to be removed to make either all digits or alternating digits same | C # program for the above approach ; Function to find longest possible subsequence of s beginning with x and y ; Iterate over the String ; Increment count ; Swap the positions ; Return the result ; Function that finds all the possible pairs ; Update count ; Return the answer ; Driver Code ; Given String s ; Find the size of the String ; Function Call ; This value is the count of minimum element to be removed
using System ; class GFG { static int solve ( String s , int x , int y ) { int res = 0 ; foreach ( char c in s . ToCharArray ( ) ) { if ( c - '0' == x ) { res ++ ; x = x + y ; y = x - y ; x = x - y ; } } if ( x != y && res % 2 == 1 ) -- res ; return res ; } static int find_min ( String s ) { int count = 0 ; for ( int i = 0 ; i < 10 ; i ++ ) { for ( int j = 0 ; j < 10 ; j ++ ) { count = Math . Max ( count , solve ( s , i , j ) ) ; } } return count ; } public static void Main ( String [ ] args ) { String s = "100120013" ; int n = s . Length ; int answer = find_min ( s ) ; Console . Write ( ( n - answer ) ) ; } }
Count total set bits in all numbers from range L to R | C # program for the above approach ; Function to count set bits in x ; Base Case ; Recursive Call ; Function that returns count of set bits present in all numbers from 1 to N ; Initialize the result ; Return the setbit count ; Driver Code ; Given L and R ; Function Call
using System ; class GFG { static int countSetBitsUtil ( int x ) { if ( x <= 0 ) return 0 ; return ( ( x % 2 == 0 ? 0 : 1 ) + countSetBitsUtil ( x / 2 ) ) ; } static int countSetBits ( int L , int R ) { int bitCount = 0 ; for ( int i = L ; i <= R ; i ++ ) { bitCount += countSetBitsUtil ( i ) ; } return bitCount ; } public static void Main ( String [ ] args ) { int L = 3 , R = 5 ; Console . Write ( " Total ▁ set ▁ bit ▁ count ▁ is ▁ { 0 } " , countSetBits ( L , R ) ) ; } }
Possible values of Q such that , for any value of R , their product is equal to X times their sum | C # program for the above approach ; Function to find all possible values of Q ; List initialization to store all numbers satisfying the given condition ; Iterate for all the values of X ; Check if condition satisfied then push the number ; Possible value of Q ; Print all the numbers ; Driver code
using System ; using System . Collections . Generic ; class GFG { static void values_of_Q ( int X ) { List < int > val_Q = new List < int > ( ) ; for ( int i = 1 ; i <= X ; i ++ ) { if ( ( ( ( X + i ) * X ) ) % i == 0 ) { val_Q . Add ( X + i ) ; } } Console . WriteLine ( val_Q . Count ) ; for ( int i = 0 ; i < val_Q . Count ; i ++ ) { Console . Write ( val_Q [ i ] + " ▁ " ) ; } } public static void Main ( String [ ] args ) { int X = 3 ; values_of_Q ( X ) ; } }
Program to find Greatest Common Divisor ( GCD ) of N strings | C # program for the above approach ; Function that finds gcd of 2 strings ; If str1 length is less than that of str2 then recur with gcd ( str2 , str1 ) ; If str1 is not the concatenation of str2 ; GCD string is found ; Cut off the common prefix part of str1 & then recur ; Function to find GCD of array of strings ; Return the GCD of strings ; Driver Code ; Given array of strings ; Function Call
using System ; class GFG { static String gcd ( String str1 , String str2 ) { if ( str1 . Length < str2 . Length ) { return gcd ( str2 , str1 ) ; } else if ( ! str1 . StartsWith ( str2 ) ) { return " " ; } else if ( str2 . Length == 0 ) { return str1 ; } else { return gcd ( str1 . Substring ( str2 . Length ) , str2 ) ; } } static String findGCD ( String [ ] arr , int n ) { String result = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { result = gcd ( result , arr [ i ] ) ; } return result ; } public static void Main ( String [ ] args ) { String [ ] arr = new String [ ] { " GFGGFG " , " GFGGFG " , " GFGGFGGFGGFG " } ; int n = arr . Length ; Console . WriteLine ( findGCD ( arr , n ) ) ; } }
Check whether the given Matrix is balanced or not | C # program for the above approach ; Define size of matrix ; Function to check given matrix balanced or unbalanced ; Flag for check matrix is balanced or unbalanced ; Iterate row until condition is true ; Iterate cols until condition is true ; Check for corner edge elements ; Check for border elements ; Check for the middle ones ; Return balanced or not ; Driver Code ; Given Matrix [ , ] mat ; Function Call
using System ; class GFG { static readonly int N = 4 ; static readonly int M = 4 ; static String balancedMatrix ( int [ , ] mat ) { bool is_balanced = true ; for ( int i = 0 ; i < N && is_balanced ; i ++ ) { for ( int j = 0 ; j < M && is_balanced ; j ++ ) { if ( ( i == 0 i == N - 1 ) && ( j == 0 j == M - 1 ) ) { if ( mat [ i , j ] >= 2 ) is_balanced = false ; } else if ( i == 0 i == N - 1 j == 0 j == M - 1 ) { if ( mat [ i , j ] >= 3 ) is_balanced = false ; } else { if ( mat [ i , j ] >= 4 ) is_balanced = false ; } } } if ( is_balanced ) return " Balanced " ; else return " Unbalanced " ; } public static void Main ( String [ ] args ) { int [ , ] mat = { { 1 , 2 , 3 , 4 } , { 3 , 5 , 2 , 6 } , { 5 , 3 , 6 , 1 } , { 9 , 5 , 6 , 0 } } ; Console . Write ( balancedMatrix ( mat ) ) ; } }
Convert Unix timestamp to DD / MM / YYYY HH : MM : SS format | Unix time is in seconds and Humar Readable Format : DATE : MONTH : YEAR : HOUR : MINUTES : SECONDS , Start of unix time : 01 Jan 1970 , 00 : 00 : 00 ; Function to convert unix time to Human readable format ; Save the time in Human readable format ; Number of days in month in normal year ; Calculate total days unix time T ; Calculating current year ; Updating extradays because it will give days till previous day and we have include current day ; Calculating MONTH and DATE ; Current Month ; Calculating HH : MM : YYYY ; Return the time ; Driver Code ; Given unix time ; Function call to convert unix time to human read able ; Print time in format DD : MM : YYYY : HH : MM : SS
using System ; class GFG { static String unixTimeToHumanReadable ( int seconds ) { String ans = " " ; int [ ] daysOfMonth = { 31 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 } ; int currYear , daysTillNow , extraTime , extraDays , index , date , month , hours , minutes , secondss , flag = 0 ; daysTillNow = seconds / ( 24 * 60 * 60 ) ; extraTime = seconds % ( 24 * 60 * 60 ) ; currYear = 1970 ; while ( daysTillNow >= 365 ) { if ( currYear % 400 == 0 || ( currYear % 4 == 0 && currYear % 100 != 0 ) ) { daysTillNow -= 366 ; } else { daysTillNow -= 365 ; } currYear += 1 ; } extraDays = daysTillNow + 1 ; if ( currYear % 400 == 0 || ( currYear % 4 == 0 && currYear % 100 != 0 ) ) flag = 1 ; month = 0 ; index = 0 ; if ( flag == 1 ) { while ( true ) { if ( index == 1 ) { if ( extraDays - 29 < 0 ) break ; month += 1 ; extraDays -= 29 ; } else { if ( extraDays - daysOfMonth [ index ] < 0 ) { break ; } month += 1 ; extraDays -= daysOfMonth [ index ] ; } index += 1 ; } } else { while ( true ) { if ( extraDays - daysOfMonth [ index ] < 0 ) { break ; } month += 1 ; extraDays -= daysOfMonth [ index ] ; index += 1 ; } } if ( extraDays > 0 ) { month += 1 ; date = extraDays ; } else { if ( month == 2 && flag == 1 ) date = 29 ; else { date = daysOfMonth [ month - 1 ] ; } } hours = extraTime / 3600 ; minutes = ( extraTime % 3600 ) / 60 ; secondss = ( extraTime % 3600 ) % 60 ; ans += String . Join ( " " , date ) ; ans += " / " ; ans += String . Join ( " " , month ) ; ans += " / " ; ans += String . Join ( " " , currYear ) ; ans += " ▁ " ; ans += String . Join ( " " , hours ) ; ans += " : " ; ans += String . Join ( " " , minutes ) ; ans += " : " ; ans += String . Join ( " " , secondss ) ; return ans ; } public static void Main ( String [ ] args ) { int T = 1595497956 ; String ans = unixTimeToHumanReadable ( T ) ; Console . Write ( ans + " STRNEWLINE " ) ; } }
Maximum area of a Rectangle that can be circumscribed about a given Rectangle of size LxW | C # program for the above approach ; Function to find area of rectangle inscribed another rectangle of length L and width W ; Area of rectangle ; Return the area ; Driver Code ; Given dimensions ; Function call
using System ; class GFG { static double AreaofRectangle ( int L , int W ) { double area = ( W + L ) * ( W + L ) / 2 ; return area ; } public static void Main ( String [ ] args ) { int L = 18 ; int W = 12 ; Console . Write ( AreaofRectangle ( L , W ) ) ; } }
Minimum number of operations required to reduce N to 0 | C # program to implement the above approach ; Function to count the minimum steps required to reduce n ; Base case ; Allocate memory for storing intermediate results ; Store base values ; Stores square root of each number ; Compute square root ; Use rule 1 to find optimized answer ; Check if it perfectly divides n ; Use of rule 2 to find the optimized answer ; Store computed value ; Return answer ; Driver Code
using System ; class GFG { static int downToZero ( int n ) { if ( n <= 3 ) return n ; int [ ] dp = new int [ n + 1 ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) dp [ i ] = - 1 ; dp [ 0 ] = 0 ; dp [ 1 ] = 1 ; dp [ 2 ] = 2 ; dp [ 3 ] = 3 ; int sqr ; for ( int i = 4 ; i <= n ; i ++ ) { sqr = ( int ) Math . Sqrt ( i ) ; int best = int . MaxValue ; while ( sqr > 1 ) { if ( i % sqr == 0 ) { best = Math . Min ( best , 1 + dp [ sqr ] ) ; } sqr -- ; } best = Math . Min ( best , 1 + dp [ i - 1 ] ) ; dp [ i ] = best ; } return dp [ n ] ; } public static void Main ( String [ ] args ) { int n = 4 ; Console . Write ( downToZero ( n ) ) ; } }
Minimum number of operations required to reduce N to 0 | C # Program to implement the above approach ; Function to find the minimum steps required to reduce n ; Base case ; Return answer based on parity of n ; Driver Code
using System ; class GFG { static int downToZero ( int n ) { if ( n <= 3 ) return n ; return n % 2 == 0 ? 3 : 4 ; } public static void Main ( String [ ] args ) { int n = 4 ; Console . WriteLine ( downToZero ( n ) ) ; } }
Minimum count of elements required to obtain the given Array by repeated mirror operations | C # program to implement the above approach ; Function to find minimum number of elements required to form [ ] A by performing mirroring operation ; Initialize K ; Odd length array cannot be formed by mirror operation ; Check if prefix of length K is palindrome ; Check if not a palindrome ; If found to be palindrome ; Otherwise ; Return the readonly answer ; Driver Code
using System ; class GFG { static int minimumrequired ( int [ ] A , int N ) { int K = N ; int ans = 0 ; while ( K > 0 ) { if ( K % 2 == 1 ) { ans = K ; break ; } int ispalindrome = 1 ; for ( int i = 0 ; i < K / 2 ; i ++ ) { if ( A [ i ] != A [ K - 1 - i ] ) ispalindrome = 0 ; } if ( ispalindrome == 1 ) { ans = K / 2 ; K /= 2 ; } else { ans = K ; break ; } } return ans ; } public static void Main ( String [ ] args ) { int [ ] a = { 1 , 2 , 2 , 1 , 1 , 2 , 2 , 1 } ; int N = a . Length ; Console . WriteLine ( minimumrequired ( a , N ) ) ; } }
Sum of product of all integers upto N with their count of divisors | C # program for the above approach ; Function to find the sum of the product of all the integers and their positive divisors up to N ; Iterate for every number between 1 and N ; Find the first multiple of i between 1 and N ; Find the last multiple of i between 1 and N ; Find the total count of multiple of in [ 1 , N ] ; Compute the contribution of i using the formula ; Add the contribution of i to the answer ; Return the result ; Driver code ; Given N ; function call
using System ; class GFG { static int sumOfFactors ( int N ) { int ans = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { int first = i ; int last = ( N / i ) * i ; int factors = ( last - first ) / i + 1 ; int totalContribution = ( ( ( factors ) * ( factors + 1 ) ) / 2 ) * i ; ans += totalContribution ; } return ans ; } public static void Main ( String [ ] args ) { int N = 3 ; Console . WriteLine ( sumOfFactors ( N ) ) ; } }
Find a number M < N such that difference between their XOR and AND is maximum | C # program for the above approach ; Function to return M < N such that N ^ M - N & M is maximum ; Initialize variables ; Iterate for all values < N ; Find the difference between Bitwise XOR and AND ; Check if new difference is greater than previous maximum ; Update variables ; Return the answer ; Driver Code ; Given number N ; Function call
using System ; class GFG { static int getMaxDifference ( int N ) { int M = - 1 ; int maxDiff = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int diff = ( N ^ i ) - ( N & i ) ; if ( diff >= maxDiff ) { maxDiff = diff ; M = i ; } } return M ; } public static void Main ( String [ ] args ) { int N = 6 ; Console . Write ( getMaxDifference ( N ) ) ; } }
Find a number M < N such that difference between their XOR and AND is maximum | C # program for the above approach ; Function to flip all bits of N ; Finding most significant bit of N ; Calculating required number ; Return the answer ; Driver Code ; Given number ; Function call
using System ; class GFG { static int findM ( int N ) { int M = 0 ; int MSB = ( int ) Math . Log ( N ) ; for ( int i = 0 ; i < MSB ; i ++ ) { if ( ( N & ( 1 << i ) ) == 0 ) M += ( 1 << i ) ; } return M ; } public static void Main ( String [ ] args ) { int N = 6 ; Console . Write ( findM ( N ) ) ; } }
Number of containers that can be filled in the given time | C # program for the above problem ; Matrix of containers ; Function to find the number of containers that will be filled in X seconds ; Container on top level ; If container gets filled ; Dividing the liquid equally in two halves ; Driver code
using System ; class GFG { static double [ , ] cont = new double [ 1000 , 1000 ] ; static void num_of_containers ( int n , double x ) { int count = 0 ; cont [ 1 , 1 ] = x ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= i ; j ++ ) { if ( cont [ i , j ] >= ( double ) 1 ) { count ++ ; cont [ i + 1 , j ] += ( cont [ i , j ] - ( double ) 1 ) / ( double ) 2 ; cont [ i + 1 , j + 1 ] += ( cont [ i , j ] - ( double ) 1 ) / ( double ) 2 ; } } } Console . Write ( count ) ; } public static void Main ( String [ ] args ) { int n = 3 ; double x = 5 ; num_of_containers ( n , x ) ; } }
Check whether there exists a triplet ( i , j , k ) such that arr [ i ] < arr [ k ] < arr [ j ] for i < j < k | C # program for the above approach ; Function to check if there exist triplet in the array such that i < j < k and arr [ i ] < arr [ k ] < arr [ j ] ; Initialize the heights of h1 and h2 to INT_MAX and INT_MIN respectively ; Store the current element as h1 ; If the element at top of stack is less than the current element then pop the stack top and keep updating the value of h3 ; Push the current element on the stack ; If current element is less than h3 , then we found such triplet and return true ; No triplet found , hence return false ; Driver code ; Given array ; Function call
using System ; using System . Collections . Generic ; class GFG { public static bool findTriplet ( int [ ] arr ) { int n = arr . Length ; Stack < int > st = new Stack < int > ( ) ; int h3 = int . MinValue ; int h1 = int . MaxValue ; for ( int i = n - 1 ; i >= 0 ; i -- ) { h1 = arr [ i ] ; while ( st . Count != 0 && st . Peek ( ) < arr [ i ] ) { h3 = st . Peek ( ) ; st . Pop ( ) ; } st . Push ( arr [ i ] ) ; if ( h1 < h3 ) { return true ; } } return false ; } public static void Main ( String [ ] args ) { int [ ] arr = { 4 , 7 , 5 , 6 } ; if ( findTriplet ( arr ) ) { Console . WriteLine ( " Yes " ) ; } else { Console . WriteLine ( " No " ) ; } } }
Minimum number of distinct elements after removing M items | Set 2 | C # program to implement the above approach ; Function to return minimum distinct character after M removals ; Count the occurences of number and store in count ; Count the occurences of the frequencies ; Take answer as total unique numbers and remove the frequency and subtract the answer ; Remove the minimum number of times ; Return the answer ; Driver code ; Initialize array ; Size of array ; Function call
using System ; using System . Collections . Generic ; class GFG { static int distinctNumbers ( int [ ] arr , int m , int n ) { Dictionary < int , int > count = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) if ( count . ContainsKey ( arr [ i ] ) ) { count [ arr [ i ] ] = count [ arr [ i ] ] + 1 ; } else { count . Add ( arr [ i ] , 1 ) ; } int [ ] fre_arr = new int [ n + 1 ] ; foreach ( int it in count . Values ) { fre_arr [ it ] ++ ; } int ans = count . Count ; for ( int i = 1 ; i <= n ; i ++ ) { int temp = fre_arr [ i ] ; if ( temp == 0 ) continue ; int t = Math . Min ( temp , m / i ) ; ans -= t ; m -= i * t ; } return ans ; } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , 4 , 1 , 5 , 3 , 5 , 1 , 3 } ; int n = arr . Length ; int m = 2 ; Console . WriteLine ( distinctNumbers ( arr , m , n ) ) ; } }
Find minimum moves to bring all elements in one cell of a matrix | C # implementation to find the minimum number of moves to bring all non - zero element in one cell of the matrix ; Function to find the minimum number of moves to bring all elements in one cell of matrix ; Moves variable to store the sum of number of moves ; Loop to count the number of the moves ; Condition to check that the current cell is a non - zero element ; Driver code ; Coordinates of given cell ; Given matrix ; Function call
using System ; class GFG { static int M = 4 ; static int N = 5 ; public static void no_of_moves ( int [ , ] Matrix , int x , int y ) { int moves = 0 ; for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( Matrix [ i , j ] != 0 ) { moves += Math . Abs ( x - i ) ; moves += Math . Abs ( y - j ) ; } } } Console . WriteLine ( moves ) ; } public static void Main ( String [ ] args ) { int x = 3 ; int y = 2 ; int [ , ] Matrix = { { 1 , 0 , 1 , 1 , 0 } , { 0 , 1 , 1 , 0 , 1 } , { 0 , 0 , 1 , 1 , 0 } , { 1 , 1 , 1 , 0 , 0 } } ; no_of_moves ( Matrix , x , y ) ; } }
Check if all array elements can be removed by the given operations | C # program to implement the above approach ; Function to check if it is possible to remove all array elements ; Condition if we can remove all elements from the array ; Driver Code
using System ; class GFG { static void removeAll ( int [ ] arr , int n ) { if ( arr [ 0 ] < arr [ n - 1 ] ) Console . Write ( " YES " ) ; else Console . Write ( " NO " ) ; } public static void Main ( String [ ] args ) { int [ ] Arr = { 10 , 4 , 7 , 1 , 3 , 6 } ; int size = Arr . Length ; removeAll ( Arr , size ) ; } }
Smallest subarray having an element with frequency greater than that of other elements | C # program for the above approach ; Function to find subarray ; If the array has only one element , then there is no answer . ; Array to store the last occurrences of the elements of the array . ; To maintain the length ; Variables to store start and end indices ; Check if element is occurring for the second time in the array ; Find distance between last and current index of the element . ; If the current distance is less then len update len and set ' start ' and ' end ' ; Set the last occurrence of current element to be ' i ' . ; If flag is equal to 0 , it means there is no answer . ; Driver code
using System ; class GFG { public static void FindSubarray ( int [ ] arr , int n ) { if ( n == 1 ) { Console . WriteLine ( " No ▁ such ▁ subarray ! " ) ; } int [ ] vis = new int [ n + 1 ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) vis [ i ] = - 1 ; vis [ arr [ 0 ] ] = 0 ; int len = int . MaxValue , flag = 0 ; int start = 0 , end = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int t = arr [ i ] ; if ( vis [ t ] != - 1 ) { int distance = i - vis [ t ] + 1 ; if ( distance < len ) { len = distance ; start = vis [ t ] ; end = i ; } flag = 1 ; } vis [ t ] = i ; } if ( flag == 0 ) Console . WriteLine ( " No ▁ such ▁ subarray ! " ) ; else { for ( int i = start ; i <= end ; i ++ ) Console . Write ( arr [ i ] + " ▁ " ) ; } } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , 3 , 2 , 4 , 5 } ; int n = arr . Length ; FindSubarray ( arr , n ) ; } }
Count substring of Binary string such that each character belongs to a palindrome of size greater than 1 | C # implementation to find the substrings in binary string such that every character belongs to a palindrome ; Function to to find the substrings in binary string such that every character belongs to a palindrome ; Total substrings ; Loop to store the count of continious characters in the given string ; Subtract non special strings from answer ; Driver code ; Given string s ; Function call
using System ; using System . Collections . Generic ; class GFG { public static int countSubstrings ( String s ) { int n = s . Length ; int answer = ( n * ( n - 1 ) ) / 2 ; int cnt = 1 ; List < int > v = new List < int > ( ) ; for ( int i = 1 ; i < n ; i ++ ) { if ( s [ i ] == s [ i - 1 ] ) cnt ++ ; else { v . Add ( cnt ) ; cnt = 1 ; } } if ( cnt > 0 ) v . Add ( cnt ) ; for ( int i = 0 ; i < v . Count - 1 ; i ++ ) { answer -= ( v [ i ] + v [ i + 1 ] - 1 ) ; } return answer ; } public static void Main ( String [ ] args ) { String s = "00111" ; Console . Write ( countSubstrings ( s ) ) ; } }
Minimum minutes needed to make the time palindromic | C # program for the above approach ; Function to get the required minutes ; Storing hour and minute value in integral form ; Keep iterating till first digit hour becomes equal to second digit of minute and second digit of hour becomes equal to first digit of minute ; If mins is 60 , increase hour , and reinitilialized to 0 ; If hours is 60 , reinitialized to 0 ; Return the required time ; Driver code ; Given Time as a string ; Function Call
using System ; class GFG { public static int get_palindrome_time ( string str ) { int hh , mm ; hh = ( str [ 0 ] - 48 ) * 10 + ( str [ 1 ] - 48 ) ; mm = ( str [ 3 ] - 48 ) * 10 + ( str [ 4 ] - 48 ) ; int requiredTime = 0 ; while ( hh % 10 != mm / 10 hh / 10 != mm % 10 ) { ++ mm ; if ( mm == 60 ) { mm = 0 ; ++ hh ; } if ( hh == 24 ) hh = 0 ; ++ requiredTime ; } return requiredTime ; } public static void Main ( string [ ] args ) { string str = "05:39" ; Console . Write ( get_palindrome_time ( str ) ) ; } }
Maximum sum of values in a given range of an Array for Q queries when shuffling is allowed | C # implementation to find the maximum sum of K subarrays when shuffling is allowed ; Function to find the maximum sum of all subarrays ; Initialize maxsum and prefixArray ; Find the frequency using prefix Array ; Perform prefix sum ; Sort both arrays to get a greedy result ; Finally multiply largest frequency with largest array element . ; Return the answer ; Driver Code ; Initial Array ; Subarrays ; Function call
using System ; using System . Collections . Generic ; class GFG { static int maximumSubarraySum ( int [ ] a , int n , List < List < int > > subarrays ) { int i , maxsum = 0 ; int [ ] prefixArray = new int [ n ] ; for ( i = 0 ; i < subarrays . Count ; ++ i ) { prefixArray [ subarrays [ i ] [ 0 ] - 1 ] ++ ; prefixArray [ subarrays [ i ] [ 1 ] ] -- ; } for ( i = 1 ; i < n ; i ++ ) { prefixArray [ i ] += prefixArray [ i - 1 ] ; } Array . Sort ( prefixArray ) ; Array . Sort ( a ) ; for ( i = 0 ; i < n ; i ++ ) maxsum += a [ i ] * prefixArray [ i ] ; return maxsum ; } static void Main ( ) { int n = 6 ; int [ ] a = { 4 , 1 , 2 , 1 , 9 , 2 } ; List < List < int > > subarrays = new List < List < int > > ( ) ; subarrays . Add ( new List < int > { 1 , 2 } ) ; subarrays . Add ( new List < int > { 1 , 3 } ) ; subarrays . Add ( new List < int > { 1 , 4 } ) ; subarrays . Add ( new List < int > { 3 , 4 } ) ; Console . WriteLine ( maximumSubarraySum ( a , n , subarrays ) ) ; } }
Maximum profit such that total stolen value is less than K to get bonus | C # implementation to find the maximum stolen value such that total stolen value is less than K ; Function to find the maximum profit from the given values ; Iterating over every possible permutation ; Driver code ; Function call
using System ; class GFG { static int maxProfit ( int [ ] value , int N , int K ) { Array . Sort ( value ) ; int maxval = value [ N - 1 ] ; int maxProfit = 0 ; int curr_val ; do { curr_val = 0 ; for ( int i = 0 ; i < N ; i ++ ) { curr_val += value [ i ] ; if ( curr_val <= K ) { maxProfit = Math . Max ( curr_val + maxval * ( i + 1 ) , maxProfit ) ; } } } while ( next_permutation ( value ) ) ; return maxProfit ; } static bool next_permutation ( int [ ] p ) { for ( int a = p . Length - 2 ; a >= 0 ; -- a ) if ( p [ a ] < p [ a + 1 ] ) for ( int b = p . Length - 1 ; ; -- b ) if ( p [ b ] > p [ a ] ) { int t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; for ( ++ a , b = p . Length - 1 ; a < b ; ++ a , -- b ) { t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; } return true ; } return false ; } static void Main ( ) { int N = 4 , K = 6 ; int [ ] values = { 5 , 2 , 7 , 3 } ; Console . WriteLine ( maxProfit ( values , N , K ) ) ; } }
Min operations to reduce N by multiplying by any number or taking square root | C # implementation of the approach ; Function to reduce N to its minimum possible value by the given operations ; Keep replacing n until is an integer ; Keep replacing n until n is divisible by i * i ; Print the answer ; Driver code ; Given N ; Function call
using System ; class GFG { static void minValue ( int n ) { while ( ( int ) Math . Sqrt ( n ) == Math . Sqrt ( n ) && n > 1 ) { n = ( int ) ( Math . Sqrt ( n ) ) ; } for ( int i = ( int ) ( Math . Sqrt ( n ) ) ; i > 1 ; i -- ) { while ( n % ( i * i ) == 0 ) n /= i ; } Console . Write ( n ) ; } public static void Main ( ) { int N = 20 ; minValue ( N ) ; } }
Count of ways to split given string into two non | C # program to implement the above approach ; Function to check whether the substring from l to r is palindrome or not ; If characters at l and r differ ; Not a palindrome ; If the string is a palindrome ; Function to count and return the number of possible splits ; Stores the count of splits ; Check if the two substrings after the split are palindromic or not ; If both are palindromes ; Print the final count ; Driver Code
using System ; class GFG { public static bool isPalindrome ( int l , int r , string s ) { while ( l <= r ) { if ( s [ l ] != s [ r ] ) return false ; l ++ ; r -- ; } return true ; } public static int numWays ( string s ) { int n = s . Length ; int ans = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( isPalindrome ( 0 , i , s ) && isPalindrome ( i + 1 , n - 1 , s ) ) { ans ++ ; } } return ans ; } public static void Main ( string [ ] args ) { string S = " aaaaa " ; Console . Write ( numWays ( S ) ) ; } }
Final direction after visiting every cell of Matrix starting from ( 0 , 0 ) | C # program to find the direction when stopped moving ; Function to find the direction when stopped moving ; Driver code ; Given size of NxM grid ; Function Call
using System ; class GFG { static void findDirection ( int n , int m ) { if ( n > m ) { if ( m % 2 == 0 ) Console . Write ( " Up STRNEWLINE " ) ; else Console . Write ( " Down STRNEWLINE " ) ; } else { if ( n % 2 == 0 ) Console . Write ( " Left STRNEWLINE " ) ; else Console . Write ( " Right STRNEWLINE " ) ; } } public static void Main ( ) { int n = 3 , m = 3 ; findDirection ( n , m ) ; } }
Maximize the sum of modulus with every Array element | C # program to find the maximum sum of modulus with every array element ; Function to return the maximum sum of modulus with every array element ; Sum of array elements ; Return the answer ; Driver Code
using System ; class GFG { static int maxModulosum ( int [ ] a , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += a [ i ] ; } return sum - n ; } public static void Main ( String [ ] args ) { int [ ] a = new int [ ] { 3 , 4 , 6 } ; int n = a . Length ; Console . Write ( maxModulosum ( a , n ) ) ; } }
Minimum jumps required to group all 1 s together in a given Binary string | C # program to find the minimum number of jumps required to group all ones together in the binary string ; Function to get the minimum jump value ; Store all indices of ones ; Populating one 's indices ; Calculate median ; Jumps required for 1 's to the left of median ; Jumps required for 1 's to the right of median ; Return the final answer ; Driver code
using System ; using System . Collections ; using System . Collections . Generic ; class GFG { public static int getMinJumps ( string s ) { ArrayList ones = new ArrayList ( ) ; int jumps = 0 , median = 0 , ind = 0 ; for ( int i = 0 ; i < s . Length ; i ++ ) { if ( s [ i ] == '1' ) ones . Add ( i ) ; } if ( ones . Count == 0 ) return jumps ; median = ( int ) ones [ ones . Count / 2 ] ; ind = median ; for ( int i = ind ; i >= 0 ; i -- ) { if ( s [ i ] == '1' ) { jumps += ind - i ; ind -- ; } } ind = median ; for ( int i = ind ; i < s . Length ; i ++ ) { if ( s [ i ] == '1' ) { jumps += i - ind ; ind ++ ; } } return jumps ; } public static void Main ( string [ ] args ) { string S = "00100000010011" ; Console . Write ( getMinJumps ( S ) ) ; } }
Find GCD of each subtree of a given node in an N | C # program to find GCD of each subtree for a given node by Q queries ; Maximum Number of nodes ; Tree represented as adjacency list ; For storing value associates with node ; For storing GCD of every subarray ; Number of nodes ; Function to find GCD of two numbers using Euclidean algo ; If b == 0 then simply return a ; DFS function to traverse the tree ; Initializing answer with GCD of this node . ; Iterate over each child of current node ; Skipping the parent ; Call DFS for each child ; Taking GCD of the answer of the child to find node 's GCD ; Calling DFS from the root ( 1 ) for precomputing answers ; Function to find and print GCD for Q queries ; Doing preprocessing ; iterate over each given query ; Driver code ; Tree : 1 ( 2 ) / \ 2 ( 3 ) 3 ( 4 ) / \ 4 ( 8 ) 5 ( 16 ) ; Making a undirected tree ; Values associated with nodes ; Function call
using System ; using System . Collections . Generic ; public class GFG { static int N = ( int ) ( 1e5 + 5 ) ; static List < int > [ ] v = new List < int > [ N ] ; static int [ ] val = new int [ N ] ; static int [ ] answer = new int [ N ] ; static int n ; static int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } static void DFS ( int node , int parent ) { answer [ node ] = val [ node ] ; foreach ( int child in v [ node ] ) { if ( child == parent ) continue ; DFS ( child , node ) ; answer [ node ] = gcd ( answer [ node ] , answer [ child ] ) ; } } static void preprocess ( ) { DFS ( 1 , - 1 ) ; } static void findGCD ( int [ ] queries , int q ) { preprocess ( ) ; for ( int i = 0 ; i < q ; i ++ ) { int GCD = answer [ queries [ i ] ] ; Console . Write ( " For ▁ subtree ▁ of ▁ " + queries [ i ] + " , ▁ GCD ▁ = ▁ " + GCD + " STRNEWLINE " ) ; } } public static void Main ( String [ ] args ) { n = 5 ; for ( int i = 0 ; i < v . Length ; i ++ ) v [ i ] = new List < int > ( ) ; v [ 1 ] . Add ( 2 ) ; v [ 2 ] . Add ( 1 ) ; v [ 1 ] . Add ( 3 ) ; v [ 3 ] . Add ( 1 ) ; v [ 3 ] . Add ( 4 ) ; v [ 4 ] . Add ( 3 ) ; v [ 3 ] . Add ( 5 ) ; v [ 5 ] . Add ( 3 ) ; val [ 1 ] = 2 ; val [ 2 ] = 3 ; val [ 3 ] = 4 ; val [ 4 ] = 8 ; val [ 5 ] = 16 ; int [ ] queries = { 2 , 3 , 1 } ; int q = queries . Length ; findGCD ( queries , q ) ; } }
Minimize cost to convert given two integers to zero using given operations | C # implementation to find the minimum cost to make the two integers equal to zero using given operations ; Function to find out the minimum cost to make two number X and Y equal to zero ; If x is greater than y then swap ; Cost of making y equal to x ; Cost if we choose 1 st operation ; Cost if we choose 2 nd operation ; Total cost ; Driver code
using System ; class GFG { static void makeZero ( int x , int y , int a , int b ) { if ( x > y ) { int temp = x ; x = y ; y = temp ; } int tot_cost = ( y - x ) * a ; int cost1 = 2 * x * a ; int cost2 = x * b ; tot_cost += Math . Min ( cost1 , cost2 ) ; Console . Write ( tot_cost ) ; } public static void Main ( ) { int X = 1 , Y = 3 ; int cost1 = 391 , cost2 = 555 ; makeZero ( X , Y , cost1 , cost2 ) ; } }
Find N fractions that sum upto a given fraction N / D | C # implementation to split the fraction into N parts ; Function to split the fraction into the N parts ; Loop to find the N - 1 fraction ; Loop to print the Fractions ; Driver Code ; Function Call
using System ; class GFG { public static void splitFraction ( int n , int d ) { long [ ] ar = new long [ n ] ; long first = d + n - 1 ; ar [ 0 ] = first ; for ( int i = 1 ; i < n ; i ++ ) { ar [ i ] = first * ( -- first ) ; } for ( int i = 0 ; i < n ; i ++ ) { if ( ar [ i ] % n == 0 ) { Console . Write ( "1 / " + ar [ i ] / n + " , ▁ " ) ; } else { Console . Write ( n + " / " + ar [ i ] + " , ▁ " ) ; } } } public static void Main ( String [ ] args ) { int N = 4 ; int D = 2 ; splitFraction ( N , D ) ; } }
Count of pairs ( i , j ) in the array such that arr [ i ] is a factor of arr [ j ] | C # Program to find the number of pairs ( i , j ) such that arr [ i ] is a factor of arr [ j ] ; Function to return the count of Pairs ; Driver code
using System ; class GFG { static int numPairs ( int [ ] arr , int n ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( arr [ j ] % arr [ i ] == 0 ) ans ++ ; } } return ans ; } public static void Main ( ) { int [ ] arr = { 1 , 1 , 2 , 2 , 3 , 3 } ; int n = arr . Length ; Console . Write ( numPairs ( arr , n ) ) ; } }
Check if array can be converted into strictly decreasing sequence | C # implementation to check that array can be converted into a strictly decreasing sequence ; Function to check that array can be converted into a strictly decreasing sequence ; Loop to check that each element is greater than the ( N - index ) ; If element is less than ( N - index ) ; If array can be converted ; Driver Code ; Function calling
using System ; class GFG { static bool check ( int [ ] arr , int n ) { bool flag = true ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < n - i ) { flag = false ; } } if ( flag ) { return true ; } else { return false ; } } static public void Main ( String [ ] args ) { int [ ] arr1 = { 11 , 11 , 11 , 11 } ; int n1 = arr1 . Length ; if ( check ( arr1 , n1 ) ) { Console . Write ( " Yes " + " STRNEWLINE " ) ; } else { Console . Write ( " No " + " STRNEWLINE " ) ; } } }
Maximum Balanced String Partitions | C # program to find a maximum number X , such that a given String can be partitioned into X subStrings that are each balanced ; Function to find a maximum number X , such that a given String can be partitioned into X subStrings that are each balanced ; If the size of the String is 0 , then answer is zero ; Variable that represents the number of ' R ' s and ' L ' s ; To store maximum number of possible partitions ; Increment the variable r if the character in the String is ' R ' ; Increment the variable l if the character in the String is ' L ' ; If r and l are equal , then increment ans ; Return the required answer ; Driver code ; Function call
using System ; class GFG { static int BalancedPartition ( string str , int n ) { if ( n == 0 ) return 0 ; int r = 0 , l = 0 ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == ' R ' ) { r ++ ; } else if ( str [ i ] == ' L ' ) { l ++ ; } if ( r == l ) { ans ++ ; } } return ans ; } public static void Main ( ) { string str = " LLRRRLLRRL " ; int n = str . Length ; Console . Write ( BalancedPartition ( str , n ) + " STRNEWLINE " ) ; } }
Minimize the non | C # implementation to minimize the non - zero elements in the array ; Function to minimize the non - zero elements in the given array ; To store the min pos needed ; Loop to iterate over the elements of the given array ; If current position A [ i ] is occupied the we can place A [ i ] , A [ i + 1 ] and A [ i + 2 ] elements together at A [ i + 1 ] if exists . ; Driver code ; Function Call
using System ; class GFG { static int minOccupiedPosition ( int [ ] A , int n ) { int minPos = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( A [ i ] > 0 ) { ++ minPos ; i += 2 ; } } return minPos ; } static void Main ( ) { int [ ] A = { 8 , 0 , 7 , 0 , 0 , 6 } ; int n = A . Length ; Console . WriteLine ( minOccupiedPosition ( A , n ) ) ; } }
Find minimum number K such that sum of array after multiplication by K exceed S | C # implementation of the approach ; Function to return the minimum value of k that satisfies the given condition ; Store sum of array elements ; Calculate the sum after ; Return minimum possible K ; Driver code
using System ; class GFG { static int findMinimumK ( int [ ] a , int n , int S ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += a [ i ] ; } return ( int ) Math . Ceiling ( ( ( S + 1 ) * 1.0 ) / ( sum * 1.0 ) ) ; } public static void Main ( String [ ] args ) { int [ ] a = { 10 , 7 , 8 , 10 , 12 , 19 } ; int n = a . Length ; int S = 200 ; Console . Write ( findMinimumK ( a , n , S ) ) ; } }
Find the largest number smaller than integer N with maximum number of set bits | C # implementation to Find the largest number smaller than integer N with maximum number of set bits ; Function to return the largest number less than N ; Iterate through all possible values ; Multiply the number by 2 i times ; Return the final result ; Driver code
using System ; class GFG { static int largestNum ( int n ) { int num = 0 ; for ( int i = 0 ; i <= 32 ; i ++ ) { int x = ( 1 << i ) ; if ( ( x - 1 ) <= n ) num = ( 1 << i ) - 1 ; else break ; } return num ; } public static void Main ( ) { int N = 345 ; Console . Write ( largestNum ( N ) ) ; } }
Find the String having each substring with exactly K distinct characters | C # program to find the string having each substring with exactly K distinct characters ; Function to find the required output string ; Each element at index i is modulus of K ; Driver code ; Initialise integers N and K
using System ; class GFG { static void findString ( int N , int K ) { for ( int i = 0 ; i < N ; i ++ ) { Console . Write ( ( char ) ( ' A ' + i % K ) ) ; } } public static void Main ( String [ ] args ) { int N = 10 ; int K = 3 ; findString ( N , K ) ; } }
Find total no of collisions taking place between the balls in which initial direction of each ball is given | C # implementation to Find total no of collisions taking place between the balls in which initial direction of each ball is given ; Function to count no of collision ; length of the string ; Driver code
using System ; class GFG { static int count ( String s ) { int N , i , cnt = 0 , ans = 0 ; N = s . Length ; for ( i = 0 ; i < N ; i ++ ) { if ( s [ i ] == ' R ' ) cnt ++ ; if ( s [ i ] == ' L ' ) ans += cnt ; } return ans ; } public static void Main ( String [ ] args ) { String s = " RRLL " ; Console . Write ( count ( s ) ) ; } }
Maximum number on 7 | C # implementation to find the maximum number that can be using the N segments in N segments display ; Function to find the maximum number that can be displayed using the N segments ; Condition to check base case ; Condition to check if the number is even ; Condition to check if the number is odd ; Driver Code
using System ; class GFG { static void segments ( int n ) { if ( n == 1 n == 0 ) { return ; } if ( n % 2 == 0 ) { Console . Write ( "1" ) ; segments ( n - 2 ) ; } else if ( n % 2 == 1 ) { Console . Write ( "7" ) ; segments ( n - 3 ) ; } } public static void Main ( ) { int n ; n = 11 ; segments ( n ) ; } }
Minimum number of subsequences required to convert one string to another using Greedy Algorithm | C # implementation for minimum number of subsequences required to convert one String to another ; Function to find the minimum number of subsequences required to convert one String to another S2 == A and S1 == B ; At least 1 subsequence is required Even in best case , when A is same as B ; size of B ; size of A ; Create an 2D array next [ , ] of size 26 * sizeOfB to store the next occurrence of a character ( ' a ' to ' z ' ) as an index [ 0 , sizeOfA - 1 ] ; Array Initialization with infinite ; Loop to Store the values of index ; If the value of next [ i , j ] is infinite then update it with next [ i , j + 1 ] ; Greedy algorithm to obtain the maximum possible subsequence of B to cover the remaining String of A using next subsequence ; Loop to iterate over the String A ; Condition to check if the character is not present in the String B ; Condition to check if there is an element in B matching with character A [ i ] on or next to B [ pos ] given by next [ A [ i ] - ' a ' , pos ] ; Condition to check if reached at the end of B or no such element exists on or next to A [ pos ] , thus increment number by one and reinitialise pos to zero ; Driver Code
using System ; class GFG { static int findMinimumSubsequences ( String A , String B ) { int numberOfSubsequences = 1 ; int sizeOfB = B . Length ; int sizeOfA = A . Length ; int inf = 1000000 ; int [ , ] next = new int [ 26 , sizeOfB ] ; for ( int i = 0 ; i < 26 ; i ++ ) { for ( int j = 0 ; j < sizeOfB ; j ++ ) { next [ i , j ] = inf ; } } for ( int i = 0 ; i < sizeOfB ; i ++ ) { next [ B [ i ] - ' a ' , i ] = i ; } for ( int i = 0 ; i < 26 ; i ++ ) { for ( int j = sizeOfB - 2 ; j >= 0 ; j -- ) { if ( next [ i , j ] == inf ) { next [ i , j ] = next [ i , j + 1 ] ; } } } int pos = 0 ; int I = 0 ; while ( I < sizeOfA ) { if ( pos == 0 && next [ A [ I ] - ' a ' , pos ] == inf ) { numberOfSubsequences = - 1 ; break ; } else if ( pos < sizeOfB && next [ A [ I ] - ' a ' , pos ] < inf ) { int nextIndex = next [ A [ I ] - ' a ' , pos ] + 1 ; pos = nextIndex ; I ++ ; } else { numberOfSubsequences ++ ; pos = 0 ; } } return numberOfSubsequences ; } public static void Main ( String [ ] args ) { String A = " aacbe " ; String B = " aceab " ; Console . Write ( findMinimumSubsequences ( A , B ) ) ; } }
Vertical and Horizontal retrieval ( MRT ) on Tapes | C # program to print Horizontal filling ; It is used for checking whether tape is full or not ; It is used for calculating total retrieval time ; It is used for calculating mean retrieval time ; vector is used because n number of records can insert in one tape with size constraint ; Null vector obtained to use fresh vector ' v ' ; initialize variables to 0 for each iteration ; sum is used for checking whether i 'th tape is full or not ; check sum less than size of tape ; increment in j for next record ; calculating total retrieval time ; MRT formula ; calculating mean retrieval time using formula ; v . Count is function of vector is used to get size of vector ; Driver Code ; store the size of records [ ] ; store the size of tapes [ ] ; sorting of an array is required to attain greedy approach of algorithm
using System ; using System . Collections . Generic ; class GFG { static void horizontalFill ( int [ ] records , int [ ] tape , int nt ) { int sum = 0 ; int Retrieval_Time = 0 ; double Mrt ; int current = 0 ; List < int > v = new List < int > ( ) ; for ( int i = 0 ; i < nt ; i ++ ) { v . Clear ( ) ; Retrieval_Time = 0 ; sum = 0 ; Console . Write ( " tape ▁ " + ( i + 1 ) + " ▁ : ▁ [ ▁ " ) ; sum += records [ current ] ; while ( sum <= tape [ i ] ) { Console . Write ( records [ current ] + " ▁ " ) ; v . Add ( records [ current ] ) ; current ++ ; sum += records [ current ] ; } Console . Write ( " ] " ) ; for ( int j = 0 ; j < v . Count ; j ++ ) { Retrieval_Time += v [ j ] * ( v . Count - j ) ; } Mrt = ( double ) Retrieval_Time / v . Count ; Console . Write ( " TABSYMBOL MRT ▁ : ▁ " + Mrt + " STRNEWLINE " ) ; } } public static void Main ( String [ ] args ) { int [ ] records = { 15 , 2 , 8 , 23 , 45 , 50 , 60 , 120 } ; int [ ] tape = { 25 , 80 , 160 } ; int n = records . Length ; int m = tape . Length ; Array . Sort ( records ) ; horizontalFill ( records , tape , m ) ; } }
Circular Convolution using Matrix Method | C # program to compute circular convolution of two arrays ; Function to find circular convolution ; Finding the maximum size between the two input sequence sizes ; Copying elements of x to row_vec and padding zeros if size of x < maxSize ; Copying elements of h to col_vec and padding zeros if size of h is less than maxSize ; Generating 2D matrix of circularly shifted elements ; Computing result by matrix multiplication and printing results ; Driver program
using System ; class GFG { readonly static int MAX_SIZE = 10 ; static void convolution ( int [ ] x , int [ ] h , int n , int m ) { int [ ] row_vec = new int [ MAX_SIZE ] ; int [ ] col_vec = new int [ MAX_SIZE ] ; int [ ] out_ = new int [ MAX_SIZE ] ; int [ , ] circular_shift_mat = new int [ MAX_SIZE , MAX_SIZE ] ; int maxSize = n > m ? n : m ; for ( int i = 0 ; i < maxSize ; i ++ ) { if ( i >= n ) { row_vec [ i ] = 0 ; } else { row_vec [ i ] = x [ i ] ; } } for ( int i = 0 ; i < maxSize ; i ++ ) { if ( i >= m ) { col_vec [ i ] = 0 ; } else { col_vec [ i ] = h [ i ] ; } } int k = 0 , d = 0 ; for ( int i = 0 ; i < maxSize ; i ++ ) { int curIndex = k - d ; for ( int j = 0 ; j < maxSize ; j ++ ) { circular_shift_mat [ j , i ] = row_vec [ curIndex % maxSize ] ; curIndex ++ ; } k = maxSize ; d ++ ; } for ( int i = 0 ; i < maxSize ; i ++ ) { for ( int j = 0 ; j < maxSize ; j ++ ) { out_ [ i ] += circular_shift_mat [ i , j ] * col_vec [ j ] ; } Console . Write ( out_ [ i ] + " ▁ " ) ; } } public static void Main ( String [ ] args ) { int [ ] x = { 5 , 7 , 3 , 2 } ; int n = x . Length ; int [ ] h = { 1 , 5 } ; int m = h . Length ; convolution ( x , h , n , m ) ; } }
Maximize the number of palindromic Strings | C # program for the above approach ; To check if there is any string of odd length ; If there is at least 1 string of odd length . ; If all the strings are of even length . ; Count of 0 's in all the strings ; Count of 1 's in all the strings ; If z is even and o is even then ans will be N . ; Otherwise ans will be N - 1. ; Driver code
using System ; class GFG { static int max_palindrome ( string [ ] s , int n ) { int flag = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] . Length % 2 != 0 ) { flag = 1 ; } } if ( flag == 1 ) { return n ; } int z = 0 ; int o = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < s [ i ] . Length ; j ++ ) { if ( s [ i ] [ j ] == '0' ) z += 1 ; else o += 1 ; } } if ( o % 2 == 0 && z % 2 == 0 ) { return n ; } else { return n - 1 ; } } public static void Main ( ) { int n = 3 ; string [ ] s = { "1110" , "100110" , "010101" } ; Console . WriteLine ( max_palindrome ( s , n ) ) ; } }
Minimum possible travel cost among N cities | C # implementation of the approach ; Function to return the minimum cost to travel from the first city to the last ; To store the total cost ; Start from the first city ; If found any city with cost less than that of the previous boarded bus then change the bus ; Calculate the cost to travel from the currently boarded bus till the current city ; Update the currently boarded bus ; Finally calculate the cost for the last boarding bus till the ( N + 1 ) th city ; Driver code
using System ; class GFG { static int minCost ( int [ ] cost , int n ) { int totalCost = 0 ; int boardingBus = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( cost [ boardingBus ] > cost [ i ] ) { totalCost += ( ( i - boardingBus ) * cost [ boardingBus ] ) ; boardingBus = i ; } } totalCost += ( ( n - boardingBus ) * cost [ boardingBus ] ) ; return totalCost ; } public static void Main ( String [ ] args ) { int [ ] cost = { 4 , 7 , 8 , 3 , 4 } ; int n = cost . Length ; Console . Write ( minCost ( cost , n ) ) ; } }
Minimum cells to be flipped to get a 2 * 2 submatrix with equal elements | C # implementation of the approach ; Function to return the minimum flips required such that the submatrix from mat [ i , j ] to mat [ i + 1 , j + 1 ] contains all equal elements ; Function to return the minimum number of slips required such that the matrix contains at least a single submatrix of size 2 * 2 with all equal elements ; To store the result ; For every submatrix of size 2 * 2 ; Update the count of flips required for the current submatrix ; Driver code
using System ; class GFG { static int minFlipsSub ( String [ ] mat , int i , int j ) { int cnt0 = 0 , cnt1 = 0 ; if ( mat [ i ] [ j ] == '1' ) cnt1 ++ ; else cnt0 ++ ; if ( mat [ i ] [ j + 1 ] == '1' ) cnt1 ++ ; else cnt0 ++ ; if ( mat [ i + 1 ] [ j ] == '1' ) cnt1 ++ ; else cnt0 ++ ; if ( mat [ i + 1 ] [ j + 1 ] == '1' ) cnt1 ++ ; else cnt0 ++ ; return Math . Min ( cnt0 , cnt1 ) ; } static int minFlips ( String [ ] mat , int r , int c ) { int res = int . MaxValue ; for ( int i = 0 ; i < r - 1 ; i ++ ) { for ( int j = 0 ; j < c - 1 ; j ++ ) { res = Math . Min ( res , minFlipsSub ( mat , i , j ) ) ; } } return res ; } public static void Main ( String [ ] args ) { String [ ] mat = { "0101" , "0101" , "0101" } ; int r = mat . Length ; int c = mat . GetLength ( 0 ) ; Console . Write ( minFlips ( mat , r , c ) ) ; } }
Count set bits in the Kth number after segregating even and odd from N natural numbers | C # implementation of the above approach ; Function to return the kth element of the Odd - Even sequence of length n ; Finding the index from where the even numbers will be stored ; Return the kth element ; Function to return the count of set bits in the kth number of the odd even sequence of length n ; Required kth number ; Return the count of set bits ; Driver code
using System ; class GFG { static int findK ( int n , int k ) { int pos ; if ( n % 2 == 0 ) { pos = n / 2 ; } else { pos = ( n / 2 ) + 1 ; } if ( k <= pos ) { return ( k * 2 - 1 ) ; } else return ( ( k - pos ) * 2 ) ; } static int countSetBits ( int n , int k ) { int kth = findK ( n , k ) ; int count = 0 ; while ( kth > 0 ) { count += kth & 1 ; kth >>= 1 ; } return count ; } public static void Main ( String [ ] args ) { int n = 18 , k = 12 ; Console . WriteLine ( countSetBits ( n , k ) ) ; } }
Minimum cost to convert str1 to str2 with the given operations | C # implementation of the approach ; Function to return the minimum cost to convert str1 to sr2 ; For every character of str1 ; If current character is not equal in both the strings ; If the next character is also different in both the strings then these characters can be swapped ; Change the current character ; Driver code
using System ; class GFG { static int minCost ( string str1 , string str2 , int n ) { int cost = 0 ; char [ ] array = str1 . ToCharArray ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( str1 [ i ] != str2 [ i ] ) { if ( i < n - 1 && str1 [ i + 1 ] != str2 [ i + 1 ] ) { char temp = array [ i ] ; array [ i ] = array [ i + 1 ] ; array [ i + 1 ] = temp ; cost ++ ; } else { cost ++ ; } } } return cost ; } static public void Main ( ) { string str1 = " abb " , str2 = " bba " ; int n = str1 . Length ; Console . WriteLine ( minCost ( str1 , str2 , n ) ) ; } }
Partition first N natural number into two sets such that their sum is not coprime | C # implementation of the approach ; Function to find the required sets ; Impossible case ; Sum of first n - 1 natural numbers ; Driver code
using System ; class GFG { static void find_set ( int n ) { if ( n <= 2 ) { Console . WriteLine ( " - 1" ) ; return ; } int sum1 = ( n * ( n - 1 ) ) / 2 ; int sum2 = n ; Console . WriteLine ( sum1 + " ▁ " + sum2 ) ; } public static void Main ( ) { int n = 8 ; find_set ( n ) ; } }
Count common elements in two arrays containing multiples of N and M | C # implementation of the above approach ; Recursive function to find gcd using euclidean algorithm ; Function to find lcm of two numbers using gcd ; Driver code
using System ; class GFG { static int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } static int lcm ( int n , int m ) { return ( n * m ) / gcd ( n , m ) ; } public static void Main ( String [ ] args ) { int n = 2 , m = 3 , k = 5 ; Console . WriteLine ( k / lcm ( n , m ) ) ; } }
Check whether a subsequence exists with sum equal to k if arr [ i ] > 2 * arr [ i | C # implementation of above approach ; Function to check whether sum of any set of the array element is equal to k or not ; Traverse the array from end to start ; if k is greater than arr [ i ] then subtract it from k ; If there is any subsequence whose sum is equal to k ; Driver code
using System ; class GFG { static bool CheckForSequence ( int [ ] arr , int n , int k ) { for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( k >= arr [ i ] ) k -= arr [ i ] ; } if ( k != 0 ) return false ; else return true ; } public static void Main ( ) { int [ ] A = { 1 , 3 , 7 , 15 , 31 } ; int n = A . Length ; Console . WriteLine ( CheckForSequence ( A , n , 18 ) ? " True " : " False " ) ; } }
Maximum possible sub | C # implementation of the approach ; Function to return the maximum sub - array sum after at most x swaps ; To store the required answer ; For all possible intervals ; Keep current ans as zero ; To store the integers which are not part of the sub - array currently under consideration ; To store elements which are part of the sub - array currently under consideration ; Create two sets ; Swap at most X elements ; Remove the minimum of the taken elements ; Add maximum of the discarded elements ; Update the answer ; Return the maximized sub - array sum ; Driver code .
using System ; using System . Collections . Generic ; class GFG { static int SubarraySum ( int [ ] a , int n , int x ) { int ans = - 10000 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { int curans = 0 ; List < int > pq = new List < int > ( ) ; List < int > pq2 = new List < int > ( ) ; for ( int k = 0 ; k < n ; k ++ ) { if ( k >= i && k <= j ) { curans += a [ k ] ; pq2 . Add ( a [ k ] ) ; } else pq . Add ( a [ k ] ) ; } pq . Sort ( ) ; pq . Reverse ( ) ; pq2 . Sort ( ) ; ans = Math . Max ( ans , curans ) ; for ( int k = 1 ; k <= x ; k ++ ) { if ( pq . Count == 0 pq2 . Count == 0 pq2 [ 0 ] >= pq [ 0 ] ) break ; curans -= pq2 [ 0 ] ; pq2 . RemoveAt ( 0 ) ; curans += pq [ 0 ] ; pq . RemoveAt ( 0 ) ; ans = Math . Max ( ans , curans ) ; } } } return ans ; } static void Main ( ) { int [ ] a = { 5 , - 1 , 2 , 3 , 4 , - 2 , 5 } ; int x = 2 ; int n = a . Length ; Console . WriteLine ( SubarraySum ( a , n , x ) ) ; } }
Generate an array of size K which satisfies the given conditions | C # implementation of the approach ; Function to generate and print the required array ; Initializing the array ; Finding r ( from above approach ) ; If r < 0 ; Finding ceiling and floor values ; Fill the array with ceiling values ; Fill the array with floor values ; Add 1 , 2 , 3 , ... with corresponding values ; There is no solution for below cases ; Modify A [ 1 ] and A [ k - 1 ] to get the required array ; Driver Code
using System ; class GFG { static void generateArray ( int n , int k ) { int [ ] array = new int [ k ] ; int remaining = n - ( k * ( k + 1 ) / 2 ) ; if ( remaining < 0 ) Console . Write ( " NO " ) ; int right_most = remaining % k ; int high = ( int ) Math . Ceiling ( remaining / ( k * 1.0 ) ) ; int low = ( int ) Math . Floor ( remaining / ( k * 1.0 ) ) ; for ( int i = k - right_most ; i < k ; i ++ ) array [ i ] = high ; for ( int i = 0 ; i < ( k - right_most ) ; i ++ ) array [ i ] = low ; for ( int i = 0 ; i < k ; i ++ ) array [ i ] += i + 1 ; if ( k - 1 != remaining k == 1 ) { foreach ( int u in array ) Console . Write ( u + " ▁ " ) ; } else if ( k == 2 k == 3 ) Console . Write ( " - 1 STRNEWLINE " ) ; else { array [ 1 ] -= 1 ; array [ k - 1 ] += 1 ; foreach ( int u in array ) Console . Write ( u + " ▁ " ) ; } } public static void Main ( String [ ] args ) { int n = 26 , k = 6 ; generateArray ( n , k ) ; } }
Maximize the given number by replacing a segment of digits with the alternate digits given | C # implementation of the approach ; Function to return the maximized number ; Iterate till the end of the string ; Check if it is greater or not ; Replace with the alternate till smaller ; Return original s in case no change took place ; Driver Code
using System ; class GFG { static String get_maximum ( char [ ] s , int [ ] a ) { int n = s . Length ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] - '0' < a [ s [ i ] - '0' ] ) { int j = i ; while ( j < n && ( s [ j ] - '0' <= a [ s [ j ] - '0' ] ) ) { s [ j ] = ( char ) ( '0' + a [ s [ j ] - '0' ] ) ; j ++ ; } return String . Join ( " " , s ) ; } } return String . Join ( " " , s ) ; } public static void Main ( String [ ] args ) { String s = "1337" ; int [ ] a = { 0 , 1 , 2 , 5 , 4 , 6 , 6 , 3 , 1 , 9 } ; Console . WriteLine ( get_maximum ( s . ToCharArray ( ) , a ) ) ; } }
Number of times the largest perfect square number can be subtracted from N | C # implementation of the approach ; Function to return the count of steps ; Variable to store the count of steps ; Iterate while N > 0 ; Get the largest perfect square and subtract it from N ; Increment steps ; Return the required count ; Driver code
using System ; class GfG { static int countSteps ( int n ) { int steps = 0 ; while ( n > 0 ) { int largest = ( int ) Math . Sqrt ( n ) ; n -= ( largest * largest ) ; steps ++ ; } return steps ; } public static void Main ( ) { int n = 85 ; Console . WriteLine ( countSteps ( n ) ) ; } }
Maximum array sum that can be obtained after exactly k changes | C # implementation of the above approach ; Utility function to return the sum of the array elements ; Function to return the maximized sum of the array after performing the given operation exactly k times ; Sort the array elements ; Change signs of the negative elements starting from the smallest ; If a single operation has to be performed then it must be performed on the smallest positive element ; To store the index of the minimum element ; Update the minimum index ; Perform remaining operation on the smallest element ; Return the sum of the updated array ; Driver code
using System ; using System . Linq ; class GFG { static int sumArr ( int [ ] arr , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; return sum ; } static int maxSum ( int [ ] arr , int n , int k ) { Array . Sort ( arr ) ; int i = 0 ; while ( i < n && k > 0 && arr [ i ] < 0 ) { arr [ i ] *= - 1 ; k -- ; i ++ ; } if ( k % 2 == 1 ) { int min = 0 ; for ( i = 1 ; i < n ; i ++ ) if ( arr [ min ] > arr [ i ] ) min = i ; arr [ min ] *= - 1 ; } return sumArr ( arr , n ) ; } static void Main ( ) { int [ ] arr = { - 5 , 4 , 1 , 3 , 2 } ; int n = arr . Length ; int k = 4 ; Console . WriteLine ( maxSum ( arr , n , k ) ) ; } }
Spanning Tree With Maximum Degree ( Using Kruskal 's Algorithm) | C # implementation of the approach ; par and rank will store the parent and rank of particular node in the Union Find Algorithm ; Find function of Union Find Algorithm ; Union function of Union Find Algorithm ; Function to find the required spanning tree ; Initialising parent of a node by itself ; Variable to store the node with maximum degree ; Finding the node with maximum degree ; Union of all edges incident on vertex with maximum degree ; Carrying out normal Kruskal Algorithm ; Driver code ; Number of nodes ; Number of edges ; ArrayList to store the graph ; Array to store the degree of each node in the graph ; Add edges and update degrees
using System ; using System . Collections . Generic ; class GFG { static int [ ] par ; static int [ ] rank ; static int find ( int x ) { if ( par [ x ] != x ) par [ x ] = find ( par [ x ] ) ; return par [ x ] ; } static void union ( int u , int v ) { int x = find ( u ) ; int y = find ( v ) ; if ( x == y ) return ; if ( rank [ x ] > rank [ y ] ) par [ y ] = x ; else if ( rank [ x ] < rank [ y ] ) par [ x ] = y ; else { par [ x ] = y ; rank [ y ] ++ ; } } static void findSpanningTree ( int [ ] deg , int n , int m , List < int > [ ] g ) { par = new int [ n + 1 ] ; rank = new int [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) par [ i ] = i ; int max = 1 ; for ( int i = 2 ; i <= n ; i ++ ) if ( deg [ i ] > deg [ max ] ) max = i ; foreach ( int v in g [ max ] ) { Console . WriteLine ( max + " ▁ " + v ) ; union ( max , v ) ; } for ( int u = 1 ; u <= n ; u ++ ) { foreach ( int v in g [ u ] ) { int x = find ( u ) ; int y = find ( v ) ; if ( x == y ) continue ; union ( x , y ) ; Console . WriteLine ( u + " ▁ " + v ) ; } } } public static void Main ( String [ ] args ) { int n = 5 ; int m = 5 ; List < int > [ ] g = new List < int > [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) g [ i ] = new List < int > ( ) ; int [ ] deg = new int [ n + 1 ] ; g [ 1 ] . Add ( 2 ) ; g [ 2 ] . Add ( 1 ) ; deg [ 1 ] ++ ; deg [ 2 ] ++ ; g [ 1 ] . Add ( 5 ) ; g [ 5 ] . Add ( 1 ) ; deg [ 1 ] ++ ; deg [ 5 ] ++ ; g [ 2 ] . Add ( 3 ) ; g [ 3 ] . Add ( 2 ) ; deg [ 2 ] ++ ; deg [ 3 ] ++ ; g [ 5 ] . Add ( 3 ) ; g [ 3 ] . Add ( 5 ) ; deg [ 3 ] ++ ; deg [ 5 ] ++ ; g [ 3 ] . Add ( 4 ) ; g [ 4 ] . Add ( 3 ) ; deg [ 3 ] ++ ; deg [ 4 ] ++ ; findSpanningTree ( deg , n , m , g ) ; } }
Given count of digits 1 , 2 , 3 , 4 , find the maximum sum possible | C # program to maximum possible sum ; Function to find the maximum possible sum ; To store required sum ; Number of 234 's can be formed ; Sum obtained with 234 s ; Remaining 2 's ; Sum obtained with 12 s ; Return the required sum ; Driver code
using System ; class GFG { static int Maxsum ( int c1 , int c2 , int c3 , int c4 ) { int sum = 0 ; int two34 = Math . Min ( c2 , Math . Min ( c3 , c4 ) ) ; sum = two34 * 234 ; c2 -= two34 ; sum += Math . Min ( c2 , c1 ) * 12 ; return sum ; } public static void Main ( ) { int c1 = 5 , c2 = 2 , c3 = 3 , c4 = 4 ; Console . WriteLine ( Maxsum ( c1 , c2 , c3 , c4 ) ) ; } }
Replace all elements by difference of sums of positive and negative numbers after that element | C # program to implement above approach ; Function to print the array elements ; Function to replace all elements with absolute difference of absolute sums of positive and negative elements ; calculate difference of both sums ; if i - th element is positive , add it to positive sum ; if i - th element is negative , add it to negative sum ; replace i - th elements with absolute difference ; Driver Code
using System ; class GFG { static void printArray ( int N , int [ ] arr ) { for ( int i = 0 ; i < N ; i ++ ) Console . Write ( arr [ i ] + " ▁ " ) ; Console . WriteLine ( ) ; } static void replacedArray ( int N , int [ ] arr ) { int pos_sum , neg_sum , i , diff ; pos_sum = 0 ; neg_sum = 0 ; for ( i = N - 1 ; i >= 0 ; i -- ) { diff = Math . Abs ( pos_sum ) - Math . Abs ( neg_sum ) ; if ( arr [ i ] > 0 ) pos_sum += arr [ i ] ; else neg_sum += arr [ i ] ; arr [ i ] = Math . Abs ( diff ) ; } } public static void Main ( ) { int N = 5 ; int [ ] arr = { 1 , - 1 , 2 , 3 , - 2 } ; replacedArray ( N , arr ) ; printArray ( N , arr ) ; N = 6 ; int [ ] arr1 = { - 3 , - 4 , - 2 , 5 , 1 , - 2 } ; replacedArray ( N , arr1 ) ; printArray ( N , arr1 ) ; } }
Count of pairs from 1 to a and 1 to b whose sum is divisible by N | C # implementation of above approach ; Function to find the distinct pairs from 1 - a & 1 - b such that their sum is divisible by n . ; pairs from 1 to n * ( a / n ) and 1 to n * ( b / n ) ; pairs from 1 to n * ( a / n ) and n * ( b / n ) to b ; pairs from n * ( a / n ) to a and 1 to n * ( b / n ) ; pairs from n * ( a / n ) to a and n * ( b / n ) to b ; Return answer ; Driver code
using System ; class GFG { static int findCountOfPairs ( int a , int b , int n ) { int ans = 0 ; ans += n * ( a / n ) * ( b / n ) ; ans += ( a / n ) * ( b % n ) ; ans += ( a % n ) * ( b / n ) ; ans += ( ( a % n ) + ( b % n ) ) / n ; return ans ; } static public void Main ( ) { int a = 5 , b = 13 , n = 3 ; Console . WriteLine ( findCountOfPairs ( a , b , n ) ) ; } }
Generate array with minimum sum which can be deleted in P steps | C # implementation of the approach ; Function to find the required array ; calculating minimum possible sum ; Array ; place first P natural elements ; Fill rest of the elements with 1 ; Driver Code
using System ; class GFG { static void findArray ( int N , int P ) { int ans = ( P * ( P + 1 ) ) / 2 + ( N - P ) ; int [ ] arr = new int [ N + 1 ] ; for ( int i = 1 ; i <= P ; i ++ ) { arr [ i ] = i ; } for ( int i = P + 1 ; i <= N ; i ++ ) { arr [ i ] = 1 ; } Console . Write ( " The ▁ Minimum ▁ Possible ▁ Sum ▁ is : ▁ " + ans + " STRNEWLINE " ) ; Console . Write ( " The ▁ Array ▁ Elements ▁ are : ▁ STRNEWLINE " ) ; for ( int i = 1 ; i <= N ; i ++ ) { Console . Write ( arr [ i ] + " ▁ " ) ; } } public static void Main ( ) { int N = 5 , P = 3 ; findArray ( N , P ) ; } }
Find Intersection of all Intervals | C # implementation of the approach ; Function to print the intersection ; First interval ; Check rest of the intervals and find the intersection ; If no intersection exists ; Else update the intersection ; Driver code
using System ; class GFG { static void findIntersection ( int [ , ] intervals , int N ) { int l = intervals [ 0 , 0 ] ; int r = intervals [ 0 , 1 ] ; for ( int i = 1 ; i < N ; i ++ ) { if ( intervals [ i , 0 ] > r intervals [ i , 1 ] < l ) { Console . WriteLine ( - 1 ) ; return ; } else { l = Math . Max ( l , intervals [ i , 0 ] ) ; r = Math . Min ( r , intervals [ i , 1 ] ) ; } } Console . WriteLine ( " [ " + l + " , ▁ " + r + " ] " ) ; } public static void Main ( ) { int [ , ] intervals = { { 1 , 6 } , { 2 , 8 } , { 3 , 10 } , { 5 , 8 } } ; int N = intervals . GetLength ( 0 ) ; findIntersection ( intervals , N ) ; } }
Maximum size of sub | C # implementation of the approach ; Function that compares a and b ; Function to return length of longest subarray that satisfies one of the given conditions ; Driver Code ; Print the required answer
using System ; class GFG { static int cmp ( int a , int b ) { if ( a > b ) return 1 ; else if ( a == b ) return 0 ; else return - 1 ; } static int maxSubarraySize ( int [ ] arr , int n ) { int ans = 1 ; int anchor = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int c = cmp ( arr [ i - 1 ] , arr [ i ] ) ; if ( c == 0 ) anchor = i ; else if ( i == n - 1 || c * cmp ( arr [ i ] , arr [ i + 1 ] ) != - 1 ) { ans = Math . Max ( ans , i - anchor + 1 ) ; anchor = i ; } } return ans ; } static void Main ( ) { int [ ] arr = { 9 , 4 , 2 , 10 , 7 , 8 , 8 , 1 , 9 } ; int n = arr . Length ; Console . WriteLine ( maxSubarraySize ( arr , n ) ) ; } }
Maximum count of sub | C # implementation of the approach ; Function to return the count of the required sub - strings ; Iterate over all characters ; Count with current character ; If the substring has a length k then increment count with current character ; Update max count ; Driver Code
using System ; class GFG { static int maxSubStrings ( String s , int k ) { int maxSubStr = 0 , n = s . Length ; for ( int c = 0 ; c < 26 ; c ++ ) { char ch = ( char ) ( ( int ) ' a ' + c ) ; int curr = 0 ; for ( int i = 0 ; i <= n - k ; i ++ ) { if ( s [ i ] != ch ) continue ; int cnt = 0 ; while ( i < n && s [ i ] == ch && cnt != k ) { i ++ ; cnt ++ ; } i -- ; if ( cnt == k ) curr ++ ; } maxSubStr = Math . Max ( maxSubStr , curr ) ; } return maxSubStr ; } public static void Main ( ) { string s = " aaacaabbaa " ; int k = 2 ; Console . WriteLine ( maxSubStrings ( s , k ) ) ; } }
Count valid pairs in the array satisfying given conditions | C # implementation of the approach ; Function to return total valid pairs ; Initialize count of all the elements ; frequency count of all the elements ; Add total valid pairs ; Exclude pairs made with a single element i . e . ( x , x ) ; Driver Code ; Function call to print required answer
using System ; class GFG { static int ValidPairs ( int [ ] arr , int n ) { int [ ] count = new int [ 121 ] ; for ( int i = 0 ; i < n ; i ++ ) count [ arr [ i ] ] += 1 ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ i ] < arr [ j ] ) continue ; if ( Math . Abs ( arr [ i ] - arr [ j ] ) % 2 == 1 ) continue ; ans += count [ arr [ i ] ] * count [ arr [ j ] ] ; if ( arr [ i ] == arr [ j ] ) ans -= count [ arr [ i ] ] ; } return ans ; } public static void Main ( ) { int [ ] arr = new int [ ] { 16 , 17 , 18 } ; int n = arr . Length ; Console . WriteLine ( ValidPairs ( arr , n ) ) ; } }
Distribution of candies according to ages of students | C # implementation of the approach ; Function to check The validity of distribution ; Stroring the max age of all students + 1 ; Stroring the max candy + 1 ; Creating the frequency array of the age of students ; Creating the frequency array of the packets of candies ; Pointer to tell whether we have reached the end of candy frequency array ; Flag to tell if distribution is possible or not ; Flag to tell if we can choose some candy packets for the students with age j ; If the quantity of packets is greater than or equal to the number of students of age j , then we can choose these packets for the students ; Start searching from k + 1 in next operation ; If we cannot choose any packets then the answer is NO ; Driver code
using System . IO ; using System ; class GFG { static void check_distribution ( int n , int k , int [ ] age , int [ ] candy ) { int mxage = age [ 0 ] ; for ( int i = 0 ; i < age . Length ; i ++ ) { if ( mxage < age [ i ] ) { mxage = age [ i ] ; } } int mxcandy = candy [ 0 ] ; for ( int i = 0 ; i < candy . Length ; i ++ ) { if ( mxcandy < candy [ i ] ) { mxcandy = candy [ i ] ; } } int [ ] fr1 = new int [ mxage + 1 ] ; Array . Fill ( fr1 , 0 ) ; int [ ] fr2 = new int [ mxcandy + 1 ] ; Array . Fill ( fr2 , 0 ) ; for ( int j = 0 ; j < n ; j ++ ) { fr1 [ age [ j ] ] += 1 ; } for ( int j = 0 ; j < k ; j ++ ) { fr2 [ candy [ j ] ] += 1 ; } k = 0 ; bool Tf = true ; for ( int j = 0 ; j < mxage ; j ++ ) { if ( fr1 [ j ] == 0 ) { continue ; } bool flag = false ; while ( k < mxcandy ) { if ( fr1 [ j ] <= fr2 [ k ] ) { flag = true ; break ; } k += 1 ; } k = k + 1 ; if ( flag == false ) { Tf = false ; break ; } } if ( Tf ) { Console . WriteLine ( " Yes " ) ; } else { Console . WriteLine ( " No " ) ; } } static void Main ( ) { int [ ] age = { 5 , 15 , 10 } ; int [ ] candy = { 2 , 2 , 2 , 3 , 3 , 4 } ; int n = age . Length ; int k = candy . Length ; check_distribution ( n , k , age , candy ) ; } }
Find a palindromic string B such that given String A is a subsequense of B | C # program to find a palindromic string B such that given String A is a subsequense of B ; Function to check if a string is palindrome ; Reversing a string ; check if reversed string is equal to given string ; Function to find a palindromic string B such that given String A is a subsequense of B ; Reversing the string A ; If the string A is already a palindrome return A ; else return B ; Swap values of left and right ; Driver Code
using System ; class GFG { static bool checkPalindrome ( String s ) { String x = reverse ( s ) ; return x . Equals ( s ) ; } static String findStringB ( String A ) { String B = reverse ( A ) ; B = B + A ; if ( checkPalindrome ( A ) ) { return A ; } return B ; } static String reverse ( String input ) { char [ ] temparray = input . ToCharArray ( ) ; int left , right = 0 ; right = temparray . Length - 1 ; for ( left = 0 ; left < right ; left ++ , right -- ) { char temp = temparray [ left ] ; temparray [ left ] = temparray [ right ] ; temparray [ right ] = temp ; } return String . Join ( " " , temparray ) ; } public static void Main ( String [ ] args ) { String A = " ab " ; Console . WriteLine ( findStringB ( A ) ) ; } }
Minimum number of 1 's to be replaced in a binary array | C # program to find minimum number of 1 ' s ▁ to ▁ be ▁ replaced ▁ to ▁ 0' s ; Function to find minimum number of 1 ' s ▁ to ▁ be ▁ replaced ▁ to ▁ 0' s ; return final answer ; Driver Code
using System ; class GFG { static int minChanges ( int [ ] A , int n ) { int cnt = 0 ; for ( int i = 0 ; i < n - 2 ; ++ i ) { if ( ( i - 1 >= 0 ) && A [ i - 1 ] == 1 && A [ i + 1 ] == 1 && A [ i ] == 0 ) { A [ i + 1 ] = 0 ; cnt ++ ; } } return cnt ; } public static void Main ( ) { int [ ] A = { 1 , 1 , 0 , 1 , 1 , 0 , 1 , 0 , 1 , 0 } ; int n = A . Length ; Console . Write ( minChanges ( A , n ) ) ; } }
Number of closing brackets needed to complete a regular bracket sequence | C # program to find number of closing brackets needed and complete a regular bracket sequence ; Function to find number of closing brackets and complete a regular bracket sequence ; Finding the length of sequence ; Counting opening brackets ; Counting closing brackets ; Checking if at any position the number of closing bracket is more then answer is impossible ; If possible , print ' s ' and required closing brackets . ; Driver Code
using System ; class GFG { static void completeSequence ( String s ) { int n = s . Length ; int open = 0 , close = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ' ( ' ) open ++ ; else close ++ ; if ( close > open ) { Console . Write ( " IMPOSSIBLE " ) ; return ; } } Console . Write ( s ) ; for ( int i = 0 ; i < open - close ; i ++ ) Console . Write ( " ) " ) ; } static void Main ( ) { String s = " ( ( ) ( ( ) ( " ; completeSequence ( s ) ; } }
Lexicographically smallest permutation with no digits at Original Index | C # program to find the smallest permutation ; Function to print the smallest permutation ; when n is even ; when n is odd ; handling last 3 digit ; add EOL and print result ; Driver Code
using System ; class GFG { static void smallestPermute ( int n ) { char [ ] res = new char [ n + 1 ] ; if ( n % 2 == 0 ) { for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) res [ i ] = ( char ) ( 48 + i + 2 ) ; else res [ i ] = ( char ) ( 48 + i ) ; } } else { for ( int i = 0 ; i < n - 2 ; i ++ ) { if ( i % 2 == 0 ) res [ i ] = ( char ) ( 48 + i + 2 ) ; else res [ i ] = ( char ) ( 48 + i ) ; } res [ n - 1 ] = ( char ) ( 48 + n - 2 ) ; res [ n - 2 ] = ( char ) ( 48 + n ) ; res [ n - 3 ] = ( char ) ( 48 + n - 1 ) ; } res [ n ] = ' \0' ; for ( int i = 0 ; i < n ; i ++ ) { Console . Write ( res [ i ] ) ; } } public static void Main ( ) { int n = 7 ; smallestPermute ( n ) ; } }
Minimum array insertions required to make consecutive difference <= K | C # implementation of above approach ; Function to return minimum number of insertions required ; Initialize insertions to 0 ; return total insertions ; Driver Code
using System ; class GFG { static int minInsertions ( int [ ] H , int n , int K ) { int inser = 0 ; for ( int i = 1 ; i < n ; ++ i ) { float diff = Math . Abs ( H [ i ] - H [ i - 1 ] ) ; if ( diff <= K ) continue ; else inser += ( int ) Math . Ceiling ( diff / K ) - 1 ; } return inser ; } static void Main ( ) { int [ ] H = new int [ ] { 2 , 4 , 8 , 16 } ; int K = 3 ; int n = H . Length ; Console . WriteLine ( minInsertions ( H , n , K ) ) ; } }
Minimum number of operations required to reduce N to 1 | C # implementation of above approach ; Function that returns the minimum number of operations to be performed to reduce the number to 1 ; To stores the total number of operations to be performed ; if n is divisible by 3 then reduce it to n / 3 ; if n modulo 3 is 1 decrement it by 1 ; if n modulo 3 is 2 then increment it by 1 ; update the counter ; Driver code
using System ; public class GFG { static int count_minimum_operations ( long n ) { int count = 0 ; while ( n > 1 ) { if ( n % 3 == 0 ) n /= 3 ; else if ( n % 3 == 1 ) n -- ; else { if ( n == 2 ) n -- ; else n ++ ; } count ++ ; } return count ; } static public void Main ( ) { long n = 4 ; long ans = count_minimum_operations ( n ) ; Console . WriteLine ( ans ) ; } }
Minimum number of operations required to reduce N to 1 | C # implementation of above approach ; Function that returns the minimum number of operations to be performed to reduce the number to 1 ; Base cases ; Driver code
using System ; class GFG { static int count_minimum_operations ( int n ) { if ( n == 2 ) { return 1 ; } else if ( n == 1 ) { return 0 ; } if ( n % 3 == 0 ) { return 1 + count_minimum_operations ( n / 3 ) ; } else if ( n % 3 == 1 ) { return 1 + count_minimum_operations ( n - 1 ) ; } else { return 1 + count_minimum_operations ( n + 1 ) ; } } static void Main ( ) { int n = 4 ; int ans = count_minimum_operations ( n ) ; Console . WriteLine ( ans ) ; } }
Maximize the sum of array by multiplying prefix of array with | C # implementation of the approach ; To store sum ; To store ending indices of the chosen prefix array vect ; Adding the absolute value of a [ i ] ; If i == 0 then there is no index to be flipped in ( i - 1 ) position ; print the maximised sum ; print the ending indices of the chosen prefix arrays ; Driver Code
using System ; using System . Collections . Generic ; class GFG { static void maxSum ( int [ ] a , int n ) { List < int > l = new List < int > ( ) ; int s = 0 ; for ( int i = 0 ; i < n ; i ++ ) { s += Math . Abs ( a [ i ] ) ; if ( a [ i ] >= 0 ) continue ; if ( i == 0 ) l . Add ( i + 1 ) ; else { l . Add ( i + 1 ) ; l . Add ( i ) ; } } Console . WriteLine ( s ) ; for ( int i = 0 ; i < l . Count ; i ++ ) Console . Write ( l [ i ] + " ▁ " ) ; } public static void Main ( String [ ] args ) { int n = 4 ; int [ ] a = { 1 , - 2 , - 3 , 4 } ; maxSum ( a , n ) ; } }
Find the longest common prefix between two strings after performing swaps on second string | C # program to find the longest common prefix between two strings after performing swaps on the second string ; int a = x . Length ; length of x int b = y . Length ; length of y ; creating frequency array of characters of y ; storing the length of longest common prefix ; checking if the frequency of the character at position i in x in b is greater than zero or not if zero we increase the prefix count by 1 ; Driver Code
using System ; class GFG { static void LengthLCP ( String x , String y ) { int [ ] fr = new int [ 26 ] ; for ( int i = 0 ; i < b ; i ++ ) { fr [ y [ i ] - 97 ] += 1 ; } int c = 0 ; for ( int i = 0 ; i < a ; i ++ ) { if ( fr [ x [ i ] - 97 ] > 0 ) { c += 1 ; fr [ x [ i ] - 97 ] -= 1 ; } else break ; } Console . Write ( ( c ) ) ; } public static void Main ( ) { String x = " here " , y = " there " ; LengthLCP ( x , y ) ; } }
All possible co | C # implementation of the approach ; Function to count possible pairs ; total count of numbers in range ; printing count of pairs ; Driver code
using System ; class GFG { static void CountPair ( int L , int R ) { int x = ( R - L + 1 ) ; Console . WriteLine ( x / 2 + " STRNEWLINE " ) ; } public static void Main ( ) { int L , R ; L = 1 ; R = 8 ; CountPair ( L , R ) ; } }
Problems not solved at the end of Nth day | C # program to find problems not solved at the end of Nth day ; Function to find problems not solved at the end of Nth day ; Driver Code
using System ; class GFG { public static int problemsLeft ( int K , int P , int N ) { if ( K <= P ) return 0 ; else return ( ( K - P ) * N ) ; } public static void Main ( ) { int K , P , N ; K = 4 ; P = 1 ; N = 10 ; Console . WriteLine ( problemsLeft ( K , P , N ) ) ; } }
Kruskal 's Algorithm (Simple Implementation for Adjacency Matrix) | Simple C # implementation for Kruskal 's algorithm ; Find set of vertex i ; Does union of i and j . It returns false if i and j are already in same set . ; Finds MST using Kruskal 's algorithm ; Initialize sets of disjoint sets . ; Include minimum weight edges one by one ; Driver code ; Let us create the following graph 2 3 ( 0 ) -- ( 1 ) -- ( 2 ) | / \ | 6 | 8 / \ 5 | 7 | / \ | ( 3 ) -- -- -- - ( 4 ) 9 ; Print the solution
using System ; class GFG { static int V = 5 ; static int [ ] parent = new int [ V ] ; static int INF = int . MaxValue ; static int find ( int i ) { while ( parent [ i ] != i ) i = parent [ i ] ; return i ; } static void union1 ( int i , int j ) { int a = find ( i ) ; int b = find ( j ) ; parent [ a ] = b ; } static void kruskalMST ( int [ , ] cost ) { for ( int i = 0 ; i < V ; i ++ ) parent [ i ] = i ; int edge_count = 0 ; while ( edge_count < V - 1 ) { int min = INF , a = - 1 , b = - 1 ; for ( int i = 0 ; i < V ; i ++ ) { for ( int j = 0 ; j < V ; j ++ ) { if ( find ( i ) != find ( j ) && cost [ i , j ] < min ) { min = cost [ i , j ] ; a = i ; b = j ; } } } union1 ( a , b ) ; Console . Write ( " Edge ▁ { 0 } : ( { 1 } , ▁ { 2 } ) ▁ cost : { 3 } ▁ STRNEWLINE " , edge_count ++ , a , b , min ) ; mincost += min ; } Console . Write ( " cost = { 0 } " , mincost ) ; } public static void Main ( String [ ] args ) { int [ , ] cost = { { INF , 2 , INF , 6 , INF } , { 2 , INF , 3 , 8 , 5 } , { INF , 3 , INF , INF , 7 } , { 6 , 8 , INF , INF , 9 } , { INF , 5 , 7 , 9 , INF } , } ; kruskalMST ( cost ) ; } }
Number of chocolates left after k iterations | C # program to find remaining chocolates after k iterations ; Function to find the chocolates left ; Driver code
using System ; class GFG { static int results ( int n , int k ) { return ( int ) Math . Round ( Math . Pow ( n , ( 1.0 / Math . Pow ( 2.0 , k ) ) ) ) ; } public static void Main ( ) { int k = 3 , n = 100000000 ; Console . Write ( " Chocolates ▁ left ▁ after ▁ " + k + " ▁ iterations ▁ are ▁ " + results ( n , k ) ) ; } }
Subarray whose absolute sum is closest to K | C # code to find sub - array whose sum shows the minimum deviation ; Starting index , ending index , Deviation ; Iterate i and j to get all subarrays ; Found sub - array with less sum ; Exactly same sum ; Driver Code ; Array to store return values
using System ; class GFG { public static int [ ] getSubArray ( int [ ] arr , int n , int K ) { int i = - 1 ; int j = - 1 ; int currSum = 0 ; int [ ] result = { i , j , Math . Abs ( K - Math . Abs ( currSum ) ) } ; for ( i = 0 ; i < n ; i ++ ) { currSum = 0 ; for ( j = i ; j < n ; j ++ ) { currSum += arr [ j ] ; int currDev = Math . Abs ( K - Math . Abs ( currSum ) ) ; if ( currDev < result [ 2 ] ) { result [ 0 ] = i ; result [ 1 ] = j ; result [ 2 ] = currDev ; } if ( currDev == 0 ) return result ; } } return result ; } public static void Main ( string [ ] args ) { int [ ] arr = { 15 , - 3 , 5 , 2 , 7 , 6 , 34 , - 6 } ; int n = arr . Length ; int K = 50 ; int [ ] ans = getSubArray ( arr , n , K ) ; if ( ans [ 0 ] == - 1 ) { Console . Write ( " The ▁ empty ▁ array ▁ " + " shows ▁ minimum ▁ Deviation " ) ; } else { for ( int i = ans [ 0 ] ; i <= ans [ 1 ] ; i ++ ) Console . Write ( arr [ i ] + " ▁ " ) ; } } }
Longest subsequence whose average is less than K | C # program to perform Q queries to find longest subsequence whose average is less than K ; Function to print the length for evey query ; sort array of N elements ; Array to store average from left ; Sort array of average ; number of queries ; print answer to every query using binary search ; Driver Code ; 4 queries
using System ; class GFG { static void longestSubsequence ( int [ ] a , int n , int [ ] q , int m ) { Array . Sort ( a ) ; int sum = 0 ; int [ ] b = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { sum += a [ i ] ; double av = ( double ) ( sum ) / ( double ) ( i + 1 ) ; b [ i ] = ( ( int ) ( av + 1 ) ) ; } Array . Sort ( b ) ; for ( int i = 0 ; i < m ; i ++ ) { int k = q [ i ] ; int longest = upperBound ( b , 0 , n , k ) ; Console . WriteLine ( " Answer ▁ to ▁ Query " + ( i + 1 ) + " : ▁ " + longest ) ; } } private static int upperBound ( int [ ] a , int low , int high , int element ) { while ( low < high ) { int middle = low + ( high - low ) / 2 ; if ( a [ middle ] > element ) high = middle ; else low = middle + 1 ; } return low ; } static public void Main ( ) { int [ ] a = { 1 , 3 , 2 , 5 , 4 } ; int n = a . Length ; int [ ] q = { 4 , 2 , 1 , 5 } ; int m = q . Length ; longestSubsequence ( a , n , q , m ) ; } }
Make array elements equal in Minimum Steps | C # program to make the array elements equal in minimum steps ; Returns the minimum steps required to make an array of N elements equal , where the first array element equals M ; Corner Case 1 : When N = 1 ; Corner Case 2 : When N = 2 else if ( N == 2 ) corner case 2 ; Driver Code
using System ; class GFG { static int steps ( int N , int M ) { if ( N == 1 ) return 0 ; return M ; return 2 * M + ( N - 3 ) ; } public static void Main ( ) { int N = 4 , M = 4 ; Console . WriteLine ( steps ( N , M ) ) ; } }
Minimum increment / decrement to make array non | C # code to count the change required to convert the array into non - increasing array ; min heap ; Here in the loop we will check that whether the upcoming element of array is less than top of priority queue . If yes then we calculate the difference . After that we will remove that element and push the current element in queue . And the sum is incremented by the value of difference ; Driver code
using System ; using System . Collections . Generic ; class GFG { static int DecreasingArray ( int [ ] a , int n ) { int sum = 0 , dif = 0 ; List < int > pq = new List < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( pq . Count > 0 && pq [ 0 ] < a [ i ] ) { dif = a [ i ] - pq [ 0 ] ; sum += dif ; pq . RemoveAt ( 0 ) ; } pq . Add ( a [ i ] ) ; pq . Sort ( ) ; } return sum ; } static void Main ( ) { int [ ] a = { 3 , 1 , 2 , 1 } ; int n = a . Length ; Console . Write ( DecreasingArray ( a , n ) ) ; } }
Schedule jobs so that each server gets equal load | C # program to schedule jobs so that each server gets equal load . ; Function to find new array a ; find sum S of both arrays a and b . ; Single element case . ; This checks whether sum s can be divided equally between all array elements . i . e . whether all elements can take equal value or not . ; Compute possible value of new array elements . ; Possibility 1 ; ensuring that all elements of array b are used . ; If a ( i ) already updated to x move to next element in array a . ; Possibility 2 ; Possibility 3 ; Possibility 4 ; If a ( i ) can not be made equal to x even after adding all possible elements from b ( i ) then print - 1. ; check whether all elements of b are used . ; Return the new array element value . ; Driver code
using System ; class GFG { static int solve ( int [ ] a , int [ ] b , int n ) { int i ; int s = 0 ; for ( i = 0 ; i < n ; i ++ ) s += ( a [ i ] + b [ i ] ) ; if ( n == 1 ) return a [ 0 ] + b [ 0 ] ; if ( s % n != 0 ) return - 1 ; int x = s / n ; for ( i = 0 ; i < n ; i ++ ) { if ( a [ i ] > x ) return - 1 ; if ( i > 0 ) { a [ i ] += b [ i - 1 ] ; b [ i - 1 ] = 0 ; } if ( a [ i ] == x ) continue ; int y = a [ i ] + b [ i ] ; if ( i + 1 < n ) y += b [ i + 1 ] ; if ( y == x ) { a [ i ] = y ; b [ i ] = 0 ; continue ; } if ( a [ i ] + b [ i ] == x ) { a [ i ] += b [ i ] ; b [ i ] = 0 ; continue ; } if ( i + 1 < n && a [ i ] + b [ i + 1 ] == x ) { a [ i ] += b [ i + 1 ] ; b [ i + 1 ] = 0 ; continue ; } return - 1 ; } for ( i = 0 ; i < n ; i ++ ) if ( b [ i ] != 0 ) return - 1 ; return x ; } public static void Main ( String [ ] args ) { int [ ] a = { 6 , 14 , 21 , 1 } ; int [ ] b = { 15 , 7 , 10 , 10 } ; int n = a . Length ; Console . WriteLine ( solve ( a , b , n ) ) ; } }
Check if it is possible to survive on Island | C # program to find the minimum days on which you need to buy food from the shop so that you can survive the next S days ; function to find the minimum days ; If we can not buy at least a week supply of food during the first week OR We can not buy a day supply of food on the first day then we can 't survive. ; If we can survive then we can buy ceil ( A / N ) times where A is total units of food required . ; Driver code
using System ; class GFG { static void survival ( int S , int N , int M ) { if ( ( ( N * 6 ) < ( M * 7 ) && S > 6 ) M > N ) Console . Write ( " No " ) ; else { int days = ( M * S ) / N ; if ( ( ( M * S ) % N ) != 0 ) days ++ ; Console . WriteLine ( " Yes ▁ " + days ) ; } } public static void Main ( ) { int S = 10 , N = 16 , M = 2 ; survival ( S , N , M ) ; } }
Lexicographically largest subsequence such that every character occurs at least k times | C # program to find lexicographically largest subsequence where every character appears at least k times . ; Find lexicographically largest subsequence of s [ 0. . n - 1 ] such that every character appears at least k times . The result is filled in t [ ] ; Starting from largest character ' z ' to ' a ' ; Counting the frequency of the character ; If frequency is greater than k ; From the last point we leave ; check if string contain ch ; If yes , append to output string ; Update the last point . ; Driver code
using System ; class GFG { static void subsequence ( char [ ] s , char [ ] t , int n , int k ) { int last = 0 , cnt = 0 , new_last = 0 , size = 0 ; for ( char ch = ' z ' ; ch >= ' a ' ; ch -- ) { cnt = 0 ; for ( int i = last ; i < n ; i ++ ) { if ( s [ i ] == ch ) cnt ++ ; } if ( cnt >= k ) { for ( int i = last ; i < n ; i ++ ) { if ( s [ i ] == ch ) { t [ size ++ ] = ch ; new_last = i ; } } last = new_last ; } } t [ size ] = ' \0' ; } public static void Main ( ) { char [ ] s = { ' b ' , ' a ' , ' n ' , ' a ' , ' n ' , ' a ' } ; int n = s . Length ; int k = 2 ; char [ ] t = new char [ n ] ; subsequence ( s , t , n - 1 , k ) ; for ( int i = 0 ; i < t . Length ; i ++ ) if ( t [ i ] != 0 ) Console . Write ( t [ i ] ) ; } }
Program for Least Recently Used ( LRU ) Page Replacement algorithm | C # implementation of above algorithm ; Method to find page faults using indexes ; To represent set of current pages . We use an unordered_set so that we quickly check if a page is present in set or not ; To store least recently used indexes of pages . ; Start from initial page ; Check if the set can hold more pages ; Insert it into set if not present already which represents page fault ; increment page fault ; Store the recently used index of each page ; If the set is full then need to perform lru i . e . remove the least recently used page and insert the current page ; Check if current page is not already present in the set ; Find the least recently used pages that is present in the set ; Remove the indexes page ; remove lru from hashmap ; insert the current page ; Increment page faults ; Update the current page index ; Driver Code
using System ; using System . Collections . Generic ; class GFG { static int pageFaults ( int [ ] pages , int n , int capacity ) { HashSet < int > s = new HashSet < int > ( capacity ) ; Dictionary < int , int > indexes = new Dictionary < int , int > ( ) ; int page_faults = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . Count < capacity ) { if ( ! s . Contains ( pages [ i ] ) ) { s . Add ( pages [ i ] ) ; page_faults ++ ; } if ( indexes . ContainsKey ( pages [ i ] ) ) indexes [ pages [ i ] ] = i ; else indexes . Add ( pages [ i ] , i ) ; } else { if ( ! s . Contains ( pages [ i ] ) ) { int lru = int . MaxValue , val = int . MinValue ; foreach ( int itr in s ) { int temp = itr ; if ( indexes [ temp ] < lru ) { lru = indexes [ temp ] ; val = temp ; } } s . Remove ( val ) ; indexes . Remove ( val ) ; s . Add ( pages [ i ] ) ; page_faults ++ ; } if ( indexes . ContainsKey ( pages [ i ] ) ) indexes [ pages [ i ] ] = i ; else indexes . Add ( pages [ i ] , i ) ; } } return page_faults ; } public static void Main ( String [ ] args ) { int [ ] pages = { 7 , 0 , 1 , 2 , 0 , 3 , 0 , 4 , 2 , 3 , 0 , 3 , 2 } ; int capacity = 4 ; Console . WriteLine ( pageFaults ( pages , pages . Length , capacity ) ) ; } }
Largest permutation after at most k swaps | C # Program to find the largest permutation after at most k swaps using unordered_map . ; Function to find the largest permutation after k swaps ; Storing the elements and their index in map ; If number of swaps allowed are equal to number of elements then the resulting permutation will be descending order of given permutation . ; if j is not at it 's best index ; Change the index of the element which was at position 0. Swap the element basically . ; decrement number of swaps ; Driver code ; K is the number of swaps ; n is the size of the array ; Function calling
using System ; using System . Collections . Generic ; class GFG { static void bestpermutation ( List < int > arr , int k , int n ) { Dictionary < int , int > h = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { h . Add ( arr [ i ] , i ) ; } if ( n <= k ) { arr . Sort ( ) ; arr . Reverse ( ) ; } else { for ( int j = n ; j >= 1 ; j -- ) { if ( k > 0 ) { int initial_index = h [ j ] ; int best_index = n - j ; if ( initial_index != best_index ) { h [ j ] = best_index ; int element = arr [ best_index ] ; h [ element ] = initial_index ; int temp = arr [ best_index ] ; arr [ best_index ] = arr [ initial_index ] ; arr [ initial_index ] = temp ; k -- ; } } } } } static void Main ( ) { List < int > arr = new List < int > ( new int [ ] { 3 , 1 , 4 , 2 , 5 } ) ; int k = 10 ; int n = arr . Count ; bestpermutation ( arr , k , n ) ; Console . Write ( " Largest ▁ possible ▁ permutation ▁ after ▁ " + k + " ▁ swaps ▁ is ▁ " ) ; for ( int i = 0 ; i < n ; i ++ ) Console . Write ( arr [ i ] + " ▁ " ) ; } }