text
stringlengths 17
3.65k
| code
stringlengths 60
5.26k
|
---|---|
Shuffle a pack of cards and answer the query | C # program to find the card at given index after N shuffles ; function to find card at given index ; Answer will be reversal of N bits from MSB ; Calculating the reverse binary representation ; Printing the result ; Driver code ; No . of Shuffle Steps ; Key position
|
using System ; class GFG { static void shuffle ( int N , int key ) { int NO_OF_BITS = N ; int reverse_num = 0 , temp ; for ( int i = 0 ; i < NO_OF_BITS ; i ++ ) { temp = ( key & ( 1 << i ) ) ; if ( temp > 0 ) reverse_num |= ( 1 << ( ( NO_OF_BITS - 1 ) - i ) ) ; } Console . Write ( reverse_num ) ; } public static void Main ( ) { int N = 3 ; int key = 3 ; shuffle ( N , key ) ; } }
|
Sum of numbers with exactly 2 bits set | C # program to find sum of numbers upto n whose 2 bits are set ; To count number of set bits ; To calculate sum of numbers ; To count sum of number whose 2 bit are set ; Driver Code
|
using System ; class GFG { static int countSetBits ( int n ) { int count = 0 ; while ( n > 0 ) { n = n & ( n - 1 ) ; count ++ ; } return count ; } static int findSum ( int n ) { int sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) if ( countSetBits ( i ) == 2 ) sum += i ; return sum ; } static public void Main ( ) { int n = 10 ; Console . WriteLine ( findSum ( n ) ) ; } }
|
Toggle the last m bits | C # implementation to toggle the last m bits ; Function to toggle the last m bits ; Calculating a number ' num ' having ' m ' bits and all are set ; Toggle the last m bits and return the number ; Driver Code
|
using System ; namespace Toggle { public class GFG { public static int toggleLastMBits ( int n , int m ) { int num = ( 1 << m ) - 1 ; return ( n ^ num ) ; } public static void Main ( ) { int n = 107 , m = 4 ; n = toggleLastMBits ( n , m ) ; Console . Write ( n ) ; } } }
|
Set the rightmost unset bit | C # implementation to set the rightmost unset bit ; Function to find the position of rightmost set bit ; If n = 0 , return 1 ; If all bits of ' n ' are set ; Position of rightmost unset bit in ' n ' passing ~ n as argument ; Set the bit at position ' pos ' ; Driver code
|
using System ; class GFG { static int getPosOfRightmostSetBit ( int n ) { return ( int ) ( ( Math . Log10 ( n & - n ) ) / ( Math . Log10 ( 2 ) ) ) + 1 ; } static int setRightmostUnsetBit ( int n ) { if ( n == 0 ) return 1 ; if ( ( n & ( n + 1 ) ) == 0 ) return n ; int pos = getPosOfRightmostSetBit ( ~ n ) ; return ( ( 1 << ( pos - 1 ) ) n ) ; } public static void Main ( String [ ] arg ) { int n = 21 ; Console . Write ( setRightmostUnsetBit ( n ) ) ; } }
|
Previous smaller integer having one less number of set bits | C # implementation to find the previous smaller integer with one less number of set bits ; function to find the position of rightmost set bit . ; function to find the previous smaller integer ; position of rightmost set bit of n ; turn off or unset the bit at position ' pos ' ; Driver code
|
using System ; class GFG { static int getFirstSetBitPos ( int n ) { return ( int ) ( Math . Log ( n & - n ) / Math . Log ( 2 ) ) + 1 ; } static int previousSmallerInteger ( int n ) { int pos = getFirstSetBitPos ( n ) ; return ( n & ~ ( 1 << ( pos - 1 ) ) ) ; } public static void Main ( ) { int n = 25 ; Console . WriteLine ( " Previous β small β Integer β = " + previousSmallerInteger ( n ) ) ; } }
|
Check if all bits of a number are set | C # implementation to check whether every digit in the binary representation of the given number is set or not ; function to check if all the bits are set or not in the binary representation of ' n ' ; all bits are not set ; loop till n becomes '0' ; if the last bit is not set ; right shift ' n ' by 1 ; all bits are set ; Driver Code
|
using System ; class GFG { static String areAllBitsSet ( int n ) { if ( n == 0 ) return " No " ; while ( n > 0 ) { if ( ( n & 1 ) == 0 ) return " No " ; n = n >> 1 ; } return " Yes " ; } static public void Main ( ) { int n = 7 ; Console . WriteLine ( areAllBitsSet ( n ) ) ; } }
|
Check if all bits of a number are set | C # implementation to check whether every digit in the binary representation of the given number is set or not ; function to check if all the bits are set or not in the binary representation of ' n ' ; all bits are not set ; if true , then all bits are set ; else all bits are not set ; Driver Code
|
using System ; class GFG { static String areAllBitsSet ( int n ) { if ( n == 0 ) return " No " ; if ( ( ( n + 1 ) & n ) == 0 ) return " Yes " ; return " No " ; } static public void Main ( ) { int n = 7 ; Console . WriteLine ( areAllBitsSet ( n ) ) ; } }
|
Next greater integer having one more number of set bits | C # implementation to find the next greater integer with one more number of set bits ; function to find the position of rightmost set bit . Returns - 1 if there are no set bits ; function to find the next greater integer ; position of rightmost unset bit of n by passing ~ n as argument ; if n consists of unset bits , then set the rightmost unset bit ; n does not consists of unset bits ; Driver code
|
using System ; class GFG { static int getFirstSetBitPos ( int n ) { return ( ( int ) ( Math . Log ( n & - n ) / Math . Log ( 2 ) ) + 1 ) - 1 ; } static int nextGreaterWithOneMoreSetBit ( int n ) { int pos = getFirstSetBitPos ( ~ n ) ; if ( pos > - 1 ) return ( 1 << pos ) | n ; return ( ( n << 1 ) + 1 ) ; } public static void Main ( ) { int n = 10 ; Console . Write ( " Next β greater β integer β = β " + nextGreaterWithOneMoreSetBit ( n ) ) ; } }
|
Count numbers whose sum with x is equal to XOR with x | C # program to count numbers whose bitwise XOR and sum with x are equal ; Function to find total 0 bit in a number ; Function to find Count of non - negative numbers less than or equal to x , whose bitwise XOR and SUM with x are equal . ; count number of zero bit in x ; power of 2 to count ; Driver code ; Function call
|
using System ; class GFG { static int CountZeroBit ( int x ) { int count = 0 ; while ( x > 0 ) { if ( ( x & 1 ) == 0 ) count ++ ; x >>= 1 ; } return count ; } static int CountXORandSumEqual ( int x ) { int count = CountZeroBit ( x ) ; return ( 1 << count ) ; } static public void Main ( ) { int x = 10 ; Console . WriteLine ( CountXORandSumEqual ( x ) ) ; } }
|
Find missing number in another array which is shuffled copy | C # implementation to find the missing number in shuffled array ; Returns the missing number Size of arr2 [ ] is n - 1 ; Missing number ' mnum ' ; 1 st array is of size ' n ' ; 2 nd array is of size ' n β - β 1' ; Required missing number ; Driver Code
|
using System ; class GFG { static int missingNumber ( int [ ] arr1 , int [ ] arr2 , int n ) { int mnum = 0 ; for ( int i = 0 ; i < n ; i ++ ) mnum = mnum ^ arr1 [ i ] ; for ( int i = 0 ; i < n - 1 ; i ++ ) mnum = mnum ^ arr2 [ i ] ; return mnum ; } public static void Main ( ) { int [ ] arr1 = { 4 , 8 , 1 , 3 , 7 } ; int [ ] arr2 = { 7 , 4 , 3 , 1 } ; int n = arr1 . Length ; Console . Write ( " Missing β number β = β " + missingNumber ( arr1 , arr2 , n ) ) ; } }
|
Find Duplicates of array using bit array | A class to represent array of bits using array of integers ; Constructor ; Divide by 32. To store n bits , we need n / 32 + 1 integers ( Assuming int is stored using 32 bits ) ; Get value of a bit at given position ; Divide by 32 to find position of integer . ; Now find bit number in arr [ index ] ; Find value of given bit number in arr [ index ] ; Sets a bit at given position ; Find index of bit position ; Set bit number in arr [ index ] ; Main function to print all Duplicates ; create a bit with 32000 bits ; Traverse array elements ; Index in bit array ; If num is already present in bit array ; Else insert num ; Driver code
|
using System ; class BitArray { int [ ] arr ; public BitArray ( int n ) { arr = new int [ ( int ) ( n >> 5 ) + 1 ] ; } bool get ( int pos ) { int index = ( pos >> 5 ) ; int bitNo = ( pos & 0x1F ) ; return ( arr [ index ] & ( 1 << bitNo ) ) != 0 ; } void set ( int pos ) { int index = ( pos >> 5 ) ; int bitNo = ( pos & 0x1F ) ; arr [ index ] |= ( 1 << bitNo ) ; } static void checkDuplicates ( int [ ] arr ) { BitArray ba = new BitArray ( 320000 ) ; for ( int i = 0 ; i < arr . Length ; i ++ ) { int num = arr [ i ] ; if ( ba . get ( num ) ) Console . Write ( num + " β " ) ; else ba . set ( num ) ; } } public static void Main ( ) { int [ ] arr = { 1 , 5 , 1 , 10 , 12 , 10 } ; checkDuplicates ( arr ) ; } }
|
Count smaller values whose XOR with x is greater than x | C # program to find count of values whose XOR with x is greater than x and values are smaller than x ; Initialize result ; Traversing through all bits of x ; If current last bit of x is set then increment count by n . Here n is a power of 2 corresponding to position of bit ; Simultaneously calculate the 2 ^ n ; Replace x with x / 2 ; ; Driver code
|
using System ; class GFG { static int countValues ( int x ) { int count = 0 , n = 1 ; while ( x != 0 ) { if ( x % 2 == 0 ) count += n ; n *= 2 ; x /= 2 ; } return count ; } public static void Main ( ) { int x = 10 ; Console . Write ( countValues ( x ) ) ; } }
|
Construct an array from XOR of all elements of array except element at same index | C # program to construct array from XOR of elements of given array ; function to construct new array ; calculate xor of array ; update array ; Driver code ; print result
|
using System ; class GFG { static void constructXOR ( int [ ] A , int n ) { int XOR = 0 ; for ( int i = 0 ; i < n ; i ++ ) XOR ^= A [ i ] ; for ( int i = 0 ; i < n ; i ++ ) A [ i ] = XOR ^ A [ i ] ; } public static void Main ( ) { int [ ] A = { 2 , 4 , 1 , 3 , 5 } ; int n = A . Length ; constructXOR ( A , n ) ; for ( int i = 0 ; i < n ; i ++ ) Console . Write ( A [ i ] + " β " ) ; } }
|
Count all pairs of an array which differ in K bits | C # program to count all pairs with bit difference as k ; Utility function to count total ones in a number ; Function to count pairs of K different bits ; long ans = 0 ; initialize final answer ; Check for K differ bit ; Driver code
|
using System ; class GFG { static int bitCount ( int n ) { int count = 0 ; while ( n > 0 ) { if ( ( n & 1 ) > 0 ) ++ count ; n >>= 1 ; } return count ; } static long countPairsWithKDiff ( int [ ] arr , int n , int k ) { for ( int i = 0 ; i < n - 1 ; ++ i ) { for ( int j = i + 1 ; j < n ; ++ j ) { int xoredNum = arr [ i ] ^ arr [ j ] ; if ( k == bitCount ( xoredNum ) ) ++ ans ; } } return ans ; } public static void Main ( ) { int k = 2 ; int [ ] arr = { 2 , 4 , 1 , 3 , 1 } ; int n = arr . Length ; Console . WriteLine ( " Total β pairs β for β k β = β " + k + " β are β " + countPairsWithKDiff ( arr , n , k ) + " STRNEWLINE " ) ; } }
|
Count all pairs of an array which differ in K bits | Below is C # approach of finding total k bit difference pairs ; Function to calculate K bit different pairs in array ; Get the maximum value among all array elemensts ; Set the count array to 0 , count [ ] stores the total frequency of array elements ; Initialize result ; For 0 bit answer will be total count of same number ; if count [ i ] is 0 , skip the next loop as it will not contribute the answer ; Update answer if k differ bit found ; Driver code
|
using System ; using System . Linq ; class GFG { static long kBitDifferencePairs ( int [ ] arr , int n , int k ) { int MAX = arr . Max ( ) ; long [ ] count = new long [ MAX + 1 ] ; for ( int i = 0 ; i < n ; ++ i ) ++ count [ arr [ i ] ] ; long ans = 0 ; if ( k == 0 ) { for ( int i = 0 ; i <= MAX ; ++ i ) ans += ( count [ i ] * ( count [ i ] - 1 ) ) / 2 ; return ans ; } for ( int i = 0 ; i <= MAX ; ++ i ) { if ( count [ i ] == 0 ) continue ; for ( int j = i + 1 ; j <= MAX ; ++ j ) { if ( BitCount ( i ^ j ) == k ) ans += count [ i ] * count [ j ] ; } } return ans ; } static int BitCount ( int n ) { int count = 0 ; while ( n > 0 ) { count += n & 1 ; n >>= 1 ; } return count ; } public static void Main ( String [ ] args ) { int k = 2 ; int [ ] arr = { 2 , 4 , 1 , 3 , 1 } ; int n = arr . Length ; Console . WriteLine ( " Total β pairs β for β k β = β " + k + " β are β = β " + kBitDifferencePairs ( arr , n , k ) ) ; k = 3 ; Console . WriteLine ( " Total β pairs β for β k β = β " + k + " β are β = β " + kBitDifferencePairs ( arr , n , k ) ) ; } }
|
Ways to represent a number as a sum of 1 ' s β and β 2' s | C # program to find number of ways to representing a number as a sum of 1 ' s β and β 2' s ; Function to multiply matrix . ; Power function in log n ; function that returns ( n + 1 ) th Fibonacci number Or number of ways to represent n as sum of 1 ' s β β 2' s ; Driver program
|
class GFG { static void multiply ( int [ , ] F , int [ , ] M ) { int x = F [ 0 , 0 ] * M [ 0 , 0 ] + F [ 0 , 1 ] * M [ 1 , 0 ] ; int y = F [ 0 , 0 ] * M [ 0 , 1 ] + F [ 0 , 1 ] * M [ 1 , 1 ] ; int z = F [ 1 , 0 ] * M [ 0 , 0 ] + F [ 1 , 1 ] * M [ 1 , 0 ] ; int w = F [ 1 , 0 ] * M [ 0 , 1 ] + F [ 1 , 1 ] * M [ 1 , 1 ] ; F [ 0 , 0 ] = x ; F [ 0 , 1 ] = y ; F [ 1 , 0 ] = z ; F [ 1 , 1 ] = w ; } static void power ( int [ , ] F , int n ) { if ( n == 0 n == 1 ) { return ; } int [ , ] M = { { 1 , 1 } , { 1 , 0 } } ; power ( F , n / 2 ) ; multiply ( F , F ) ; if ( n % 2 != 0 ) { multiply ( F , M ) ; } } static int countWays ( int n ) { int [ , ] F = { { 1 , 1 } , { 1 , 0 } } ; if ( n == 0 ) { return 0 ; } power ( F , n ) ; return F [ 0 , 0 ] ; } public static void Main ( ) { int n = 5 ; System . Console . WriteLine ( countWays ( n ) ) ; } }
|
Multiplication of two numbers with shift operator | C # program to find multiplication of two number without use of multiplication operator ; Function for multiplication ; check for set bit and left shift n , count times ; increment of place value ( count ) ; Driver Code
|
using System ; class GFG { static int multiply ( int n , int m ) { int ans = 0 , count = 0 ; while ( m > 0 ) { if ( m % 2 == 1 ) ans += n << count ; count ++ ; m /= 2 ; } return ans ; } public static void Main ( ) { int n = 20 , m = 13 ; Console . WriteLine ( multiply ( n , m ) ) ; } }
|
Compare two integers without using any Comparison operator | C # program to compare two integers without any comparison operator . ; function return true if A ^ B > 0 else false ; Driver Code
|
using System ; class GFG { static bool EqualNumber ( int A , int B ) { if ( ( A ^ B ) > 0 ) return true ; else return false ; } public static void Main ( ) { int A = 5 , B = 6 ; if ( ! EqualNumber ( A , B ) == false ) Console . WriteLine ( "0" ) ; else Console . WriteLine ( "1" ) ; } }
|
Check if bits of a number has count of consecutive set bits in increasing order | C # program to check if counts of consecutive 1 s are increasing order . ; Returns true if n has counts of consecutive 1 's are increasing order. ; Initialize previous count ; We traverse bits from right to left and check if counts are decreasing order . ; Ignore 0 s until we reach a set bit . ; Count current set bits ; Compare current with previous and update previous . ; Driver code
|
using System ; class GFG { static bool areSetBitsIncreasing ( int n ) { int prev_count = int . MaxValue ; while ( n > 0 ) { while ( n > 0 && n % 2 == 0 ) n = n / 2 ; int curr_count = 1 ; while ( n > 0 && n % 2 == 1 ) { n = n / 2 ; curr_count ++ ; } if ( curr_count >= prev_count ) return false ; prev_count = curr_count ; } return true ; } static public void Main ( ) { int n = 10 ; if ( areSetBitsIncreasing ( n ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
|
Check if a number has bits in alternate pattern | Set 1 | Program to find if a number has alternate bit pattern ; Returns true if n has alternate bit pattern else returns false ; Store last bit ; Traverse through remaining bits ; If current bit is same as previous ; Driver method
|
using System ; class Test { static bool findPattern ( int n ) { int prev = n % 2 ; n = n / 2 ; while ( n > 0 ) { int curr = n % 2 ; if ( curr == prev ) return false ; prev = curr ; n = n / 2 ; } return true ; } public static void Main ( ) { int n = 10 ; Console . WriteLine ( findPattern ( n ) ? " Yes " : " No " ) ; } }
|
XOR counts of 0 s and 1 s in binary representation | C # program to find XOR of counts 0 s and 1 s in binary representation of n . ; Returns XOR of counts 0 s and 1 s in binary representation of n . ; calculating count of zeros and ones ; Driver Program
|
using System ; class GFG { static int countXOR ( int n ) { int count0 = 0 , count1 = 0 ; while ( n != 0 ) { if ( n % 2 == 0 ) count0 ++ ; else count1 ++ ; n /= 2 ; } return ( count0 ^ count1 ) ; } public static void Main ( ) { int n = 31 ; Console . WriteLine ( countXOR ( n ) ) ; } }
|
Count all pairs with given XOR | C # program to Count all pair with given XOR value x ; Returns count of pairs in arr [ 0. . n - 1 ] with XOR value equals to x . ; create empty map that stores counts of individual elements of array . ; If there exist an element in map m with XOR equals to x ^ arr [ i ] , that means there exist an element such that the XOR of element with arr [ i ] is equal to x , then increment count . ; Increment count of current element ; return total count of pairs with XOR equal to x ; Driver code
|
using System ; using System . Collections . Generic ; class GFG { static int xorPairCount ( int [ ] arr , int n , int x ) { Dictionary < int , int > m = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int curr_xor = x ^ arr [ i ] ; if ( m . ContainsKey ( curr_xor ) ) result += m [ curr_xor ] ; if ( m . ContainsKey ( arr [ i ] ) ) { var val = m [ arr [ i ] ] ; m . Remove ( arr [ i ] ) ; m . Add ( arr [ i ] , val + 1 ) ; } else { m . Add ( arr [ i ] , 1 ) ; } } return result ; } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , 5 , 2 } ; int n = arr . Length ; int x = 0 ; Console . WriteLine ( " Count β of β pairs β with β given β XOR β = β " + xorPairCount ( arr , n , x ) ) ; } }
|
Bitwise and ( or & ) of a range | An efficient C # program to find bit - wise & of all numbers from x to y . ; Find position of MSB in n . For example if n = 17 , then position of MSB is 4. If n = 7 , value of MSB is 3 ; Function to find Bit - wise & of all numbers from x to y . ; Initialize result ; Find positions of MSB in x and y ; If positions are not same , return ; Add 2 ^ msb_p1 to result ; subtract 2 ^ msb_p1 from x and y . ; Driver code
|
using System ; class GFG { static int msbPos ( long n ) { int msb_p = - 1 ; while ( n > 0 ) { n = n >> 1 ; msb_p ++ ; } return msb_p ; } static long andOperator ( long x , long y ) { long res = 0 ; while ( x > 0 && y > 0 ) { int msb_p1 = msbPos ( x ) ; int msb_p2 = msbPos ( y ) ; if ( msb_p1 != msb_p2 ) break ; long msb_val = ( 1 << msb_p1 ) ; res = res + msb_val ; x = x - msb_val ; y = y - msb_val ; } return res ; } public static void Main ( ) { long x = 10 , y = 15 ; Console . WriteLine ( andOperator ( x , y ) ) ; } }
|
Multiply a number with 10 without using multiplication operator | C # Code to Multiply a number with 10 without using multiplication operator ; Function to find multiplication of n with 10 without using multiplication operator ; Driver Code
|
using System ; class GFG { public static int multiplyTen ( int n ) { return ( n << 1 ) + ( n << 3 ) ; } public static void Main ( ) { int n = 50 ; Console . Write ( multiplyTen ( n ) ) ; } }
|
Equal Sum and XOR | C # program to print count of values such that n + i = n ^ i ; function to count number of values less than equal to n that satisfy the given condition ; Traverse all numbers from 0 to n and increment result only when given condition is satisfied . ; Driver program to test above function
|
using System ; class GFG { public static int countValues ( int n ) { int countV = 0 ; for ( int i = 0 ; i <= n ; i ++ ) if ( ( n + i ) == ( n ^ i ) ) countV ++ ; return countV ; } public static void Main ( ) { int n = 12 ; Console . WriteLine ( countValues ( n ) ) ; } }
|
Equal Sum and XOR | C # program to print count of values such that n + i = n ^ i ; function to count number of values less than equal to n that satisfy the given condition ; unset_bits keeps track of count of un - set bits in binary representation of n ; Return 2 ^ unset_bits ; Driver program to test above function
|
using System ; public class GFG { public static int countValues ( int n ) { int unset_bits = 0 ; while ( n > 0 ) { if ( ( n & 1 ) == 0 ) unset_bits ++ ; n = n >> 1 ; } return 1 << unset_bits ; } public static void Main ( String [ ] args ) { int n = 12 ; Console . WriteLine ( countValues ( n ) ) ; } }
|
Find profession in a special family | C # program to find profession of a person at given level and position ; Returns ' e ' if profession of node at given level and position is engineer . Else doctor . The function assumes that given position and level have valid values . ; Base case ; Recursively find parent 's profession. If parent is a Doctor, this node will be a Doctor if it is at odd position and an engineer if at even position ; If parent is an engineer , then current node will be an engineer if at add position and doctor if even position . ; Driver code
|
using System ; class GFG { static char findProffesion ( int level , int pos ) { if ( level == 1 ) return ' e ' ; if ( findProffesion ( level - 1 , ( pos + 1 ) / 2 ) == ' d ' ) return ( pos % 2 > 0 ) ? ' d ' : ' e ' ; return ( pos % 2 > 0 ) ? ' e ' : ' d ' ; } public static void Main ( ) { int level = 4 , pos = 2 ; if ( findProffesion ( level , pos ) == ' e ' ) Console . WriteLine ( " Engineer " ) ; else Console . WriteLine ( " Doctor " ) ; } }
|
Print first n numbers with exactly two set bits | C # program to print first n numbers with exactly two set bits ; Function to print first n numbers with two set bits ; Initialize higher of two sets bits ; Keep reducing n for every number with two set bits ; Consider all lower set bits for current higher set bit ; Print current number ; If we have found n numbers ; Consider next lower bit for current higher bit . ; Increment higher set bit ; Driver program
|
using System ; class GFG { static void printTwoSetBitNums ( int n ) { int x = 1 ; while ( n > 0 ) { int y = 0 ; while ( y < x ) { Console . Write ( ( ( 1 << x ) + ( 1 << y ) ) + " β " ) ; n -- ; if ( n == 0 ) return ; y ++ ; } x ++ ; } } public static void Main ( ) { int n = 4 ; printTwoSetBitNums ( n ) ; } }
|
Find even occurring elements in an array of limited range | C # Program to find the even occurring elements in given array ; Function to find the even occurring elements in given array ; do for each element of array ; left - shift 1 by value of current element ; Toggle the bit everytime element gets repeated ; Traverse array again and use _xor to find even occurring elements ; left - shift 1 by value of current element ; Each 0 in _xor represents an even occurrence ; print the even occurring numbers ; set bit as 1 to avoid printing duplicates ; Driver code
|
using System ; class GFG { static void printRepeatingEven ( int [ ] arr , int n ) { long _xor = 0L ; long pos ; for ( int i = 0 ; i < n ; ++ i ) { pos = 1 << arr [ i ] ; _xor ^= pos ; } for ( int i = 0 ; i < n ; ++ i ) { pos = 1 << arr [ i ] ; if ( ! ( ( pos & _xor ) != 0 ) ) { Console . Write ( arr [ i ] + " β " ) ; _xor ^= pos ; } } } public static void Main ( ) { int [ ] arr = { 9 , 12 , 23 , 10 , 12 , 12 , 15 , 23 , 14 , 12 , 15 } ; int n = arr . Length ; printRepeatingEven ( arr , n ) ; } }
|
Check if a number is Bleak | A simple C # program to check Bleak Number ; Function to get no of set bits in binary representation of passed binary no . ; Returns true if n is Bleak ; Check for all numbers ' x ' smaller than n . If x + countSetBits ( x ) becomes n , then n can 't be Bleak ; Driver code
|
using System ; class GFG { static int countSetBits ( int x ) { int count = 0 ; while ( x != 0 ) { x &= ( x - 1 ) ; count ++ ; } return count ; } static bool isBleak ( int n ) { for ( int x = 1 ; x < n ; x ++ ) if ( x + countSetBits ( x ) == n ) return false ; return true ; } public static void Main ( ) { if ( isBleak ( 3 ) ) Console . Write ( " Yes " ) ; else Console . WriteLine ( " No " ) ; if ( isBleak ( 4 ) ) Console . Write ( " Yes " ) ; else Console . Write ( " No " ) ; } }
|
Find the maximum subset XOR of a given set | C # program to find maximum XOR subset ; Number of bits to represent int ; Function to return maximum XOR subset in set [ ] ; Initialize index of chosen elements ; Traverse through all bits of integer starting from the most significant bit ( MSB ) ; Initialize index of maximum element and the maximum element ; If i 'th bit of set[j] is set and set[j] is greater than max so far. ; If there was no element with i 'th bit set, move to smaller i ; Put maximum element with i ' th β bit β set β β at β index β ' index ' ; Update maxInd and increment index ; Do XOR of set [ maxIndex ] with all numbers having i 'th bit as set. ; XOR set [ maxInd ] those numbers which have the i 'th bit set ; Increment index of chosen elements ; Final result is XOR of all elements ; Driver code
|
using System ; class GFG { static int INT_BITS = 32 ; static int maxSubarrayXOR ( int [ ] set , int n ) { int index = 0 ; for ( int i = INT_BITS - 1 ; i >= 0 ; i -- ) { int maxInd = index ; int maxEle = int . MinValue ; for ( int j = index ; j < n ; j ++ ) { if ( ( set [ j ] & ( 1 << i ) ) != 0 && set [ j ] > maxEle ) { maxEle = set [ j ] ; maxInd = j ; } } if ( maxEle == - 2147483648 ) continue ; int temp = set [ index ] ; set [ index ] = set [ maxInd ] ; set [ maxInd ] = temp ; maxInd = index ; for ( int j = 0 ; j < n ; j ++ ) { if ( j != maxInd && ( set [ j ] & ( 1 << i ) ) != 0 ) set [ j ] = set [ j ] ^ set [ maxInd ] ; } index ++ ; } int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) res ^= set [ i ] ; return res ; } public static void Main ( ) { int [ ] set = { 9 , 8 , 5 } ; int n = set . Length ; Console . Write ( " Max β subset β XOR β is β " ) ; Console . Write ( maxSubarrayXOR ( set , n ) ) ; } }
|
Given a set , find XOR of the XOR 's of all subsets. | C # program to find XOR of XOR 's of all subsets ; Returns XOR of all XOR 's of given subset ; XOR is 1 only when n is 1 , else 0 ; Driver code
|
using System ; class GFG { static int findXOR ( int [ ] Set , int n ) { if ( n == 1 ) return Set [ 0 ] ; else return 0 ; } public static void Main ( ) { int [ ] Set = { 1 , 2 , 3 } ; int n = Set . Length ; Console . Write ( " XOR β of β XOR ' s β of β all β subsets β is β " + findXOR ( Set , n ) ) ; } }
|
Find XOR of two number without using XOR operator | C # program to find XOR without using ^ ; Returns XOR of x and y ; Initialize result ; Assuming 32 - bit int ; Find current bits in x and y ; If both are 1 then 0 else xor is same as OR ; Update result ; Driver Code
|
using System ; class GFG { static int myXOR ( int x , int y ) { int res = 0 ; for ( int i = 31 ; i >= 0 ; i -- ) { int b1 = ( ( x & ( 1 << i ) ) == 0 ) ? 0 : 1 ; int b2 = ( ( y & ( 1 << i ) ) == 0 ) ? 0 : 1 ; int xoredBit = ( ( b1 & b2 ) != 0 ) ? 0 : ( b1 b2 ) ; res <<= 1 ; res |= xoredBit ; } return res ; } public static void Main ( String [ ] args ) { int x = 3 , y = 5 ; Console . WriteLine ( " XOR β is β " + myXOR ( x , y ) ) ; } }
|
Find XOR of two number without using XOR operator | C # program to find XOR without using ^ ; Returns XOR of x and y ; Driver Code
|
using System ; class GFG { static int myXOR ( int x , int y ) { return ( x y ) & ( ~ x ~ y ) ; } static public void Main ( ) { int x = 3 , y = 5 ; Console . WriteLine ( " XOR β is β " + ( myXOR ( x , y ) ) ) ; } }
|
How to swap two bits in a given integer ? | C # program to swap bits in an integer ; This function swaps bit at positions p1 and p2 in an integer n ; Move p1 'th to rightmost side ; Move p2 'th to rightmost side ; XOR the two bits ; Put the xor bit back to their original positions ; XOR ' x ' with the original number so that the two sets are swapped ; Driver code
|
using System ; class GFG { static int swapBits ( int n , int p1 , int p2 ) { int bit1 = ( n >> p1 ) & 1 ; int bit2 = ( n >> p2 ) & 1 ; int x = ( bit1 ^ bit2 ) ; x = ( x << p1 ) | ( x << p2 ) ; int result = n ^ x ; return result ; } public static void Main ( string [ ] args ) { int res = swapBits ( 28 , 0 , 3 ) ; Console . Write ( " Result β = β " + res ) ; } }
|
Write a function that returns 2 for input 1 and returns 1 for 2 |
|
static int invert ( int x ) { if ( x == 1 ) return 2 ; else return 1 ; }
|
Maximum length sub | C # implementation of the approach ; Function to return the maximum length of the required sub - array ; For the first consecutive pair of elements ; While a consecutive pair can be selected ; If current pair forms a valid sub - array ; 2 is the length of the current sub - array ; To extend the sub - array both ways ; While elements at indices l and r are part of a valid sub - array ; Update the maximum length so far ; Select the next consecutive pair ; Return the maximum length ; Driver code
|
using System ; class GFG { static int maxLength ( int [ ] arr , int n ) { int maxLen = 0 ; int i = 0 ; int j = i + 1 ; while ( j < n ) { if ( arr [ i ] != arr [ j ] ) { maxLen = Math . Max ( maxLen , 2 ) ; int l = i - 1 ; int r = j + 1 ; while ( l >= 0 && r < n && arr [ l ] == arr [ i ] && arr [ r ] == arr [ j ] ) { l -- ; r ++ ; } maxLen = Math . Max ( maxLen , 2 * ( r - j ) ) ; } i ++ ; j = i + 1 ; } return maxLen ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 1 , 1 , 0 , 0 , 1 , 1 } ; int n = arr . Length ; Console . WriteLine ( maxLength ( arr , n ) ) ; } }
|
FreivaldΓ’ β¬β’ s Algorithm to check if a matrix is product of two | C # code to implement Freivald 's Algorithm ; Function to check if ABx = Cx ; Generate a random vector ; Now compute B * r for evaluating expression A * ( B * r ) - ( C * r ) ; Now compute C * r for evaluating expression A * ( B * r ) - ( C * r ) ; Now compute A * ( B * r ) for evaluating expression A * ( B * r ) - ( C * r ) ; Finally check if value of expression A * ( B * r ) - ( C * r ) is 0 or not ; Runs k iterations Freivald . The value of k determines accuracy . Higher value means higher accuracy . ; Driver code
|
using System ; class GFG { static int N = 2 ; static bool freivald ( int [ , ] a , int [ , ] b , int [ , ] c ) { Random rand = new Random ( ) ; int [ ] r = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) r [ i ] = ( int ) ( rand . Next ( ) ) % 2 ; int [ ] br = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) br [ i ] = br [ i ] + b [ i , j ] * r [ j ] ; int [ ] cr = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) cr [ i ] = cr [ i ] + c [ i , j ] * r [ j ] ; int [ ] axbr = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) axbr [ i ] = axbr [ i ] + a [ i , j ] * br [ j ] ; for ( int i = 0 ; i < N ; i ++ ) if ( axbr [ i ] - cr [ i ] != 0 ) return false ; return true ; } static bool isProduct ( int [ , ] a , int [ , ] b , int [ , ] c , int k ) { for ( int i = 0 ; i < k ; i ++ ) if ( freivald ( a , b , c ) == false ) return false ; return true ; } static void Main ( ) { int [ , ] a = new int [ , ] { { 1 , 1 } , { 1 , 1 } } ; int [ , ] b = new int [ , ] { { 1 , 1 } , { 1 , 1 } } ; int [ , ] c = new int [ , ] { { 2 , 2 } , { 2 , 2 } } ; int k = 2 ; if ( isProduct ( a , b , c , k ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
|
Expectation or expected value of an array | C # code to calculate expected value of an array ; Function to calculate expectation ; Variable prb is for probability of each element which is same for each element ; calculating expectation overall ; returning expectation as sum ; Driver program ; Function for calculating expectation ; Display expectation of given array
|
using System ; class GFG { static float calc_Expectation ( float [ ] a , float n ) { float prb = ( 1 / n ) ; float sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += a [ i ] * prb ; return sum ; } public static void Main ( ) { float expect , n = 6f ; float [ ] a = { 1f , 2f , 3f , 4f , 5f , 6f } ; expect = calc_Expectation ( a , n ) ; Console . WriteLine ( " Expectation " + " β of β array β E ( X ) β is β : β " + expect ) ; } }
|
Sum of N | C # implementation to illustrate the program ; Function to calculate the sum recursively ; Base cases ; If n is odd ; If n is even ; Function to prlong the value of Sum ; Driver Code ; First element ; Common difference ; Number of elements ; Mod value
|
using System ; class GFG { static long SumGPUtil ( long r , long n , long m ) { if ( n == 0 ) return 1 ; if ( n == 1 ) return ( 1 + r ) % m ; long ans ; if ( n % 2 == 1 ) { ans = ( 1 + r ) * SumGPUtil ( ( r * r ) % m , ( n - 1 ) / 2 , m ) ; } else { ans = 1 + ( r * ( 1 + r ) * SumGPUtil ( ( r * r ) % m , ( n / 2 ) - 1 , m ) ) ; } return ( ans % m ) ; } static void SumGP ( long a , long r , long N , long M ) { long answer ; answer = a * SumGPUtil ( r , N , M ) ; answer = answer % M ; Console . WriteLine ( answer ) ; } public static void Main ( ) { long a = 1 ; long r = 4 ; long N = 10000 ; long M = 100000 ; SumGP ( a , r , N , M ) ; } }
|
Length of longest subarray in which elements greater than K are more than elements not greater than K | C # implementation of above approach ; Function to find the length of a longest subarray in which elements greater than K are more than elements not greater than K ; Create a new array in which we store 1 if a [ i ] > k otherwise we store - 1. ; Taking prefix sum over it ; len will store maximum length of subarray ; This indicate there is at least one subarray of length mid that has sum > 0 ; Check every subarray of length mid if it has sum > 0 or not if sum > 0 then it will satisfy our required condition ; x will store the sum of subarray of length mid ; Satisfy our given condition ; Check for higher length as we get length mid ; Check for lower length as we did not get length mid ; Driver code
|
using System ; class GFG { static int LongestSubarray ( int [ ] a , int n , int k ) { int [ ] pre = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] > k ) pre [ i ] = 1 ; else pre [ i ] = - 1 ; } for ( int i = 1 ; i < n ; i ++ ) pre [ i ] = pre [ i - 1 ] + pre [ i ] ; int len = 0 ; int lo = 1 , hi = n ; while ( lo <= hi ) { int mid = ( lo + hi ) / 2 ; bool ok = false ; for ( int i = mid - 1 ; i < n ; i ++ ) { int x = pre [ i ] ; if ( i - mid >= 0 ) x -= pre [ i - mid ] ; if ( x > 0 ) { ok = true ; break ; } } if ( ok == true ) { len = mid ; lo = mid + 1 ; } else hi = mid - 1 ; } return len ; } public static void Main ( ) { int [ ] a = { 2 , 3 , 4 , 5 , 3 , 7 } ; int k = 3 ; int n = a . Length ; Console . WriteLine ( LongestSubarray ( a , n , k ) ) ; } }
|
Choose points from two ranges such that no point lies in both the ranges | C # implementation of the approach ; Function to find the required points ; Driver code
|
using System ; class GFG { static void findPoints ( int l1 , int r1 , int l2 , int r2 ) { int x = ( l1 != l2 ) ? Math . Min ( l1 , l2 ) : - 1 ; int y = ( r1 != r2 ) ? Math . Max ( r1 , r2 ) : - 1 ; Console . WriteLine ( x + " β " + y ) ; } public static void Main ( ) { int l1 = 5 , r1 = 10 , l2 = 1 , r2 = 7 ; findPoints ( l1 , r1 , l2 , r2 ) ; } }
|
Tail Recursion | A NON - tail - recursive function . The function is not tail recursive because the value returned by fact ( n - 1 ) is used in fact ( n ) and call to fact ( n - 1 ) is not the last thing done by fact ( n ) ; Driver program to test above function
|
using System ; class GFG { static int fact ( int n ) { if ( n == 0 ) return 1 ; return n * fact ( n - 1 ) ; } public static void Main ( ) { Console . Write ( fact ( 5 ) ) ; } }
|
Minimum number of working days required to achieve each of the given scores | C # program for the above approach ; Function to find the minimum number of days required to work to at least arr [ i ] points for every array element ; Traverse the array P [ ] ; Find the prefix sum ; Traverse the array arr [ ] ; Find the minimum index of the array having value at least arr [ i ] ; If the index is not - 1 ; Otherwise ; Function to find the lower bound of N using binary search ; Stores the lower bound ; Stores the upper bound ; Stores the minimum index having value is at least N ; Iterater while i <= j ; Stores the mid index of the range [ i , j ] ; If P [ mid ] is at least N ; Update the value of mid to index ; Update the value of j ; Update the value of i ; Return the resultant index ; Driver Code
|
using System ; class GFG { static void minDays ( int [ ] P , int [ ] arr ) { for ( int i = 1 ; i < P . Length ; i ++ ) { P [ i ] += P [ i ] + P [ i - 1 ] ; } for ( int i = 0 ; i < arr . Length ; i ++ ) { int index = binarySeach ( P , arr [ i ] ) ; if ( index != - 1 ) { Console . Write ( index + 1 + " β " ) ; } else { Console . Write ( - 1 + " β " ) ; } } } static int binarySeach ( int [ ] P , int N ) { int i = 0 ; int j = P . Length - 1 ; int index = - 1 ; while ( i <= j ) { int mid = i + ( j - i ) / 2 ; if ( P [ mid ] >= N ) { index = mid ; j = mid - 1 ; } else { i = mid + 1 ; } } return index ; } public static void Main ( string [ ] args ) { int [ ] arr = { 400 , 200 , 700 , 900 , 1400 } ; int [ ] P = { 100 , 300 , 400 , 500 , 600 } ; minDays ( P , arr ) ; } }
|
Maximize profit that can be earned by selling an item among N buyers | C # program for the above approach ; Function to find the maximum profit earned by selling an item among N buyers ; Stores the maximum profit ; Stores the price of the item ; Traverse the array ; Count of buyers with budget >= arr [ i ] ; Increment count ; Update the maximum profit ; Return the maximum possible price ; Driver Code
|
using System ; class GFG { public static int maximumProfit ( int [ ] arr ) { int ans = Int32 . MinValue ; int price = 0 ; int n = arr . Length ; for ( int i = 0 ; i < n ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ i ] <= arr [ j ] ) { count ++ ; } } if ( ans < count * arr [ i ] ) { price = arr [ i ] ; ans = count * arr [ i ] ; } } return price ; } public static void Main ( string [ ] args ) { int [ ] arr = { 22 , 87 , 9 , 50 , 56 , 43 } ; Console . Write ( maximumProfit ( arr ) ) ; } }
|
Maximum length palindromic substring for every index such that it starts and ends at that index | C # program for the above approach ; Function to return true if S [ i ... j ] is a palindrome ; Iterate until i < j ; If unequal character encountered ; Otherwise ; Function to find for every index , longest palindromic substrings starting or ending at that index ; Stores the maximum palindromic substring length for each index ; Traverse the string ; Stores the maximum length of palindromic substring ; Consider that palindromic substring ends at index i ; If current character is a valid starting index ; If S [ i , j ] is palindrome , ; Update the length of the longest palindrome ; Consider that palindromic substring starts at index i ; If current character is a valid ending index ; If str [ i , j ] is palindrome ; Update the length of the longest palindrome ; Update length of the longest palindromic substring for index i ; Print the length of the longest palindromic substring ; Driver Code
|
using System ; class GFG { static bool isPalindrome ( string S , int i , int j ) { while ( i < j ) { if ( S [ i ] != S [ j ] ) return false ; i ++ ; j -- ; } return true ; } static void printLongestPalindrome ( string S , int N ) { int [ ] palLength = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { int maxlength = 1 ; for ( int j = 0 ; j < i ; j ++ ) { if ( S [ j ] == S [ i ] ) { if ( ( isPalindrome ( S , j , i ) ) != false ) { maxlength = i - j + 1 ; break ; } } } for ( int j = N - 1 ; j > i ; j -- ) { if ( S [ j ] == S [ i ] ) { if ( isPalindrome ( S , i , j ) ) { maxlength = Math . Max ( j - i + 1 , maxlength ) ; break ; } } } palLength [ i ] = maxlength ; } for ( int i = 0 ; i < N ; i ++ ) { Console . Write ( palLength [ i ] + " β " ) ; } } static public void Main ( ) { string S = " bababa " ; int N = S . Length ; printLongestPalindrome ( S , N ) ; } }
|
Sum of array elements which are multiples of a given number | C # program for the above approach ; Function to find the sum of array elements which are multiples of N ; Stores the sum ; Traverse the given array ; If current element is a multiple of N ; Print total sum ; Driver Code ; Given arr [ ]
|
using System ; public class GFG { static void mulsum ( int [ ] arr , int n , int N ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % N == 0 ) { sum = sum + arr [ i ] ; } } Console . Write ( sum ) ; } static public void Main ( ) { int [ ] arr = { 1 , 2 , 3 , 5 , 6 } ; int n = arr . Length ; int N = 3 ; mulsum ( arr , n , N ) ; } }
|
Farthest index that can be reached from the Kth index of given array by given operations | C # program for the above approach ; Function to find the farthest index that can be reached ; Declare a priority queue ; Iterate the array ; If current element is greater than the next element ; Otherwise , store their difference ; Push diff into pq ; If size of pq exceeds Y ; Decrease X by the top element of pq ; Remove top of pq ; If X is exhausted ; Current index is the farthest possible ; Print N - 1 as farthest index ; Driver code ; Function Call
|
using System ; using System . Collections . Generic ; class GFG { public static void farthestHill ( int [ ] arr , int X , int Y , int N , int K ) { int i , diff ; List < int > pq = new List < int > ( ) ; for ( i = K ; i < N - 1 ; i ++ ) { if ( arr [ i ] >= arr [ i + 1 ] ) continue ; diff = arr [ i + 1 ] - arr [ i ] ; pq . Add ( diff ) ; pq . Sort ( ) ; pq . Reverse ( ) ; if ( pq . Count > Y ) { X -= pq [ 0 ] ; pq . RemoveAt ( 0 ) ; } if ( X < 0 ) { Console . Write ( i ) ; return ; } } Console . Write ( N - 1 ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 4 , 2 , 7 , 6 , 9 , 14 , 12 } ; int X = 5 , Y = 1 ; int K = 0 ; int N = arr . Length ; farthestHill ( arr , X , Y , N , K ) ; } }
|
Lexicographically largest string possible consisting of at most K consecutive similar characters | C # solution for above approach ; Function to find largest string ; Stores the frequency of characters ; Traverse the string ; Stores the resultant string ; Append larger character ; Decrease count in charset ; Increase count ; Check if count reached to charLimit ; Find nearest lower char ; If no character can be appended ; Append nearest lower character ; Reset count for next calculation ; Return new largest string ; Function to return nearest lower character ; Traverse charset from start - 1 ; If no character can be appended ; Driver Code
|
using System ; using System . Text ; class GFG { static String newString ( String originalLabel , int limit ) { int n = originalLabel . Length ; int [ ] charset = new int [ 26 ] ; for ( int i = 0 ; i < n ; i ++ ) { charset [ originalLabel [ i ] - ' a ' ] ++ ; } StringBuilder newString = new StringBuilder ( n ) ; for ( int i = 25 ; i >= 0 ; i -- ) { int count = 0 ; while ( charset [ i ] > 0 ) { newString . Append ( ( char ) ( i + ' a ' ) ) ; charset [ i ] -- ; count ++ ; if ( charset [ i ] > 0 && count == limit ) { char next = nextAvailableChar ( charset , i ) ; if ( next == 0 ) return newString . ToString ( ) ; newString . Append ( next ) ; count = 0 ; } } } return newString . ToString ( ) ; } static char nextAvailableChar ( int [ ] charset , int start ) { for ( int i = start - 1 ; i >= 0 ; i -- ) { if ( charset [ i ] > 0 ) { charset [ i ] -- ; return ( char ) ( i + ' a ' ) ; } } return ' \0' ; } public static void Main ( String [ ] args ) { String S = " ccbbb " ; int K = 2 ; Console . WriteLine ( newString ( S , K ) ) ; } }
|
Rearrange array by interchanging positions of even and odd elements in the given array | C # program for the above approach ; Function to replace odd elements with even elements and vice versa ; Length of the array ; Traverse the given array ; If arr [ i ] is visited ; Find the next odd element ; Find next even element ; Mark them visited ; Swap them ; Print the readonly array ; Driver Code ; Given array [ ] arr ; Function Call
|
using System ; class GFG { static void swapEvenOdd ( int [ ] arr ) { int n = arr . Length ; int o = - 1 , e = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < 0 ) continue ; int r = - 1 ; if ( arr [ i ] % 2 == 0 ) { o ++ ; while ( arr [ o ] % 2 == 0 arr [ o ] < 0 ) o ++ ; r = o ; } else { e ++ ; while ( arr [ e ] % 2 == 1 arr [ e ] < 0 ) e ++ ; r = e ; } arr [ i ] *= - 1 ; arr [ r ] *= - 1 ; int tmp = arr [ i ] ; arr [ i ] = arr [ r ] ; arr [ r ] = tmp ; } for ( int i = 0 ; i < n ; i ++ ) { Console . Write ( ( - 1 * arr [ i ] ) + " β " ) ; } } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 3 , 2 , 4 } ; swapEvenOdd ( arr ) ; } }
|
Check if a palindromic string can be obtained by concatenating substrings split from same indices of two given strings | C # program to implement the above approach ; iterate through the length if we could find a [ i ] = = b [ j ] we could increment I and decrement j ; else we could just break the loop as its not a palindrome type sequence ; we could concatenate the a ' s β left β part β + b ' s right part in a variable a and a ' s β right β part + b ' s left in the variable b ; we would check for the palindrome condition if yes we print True else False ; Driver code
|
using System ; class GFG { static string rev ( string str ) { int st = 0 ; int ed = str . Length - 1 ; char [ ] s = str . ToCharArray ( ) ; while ( st < ed ) { char temp = s [ st ] ; s [ st ] = s [ ed ] ; s [ ed ] = temp ; st ++ ; ed -- ; } return new string ( s ) ; } static bool check ( string a , string b , int n ) { int i = 0 ; int j = n - 1 ; while ( i < n ) { if ( a [ i ] != b [ j ] ) break ; i += 1 ; j -= 1 ; string xa = a . Substring ( i , j + 1 - i ) ; string xb = b . Substring ( i , j + 1 - i ) ; char [ ] XA = xa . ToCharArray ( ) ; Array . Reverse ( XA ) ; char [ ] XB = xb . ToCharArray ( ) ; Array . Reverse ( XB ) ; if ( string . Compare ( xa , new string ( XA ) ) == 0 || string . Compare ( xb , new string ( XB ) ) == 0 ) return true ; } return false ; } static void Main ( ) { string a = " xbdef " ; string b = " cabex " ; if ( check ( a , b , a . Length ) || check ( b , a , a . Length ) ) Console . WriteLine ( " True " ) ; else Console . WriteLine ( " False " ) ; } }
|
Maximize length of subarray having equal elements by adding at most K | C # program for the above approach ; Function to find the maximum number of indices having equal elements after adding at most k numbers ; Sort the array in ascending order ; Make prefix sum array ; Initialize variables ; Update mid ; Check if any subarray can be obtained of length mid having equal elements ; Decrease max to mid ; Function to check if a subarray of length len consisting of equal elements can be obtained or not ; Sliding window ; Last element of the sliding window will be having the max size in the current window ; The current number of element in all indices of the current sliding window ; If the current number of the window , added to k exceeds totalNumbers ; Driver Code ; Function call
|
using System ; class GFG { public static int maxEqualIdx ( int [ ] arr , int k ) { Array . Sort ( arr ) ; int [ ] prefixSum = new int [ arr . Length + 1 ] ; prefixSum [ 1 ] = arr [ 0 ] ; for ( int i = 1 ; i < prefixSum . Length - 1 ; ++ i ) { prefixSum [ i + 1 ] = prefixSum [ i ] + arr [ i ] ; } int max = arr . Length ; int min = 1 ; int ans = 1 ; while ( min <= max ) { int mid = ( max + min ) / 2 ; if ( check ( prefixSum , mid , k , arr ) ) { ans = mid ; min = mid + 1 ; } else { max = mid - 1 ; } } return ans ; } public static bool check ( int [ ] pSum , int len , int k , int [ ] a ) { int i = 0 ; int j = len ; while ( j <= a . Length ) { int maxSize = a [ j - 1 ] ; int totalNumbers = maxSize * len ; int currNumbers = pSum [ j ] - pSum [ i ] ; if ( currNumbers + k >= totalNumbers ) { return true ; } else { i ++ ; j ++ ; } } return false ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 1 , 1 } ; int k = 7 ; Console . WriteLine ( maxEqualIdx ( arr , k ) ) ; } }
|
Sum of product of all pairs of a Binary Array | C # program to implement the above approach ; Function to print the sum of product of all pairs of the given array ; Stores count of one in the given array ; Stores the size of the given array ; If current element is 1 ; Increase count ; Return the sum of product of all pairs ; Driver Code
|
using System ; class GFG { static int productSum ( int [ ] arr ) { int cntOne = 0 ; int N = arr . Length ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == 1 ) cntOne ++ ; } return cntOne * ( cntOne - 1 ) / 2 ; } public static void Main ( ) { int [ ] arr = { 0 , 1 , 1 , 0 , 1 } ; Console . Write ( productSum ( arr ) ) ; } }
|
Minimum value of X that can be added to N to minimize sum of the digits to Γ Β’ Γ’ β¬Β°Β€ K | C # program for the above approach ; Function to find the minimum number needed to be added so that the sum of the digits does not exceed K ; Find the number of digits ; Calculate sum of the digits ; Add the digits of num2 ; If the sum of the digits of N is less than or equal to K ; No number needs to be added ; Otherwise ; Calculate the sum of digits from least significant digit ; If sum exceeds K ; Increase previous digit by 1 ; Add zeros to the end ; Calculate difference between the result and N ; Return the result ; Driver Code
|
using System ; class GFG { static int minDigits ( int N , int K ) { int digits_num = ( int ) Math . Floor ( Math . Log ( N ) + 1 ) ; int temp_sum = 0 ; int temp = digits_num ; int result = 0 ; int X , var ; int sum = 0 ; int num2 = N ; while ( num2 != 0 ) { sum += num2 % 10 ; num2 /= 10 ; } if ( sum <= K ) { X = 0 ; } else { while ( temp > 0 ) { var = ( N / ( ( int ) Math . Pow ( 10 , temp - 1 ) ) ) ; . temp_sum += var % 10 ; if ( temp_sum >= K ) { var /= 10 ; var ++ ; result = var * ( int ) Math . Pow ( 10 , temp ) ; break ; } temp -- ; } X = result - N ; return X ; } return - 1 ; } public static void Main ( String [ ] args ) { int N = 11 ; int K = 1 ; Console . WriteLine ( minDigits ( N , K ) ) ; } }
|
Count of Ways to obtain given Sum from the given Array elements | C # program to implement the above approach ; Function to call dfs to calculate the number of ways ; Iterate till the length of array ; Initialize the memorization table ; Function to perform the DFS to calculate the number of ways ; Base case : Reached the end of array ; If current sum is obtained ; Otherwise ; If previously calculated subproblem occurred ; Check if the required sum can be obtained by adding current element or by subtracting the current index element ; Store the count of ways ; Driver Code
|
using System ; class GFG { static int findWays ( int [ ] nums , int S ) { int sum = 0 ; for ( int i = 0 ; i < nums . Length ; i ++ ) sum += nums [ i ] ; int [ , ] memo = new int [ nums . Length + 1 , 2 * sum + 1 ] ; for ( int i = 0 ; i < memo . GetLength ( 0 ) ; i ++ ) { for ( int j = 0 ; j < memo . GetLength ( 1 ) ; j ++ ) { memo [ i , j ] = int . MinValue ; } } return dfs ( memo , nums , S , 0 , 0 , sum ) ; } static int dfs ( int [ , ] memo , int [ ] nums , int S , int curr_sum , int index , int sum ) { if ( index == nums . Length ) { if ( S == curr_sum ) return 1 ; else return 0 ; } if ( memo [ index , curr_sum + sum ] != int . MinValue ) { return memo [ index , curr_sum + sum ] ; } int ans = dfs ( memo , nums , index + 1 , curr_sum + nums [ index ] , S , sum ) + dfs ( memo , nums , index + 1 , curr_sum - nums [ index ] , S , sum ) ; memo [ index , curr_sum + sum ] = ans ; return ans ; } public static void Main ( String [ ] args ) { int S = 3 ; int [ ] arr = new int [ ] { 1 , 2 , 3 , 4 , 5 } ; int answer = findWays ( arr , S ) ; Console . WriteLine ( answer ) ; } }
|
Longest subarray with sum not divisible by X | C # program to implement the above approach ; Function to print the longest subarray with sum of elements not divisible by X ; Pref [ ] stores the prefix sum Suff [ ] stores the suffix sum ; If array element is divisibile by x ; Increase count ; If all the array elements are divisible by x ; No subarray possible ; Reverse v to calculate the suffix sum ; Calculate the suffix sum ; Reverse to original form ; Reverse the suffix sum array ; Calculate the prefix sum ; Stores the starting index of required subarray ; Stores the ending index of required subarray ; If suffix sum till i - th index is not divisible by x ; Update the answer ; If prefix sum till i - th index is not divisible by x ; Update the answer ; Print the longest subarray ; Driver Code
|
using System ; using System . Collections . Generic ; class GFG { static void max_length ( int N , int x , int [ ] v ) { int i , a ; List < int > preff = new List < int > ( ) ; List < int > suff = new List < int > ( ) ; int ct = 0 ; for ( i = 0 ; i < N ; i ++ ) { a = v [ i ] ; if ( a % x == 0 ) { ct += 1 ; } } if ( ct == N ) { Console . Write ( - 1 + " STRNEWLINE " ) ; return ; } v = reverse ( v ) ; suff . Add ( v [ 0 ] ) ; for ( i = 1 ; i < N ; i ++ ) { suff . Add ( v [ i ] + suff [ i - 1 ] ) ; } v = reverse ( v ) ; suff . Reverse ( ) ; preff . Add ( v [ 0 ] ) ; for ( i = 1 ; i < N ; i ++ ) { preff . Add ( v [ i ] + preff [ i - 1 ] ) ; } int ans = 0 ; int lp = 0 ; int rp = N - 1 ; for ( i = 0 ; i < N ; i ++ ) { if ( suff [ i ] % x != 0 && ( ans < ( N - 1 ) ) ) { lp = i ; rp = N - 1 ; ans = Math . Max ( ans , N - i ) ; } if ( preff [ i ] % x != 0 && ( ans < ( i + 1 ) ) ) { lp = 0 ; rp = i ; ans = Math . Max ( ans , i + 1 ) ; } } for ( i = lp ; i <= rp ; i ++ ) { Console . Write ( v [ i ] + " β " ) ; } } static int [ ] reverse ( int [ ] a ) { int i , n = a . Length , t ; for ( i = 0 ; i < n / 2 ; i ++ ) { t = a [ i ] ; a [ i ] = a [ n - i - 1 ] ; a [ n - i - 1 ] = t ; } return a ; } public static void Main ( String [ ] args ) { int x = 3 ; int [ ] v = { 1 , 3 , 2 , 6 } ; int N = v . Length ; max_length ( N , x , v ) ; } }
|
Number of times Maximum and minimum value updated during traversal of array | C # implementation to find the number of times minimum and maximum value updated during the traversal of the array ; Function to find the number of times minimum and maximum value updated during the traversal of the given array ; Increment i if new highest value occurs Increment j if new lowest value occurs ; Driver Code
|
using System ; class GFG { static void maxUpdated ( int [ ] arr ) { int h_score = arr [ 0 ] ; int l_score = arr [ 0 ] ; int i = 1 , j = 1 ; foreach ( int n in arr ) { if ( h_score < n ) { h_score = n ; i ++ ; } if ( l_score > n ) { l_score = n ; j ++ ; } } Console . Write ( " Number β of β times β maximum β value β " ) ; Console . Write ( " updated β = β " + i + " STRNEWLINE " ) ; Console . Write ( " Number β of β times β minimum β value β " ) ; Console . Write ( " updated β = β " + j ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 10 , 5 , 20 , 22 } ; maxUpdated ( arr ) ; } }
|
Find the farthest smaller number in the right side | C # implementation of the approach ; Function to find the farthest smaller number in the right side ; To store minimum element in the range i to n ; If current element in the suffix_min is less than a [ i ] then move right ; Print the required answer ; Driver code
|
using System ; class GFG { static void farthest_min ( int [ ] a , int n ) { int [ ] suffix_min = new int [ n ] ; suffix_min [ n - 1 ] = a [ n - 1 ] ; for ( int i = n - 2 ; i >= 0 ; i -- ) { suffix_min [ i ] = Math . Min ( suffix_min [ i + 1 ] , a [ i ] ) ; } for ( int i = 0 ; i < n ; i ++ ) { int low = i + 1 , high = n - 1 , ans = - 1 ; while ( low <= high ) { int mid = ( low + high ) / 2 ; if ( suffix_min [ mid ] < a [ i ] ) { ans = mid ; low = mid + 1 ; } else high = mid - 1 ; } Console . Write ( ans + " β " ) ; } } public static void Main ( ) { int [ ] a = { 3 , 1 , 5 , 2 , 4 } ; int n = a . Length ; farthest_min ( a , n ) ; } }
|
Print numbers in descending order along with their frequencies | C # program to print the elements in descending along with their frequencies ; Function to print the elements in descending along with their frequencies ; Sorts the element in decreasing order ; traverse the array elements ; Prints the number and count ; Prints the last step ; Driver Code
|
using System ; class GFG { static void printElements ( int [ ] a , int n ) { Array . Sort ( a ) ; a = reverse ( a ) ; int cnt = 1 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( a [ i ] != a [ i + 1 ] ) { Console . Write ( a [ i ] + " β occurs β " + cnt + " β times STRNEWLINE " ) ; cnt = 1 ; } else cnt += 1 ; } Console . Write ( a [ n - 1 ] + " β occurs β " + cnt + " β times STRNEWLINE " ) ; } static int [ ] reverse ( int [ ] a ) { int i , n = a . Length , t ; for ( i = 0 ; i < n / 2 ; i ++ ) { t = a [ i ] ; a [ i ] = a [ n - i - 1 ] ; a [ n - i - 1 ] = t ; } return a ; } public static void Main ( String [ ] args ) { int [ ] a = { 1 , 1 , 1 , 2 , 3 , 4 , 9 , 9 , 10 } ; int n = a . Length ; printElements ( a , n ) ; } }
|
Check if array can be sorted with one swap | C # program to check if an array can be sorted with at - most one swap ; Create a sorted copy of original array ; Check if 0 or 1 swap required to get the sorted array ; Driver Code
|
using System ; class GFG { static Boolean checkSorted ( int n , int [ ] arr ) { int [ ] b = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) b [ i ] = arr [ i ] ; Array . Sort ( b , 0 , n ) ; int ct = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] != b [ i ] ) ct ++ ; if ( ct == 0 ct == 2 ) return true ; else return false ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 5 , 3 , 4 , 2 } ; int n = arr . Length ; if ( checkSorted ( n , arr ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
|
Check whether ( i , j ) exists such that arr [ i ] != arr [ j ] and arr [ arr [ i ] ] is equal to arr [ arr [ j ] ] | C # implementation of the above approach ; Function that calculates marks . ; Checking 1 st condition i . e whether Arr [ i ] equal to Arr [ j ] or not ; Checking 2 nd condition i . e whether Arr [ Arr [ i ] ] equal to Arr [ Arr [ j ] ] or not . ; Driver code
|
using System ; class GFG { static bool checkIndices ( int [ ] Arr , int N ) { for ( int i = 0 ; i < N - 1 ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { if ( Arr [ i ] != Arr [ j ] ) { if ( Arr [ Arr [ i ] - 1 ] == Arr [ Arr [ j ] - 1 ] ) return true ; } } } return false ; } static public void Main ( ) { int [ ] Arr = { 3 , 2 , 1 , 1 , 4 } ; int N = Arr . Length ; if ( checkIndices ( Arr , N ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
|
Find two non | C # program to find two non - overlapping pairs having equal sum in an Array ; Declare a pair ; Function to find two non - overlapping pairs with same sum in an array ; First create an empty map key -> which is sum of a pair of elements in the array value -> list storing index of every pair having that sum ; Consider every pair ( A [ i ] , A [ j ] ) where ( j > i ) ; Calculate sum of current pair ; If sum is already present in the map ; Check every pair having desired sum ; If pairs don 't overlap, print them and return ; Insert current pair into the map ; Driver Code
|
using System ; using System . Collections . Generic ; class Pair { public int x , y ; public Pair ( int x , int y ) { this . x = x ; this . y = y ; } } class GFG { public static void findPairs ( int [ ] A ) { Dictionary < int , List < Pair > > map = new Dictionary < int , List < Pair > > ( ) ; for ( int i = 0 ; i < A . Length - 1 ; i ++ ) { for ( int j = i + 1 ; j < A . Length ; j ++ ) { int sum = A [ i ] + A [ j ] ; if ( map . ContainsKey ( sum ) ) { foreach ( Pair pair in map [ sum ] ) { int x = pair . x ; int y = pair . y ; if ( ( x != i && x != j ) && ( y != i && y != j ) ) { Console . WriteLine ( " Pair β First ( " + A [ i ] + " , β " + A [ j ] + " ) " ) ; Console . WriteLine ( " Pair β Second β ( " + A [ x ] + " , β " + A [ y ] + " ) " ) ; return ; } } } map [ sum ] = new List < Pair > ( ) ; map [ sum ] . Add ( new Pair ( i , j ) ) ; } } Console . Write ( " No β such β non - overlapping β pairs β present " ) ; } public static void Main ( String [ ] args ) { int [ ] A = { 8 , 4 , 7 , 8 , 4 } ; findPairs ( A ) ; } }
|
Print all pairs with given sum | C # implementation of simple method to find print pairs with given sum . ; Returns number of pairs in arr [ 0. . n - 1 ] with sum equal to ' sum ' ; Consider all possible pairs and check their sums ; Driver Code
|
using System ; class GFG { static void printPairs ( int [ ] arr , int n , int sum ) { for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( arr [ i ] + arr [ j ] == sum ) Console . Write ( " ( " + arr [ i ] + " , β " + arr [ j ] + " ) " + " STRNEWLINE " ) ; } public static void Main ( ) { int [ ] arr = { 1 , 5 , 7 , - 1 , 5 } ; int n = arr . Length ; int sum = 6 ; printPairs ( arr , n , sum ) ; } }
|
Ways to choose three points with distance between the most distant points <= L | C # program to count ways to choose triplets such that the distance between the farthest points <= L ; Returns the number of triplets with the distance between farthest points <= L ; sort the array ; find index of element greater than arr [ i ] + L ; find Number of elements between the ith index and indexGreater since the Numbers are sorted and the elements are distinct from the points btw these indices represent points within range ( a [ i ] + 1 and a [ i ] + L ) both inclusive ; if there are at least two elements in between i and indexGreater find the Number of ways to select two points out of these ; Driver Code ; set of n points on the X axis
|
using System ; class GFG { static int countTripletsLessThanL ( int n , int L , int [ ] arr ) { Array . Sort ( arr ) ; int ways = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int indexGreater = upper_bound ( arr , 0 , n , arr [ i ] + L ) ; int numberOfElements = indexGreater - ( i + 1 ) ; if ( numberOfElements >= 2 ) { ways += ( numberOfElements * ( numberOfElements - 1 ) / 2 ) ; } } return ways ; } static int upper_bound ( 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 ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 } ; int n = arr . Length ; int L = 4 ; int ans = countTripletsLessThanL ( n , L , arr ) ; Console . WriteLine ( " Total β Number β of β ways β = β " + ans ) ; } }
|
Making elements distinct in a sorted array by minimum increments | C # program to make sorted array elements distinct by incrementing elements and keeping sum to minimum . ; To find minimum sum of unique elements . ; While current element is same as previous or has become smaller than previous . ; Driver code
|
using System ; class GFG { static int minSum ( int [ ] arr , int n ) { int sum = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] == arr [ i - 1 ] ) { int j = i ; while ( j < n && arr [ j ] <= arr [ j - 1 ] ) { arr [ j ] = arr [ j ] + 1 ; j ++ ; } } sum = sum + arr [ i ] ; } return sum ; } public static void Main ( ) { int [ ] arr = { 2 , 2 , 3 , 5 , 6 } ; int n = arr . Length ; Console . WriteLine ( minSum ( arr , n ) ) ; } }
|
Making elements distinct in a sorted array by minimum increments | Efficient C # program to make sorted array elements distinct by incrementing elements and keeping sum to minimum . ; To find minimum sum of unique elements . ; If violation happens , make current value as 1 plus previous value and add to sum . ; No violation . ; Drivers code
|
using System ; class GFG { static int minSum ( int [ ] arr , int n ) { int sum = arr [ 0 ] , prev = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] <= prev ) { prev = prev + 1 ; sum = sum + prev ; } else { sum = sum + arr [ i ] ; prev = arr [ i ] ; } } return sum ; } public static void Main ( ) { int [ ] arr = { 2 , 2 , 3 , 5 , 6 } ; int n = arr . Length ; Console . WriteLine ( minSum ( arr , n ) ) ; } }
|
Randomized Binary Search Algorithm | C # program to implement recursive randomized algorithm . ; To generate random number between x and y ie . . [ x , y ] ; A recursive randomized binary search function . It returns location of x in given array arr [ l . . r ] is present , otherwise - 1 ; Here we have defined middle as random index between l and r ie . . [ l , r ] ; If the element is present at the middle itself ; If element is smaller than mid , then it can only be present in left subarray ; Else the element can only be present in right subarray ; We reach here when element is not present in array ; Driver code
|
using System ; class RandomizedBinarySearch { public static int getRandom ( int x , int y ) { Random r = new Random ( ) ; return ( x + ( int ) ( r . Next ( ) % ( y - x + 1 ) ) ) ; } public static int randomizedBinarySearch ( int [ ] arr , int low , int high , int key ) { if ( high >= low ) { int mid = getRandom ( low , high ) ; if ( arr [ mid ] == key ) return mid ; if ( arr [ mid ] > key ) return randomizedBinarySearch ( arr , low , mid - 1 , key ) ; return randomizedBinarySearch ( arr , mid + 1 , high , key ) ; } return - 1 ; } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , 3 , 4 , 10 , 40 } ; int n = arr . Length ; int key = 10 ; int result = randomizedBinarySearch ( arr , 0 , n - 1 , key ) ; Console . WriteLine ( ( result == - 1 ) ? " Element β is β not β present β in β array " : " Element β is β present β at β index β " + result ) ; } }
|
Program to remove vowels from a String | C # program to remove vowels from a String ; Driver method to test the above function
|
using System ; using System . Text ; using System . Linq ; using System . Collections . Generic ; public class Test { static String remVowel ( String str ) { char [ ] vowels = { ' a ' , ' e ' , ' i ' , ' o ' , ' u ' , ' A ' , ' E ' , ' I ' , ' O ' , ' U ' } ; List < char > al = vowels . OfType < char > ( ) . ToList ( ) ; ; StringBuilder sb = new StringBuilder ( str ) ; for ( int i = 0 ; i < sb . Length ; i ++ ) { if ( al . Contains ( sb [ i ] ) ) { sb . Replace ( sb [ i ] . ToString ( ) , " " ) ; i -- ; } } return sb . ToString ( ) ; } public static void Main ( ) { String str = " GeeeksforGeeks β - β A β Computer β Science β Portal β for β Geeks " ; Console . Write ( remVowel ( str ) ) ; } }
|
Make all array elements equal with minimum cost | This function assumes that a [ ] is sorted . If a [ ] is not sorted , we need to sort it first . ; If there are odd elements , we choose middle element ; If there are even elements , then we choose the average of middle two . ; After deciding the final value , find the result . ; Driver code
|
using System ; using System . Collections . Generic ; class GFG { static int minCostToMakeElementEqual ( int [ ] a , int n ) { int y ; if ( n % 2 == 1 ) y = a [ n / 2 ] ; else y = ( a [ n / 2 ] + a [ ( n - 2 ) / 2 ] ) / 2 ; int s = 0 ; for ( int i = 0 ; i < n ; i ++ ) s += Math . Abs ( a [ i ] - y ) ; return s ; } static void Main ( ) { int [ ] a = { 1 , 100 , 101 } ; int n = a . Length ; Console . WriteLine ( minCostToMakeElementEqual ( a , n ) ) ; } }
|
Check if an array can be sorted by rearranging odd and even | Function to check if array can be sorted or not ; Function to check if given array can be sorted or not ; Traverse the array ; Traverse remaining elements at indices separated by 2 ; If current element is the minimum ; If any smaller minimum exists ; Swap with current element ; If array is sorted ; Otherwise ; Driver code ; Given array
|
using System ; class GFG { public static bool isSorted ( int [ ] arr , int n ) { for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( arr [ i ] > arr [ i + 1 ] ) return false ; } return true ; } public static bool sortPoss ( int [ ] arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) { int idx = - 1 ; int minVar = arr [ i ] ; int j = i ; while ( j < n ) { if ( arr [ j ] < minVar ) { minVar = arr [ j ] ; idx = j ; } j = j + 2 ; } if ( idx != - 1 ) { int t ; t = arr [ i ] ; arr [ i ] = arr [ idx ] ; arr [ idx ] = t ; } } if ( isSorted ( arr , n ) ) return true ; else return false ; } static public void Main ( ) { int [ ] arr = { 3 , 5 , 1 , 2 , 6 } ; int n = arr . Length ; if ( sortPoss ( arr , n ) ) Console . WriteLine ( " True " ) ; else Console . WriteLine ( " False " ) ; } }
|
Print all array elements appearing more than N / K times | C # program to implement the above approach ; Function to + find the upper_bound of an array element ; Stores minimum index in which K lies ; Stores maximum index in which K lies ; Calculate the upper bound of K ; Stores mid element of l and r ; If arr [ mid ] is less than or equal to K ; Right subarray ; Left subarray ; Function to print all array elements whose frequency is greater than N / K ; Sort the array arr [ ] ; Stores index of an array element ; Traverse the array ; Stores upper bound of arr [ i ] ; If frequency of arr [ i ] is greater than N / 4 ; Update i ; Driver Code ; Given array arr [ ] ; Size of array ; Function Call
|
using System ; class GFG { static int upperBound ( int [ ] arr , int N , int K ) { int l = 0 ; int r = N ; while ( l < r ) { int mid = ( l + r ) / 2 ; if ( arr [ mid ] <= K ) { l = mid + 1 ; } else { r = mid ; } } return l ; } static void NDivKWithFreq ( int [ ] arr , int N , int K ) { Array . Sort ( arr ) ; int i = 0 ; while ( i < N ) { int X = upperBound ( arr , N , arr [ i ] ) ; if ( ( X - i ) > N / 4 ) { Console . Write ( arr [ i ] + " β " ) ; } i = X ; } } public static void Main ( string [ ] args ) { int [ ] arr = { 1 , 2 , 2 , 6 , 6 , 6 , 6 , 7 , 10 } ; int N = arr . Length ; int K = 4 ; NDivKWithFreq ( arr , N , K ) ; } }
|
Maximize sum of given array by rearranging array such that the difference between adjacent elements is atmost 1 | C # program for the above approach ; Function to find maximum possible sum after changing the array elements as per the given constraints ; Length of given array ; Stores the frequency of elements in given array ; Update frequency ; stores the previously selected integer ; Stores the maximum possible sum ; Traverse over array count [ ] ; Run loop for each k ; Update ans ; Return maximum possible sum ; Driver Code ; Given array arr [ ] ; Function call
|
using System ; class GFG { static long maxSum ( int [ ] a ) { int n = a . Length ; int [ ] count = new int [ n + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) count [ Math . Min ( a [ i ] , n ) ] ++ ; int size = 0 ; long ans = 0 ; for ( int k = 1 ; k <= n ; k ++ ) { while ( count [ k ] > 0 && size < k ) { size ++ ; ans += size ; count [ k ] -- ; } ans += k * count [ k ] ; } return ans ; } public static void Main ( ) { int [ ] arr = { 3 , 5 , 1 } ; Console . Write ( maxSum ( arr ) ) ; } }
|
Find sum of product of every number and its frequency in given range | C # program to find sum of product of every number and square of its frequency in the given range ; Function to solve queries ; Calculating answer for every query ; The end points of the ith query ; Hashmap for storing frequency ; Incrementing the frequency ; Adding the contribution of ith number ; Print answer ; Driver code ; Calling function
|
using System ; using System . Collections . Generic ; class GFG { public static void answerQueries ( int [ ] arr , int n , int [ , ] queries ) { for ( int i = 0 ; i < queries . GetLength ( 0 ) ; i ++ ) { int ans = 0 ; int l = queries [ i , 0 ] - 1 ; int r = queries [ i , 1 ] - 1 ; Dictionary < int , int > freq = new Dictionary < int , int > ( ) ; for ( int j = l ; j < r + 1 ; j ++ ) { freq [ arr [ j ] ] = freq . GetValueOrDefault ( arr [ j ] , 0 ) + 1 ; } foreach ( int k in freq . Keys ) { ans += k * freq [ k ] ; } Console . WriteLine ( ans ) ; } } static public void Main ( ) { int [ ] arr = { 1 , 2 , 1 } ; int n = arr . Length ; int [ , ] queries = { { 1 , 2 } , { 1 , 3 } } ; answerQueries ( arr , n , queries ) ; } }
|
Pandigital Product | C # code to check the number is Pandigital Product or not . ; calculate the multiplicand , multiplier , and product eligible for pandigital ; To check the string formed from multiplicand multiplier and product is pandigital ; Driver function
|
using System ; class GFG { public static bool PandigitalProduct_1_9 ( int n ) { for ( int i = 1 ; i * i <= n ; i ++ ) if ( n % i == 0 && isPandigital ( " " + n + i + n / i ) ) return true ; return false ; } public static bool isPandigital ( String str ) { if ( str . Length != 9 ) return false ; char [ ] ch = str . ToCharArray ( ) ; Array . Sort ( ch ) ; return new String ( ch ) . Equals ( "123456789" ) ; } public static void Main ( ) { int n = 6952 ; if ( PandigitalProduct_1_9 ( n ) == true ) Console . Write ( " yes " ) ; else Console . Write ( " no " ) ; } }
|
Median and Mode using Counting Sort | C # Program for Mode and Median using Counting Sort technique ; function that sort input array a [ ] and calculate mode and median using counting sort . ; The output array b [ ] will have sorted array ; variable to store max of input array which will to have size of count array ; auxiliary ( count ) array to store count . Initialize count array as 0. Size of count array will be equal to ( max + 1 ) . ; Store count of each element of input array ; mode is the index with maximum count ; Update count [ ] array with sum ; Sorted output array b [ ] to calculate median ; Median according to odd and even array size respectively . ; Output the result ; Driver Code
|
using System ; using System . Linq ; class GFG { static void printModeMedian ( int [ ] a , int n ) { int [ ] b = new int [ n ] ; int max = a . Max ( ) ; int t = max + 1 ; int [ ] count = new int [ t ] ; for ( int i = 0 ; i < t ; i ++ ) { count [ i ] = 0 ; } for ( int i = 0 ; i < n ; i ++ ) { count [ a [ i ] ] ++ ; } int mode = 0 ; int k = count [ 0 ] ; for ( int i = 1 ; i < t ; i ++ ) { if ( count [ i ] > k ) { k = count [ i ] ; mode = i ; } } for ( int i = 1 ; i < t ; i ++ ) { count [ i ] = count [ i ] + count [ i - 1 ] ; } for ( int i = 0 ; i < n ; i ++ ) { b [ count [ a [ i ] ] - 1 ] = a [ i ] ; count [ a [ i ] ] -- ; } float median ; if ( n % 2 != 0 ) { median = b [ n / 2 ] ; } else { median = ( float ) ( ( b [ ( n - 1 ) / 2 ] + b [ ( n / 2 ) ] ) / 2.0 ) ; } Console . WriteLine ( " median β = β " + median ) ; Console . WriteLine ( " mode β = β " + mode ) ; } public static void Main ( String [ ] args ) { int [ ] a = { 1 , 4 , 1 , 2 , 7 , 1 , 2 , 5 , 3 , 6 } ; int n = a . Length ; printModeMedian ( a , n ) ; } }
|
Check if both halves of the string have at least one different character | C # implementation to check if both halves of the string have at least one different character ; Function which break string into two halves Counts frequency of characters in each half Compares the two counter array and returns true if these counter arrays differ ; Declaration and initialization of counter array ; Driver function
|
using System ; class GeeksforGeeks { static int MAX = 26 ; static bool function ( String str ) { int l = str . Length ; int [ ] counter1 = new int [ MAX ] ; int [ ] counter2 = new int [ MAX ] ; for ( int i = 0 ; i < MAX ; i ++ ) { counter1 [ i ] = 0 ; counter2 [ i ] = 0 ; } for ( int i = 0 ; i < l / 2 ; i ++ ) counter1 [ str [ i ] - ' a ' ] ++ ; for ( int i = l / 2 ; i < l ; i ++ ) counter2 [ str [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < MAX ; i ++ ) { if ( counter2 [ i ] != counter1 [ i ] ) return true ; } return false ; } public static void Main ( ) { String str = " abcasdsabcae " ; if ( function ( str ) ) Console . WriteLine ( " Yes , β both β halves β " + " differ β by β at β least β one β character " ) ; else Console . WriteLine ( " No , β both β halves β " + " do β not β differ β at β all " ) ; } }
|
Check if both halves of the string have at least one different character | C # implementation of the problem ; Function which break string into two halves Increments frequency of characters for first half Decrements frequency of characters for second half true if any index has non - zero value ; Declaration and initialization of counter array ; Driver function
|
using System ; class GFG { static int MAX = 26 ; static bool function ( String str ) { int l = str . Length ; int [ ] counter = new int [ MAX ] ; for ( int i = 0 ; i < MAX ; i ++ ) counter [ i ] = 0 ; for ( int i = 0 ; i < l / 2 ; i ++ ) counter [ str [ i ] - ' a ' ] ++ ; for ( int i = l / 2 ; i < l ; i ++ ) counter [ str [ i ] - ' a ' ] -- ; for ( int i = 0 ; i < MAX ; i ++ ) if ( counter [ i ] != 0 ) return true ; return false ; } public static void Main ( ) { string str = " abcasdsabcae " ; if ( function ( str ) ) Console . Write ( " Yes , β both β halves " + " β differ β by β at β least β one β " + " character " ) ; else Console . Write ( " No , β both β halves " + " β do β not β differ β at β all " ) ; } }
|
Minimum difference between max and min of all K | C # program to find minimum difference between max and min of all subset of K size ; returns min difference between max and min of any K - size subset ; sort the array so that close elements come together . ; initialize result by a big integer number ; loop over first ( N - K ) elements of the array only ; get difference between max and min of current K - sized segment ; Driver code
|
using System ; class GFG { static int minDifferenceAmongMaxMin ( int [ ] arr , int N , int K ) { Array . Sort ( arr ) ; int res = 2147483647 ; for ( int i = 0 ; i <= ( N - K ) ; i ++ ) { int curSeqDiff = arr [ i + K - 1 ] - arr [ i ] ; res = Math . Min ( res , curSeqDiff ) ; } return res ; } public static void Main ( ) { int [ ] arr = { 10 , 20 , 30 , 100 , 101 , 102 } ; int N = arr . Length ; int K = 3 ; Console . Write ( minDifferenceAmongMaxMin ( arr , N , K ) ) ; } }
|
Position of an element after stable sort | C # program to get index of array element in sorted array ; Method returns the position of arr [ idx ] after performing stable - sort on array ; Count of elements smaller than current element plus the equal element occurring before given index ; If element is smaller then increase the smaller count ; If element is equal then increase count only if it occurs before ; Driver code to test above methods
|
using System ; class ArrayIndex { static int getIndexInSortedArray ( int [ ] arr , int n , int idx ) { int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < arr [ idx ] ) result ++ ; if ( arr [ i ] == arr [ idx ] && i < idx ) result ++ ; } return result ; } public static void Main ( ) { int [ ] arr = { 3 , 4 , 3 , 5 , 2 , 3 , 4 , 3 , 1 , 5 } ; int n = arr . Length ; int idxOfEle = 5 ; Console . WriteLine ( getIndexInSortedArray ( arr , n , idxOfEle ) ) ; } }
|
Find permutation of numbers upto N with a specific sum in a specific range | C # program for the above approach ; Function to check if sum is possible with remaining numbers ; Stores the minimum sum possible with x numbers ; Stores the maximum sum possible with x numbers ; If S lies in the range [ minSum , maxSum ] ; Function to find the resultant permutation ; Stores the count of numbers in the given segment ; If the sum is not possible with numbers in the segment ; Output - 1 ; Stores the numbers present within the given segment ; Iterate over the numbers from 1 to N ; If ( S - i ) is a positive non - zero sum and if it is possible to obtain ( S - i ) remaining numbers ; Update sum S ; Update required numbers in the segement ; Push i in vector v ; If sum has been obtained ; Break from the loop ; If sum is not obtained ; Output - 1 ; Stores the numbers which are not present in given segment ; Loop to check the numbers not present in the segment ; Pointer to check if i is present in vector v or not ; If i is not present in v ; Push i in vector v1 ; Point to the first elements of v1 and v respectively ; Print the required permutation ; Driver Code
|
using System ; using System . Collections . Generic ; class GFG { public static bool possible ( int x , int S , int N ) { int minSum = ( x * ( x + 1 ) ) / 2 ; int maxSum = ( x * ( ( 2 * N ) - x + 1 ) ) / 2 ; if ( S < minSum S > maxSum ) { return false ; } return true ; } public static void findPermutation ( int N , int L , int R , int S ) { int x = R - L + 1 ; if ( ! possible ( x , S , N ) ) { Console . WriteLine ( - 1 ) ; return ; } else { List < int > v = new List < int > ( ) ; for ( int i = N ; i >= 1 ; -- i ) { if ( ( S - i ) >= 0 && possible ( x - 1 , S - i , i - 1 ) ) { S = S - i ; x -- ; v . Add ( i ) ; } if ( S == 0 ) { break ; } } if ( S != 0 ) { Console . WriteLine ( - 1 ) ; return ; } List < int > v1 = new List < int > ( ) ; for ( int i = 1 ; i <= N ; ++ i ) { bool it = v . Contains ( i ) ; if ( ! it ) { v1 . Add ( i ) ; } } int j = 0 , f = 0 ; for ( int i = 1 ; i < L ; ++ i ) { Console . Write ( v1 [ j ] + " β " ) ; j ++ ; } for ( int i = L ; i <= R ; ++ i ) { Console . Write ( v [ f ] + " β " ) ; f ++ ; } for ( int i = R + 1 ; i <= N ; ++ i ) { Console . Write ( v1 [ j ] + " β " ) ; j ++ ; } } return ; } public static void Main ( ) { int N = 6 , L = 3 , R = 5 , S = 8 ; findPermutation ( N , L , R , S ) ; } }
|
Count triplets ( a , b , c ) such that a + b , b + c and a + c are all divisible by K | Set 2 | C # program for the above approach ; Function to count the number of triplets from the range [ 1 , N - 1 ] having sum of all pairs divisible by K ; If K is even ; Otherwise ; Driver Code
|
using System ; class GFG { static int countTriplets ( int N , int K ) { if ( K % 2 == 0 ) { int x = N / K ; int y = ( N + ( K / 2 ) ) / K ; return x * x * x + y * y * y ; } else { int x = N / K ; return x * x * x ; } } static void Main ( ) { int N = 2 , K = 2 ; Console . Write ( countTriplets ( N , K ) ) ; } }
|
Maximize count of 3 | C # program to implement the above approach ; Driver Code ; Function to count the maximum number of palindrome subsequences of length 3 considering the same index only once ; Index of the string S ; Stores the frequency of every character ; Stores the pair of frequency containing same characters ; Number of subsequences having length 3 ; Counts the frequency ; Counts the pair of frequency ; Returns the minimum value
|
using System ; class GFG { public static void Main ( String [ ] args ) { string S = " geeksforg " ; Console . WriteLine ( maxNumPalindrome ( S ) ) ; } static int maxNumPalindrome ( string S ) { int i = 0 ; int [ ] freq = new int [ 26 ] ; int freqPair = 0 ; int len = S . Length / 3 ; while ( i < S . Length ) { freq [ S [ i ] - ' a ' ] ++ ; i ++ ; } for ( i = 0 ; i < 26 ; i ++ ) { freqPair += ( freq [ i ] / 2 ) ; } return Math . Min ( freqPair , len ) ; } }
|
Minimum Bipartite Groups | Function to find the height sizeof the current component with vertex s ; Visit the current Node ; Call DFS recursively to find the maximum height of current CC ; If the node is not visited then the height recursively for next element ; Function to find the minimum Groups ; Initialise with visited array ; To find the minimum groups ; Traverse all the non visited Node and calculate the height of the tree with current node as a head ; If the current is not visited therefore , we get another CC ; Return the minimum bipartite matching ; Function that adds the current edges in the given graph ; Drivers Code ; Adjacency List ; Adding edges to List
|
using System ; using System . Collections . Generic ; class GFG { static int height ( int s , List < int > [ ] adj , int [ ] visited ) { visited [ s ] = 1 ; int h = 0 ; foreach ( int child in adj [ s ] ) { if ( visited [ child ] == 0 ) { h = Math . Max ( h , 1 + height ( child , adj , visited ) ) ; } } return h ; } static int minimumGroups ( List < int > [ ] adj , int N ) { int [ ] visited = new int [ N + 1 ] ; int groups = int . MinValue ; for ( int i = 1 ; i <= N ; i ++ ) { if ( visited [ i ] == 0 ) { int comHeight ; comHeight = height ( i , adj , visited ) ; groups = Math . Max ( groups , comHeight ) ; } } return groups ; } static void addEdge ( List < int > [ ] adj , int u , int v ) { adj [ u ] . Add ( v ) ; adj [ v ] . Add ( u ) ; } public static void Main ( String [ ] args ) { int N = 5 ; List < int > [ ] adj = new List < int > [ N + 1 ] ; for ( int i = 0 ; i < N + 1 ; i ++ ) adj [ i ] = new List < int > ( ) ; addEdge ( adj , 1 , 2 ) ; addEdge ( adj , 3 , 2 ) ; addEdge ( adj , 4 , 3 ) ; Console . Write ( minimumGroups ( adj , N ) ) ; } }
|
Sum of subsets of all the subsets of an array | O ( 2 ^ N ) | C # implementation of the approach ; To store the final ans ; Function to sum of all subsets of a given array ; Function to generate the subsets ; Base - case ; Finding the sum of all the subsets of the generated subset ; Recursively accepting and rejecting the current number ; Driver code
|
using System ; using System . Collections . Generic ; class GFG { static int ans ; static void subsetSum ( List < int > c ) { int L = c . Count ; int mul = ( int ) Math . Pow ( 2 , L - 1 ) ; for ( int i = 0 ; i < c . Count ; i ++ ) ans += c [ i ] * mul ; } static void subsetGen ( int [ ] arr , int i , int n , List < int > c ) { if ( i == n ) { subsetSum ( c ) ; return ; } subsetGen ( arr , i + 1 , n , c ) ; c . Add ( arr [ i ] ) ; subsetGen ( arr , i + 1 , n , c ) ; c . RemoveAt ( 0 ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 1 } ; int n = arr . Length ; List < int > c = new List < int > ( ) ; subsetGen ( arr , 0 , n , c ) ; Console . WriteLine ( ans ) ; } }
|
Find the maximum possible value of a [ i ] % a [ j ] over all pairs of i and j | C # implementation of the approach ; Function that returns the second largest element in the array if exists , else 0 ; There must be at least two elements ; To store the maximum and the second maximum element from the array ; If current element is greater than first then update both first and second ; If arr [ i ] is in between first and second then update second ; No second maximum found ; Driver code
|
using System ; class GFG { static int getMaxValue ( int [ ] arr , int arr_size ) { int i , first , second ; if ( arr_size < 2 ) { return 0 ; } first = second = int . MinValue ; for ( i = 0 ; i < arr_size ; i ++ ) { if ( arr [ i ] > first ) { second = first ; first = arr [ i ] ; } else if ( arr [ i ] > second && arr [ i ] != first ) { second = arr [ i ] ; } } if ( second == int . MinValue ) { return 0 ; } else { return second ; } } public static void Main ( ) { int [ ] arr = { 4 , 5 , 1 , 8 } ; int n = arr . Length ; Console . Write ( getMaxValue ( arr , n ) ) ; } }
|
Maximize the value of the given expression | C # implementation of the approach ; Function to return the maximum result ; To store the count of negative integers ; Sum of all the three integers ; Product of all the three integers ; To store the smallest and the largest among all the three integers ; Calculate the count of negative integers ; Depending upon count of negatives ; When all three are positive integers ; For single negative integer ; For two negative integers ; For three negative integers ; Driver Code
|
using System ; class GFG { static int maximumResult ( int a , int b , int c ) { int countOfNegative = 0 ; int sum = a + b + c ; int product = a * b * c ; int largest = ( a > b ) ? ( ( a > c ) ? a : c ) : ( ( b > c ) ? b : c ) ; int smallest = ( a < b ) ? ( ( a < c ) ? a : c ) : ( ( b < c ) ? b : c ) ; if ( a < 0 ) countOfNegative ++ ; if ( b < 0 ) countOfNegative ++ ; if ( c < 0 ) countOfNegative ++ ; switch ( countOfNegative ) { case 0 : return ( sum - largest ) * largest ; case 1 : return ( product / smallest ) + smallest ; case 2 : return ( product / largest ) + largest ; case 3 : return ( sum - smallest ) * smallest ; } return - 1 ; } static void Main ( ) { int a = - 2 , b = - 1 , c = - 4 ; Console . WriteLine ( maximumResult ( a , b , c ) ) ; } }
|
Maximum students to pass after giving bonus to everybody and not exceeding 100 marks | C # Implementation of above approach . ; Function to return the number of students that can pass ; maximum marks ; maximum bonus marks that can be given ; counting the number of students that can pass ; Driver code
|
using System ; using System . Collections . Generic ; using System . Collections ; using System . Linq ; class GFG { static int check ( int n , List < int > marks ) { int x = marks . Max ( ) ; int bonus = 100 - x ; int c = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( marks [ i ] + bonus >= 50 ) c += 1 ; } return c ; } public static void Main ( ) { int n = 5 ; List < int > marks = new List < int > ( new int [ ] { 0 , 21 , 83 , 45 , 64 } ) ; Console . WriteLine ( check ( n , marks ) ) ; } }
|
Sum of first N natural numbers which are not powers of K | C # program to find the sum of first n natural numbers which are not positive powers of k ; Function to return the sum of first n natural numbers which are not positive powers of k ; sum of first n natural numbers ; subtract all positive powers of k which are less than n ; next power of k ; Driver code
|
using System ; class GFG { static int find_sum ( int n , int k ) { int total_sum = ( n * ( n + 1 ) ) / 2 ; int power = k ; while ( power <= n ) { total_sum -= power ; power *= k ; } return total_sum ; } public static void Main ( ) { int n = 11 , k = 2 ; Console . WriteLine ( find_sum ( n , k ) ) ; } }
|
Minimum number of operations required to delete all elements of the array | C # implementation of the above approach ; function to find minimum operations ; sort array ; prepare hash of array ; Driver program
|
using System ; public class Solution { public const int MAX = 10000 ; public static int [ ] hashTable = new int [ MAX ] ; public static int minOperations ( int [ ] arr , int n ) { Array . Sort ( arr ) ; for ( int i = 0 ; i < n ; i ++ ) { hashTable [ arr [ i ] ] ++ ; } int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( hashTable [ arr [ i ] ] != 0 ) { for ( int j = i ; j < n ; j ++ ) { if ( arr [ j ] % arr [ i ] == 0 ) { hashTable [ arr [ j ] ] = 0 ; } } res ++ ; } } return res ; } public static void Main ( string [ ] args ) { int [ ] arr = new int [ ] { 4 , 6 , 2 , 8 , 7 , 21 , 24 , 49 , 44 } ; int n = arr . Length ; Console . Write ( minOperations ( arr , n ) ) ; } }
|
Sorting array with reverse around middle | C # Program to answer queries on sum of sum of odd number digits of all the factors of a number ; making the copy of the original array ; sorting the copied array ; checking mirror image of elements of sorted copy array and equivalent element of original array ; Driver code
|
using System ; class GFG { static bool ifPossible ( int [ ] arr , int n ) { int [ ] cp = new int [ n ] ; Array . Copy ( arr , cp , n ) ; Array . Sort ( cp ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! ( arr [ i ] == cp [ i ] ) && ! ( arr [ n - 1 - i ] == cp [ i ] ) ) return false ; } return true ; } public static void Main ( ) { int [ ] arr = new int [ ] { 1 , 7 , 6 , 4 , 5 , 3 , 2 , 8 } ; int n = arr . Length ; if ( ifPossible ( arr , n ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
|
Program for Shortest Job First ( SJF ) scheduling | Set 2 ( Preemptive ) | C # program to implement Shortest Remaining Time First Shortest Remaining Time First ( SRTF ) ; public int pid ; Process ID public int bt ; Burst Time public int art ; Arrival Time ; Method to find the waiting time for all processes ; Copy the burst time into rt [ ] ; Process until all processes gets completed ; Find process with minimum remaining time among the processes that arrives till the current time ` ; Reduce remaining time by one ; Update minimum ; If a process gets completely executed ; Increment complete ; Find finish time of current process ; Calculate waiting time ; Increment time ; Method to calculate turn around time ; calculating turnaround time by adding bt [ i ] + wt [ i ] ; Method to calculate average time ; Function to find waiting time of all processes ; Function to find turn around time for all processes ; Display processes along with all details ; Calculate total waiting time and total turnaround time ; Driver Method
|
using System ; public class Process { public Process ( int pid , int bt , int art ) { this . pid = pid ; this . bt = bt ; this . art = art ; } } public class GFG { static void findWaitingTime ( Process [ ] proc , int n , int [ ] wt ) { int [ ] rt = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) rt [ i ] = proc [ i ] . bt ; int complete = 0 , t = 0 , minm = int . MaxValue ; int shortest = 0 , finish_time ; bool check = false ; while ( complete != n ) { for ( int j = 0 ; j < n ; j ++ ) { if ( ( proc [ j ] . art <= t ) && ( rt [ j ] < minm ) && rt [ j ] > 0 ) { minm = rt [ j ] ; shortest = j ; check = true ; } } if ( check == false ) { t ++ ; continue ; } rt [ shortest ] -- ; minm = rt [ shortest ] ; if ( minm == 0 ) minm = int . MaxValue ; if ( rt [ shortest ] == 0 ) { complete ++ ; check = false ; finish_time = t + 1 ; wt [ shortest ] = finish_time - proc [ shortest ] . bt - proc [ shortest ] . art ; if ( wt [ shortest ] < 0 ) wt [ shortest ] = 0 ; } t ++ ; } } static void findTurnAroundTime ( Process [ ] proc , int n , int [ ] wt , int [ ] tat ) { for ( int i = 0 ; i < n ; i ++ ) tat [ i ] = proc [ i ] . bt + wt [ i ] ; } static void findavgTime ( Process [ ] proc , int n ) { int [ ] wt = new int [ n ] ; int [ ] tat = new int [ n ] ; int total_wt = 0 , total_tat = 0 ; findWaitingTime ( proc , n , wt ) ; findTurnAroundTime ( proc , n , wt , tat ) ; Console . WriteLine ( " Processes β " + " β Burst β time β " + " β Waiting β time β " + " β Turn β around β time " ) ; for ( int i = 0 ; i < n ; i ++ ) { total_wt = total_wt + wt [ i ] ; total_tat = total_tat + tat [ i ] ; Console . WriteLine ( " β " + proc [ i ] . pid + " TABSYMBOL TABSYMBOL " + proc [ i ] . bt + " TABSYMBOL TABSYMBOL β " + wt [ i ] + " TABSYMBOL TABSYMBOL " + tat [ i ] ) ; } Console . WriteLine ( " Average β waiting β time β = β " + ( float ) total_wt / ( float ) n ) ; Console . WriteLine ( " Average β turn β around β time β = β " + ( float ) total_tat / ( float ) n ) ; } public static void Main ( String [ ] args ) { Process [ ] proc = { new Process ( 1 , 6 , 1 ) , new Process ( 2 , 8 , 1 ) , new Process ( 3 , 7 , 2 ) , new Process ( 4 , 3 , 3 ) } ; findavgTime ( proc , proc . Length ) ; } }
|
Minimum deletions in Array to make difference of adjacent elements non | C # program for the above approach ; The maximum value of A [ i ] ; Function for finding minimum deletions so that the array becomes non - decreasing and the difference between adjacent elements is also non - decreasing ; Initializing the dp table and setting all values to 0 ; Find the maximum size valid set that can be taken and then subtract its size from N to get minimum number of deletions ; When selecting only current element and deleting all elements from 0 to i - 1 inclusive ; If this is true moving from index j to i is possible ; Iterate over all elements from 0 to diff and find the max ; Take the max set size from dp [ N - 1 ] [ 0 ] to dp [ N - 1 ] [ MAX ] ; Driver Code ; Function call
|
using System ; class GFG { static int MAX = 100001 ; static int minimumDeletions ( int [ ] A , int N ) { int [ , ] dp = new int [ N , MAX ] ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < MAX ; j ++ ) dp [ i , j ] = 0 ; for ( int i = 0 ; i < N ; i ++ ) { dp [ i , 0 ] = 1 ; for ( int j = i - 1 ; j >= 0 ; j -- ) { if ( A [ i ] >= A [ j ] ) { int diff = A [ i ] - A [ j ] ; for ( int k = 0 ; k <= diff ; k ++ ) { dp [ i , diff ] = Math . Max ( dp [ i , diff ] , dp [ j , k ] + 1 ) ; } } } } int maxSetSize = - 1 ; for ( int i = 0 ; i < MAX ; i ++ ) maxSetSize = Math . Max ( maxSetSize , dp [ N - 1 , i ] ) ; return N - maxSetSize ; } public static void Main ( ) { int [ ] A = { 1 , 4 , 5 , 7 , 20 , 21 } ; int N = A . Length ; Console . Write ( minimumDeletions ( A , N ) ) ; } }
|
Count N | C # program for the above approach ; Stores the value of overlapping states ; Function to find the count of numbers that are formed by digits X and Y and whose sum of digit also have digit X or Y ; Initialize dp array ; Base Case ; Check if sum of digits formed by only X or Y ; Return the already computed ; Place the digit X at the current position ; Place the digit Y at the current position ; Update current state result ; Function to check whether a number have only digits X or Y or not ; Until sum is positive ; If any digit is not X or Y then return 0 ; Return 1 ; Driver Code ; Function Call
|
using System ; class GFG { static int [ , ] dp = new int [ 100 + 5 , 900 + 5 ] ; static int mod = 10000007 ; public static int countNumbers ( int n , int x , int y , int sum ) { for ( int i = 0 ; i < dp . GetLength ( 0 ) ; i ++ ) { for ( int j = 0 ; j < dp . GetLength ( 1 ) ; j ++ ) { dp [ i , j ] = - 1 ; } } if ( n == 0 ) { return check ( sum , x , y ) ; } if ( dp [ n , sum ] != - 1 ) { return dp [ n , sum ] % mod ; } int option1 = countNumbers ( n - 1 , x , y , sum + x ) % mod ; int option2 = countNumbers ( n - 1 , x , y , sum + y ) % mod ; return dp [ n , sum ] = ( option1 + option2 ) % mod ; } public static int check ( int sum , int x , int y ) { while ( sum > 0 ) { int ln = sum % 10 ; if ( ln != x && ln != y ) { return 0 ; } sum /= 10 ; } return 1 ; } public static void Main ( String [ ] args ) { int N = 3 , X = 1 , Y = 5 ; Console . WriteLine ( countNumbers ( N , X , Y , 0 ) % mod ) ; } }
|
Minimum cost to generate any permutation of the given string | C # program for the above approach ; Function to find the minimum cost to form any permutation of string s ; Base Case ; Return the precomputed state ; Iterate over the string and check all possible characters available for current position ; Check if character can be placed at current position ; As there is no previous character so the cost for 1 st character is 0 ; Find the cost of current character and move to next position ; Store the answer for each current state ; Function that returns true if the current bit is set ; Function that generates any permutation of the given string with minimum cost ; Initialize dp table ; Set all the bits of the current character id ; Minimum cost of generating the permutation ; Driver Code ; Function Call
|
using System ; class GFG { public static int solve ( int [ , ] a , String s , int n , int prev , int mask , int [ , ] dp ) { if ( mask == 0 ) return 0 ; if ( dp [ mask , prev + 1 ] != - 1 ) return dp [ mask , prev + 1 ] ; int ans = 10000 ; for ( int i = 0 ; i < s . Length ; i ++ ) { int id = s [ i ] - ' a ' ; if ( check ( mask , id ) ) { if ( prev == - 1 ) { ans = Math . Min ( ans , solve ( a , s , n , id , mask ^ ( 1 << id ) , dp ) ) ; } else { ans = Math . Min ( ans , a [ prev , id ] + solve ( a , s , n , id , mask ^ ( 1 << id ) , dp ) ) ; } } } dp [ mask , prev + 1 ] = ans ; return ans ; } public static bool check ( int mask , int i ) { int c = ( mask & ( 1 << i ) ) ; return c != 0 ; } static void generatePermutation ( int mask , int n , int [ , ] a , String s ) { int [ , ] dp = new int [ ( 1 << n ) + 5 , n + 5 ] ; for ( int i = 0 ; i < ( 1 << n ) + 5 ; i ++ ) for ( int j = 0 ; j < n + 5 ; j ++ ) dp [ i , j ] = - 1 ; for ( int i = 0 ; i < s . Length ; i ++ ) { int id = s [ i ] - ' a ' ; mask |= ( 1 << id ) ; } Console . WriteLine ( solve ( a , s , n , - 1 , mask , dp ) ) ; } public static void Main ( String [ ] args ) { int N = 5 ; String str = " abcde " ; int [ , ] mat = { { 0 , 5 , 1 , 5 , 3 } , { 4 , 0 , 9 , 4 , 2 } , { 7 , 9 , 0 , 10 , 7 } , { 1 , 2 , 8 , 0 , 2 } , { 3 , 9 , 7 , 7 , 0 } } ; generatePermutation ( 0 , N , mat , str ) ; } }
|
Minimize Cost to reduce the Array to a single element by given operations | C # Program for the above approach ; Function to minimize the cost to add the array elements to a single element ; Check if the value is already stored in the array ; Compute left subproblem ; Compute left subproblem ; Calculate minimum cost ; Store the answer to avoid recalculation ; Function to generate the cost using Prefix Sum Array technique ; Function to combine the sum of the two subproblems ; Driver Code ; Initialise dp array ; Preprocessing the array
|
using System ; class GFG { static int inf = 10000000 ; public static int minCost ( int [ ] a , int i , int j , int k , int [ ] prefix , int [ , ] dp ) { if ( i >= j ) return 0 ; if ( dp [ i , j ] != - 1 ) return dp [ i , j ] ; int best_cost = inf ; for ( int pos = i ; pos < j ; pos ++ ) { int left = minCost ( a , i , pos , k , prefix , dp ) ; int right = minCost ( a , pos + 1 , j , k , prefix , dp ) ; best_cost = Math . Min ( best_cost , left + right + ( k * Combine ( prefix , i , j ) ) ) ; } return dp [ i , j ] = best_cost ; } public static int [ ] preprocess ( int [ ] a , int n ) { int [ ] p = new int [ n ] ; p [ 0 ] = a [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) p [ i ] = p [ i - 1 ] + a [ i ] ; return p ; } public static int Combine ( int [ ] p , int i , int j ) { if ( i == 0 ) return p [ j ] ; else return p [ j ] - p [ i - 1 ] ; } public static void Main ( String [ ] args ) { int n = 4 ; int [ ] a = { 4 , 5 , 6 , 7 } ; int k = 3 ; int [ , ] dp = new int [ n + 1 , n + 1 ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) { for ( int j = 0 ; j < n + 1 ; j ++ ) { dp [ i , j ] = - 1 ; } } int [ ] prefix = preprocess ( a , n ) ; Console . WriteLine ( minCost ( a , 0 , n - 1 , k , prefix , dp ) ) ; } }
|
Minimize operations required to obtain N | Function to find the minimum number of operations ; Storing the minimum operations to obtain all numbers up to N ; Initilal state ; Iterate for the remaining numbers ; If the number can be obtained by multiplication by 2 ; If the number can be obtained by multiplication by 3 ; Obtaining the number by adding 1 ; Return the minm operations to obtain n ; Driver Code
|
using System ; class GFG { static int minOperations ( int n ) { int [ ] dp = new int [ n + 1 ] ; int x ; dp [ 1 ] = 0 ; for ( int i = 2 ; i <= n ; i ++ ) { dp [ i ] = int . MaxValue ; if ( i % 2 == 0 ) { x = dp [ i / 2 ] ; if ( x + 1 < dp [ i ] ) { dp [ i ] = x + 1 ; } } if ( i % 3 == 0 ) { x = dp [ i / 3 ] ; if ( x + 1 < dp [ i ] ) { dp [ i ] = x + 1 ; } } x = dp [ i - 1 ] ; if ( x + 1 < dp [ i ] ) { dp [ i ] = x + 1 ; } } return dp [ n ] ; } public static void Main ( string [ ] args ) { int n = 15 ; Console . Write ( minOperations ( n ) ) ; } }
|
Longest Reverse Bitonic Sequence | C # program to find the longest Reverse bitonic Subsequence ; Function to return the length of the Longest Reverse Bitonic Subsequence in the array ; Allocate memory for LIS [ ] and initialize LIS values as 1 for all indexes ; Compute LIS values from left to right for every index ; Initialize LDS for all indexes as 1 ; Compute LDS values for every index from right to left ; Find the maximum value of lis [ i ] + lds [ i ] - 1 in the array ; Return the maximum ; Driver code
|
using System ; class GFG { static int ReverseBitonic ( int [ ] arr , int N ) { int i , j ; int [ ] lds = new int [ N ] ; for ( i = 0 ; i < N ; i ++ ) { lds [ i ] = 1 ; } for ( i = 1 ; i < N ; i ++ ) { for ( j = 0 ; j < i ; j ++ ) { if ( arr [ i ] < arr [ j ] && lds [ i ] < lds [ j ] + 1 ) { lds [ i ] = lds [ j ] + 1 ; } } } int [ ] lis = new int [ N ] ; for ( i = 0 ; i < N ; i ++ ) { lis [ i ] = 1 ; } for ( i = N - 2 ; i >= 0 ; i -- ) { for ( j = N - 1 ; j > i ; j -- ) { if ( arr [ i ] < arr [ j ] && lis [ i ] < lis [ j ] + 1 ) { lis [ i ] = lis [ j ] + 1 ; } } } int max = lis [ 0 ] + lds [ 0 ] - 1 ; for ( i = 1 ; i < N ; i ++ ) { if ( lis [ i ] + lds [ i ] - 1 > max ) { max = lis [ i ] + lds [ i ] - 1 ; } } return max ; } public static void Main ( ) { int [ ] arr = new int [ ] { 0 , 8 , 4 , 12 , 2 , 10 , 6 , 14 , 1 , 9 , 5 , 13 , 3 , 11 , 7 , 15 } ; int N = arr . Length ; Console . WriteLine ( " Length β of β LBS β is β " + ReverseBitonic ( arr , N ) ) ; } }
|
Maze With N doors and 1 Key | C # implementation of the approach ; Recursive function to check whether there is a path from the top left cell to the bottom right cell of the maze ; Check whether the current cell is within the maze ; If key is required to move further ; If the key hasn 't been used before ; If current cell is the destination ; Either go down or right ; If current cell is the destination ; Either go down or right ; Driver code ; We are making these { { '0' , '0' , '1' } , { '1' , '0' , '1' } , { '1' , '1' , '0' } } ; ; If there is a path from the cell ( 0 , 0 )
|
using System ; using System . Collections . Generic ; class GFG { static bool findPath ( List < List < int > > maze , int xpos , int ypos , bool key ) { if ( xpos < 0 xpos >= maze . Count ypos < 0 ypos >= maze . Count ) return false ; if ( maze [ xpos ] [ ypos ] == '1' ) { if ( key == true ) if ( xpos == maze . Count - 1 && ypos == maze . Count - 1 ) return true ; return findPath ( maze , xpos + 1 , ypos , false ) || findPath ( maze , xpos , ypos + 1 , false ) ; } if ( xpos == maze . Count - 1 && ypos == maze . Count - 1 ) return true ; return findPath ( maze , xpos + 1 , ypos , key ) || findPath ( maze , xpos , ypos + 1 , key ) ; } static bool mazeProb ( List < List < int > > maze , int xpos , int ypos ) { bool key = true ; if ( findPath ( maze , xpos , ypos , key ) ) return true ; return false ; } public static void Main ( String [ ] args ) { int size = 3 ; List < List < int > > maze = new List < List < int > > ( size ) ; for ( int i = 0 ; i < size ; i ++ ) { maze . Add ( new List < int > ( ) ) ; } maze [ 0 ] . Add ( 0 ) ; maze [ 0 ] . Add ( 0 ) ; maze [ 0 ] . Add ( 1 ) ; maze [ 1 ] . Add ( 1 ) ; maze [ 1 ] . Add ( 0 ) ; maze [ 1 ] . Add ( 1 ) ; maze [ 2 ] . Add ( 1 ) ; maze [ 2 ] . Add ( 1 ) ; maze [ 2 ] . Add ( 0 ) ; if ( mazeProb ( maze , 0 , 0 ) ) Console . Write ( " Yes " ) ; else Console . Write ( " No " ) ; } }
|
Minimum cost to reach end of array array when a maximum jump of K index is allowed | C # implementation of the above approach ; Function to return the minimum cost to reach the last index ; If we reach the last index ; Already visited state ; Initially maximum ; Visit all possible reachable index ; If inside range ; We cannot move any further ; Memoize ; Driver Code
|
using System ; class GfG { static int FindMinimumCost ( int ind , int [ ] a , int n , int k , int [ ] dp ) { if ( ind == ( n - 1 ) ) return 0 ; else if ( dp [ ind ] != - 1 ) return dp [ ind ] ; else { int ans = int . MaxValue ; for ( int i = 1 ; i <= k ; i ++ ) { if ( ind + i < n ) ans = Math . Min ( ans , Math . Abs ( a [ ind + i ] - a [ ind ] ) + FindMinimumCost ( ind + i , a , n , k , dp ) ) ; else break ; } return dp [ ind ] = ans ; } } public static void Main ( ) { int [ ] a = { 10 , 30 , 40 , 50 , 20 } ; int k = 3 ; int n = a . Length ; int [ ] dp = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) dp [ i ] = - 1 ; Console . WriteLine ( FindMinimumCost ( 0 , a , n , k , dp ) ) ; } }
|
Sum of all even factors of numbers in the range [ l , r ] | C # implementation of the approach ; Function to calculate the prefix sum of all the even factors ; Add i to all the multiples of i ; Update the prefix sum ; Function to return the sum of all the even factors of the numbers in the given range ; Driver code
|
using System ; using System ; class GFG { public const int MAX = 100000 ; public static long [ ] prefix = new long [ MAX ] ; public static void sieve_modified ( ) { for ( int i = 2 ; i < MAX ; i += 2 ) { for ( int j = i ; j < MAX ; j += i ) { prefix [ j ] += i ; } } for ( int i = 1 ; i < MAX ; i ++ ) { prefix [ i ] += prefix [ i - 1 ] ; } } public static long sumEvenFactors ( int L , int R ) { return ( prefix [ R ] - prefix [ L - 1 ] ) ; } public static void Main ( string [ ] args ) { sieve_modified ( ) ; int l = 6 , r = 10 ; Console . Write ( sumEvenFactors ( l , r ) ) ; } }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.