text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Minimize count of Subsets with difference between maximum and minimum element not exceeding K | C ++ Program to implement above approach ; Function to find the minimum count of subsets of required type ; Stores the result ; Store the maximum and minimum element of the current subset ; Update current maximum ; If difference exceeds K ; Update count ; Update maximum and minimum to the current subset ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findCount ( int arr [ ] , int N , int K ) { sort ( arr , arr + N ) ; int result = 1 ; int cur_max = arr [ 0 ] ; int cur_min = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { cur_max = arr [ i ] ; if ( cur_max - cur_min > K ) { result ++ ; cur_max = arr [ i ] ; cur_min = arr [ i ] ; } } return result ; } int main ( ) { int arr [ ] = { 1 , 10 , 8 , 3 , 9 } ; int K = 3 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findCount ( arr , N , K ) ; return 0 ; } |
Minimize the Sum of all the subarrays made up of the products of same | C ++ Program to implement the above approach ; Function to rearrange the second array such that the sum of its product of same indexed elements from both the arrays is minimized ; Stores ( i - 1 ) * ( n - i ) * a [ i ] for every i - th element ; Updating the value of pro according to the function ; Sort the array in reverse order ; Sort the products ; Updating the ans ; Return the ans ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE #define ll long long NEW_LINE using namespace std ; const int mod = ( int ) 1e9 + 7 ; bool comp ( ll a , ll b ) { if ( a > b ) return true ; else return false ; } ll findMinValue ( vector < ll > & a , vector < ll > & b ) { int n = a . size ( ) ; vector < ll > pro ( n ) ; for ( int i = 0 ; i < n ; ++ i ) { pro [ i ] = ( ( ll ) ( i + 1 ) * ( ll ) ( n - i ) ) ; pro [ i ] *= ( 1LL * a [ i ] ) ; ; } sort ( b . begin ( ) , b . end ( ) , comp ) ; sort ( pro . begin ( ) , pro . end ( ) ) ; ll ans = 0 ; for ( int i = 0 ; i < n ; ++ i ) { ans += ( pro [ i ] % mod * b [ i ] ) % mod ; ans %= mod ; } return ans ; } int main ( ) { vector < ll > a = { 1 , 2 , 3 } ; vector < ll > b = { 2 , 3 , 2 } ; cout << findMinValue ( a , b ) << endl ; } |
Maximum number of unique Triplets such that each element is selected only once | C ++ program for the above approach ; Function that finds maximum number of triplets with different elements ; Map M will store the frequency of each element in the array ; Priority queue of pairs { frequency , value } ; ans will store possible triplets ; Extract top 3 elements ; Make a triplet ; Decrease frequency and push back into priority queue if non - zero frequency ; Print the triplets ; Print the triplets ; Driver Code ; Given array arr [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findTriplets ( int ar [ ] , int n ) { unordered_map < int , int > mp ; for ( int x = 0 ; x < n ; x ++ ) mp [ ar [ x ] ] ++ ; priority_queue < pair < int , int > > pq ; for ( auto & pa : mp ) pq . push ( { pa . second , pa . first } ) ; vector < array < int , 3 > > ans ; while ( pq . size ( ) >= 3 ) { pair < int , int > ar [ 3 ] ; for ( int x = 0 ; x < 3 ; x ++ ) { ar [ x ] = pq . top ( ) ; pq . pop ( ) ; } ans . push_back ( { ar [ 0 ] . second , ar [ 1 ] . second , ar [ 2 ] . second } ) ; for ( int x = 0 ; x < 3 ; x ++ ) { ar [ x ] . first -- ; if ( ar [ x ] . first ) pq . push ( ar [ x ] ) ; } } cout << " Maximum β number β of β " << " possible β triples : β " ; cout << ans . size ( ) << endl ; for ( auto & pa : ans ) { for ( int v : pa ) cout << v << " β " ; cout << endl ; } } int main ( ) { int arr [ ] = { 2 , 2 , 3 , 3 , 4 , 4 , 4 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findTriplets ( arr , n ) ; return 0 ; } |
Sort Array such that smallest is at 0 th index and next smallest it at last index and so on | C ++ program for the above approach ; Function to perform the rearrangement ; Initialize variables ; Loop until i crosses j ; This check is to find the minimum values in the ascending order ; Condition to alternatively iterate variable i and j ; Perform swap operation ; Increment i ; Assign the value of min ; Perform swap ; Decrement i ; Assign the value of min ; Print the array ; Driver Code ; Given Array arr [ ] ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void rearrange ( int a [ ] , int N ) { int i = 0 , j = N - 1 ; int min = 0 , k , x = 0 , temp ; while ( i < j ) { for ( k = i ; k <= j ; k ++ ) { if ( a [ k ] < a [ min ] ) min = k ; } if ( x % 2 == 0 ) { temp = a [ i ] ; a [ i ] = a [ min ] ; a [ min ] = temp ; i ++ ; min = i ; } else { temp = a [ j ] ; a [ j ] = a [ min ] ; a [ min ] = temp ; j -- ; min = j ; } x ++ ; } for ( i = 0 ; i < N ; i ++ ) cout << a [ i ] << " β " ; } int main ( ) { int arr [ ] = { 1 , 3 , 3 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; rearrange ( arr , N ) ; return 0 ; } |
Maximum number of elements greater than X after equally distributing subset of array | C ++ implementation to find the maximum number of elements greater than X by equally distributing ; Function to find the maximum number of elements greater than X by equally distributing ; Sorting the array ; Loop to iterate over the elements of the array ; If no more elements can become larger than x ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void redistribute ( int arr [ ] , int n , int x ) { sort ( arr , arr + n , greater < int > ( ) ) ; int i , sum = 0 ; for ( i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; if ( sum / ( i + 1 ) < x ) { cout << i << endl ; break ; } } if ( i == n ) cout << n << endl ; } int main ( ) { int arr [ ] = { 5 , 1 , 2 , 1 } ; int x = 3 ; redistribute ( arr , 4 , x ) ; return 0 ; } |
Last element remaining by deleting two largest elements and replacing by their absolute difference if they are unequal | C ++ program for the above approach ; Function to print the remaining element ; Priority queue can be used to construct max - heap ; Insert all element of arr [ ] into priority queue ; Perform operation until heap size becomes 0 or 1 ; Remove largest element ; Remove 2 nd largest element ; If extracted element are not equal ; Find X - Y and push it to heap ; If heap size is 1 , then print the remaining element ; Else print " - 1" ; Driver Code ; Given array arr [ ] ; Size of array arr [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int final_element ( int arr [ ] , int n ) { priority_queue < int > heap ; for ( int i = 0 ; i < n ; i ++ ) heap . push ( arr [ i ] ) ; while ( heap . size ( ) > 1 ) { int X = heap . top ( ) ; heap . pop ( ) ; int Y = heap . top ( ) ; heap . pop ( ) ; if ( X != Y ) { int diff = abs ( X - Y ) ; heap . push ( diff ) ; } } if ( heap . size ( ) == 1 ) { cout << heap . top ( ) ; } else { cout << " - 1" ; } } int main ( ) { int arr [ ] = { 3 , 5 , 2 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; final_element ( arr , n ) ; return 0 ; } |
Sort a string according to the frequency of characters | C ++ implementation to Sort strings according to the frequency of characters in ascending order ; Returns count of character in the string ; Check for vowel ; Function to sort the string according to the frequency ; Vector to store the frequency of characters with respective character ; Inserting frequency with respective character in the vector pair ; Sort the vector , this will sort the pair according to the number of characters ; Print the sorted vector content ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countFrequency ( string str , char ch ) { int count = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) if ( str [ i ] == ch ) ++ count ; return count ; } void sortArr ( string str ) { int n = str . length ( ) ; vector < pair < int , char > > vp ; for ( int i = 0 ; i < n ; i ++ ) { vp . push_back ( make_pair ( countFrequency ( str , str [ i ] ) , str [ i ] ) ) ; } sort ( vp . begin ( ) , vp . end ( ) ) ; for ( int i = 0 ; i < vp . size ( ) ; i ++ ) cout << vp [ i ] . second ; } int main ( ) { string str = " geeksforgeeks " ; sortArr ( str ) ; return 0 ; } |
Maximum sum after rearranging the array for K queries | C ++ program to find the maximum sum after rearranging the array for K queries ; Function to find maximum sum after rearranging array elements ; Auxiliary array to find the count of each selected elements ; Finding count of every element to be selected ; Making it to 0 - indexing ; Prefix sum array concept is used to obtain the count array ; Iterating over the count array to get the final array ; Variable to store the maximum sum ; Sorting both the arrays ; Loop to find the maximum sum ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSumArrangement ( int A [ ] , int R [ ] [ 2 ] , int N , int M ) { int count [ N ] ; memset ( count , 0 , sizeof count ) ; for ( int i = 0 ; i < M ; ++ i ) { int l = R [ i ] [ 0 ] , r = R [ i ] [ 1 ] + 1 ; l -- ; r -- ; count [ l ] ++ ; if ( r < N ) count [ r ] -- ; } for ( int i = 1 ; i < N ; ++ i ) { count [ i ] += count [ i - 1 ] ; } for ( int i = 0 ; i < N ; ++ i ) { cout << count [ i ] ; } int ans = 0 ; sort ( count , count + N ) ; sort ( A , A + N ) ; for ( int i = 0 ; i < N ; ++ i ) { cout << endl << A [ i ] ; } for ( int i = N - 1 ; i >= 0 ; -- i ) { ans += A [ i ] * count [ i ] ; } return ans ; } int main ( ) { int A [ ] = { 2 , 6 , 10 , 1 , 5 , 6 } ; int R [ ] [ 2 ] = { { 1 , 3 } , { 4 , 6 } , { 3 , 4 } } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int M = sizeof ( R ) / sizeof ( R [ 0 ] ) ; cout << maxSumArrangement ( A , R , N , M ) ; return 0 ; } |
Sum of M maximum distinct digit sum from 1 to N that are factors of K | C ++ implementation to find the sum of maximum distinct digit sum of at most M numbers from 1 to N that are factors of K ; Function to find the factors of K in N ; Initialise a vector ; Find out the factors of K less than N ; Find the digit sum of each factor ; Sum of digits for each element in vector ; Find the largest M distinct digit sum from the digitSum vector ; Find the sum of last M numbers . ; Find the at most M numbers from N natural numbers whose digit sum is distinct and those M numbers are factors of K . ; Find out the factors of K less than N ; Sum of digits for each element in vector ; Sorting the digitSum vector ; Removing the duplicate elements ; " HashSet " is stores only unique elements ; Finding the sum and returning it ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > findFactors ( int n , int k ) { vector < int > factors ; for ( int i = 1 ; i <= sqrt ( k ) ; i ++ ) { if ( k % i == 0 ) { if ( k / i == i && i <= n ) factors . push_back ( i ) ; else { if ( i <= n ) factors . push_back ( i ) ; if ( k / i <= n ) factors . push_back ( k / i ) ; } } } return factors ; } vector < int > findDigitSum ( vector < int > a ) { for ( int i = 0 ; i < a . size ( ) ; i ++ ) { int c = 0 ; while ( a [ i ] > 0 ) { c += a [ i ] % 10 ; a [ i ] = a [ i ] / 10 ; } a [ i ] = c ; } return a ; } int findMMaxDistinctDigitSum ( vector < int > distinctDigitSum , int m ) { int sum = 0 ; for ( int i = distinctDigitSum . size ( ) - 1 ; i >= 0 && m > 0 ; i -- , m -- ) sum += distinctDigitSum [ i ] ; return sum ; } int findDistinctMnumbers ( int n , int k , int m ) { vector < int > factors = findFactors ( n , k ) ; vector < int > digitSum = findDigitSum ( factors ) ; sort ( digitSum . begin ( ) , digitSum . end ( ) ) ; vector < int > :: iterator ip ; ip = unique ( digitSum . begin ( ) , digitSum . end ( ) ) ; digitSum . resize ( distance ( digitSum . begin ( ) , ip ) ) ; return findMMaxDistinctDigitSum ( digitSum , m ) ; } int main ( ) { int n = 100 , k = 80 , m = 4 ; cout << findDistinctMnumbers ( n , k , m ) << endl ; return 0 ; } |
Sorting objects using In | C ++ implementation of the approach ; Partition function which will partition the array and into two parts ; Compare hash values of objects ; Classic quicksort algorithm ; Function to sort and print the objects ; Create a hash table ; As the sorting order is blue objects , red objects and then yellow objects ; Quick sort function ; Printing the sorted array ; Driver code ; Let 's represent objects as strings | #include <bits/stdc++.h> NEW_LINE using namespace std ; int partition ( vector < string > & objects , int l , int r , unordered_map < string , int > & hash ) { int j = l - 1 ; int last_element = hash [ objects [ r ] ] ; for ( int i = l ; i < r ; i ++ ) { if ( hash [ objects [ i ] ] <= last_element ) { j ++ ; swap ( objects [ i ] , objects [ j ] ) ; } } j ++ ; swap ( objects [ j ] , objects [ r ] ) ; return j ; } void quicksort ( vector < string > & objects , int l , int r , unordered_map < string , int > & hash ) { if ( l < r ) { int mid = partition ( objects , l , r , hash ) ; quicksort ( objects , l , mid - 1 , hash ) ; quicksort ( objects , mid + 1 , r , hash ) ; } } void sortObj ( vector < string > & objects ) { unordered_map < string , int > hash ; hash [ " blue " ] = 1 ; hash [ " red " ] = 2 ; hash [ " yellow " ] = 3 ; quicksort ( objects , 0 , int ( objects . size ( ) - 1 ) , hash ) ; for ( int i = 0 ; i < objects . size ( ) ; i ++ ) cout << objects [ i ] << " β " ; } int main ( ) { vector < string > objects { " red " , " blue " , " red " , " yellow " , " blue " } ; sortObj ( objects ) ; return 0 ; } |
Sort the numbers according to their product of digits | C ++ implementation of the approach ; Function to return the product of the digits of n ; Function to sort the array according to the product of the digits of elements ; Vector to store the digit product with respective elements ; Inserting digit product with elements in the vector pair ; Sort the vector , this will sort the pair according to the product of the digits ; Print the sorted vector content ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int productOfDigit ( int n ) { int product = 1 ; while ( n > 0 ) { product *= n % 10 ; n = n / 10 ; } return product ; } void sortArr ( int arr [ ] , int n ) { vector < pair < int , int > > vp ; for ( int i = 0 ; i < n ; i ++ ) { vp . push_back ( make_pair ( productOfDigit ( arr [ i ] ) , arr [ i ] ) ) ; } sort ( vp . begin ( ) , vp . end ( ) ) ; for ( int i = 0 ; i < vp . size ( ) ; i ++ ) cout << vp [ i ] . second << " β " ; } int main ( ) { int arr [ ] = { 12 , 10 , 102 , 31 , 15 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortArr ( arr , n ) ; return 0 ; } |
Minimum steps required to reduce all the elements of the array to zero | C ++ implementation of the approach ; Function to return the minimum steps required to reduce all the elements to 0 ; Maximum element from the array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minSteps ( int arr [ ] , int n ) { int maxVal = * max_element ( arr , arr + n ) ; return maxVal ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << minSteps ( arr , n ) ; return 0 ; } |
Maximum water that can be stored between two buildings | C ++ implementation of the above approach ; Return the maximum water that can be stored ; Check all possible pairs of buildings ; Maximum so far ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxWater ( int height [ ] , int n ) { int maximum = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { int current = ( min ( height [ i ] , height [ j ] ) * ( j - i - 1 ) ) ; maximum = max ( maximum , current ) ; } } return maximum ; } int main ( ) { int height [ ] = { 2 , 1 , 3 , 4 , 6 , 5 } ; int n = sizeof ( height ) / sizeof ( height [ 0 ] ) ; cout << maxWater ( height , n ) ; return 0 ; } |
Maximum water that can be stored between two buildings | C ++ implementation of the above approach ; Return the maximum water that can be stored ; Make pairs with indices ; Sort array based on heights ; To store the min and max index so far from the right ; Current building paired with the building greater in height and on the extreme left ; Current building paired with the building greater in height and on the extreme right ; Maximum so far ; Update the maximum and minimum so far ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool compareTo ( pair < int , int > p1 , pair < int , int > p2 ) { return p1 . second < p2 . second ; } int maxWater ( int height [ ] , int n ) { pair < int , int > pairs [ n ] ; for ( int i = 0 ; i < n ; i ++ ) pairs [ i ] = make_pair ( i , height [ i ] ) ; sort ( pairs , pairs + n , compareTo ) ; int minIndSoFar = pairs [ n - 1 ] . first ; int maxIndSoFar = pairs [ n - 1 ] . first ; int maxi = 0 ; for ( int i = n - 2 ; i >= 0 ; i -- ) { int left = 0 ; if ( minIndSoFar < pairs [ i ] . first ) { left = ( pairs [ i ] . second * ( pairs [ i ] . first - minIndSoFar - 1 ) ) ; } int right = 0 ; if ( maxIndSoFar > pairs [ i ] . first ) { right = ( pairs [ i ] . second * ( maxIndSoFar - pairs [ i ] . first - 1 ) ) ; } maxi = max ( left , max ( right , maxi ) ) ; minIndSoFar = min ( minIndSoFar , pairs [ i ] . first ) ; maxIndSoFar = max ( maxIndSoFar , pairs [ i ] . first ) ; } return maxi ; } int main ( ) { int height [ ] = { 2 , 1 , 3 , 4 , 6 , 5 } ; int n = sizeof ( height ) / sizeof ( height [ 0 ] ) ; cout << maxWater ( height , n ) ; } |
Check if the given array contains all the divisors of some integer | C ++ implementation of the approach ; Function that returns true if arr [ ] contains all the divisors of some integer ; Maximum element from the array ; Vector to store divisors of the maximum element i . e . X ; Store all the divisors of X ; If the lengths of a [ ] and b are different return false ; Sort a [ ] and b ; If divisors are not equal return false ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkDivisors ( int a [ ] , int n ) { int X = * max_element ( a , a + n ) ; vector < int > b ; for ( int i = 1 ; i * i <= X ; i ++ ) { if ( X % i == 0 ) { b . push_back ( i ) ; if ( X / i != i ) b . push_back ( X / i ) ; } } if ( b . size ( ) != n ) return false ; sort ( a , a + n ) ; sort ( b . begin ( ) , b . end ( ) ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( b [ i ] != a [ i ] ) return false ; } return true ; } int main ( ) { int arr [ ] = { 8 , 1 , 2 , 12 , 48 , 6 , 4 , 24 , 16 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( checkDivisors ( arr , N ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Kth largest node among all directly connected nodes to the given node in an undirected graph | C ++ implementation of the approach ; Function to print Kth node for each node ; Vector to store nodes directly connected to ith node along with their values ; Add edges to the vector along with the values of the node ; Sort neighbors of every node and find the Kth node ; Get the kth node ; If total nodes are < k ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findKthNode ( int u [ ] , int v [ ] , int n , int val [ ] , int V , int k ) { vector < pair < int , int > > g [ V ] ; for ( int i = 0 ; i < n ; i ++ ) { g [ u [ i ] ] . push_back ( make_pair ( val [ v [ i ] ] , v [ i ] ) ) ; g [ v [ i ] ] . push_back ( make_pair ( val [ u [ i ] ] , u [ i ] ) ) ; } for ( int i = 0 ; i < V ; i ++ ) { if ( g [ i ] . size ( ) > 0 ) sort ( g [ i ] . begin ( ) , g [ i ] . end ( ) ) ; if ( k <= g [ i ] . size ( ) ) printf ( " % d STRNEWLINE " , g [ i ] [ g [ i ] . size ( ) - k ] . second ) ; else printf ( " - 1 STRNEWLINE " ) ; } return ; } int main ( ) { int V = 3 ; int val [ ] = { 2 , 4 , 3 } ; int u [ ] = { 0 , 0 , 1 } ; int v [ ] = { 2 , 1 , 2 } ; int n = sizeof ( u ) / sizeof ( int ) ; int k = 2 ; findKthNode ( u , v , n , val , V , k ) ; return 0 ; } |
Minimum length of square to contain at least half of the given Coordinates | C ++ implementation of the above approach ; Function to Calculate Absolute Value ; Function to Calculate the Minimum value of M ; To store the minimum M for each point in array ; Sort the array ; Index at which atleast required point are inside square of length 2 * M ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int mod ( int x ) { if ( x >= 0 ) return x ; return - x ; } void findSquare ( int n ) { int points [ n ] [ 2 ] = { { 1 , 2 } , { -3 , 4 } , { 1 , 78 } , { -3 , -7 } } ; int a [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { int x , y ; x = points [ i ] [ 0 ] ; y = points [ i ] [ 1 ] ; a [ i ] = max ( mod ( x ) , mod ( y ) ) ; } sort ( a , a + n ) ; int index = floor ( n / 2 ) - 1 ; cout << " Minimum β M β required β is : β " << a [ index ] << endl ; } int main ( ) { int N ; N = 4 ; findSquare ( N ) ; return 0 ; } |
Eulerian Path in undirected graph | Efficient C ++ program to find out Eulerian path ; Function to find out the path It takes the adjacency matrix representation of the graph as input ; Find out number of edges each vertex has ; Find out how many vertex has odd number edges ; If number of vertex with odd number of edges is greater than two return " No β Solution " . ; If there is a path find the path Initialize empty stack and path take the starting current as discussed ; Loop will run until there is element in the stack or current edge has some neighbour . ; If current node has not any neighbour add it to path and pop stack set new current to the popped element ; If the current vertex has at least one neighbour add the current vertex to stack , remove the edge between them and set the current to its neighbour . ; print the path ; Driver Code ; Test case 1 ; Test case 2 ; Test case 3 | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findpath ( int graph [ ] [ 5 ] , int n ) { vector < int > numofadj ; for ( int i = 0 ; i < n ; i ++ ) numofadj . push_back ( accumulate ( graph [ i ] , graph [ i ] + 5 , 0 ) ) ; int startpoint = 0 , numofodd = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( numofadj [ i ] % 2 == 1 ) { numofodd ++ ; startpoint = i ; } } if ( numofodd > 2 ) { cout << " No β Solution " << endl ; return ; } stack < int > stack ; vector < int > path ; int cur = startpoint ; while ( ! stack . empty ( ) or accumulate ( graph [ cur ] , graph [ cur ] + 5 , 0 ) != 0 ) { if ( accumulate ( graph [ cur ] , graph [ cur ] + 5 , 0 ) == 0 ) { path . push_back ( cur ) ; cur = stack . top ( ) ; stack . pop ( ) ; } else { for ( int i = 0 ; i < n ; i ++ ) { if ( graph [ cur ] [ i ] == 1 ) { stack . push ( cur ) ; graph [ cur ] [ i ] = 0 ; graph [ i ] [ cur ] = 0 ; cur = i ; break ; } } } } for ( auto ele : path ) cout << ele << " β - > β " ; cout << cur << endl ; } int main ( ) { int graph1 [ ] [ 5 ] = { { 0 , 1 , 0 , 0 , 1 } , { 1 , 0 , 1 , 1 , 0 } , { 0 , 1 , 0 , 1 , 0 } , { 0 , 1 , 1 , 0 , 0 } , { 1 , 0 , 0 , 0 , 0 } } ; int n = sizeof ( graph1 ) / sizeof ( graph1 [ 0 ] ) ; findpath ( graph1 , n ) ; int graph2 [ ] [ 5 ] = { { 0 , 1 , 0 , 1 , 1 } , { 1 , 0 , 1 , 0 , 1 } , { 0 , 1 , 0 , 1 , 1 } , { 1 , 1 , 1 , 0 , 0 } , { 1 , 0 , 1 , 0 , 0 } } ; n = sizeof ( graph1 ) / sizeof ( graph1 [ 0 ] ) ; findpath ( graph2 , n ) ; int graph3 [ ] [ 5 ] = { { 0 , 1 , 0 , 0 , 1 } , { 1 , 0 , 1 , 1 , 1 } , { 0 , 1 , 0 , 1 , 0 } , { 0 , 1 , 1 , 0 , 1 } , { 1 , 1 , 0 , 1 , 0 } } ; n = sizeof ( graph1 ) / sizeof ( graph1 [ 0 ] ) ; findpath ( graph3 , n ) ; } |
Array element with minimum sum of absolute differences | C ++ implementation of the approach ; Function to return the minimized sum ; Sort the array ; Median of the array ; Calculate the minimized sum ; Return the required sum ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minSum ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int x = arr [ n / 2 ] ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += abs ( arr [ i ] - x ) ; return sum ; } int main ( ) { int arr [ ] = { 1 , 3 , 9 , 3 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minSum ( arr , n ) ; return 0 ; } |
Sort even and odd placed elements in increasing order | C ++ implementation of above approach ; function to print the odd and even indexed digits ; lists to store the odd and even positioned digits ; traverse through all the indexes in the integer ; if the digit is in odd_index position append it to odd_position list ; else append it to the even_position list ; print the elements in the list in sorted order ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void odd_even ( int arr [ ] , int n ) { vector < int > odd_indexes ; vector < int > even_indexes ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) odd_indexes . push_back ( arr [ i ] ) ; else even_indexes . push_back ( arr [ i ] ) ; } sort ( odd_indexes . begin ( ) , odd_indexes . end ( ) ) ; sort ( even_indexes . begin ( ) , even_indexes . end ( ) ) ; for ( int i = 0 ; i < odd_indexes . size ( ) ; i ++ ) cout << odd_indexes [ i ] << " β " ; for ( int i = 0 ; i < even_indexes . size ( ) ; i ++ ) cout << even_indexes [ i ] << " β " ; } int main ( ) { int arr [ ] = { 3 , 2 , 7 , 6 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; odd_even ( arr , n ) ; } |
Number of pairs whose sum is a power of 2 | C ++ implementation of above approach ; Function to return the count of valid pairs ; Storing occurrences of each element ; Sort the array in deceasing order ; Start taking largest element each time ; If element has already been paired ; Find the number which is greater than a [ i ] and power of two ; If there is a number which adds up with a [ i ] to form a power of two ; Edge case when a [ i ] and crr - a [ i ] is same and we have only one occurrence of a [ i ] then it cannot be paired ; Remove already paired elements ; Return the count ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int a [ ] , int n ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) mp [ a [ i ] ] ++ ; sort ( a , a + n , greater < int > ( ) ) ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp [ a [ i ] ] < 1 ) continue ; int cur = 1 ; while ( cur <= a [ i ] ) cur <<= 1 ; if ( mp [ cur - a [ i ] ] ) { if ( cur - a [ i ] == a [ i ] and mp [ a [ i ] ] == 1 ) continue ; count ++ ; mp [ cur - a [ i ] ] -- ; mp [ a [ i ] ] -- ; } } return count ; } int main ( ) { int a [ ] = { 3 , 11 , 14 , 5 , 13 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << countPairs ( a , n ) ; return 0 ; } |
In | Merge In Place in C ++ ; Both sorted sub - arrays must be adjacent in ' a ' ' an ' is the length of the first sorted section in ' a ' ' bn ' is the length of the second sorted section in ' a ' ; Return right now if we 're done ; Do insertion sort to merge if size of sub - arrays are small enough ; p -- ) Insert Sort A into B ; p ++ ) Insert Sort B into A ; Find the pivot points . Basically this is just finding the point in ' a ' where we can swap in the first part of ' b ' such that after the swap the last element in ' a ' will be less than or equal to the least element in ' b ' ; Swap first part of b with last part of a ; Now merge the two sub - array pairings ; } merge_array_inplace ; Merge Sort Implementation ; Sort first and second halves ; Now merge the two sorted sub - arrays together ; Function to print an array ; Driver program to test sort utility | #include <iostream> NEW_LINE using namespace std ; #define __INSERT_THRESH 5 NEW_LINE #define __swap ( x , y ) (t = *(x), *(x) = *(y), *(y) = t) NEW_LINE static void merge ( int * a , size_t an , size_t bn ) { int * b = a + an , * e = b + bn , * s , t ; if ( an == 0 || bn == 0 || ! ( * b < * ( b - 1 ) ) ) return ; if ( an < __INSERT_THRESH && an <= bn ) { for ( int * p = b , * v ; p > a ; for ( v = p , s = p - 1 ; v < e && * v < * s ; s = v , v ++ ) __swap ( s , v ) ; return ; } if ( bn < __INSERT_THRESH ) { for ( int * p = b , * v ; p < e ; for ( s = p , v = p - 1 ; s > a && * s < * v ; s = v , v -- ) __swap ( s , v ) ; return ; } int * pa = a , * pb = b ; for ( s = a ; s < b && pb < e ; s ++ ) if ( * pb < * pa ) pb ++ ; else pa ++ ; pa += b - s ; for ( int * la = pa , * fb = b ; la < b ; la ++ , fb ++ ) __swap ( la , fb ) ; merge ( a , pa - a , pb - b ) ; merge ( b , pb - b , e - pb ) ; #undef __swap #undef __INSERT_THRESH void merge_sort ( int * a , size_t n ) { size_t m = ( n + 1 ) / 2 ; if ( m > 1 ) merge_sort ( a , m ) ; if ( n - m > 1 ) merge_sort ( a + m , n - m ) ; merge ( a , m , n - m ) ; } void print_array ( int a [ ] , size_t n ) { if ( n > 0 ) { cout << " β " << a [ 0 ] ; for ( size_t i = 1 ; i < n ; i ++ ) cout << " β " << a [ i ] ; } cout << " STRNEWLINE " ; } int main ( ) { int a [ ] = { 3 , 16 , 5 , 14 , 8 , 10 , 7 , 15 , 1 , 13 , 4 , 9 , 12 , 11 , 6 , 2 } ; size_t n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; merge_sort ( a , n ) ; print_array ( a , n ) ; return 0 ; } |
Maximizing the elements with a [ i + 1 ] > a [ i ] | C ++ implementation of the approach ; returns the number of positions where A ( i + 1 ) is greater than A ( i ) after rearrangement of the array ; Creating a HashMap containing char as a key and occurrences as a value ; Find the maximum frequency ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countMaxPos ( int arr [ ] , int n ) { unordered_map < int , int > map ; for ( int i = 0 ; i < n ; i ++ ) { if ( map . count ( arr [ i ] ) ) map . insert ( { arr [ i ] , ( map . count ( arr [ i ] ) + 1 ) } ) ; else map . insert ( { arr [ i ] , 1 } ) ; } int max_freq = 0 ; for ( auto i : map ) { if ( max_freq < i . second ) { max_freq = i . second ; } } return n - max_freq ; } int main ( ) { int arr [ ] = { 20 , 30 , 10 , 50 , 40 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ( countMaxPos ( arr , n ) ) ; } |
Permutation of an array that has smaller values from another array | C ++ program to find permutation of an array that has smaller values from another array ; Function to print required permutation ; Storing elements and indexes ; Filling the answer array ; pair element of A and B ; Fill the remaining elements of answer ; Output required permutation ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void anyPermutation ( int A [ ] , int B [ ] , int n ) { vector < pair < int , int > > Ap , Bp ; for ( int i = 0 ; i < n ; i ++ ) Ap . push_back ( make_pair ( A [ i ] , i ) ) ; for ( int i = 0 ; i < n ; i ++ ) Bp . push_back ( make_pair ( B [ i ] , i ) ) ; sort ( Ap . begin ( ) , Ap . end ( ) ) ; sort ( Bp . begin ( ) , Bp . end ( ) ) ; int i = 0 , j = 0 , ans [ n ] = { 0 } ; vector < int > remain ; while ( i < n && j < n ) { if ( Ap [ i ] . first > Bp [ j ] . first ) { ans [ Bp [ j ] . second ] = Ap [ i ] . first ; i ++ ; j ++ ; } else { remain . push_back ( i ) ; i ++ ; } } j = 0 ; for ( int i = 0 ; i < n ; ++ i ) if ( ans [ i ] == 0 ) { ans [ i ] = Ap [ remain [ j ] ] . first ; j ++ ; } for ( int i = 0 ; i < n ; ++ i ) cout << ans [ i ] << " β " ; } int main ( ) { int A [ ] = { 12 , 24 , 8 , 32 } ; int B [ ] = { 13 , 25 , 32 , 11 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; anyPermutation ( A , B , n ) ; return 0 ; } |
Rearrange all elements of array which are multiples of x in increasing order | C ++ implementation of the approach ; Function to sort all the multiples of x from the array in ascending order ; Insert all multiples of 5 to a vector ; Sort the vector ; update the array elements ; Driver code ; Print the result | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sortMultiples ( int arr [ ] , int n , int x ) { vector < int > v ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] % x == 0 ) v . push_back ( arr [ i ] ) ; sort ( v . begin ( ) , v . end ( ) ) ; int j = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % x == 0 ) arr [ i ] = v [ j ++ ] ; } } int main ( ) { int arr [ ] = { 125 , 3 , 15 , 6 , 100 , 5 } ; int x = 5 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortMultiples ( arr , n , x ) ; for ( int i = 0 ; i < n ; i ++ ) { cout << arr [ i ] << " β " ; } return 0 ; } |
Minimum increment in the sides required to get non | C ++ program to find Minimum increase in sides to get non - negative area of a triangle ; Function to return the minimum increase in side lengths of the triangle ; push the three sides to a array ; sort the array ; check if sum is greater than third side ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumIncrease ( int a , int b , int c ) { int arr [ ] = { a , b , c } ; sort ( arr , arr + 3 ) ; if ( arr [ 0 ] + arr [ 1 ] >= arr [ 2 ] ) return 0 ; else return arr [ 2 ] - ( arr [ 0 ] + arr [ 1 ] ) ; } int main ( ) { int a = 3 , b = 5 , c = 10 ; cout << minimumIncrease ( a , b , c ) ; return 0 ; } |
Minimum sum of differences with an element in an array | C ++ program to find minimum sum of absolute differences with an array element . ; function to find min sum after operation ; Sort the array ; Pick middle value ; Sum of absolute differences . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int absSumDidd ( int a [ ] , int n ) { sort ( a , a + n ) ; int midValue = a [ ( int ) ( n / 2 ) ] ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum = sum + abs ( a [ i ] - midValue ) ; } return sum ; } int main ( ) { int arr [ ] = { 5 , 11 , 14 , 10 , 17 , 15 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << absSumDidd ( arr , n ) ; } |
Printing frequency of each character just after its consecutive occurrences | CPP program to print run length encoding of a string ; Counting occurrences of s [ i ] ; Driver code | #include <iostream> NEW_LINE using namespace std ; void printRLE ( string s ) { for ( int i = 0 ; s [ i ] != ' \0' ; i ++ ) { int count = 1 ; while ( s [ i ] == s [ i + 1 ] ) { i ++ ; count ++ ; } cout << s [ i ] << count << " β " ; } cout << endl ; } int main ( ) { printRLE ( " GeeeEEKKKss " ) ; printRLE ( " ccccOddEEE " ) ; return 0 ; } |
Word Ladder ( Length of shortest chain to reach a target word ) | C ++ program to find length of the shortest chain transformation from source to target ; Returns length of shortest chain to reach ' target ' from ' start ' using minimum number of adjacent moves . D is dictionary ; If the target string is not present in the dictionary ; To store the current chain length and the length of the words ; Push the starting word into the queue ; While the queue is non - empty ; Increment the chain length ; Current size of the queue ; Since the queue is being updated while it is being traversed so only the elements which were already present in the queue before the start of this loop will be traversed for now ; Remove the first word from the queue ; For every character of the word ; Retain the original character at the current position ; Replace the current character with every possible lowercase alphabet ; If the new word is equal to the target word ; Remove the word from the set if it is found in it ; And push the newly generated word which will be a part of the chain ; Restore the original character at the current position ; Driver program ; make dictionary | #include <bits/stdc++.h> NEW_LINE using namespace std ; int shortestChainLen ( string start , string target , set < string > & D ) { if ( start == target ) return 0 ; if ( D . find ( target ) == D . end ( ) ) return 0 ; int level = 0 , wordlength = start . size ( ) ; queue < string > Q ; Q . push ( start ) ; while ( ! Q . empty ( ) ) { ++ level ; int sizeofQ = Q . size ( ) ; for ( int i = 0 ; i < sizeofQ ; ++ i ) { string word = Q . front ( ) ; Q . pop ( ) ; for ( int pos = 0 ; pos < wordlength ; ++ pos ) { char orig_char = word [ pos ] ; for ( char c = ' a ' ; c <= ' z ' ; ++ c ) { word [ pos ] = c ; if ( word == target ) return level + 1 ; if ( D . find ( word ) == D . end ( ) ) continue ; D . erase ( word ) ; Q . push ( word ) ; } word [ pos ] = orig_char ; } } } return 0 ; } int main ( ) { set < string > D ; D . insert ( " poon " ) ; D . insert ( " plee " ) ; D . insert ( " same " ) ; D . insert ( " poie " ) ; D . insert ( " plie " ) ; D . insert ( " poin " ) ; D . insert ( " plea " ) ; string start = " toon " ; string target = " plea " ; cout << " Length β of β shortest β chain β is : β " << shortestChainLen ( start , target , D ) ; return 0 ; } |
Reverse tree path | CPP program for the above approach ; Function to print inorder traversal of the tree ; Utility function to track root to leaf paths ; Check if root is null then return ; Store the node in path array ; Check if we find the node upto which oath needs to be reversed ; Current path array contains the path which needs to be reversed ; Swap the data of two nodes ; Check if the node is a leaf node then return ; Call utility function for left and right subtree recursively ; Function to reverse tree path ; Initialize a vector to store paths ; Driver Code ; 7 / \ 6 5 / \ / \ 4 3 2 1 | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define nl " NEW_LINE " class Node { public : int data ; Node * left ; Node * right ; Node ( int value ) { data = value ; } } ; void inorder ( Node * temp ) { if ( temp == NULL ) return ; inorder ( temp -> left ) ; cout << temp -> data << " β " ; inorder ( temp -> right ) ; } void reverseTreePathUtil ( Node * root , vector < Node * > path , int pathLen , int key ) { if ( root == NULL ) return ; path [ pathLen ] = root ; pathLen ++ ; if ( root -> data == key ) { int i = 0 , j = pathLen - 1 ; while ( i < j ) { int temp = path [ i ] -> data ; path [ i ] -> data = path [ j ] -> data ; path [ j ] -> data = temp ; i ++ ; j -- ; } } if ( ! root -> left and ! root -> right ) return ; reverseTreePathUtil ( root -> left , path , pathLen , key ) ; reverseTreePathUtil ( root -> right , path , pathLen , key ) ; } void reverseTreePath ( Node * root , int key ) { if ( root == NULL ) return ; vector < Node * > path ( 50 , NULL ) ; reverseTreePathUtil ( root , path , 0 , key ) ; } int main ( ) { Node * root = new Node ( 7 ) ; root -> left = new Node ( 6 ) ; root -> right = new Node ( 5 ) ; root -> left -> left = new Node ( 4 ) ; root -> left -> right = new Node ( 3 ) ; root -> right -> left = new Node ( 2 ) ; root -> right -> right = new Node ( 1 ) ; int key = 4 ; reverseTreePath ( root , key ) ; inorder ( root ) ; return 0 ; } |
Find if an array of strings can be chained to form a circle | Set 2 | C ++ code to check if cyclic order is possible among strings under given constrainsts ; Utility method for a depth first search among vertices ; Returns true if all vertices are strongly connected i . e . can be made as loop ; Initialize all vertices as not visited ; perform a dfs from s ; now loop through all characters ; I character is marked ( i . e . it was first or last character of some string ) then it should be visited in last dfs ( as for looping , graph should be strongly connected ) ; If we reach that means graph is connected ; return true if an order among strings is possible ; Create an empty graph ; Initialize all vertices as not marked ; Initialize indegree and outdegree of every vertex as 0. ; Process all strings one by one ; Find first and last characters ; Mark the characters ; increase indegree and outdegree count ; Add an edge in graph ; If for any character indegree is not equal to outdegree then ordering is not possible ; Driver code to test above methods | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define M 26 NEW_LINE void dfs ( vector < int > g [ ] , int u , vector < bool > & visit ) { visit [ u ] = true ; for ( int i = 0 ; i < g [ u ] . size ( ) ; ++ i ) if ( ! visit [ g [ u ] [ i ] ] ) dfs ( g , g [ u ] [ i ] , visit ) ; } bool isConnected ( vector < int > g [ ] , vector < bool > & mark , int s ) { vector < bool > visit ( M , false ) ; dfs ( g , s , visit ) ; for ( int i = 0 ; i < M ; i ++ ) { if ( mark [ i ] && ! visit [ i ] ) return false ; } return true ; } bool possibleOrderAmongString ( string arr [ ] , int N ) { vector < int > g [ M ] ; vector < bool > mark ( M , false ) ; vector < int > in ( M , 0 ) , out ( M , 0 ) ; for ( int i = 0 ; i < N ; i ++ ) { int f = arr [ i ] . front ( ) - ' a ' ; int l = arr [ i ] . back ( ) - ' a ' ; mark [ f ] = mark [ l ] = true ; in [ l ] ++ ; out [ f ] ++ ; g [ f ] . push_back ( l ) ; } for ( int i = 0 ; i < M ; i ++ ) if ( in [ i ] != out [ i ] ) return false ; return isConnected ( g , mark , arr [ 0 ] . front ( ) - ' a ' ) ; } int main ( ) { string arr [ ] = { " ab " , " bc " , " cd " , " de " , " ed " , " da " } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( possibleOrderAmongString ( arr , N ) == false ) cout << " Ordering β not β possible STRNEWLINE " ; else cout << " Ordering β is β possible STRNEWLINE " ; return 0 ; } |
Dynamic Connectivity | Set 1 ( Incremental ) | C ++ implementation of incremental connectivity ; Finding the root of node i ; union of two nodes a and b ; union based on rank ; Returns true if two nodes have same root ; Performing an operation according to query type ; type 1 query means checking if node x and y are connected or not ; If roots of x and y is same then yes is the answer ; type 2 query refers union of x and y ; If x and y have different roots then union them ; Driver function ; No . of nodes ; The following two arrays are used to implement disjoint set data structure . arr [ ] holds the parent nodes while rank array holds the rank of subset ; initializing both array and rank ; number of queries | #include <bits/stdc++.h> NEW_LINE using namespace std ; int root ( int arr [ ] , int i ) { while ( arr [ i ] != i ) { arr [ i ] = arr [ arr [ i ] ] ; i = arr [ i ] ; } return i ; } void weighted_union ( int arr [ ] , int rank [ ] , int a , int b ) { int root_a = root ( arr , a ) ; int root_b = root ( arr , b ) ; if ( rank [ root_a ] < rank [ root_b ] ) { arr [ root_a ] = arr [ root_b ] ; rank [ root_b ] += rank [ root_a ] ; } else { arr [ root_b ] = arr [ root_a ] ; rank [ root_a ] += rank [ root_b ] ; } } bool areSame ( int arr [ ] , int a , int b ) { return ( root ( arr , a ) == root ( arr , b ) ) ; } void query ( int type , int x , int y , int arr [ ] , int rank [ ] ) { if ( type == 1 ) { if ( areSame ( arr , x , y ) == true ) cout << " Yes " << endl ; else cout << " No " << endl ; } else if ( type == 2 ) { if ( areSame ( arr , x , y ) == false ) weighted_union ( arr , rank , x , y ) ; } } int main ( ) { int n = 7 ; int arr [ n ] , rank [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { arr [ i ] = i ; rank [ i ] = 1 ; } int q = 11 ; query ( 1 , 0 , 1 , arr , rank ) ; query ( 2 , 0 , 1 , arr , rank ) ; query ( 2 , 1 , 2 , arr , rank ) ; query ( 1 , 0 , 2 , arr , rank ) ; query ( 2 , 0 , 2 , arr , rank ) ; query ( 2 , 2 , 3 , arr , rank ) ; query ( 2 , 3 , 4 , arr , rank ) ; query ( 1 , 0 , 5 , arr , rank ) ; query ( 2 , 4 , 5 , arr , rank ) ; query ( 2 , 5 , 6 , arr , rank ) ; query ( 1 , 2 , 6 , arr , rank ) ; return 0 ; } |
Perfect Binary Tree Specific Level Order Traversal | C ++ program for special order traversal ; A binary tree node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Given a perfect binary tree , print its nodes in specific level order ; Let us print root and next level first ; / Since it is perfect Binary Tree , right is not checked ; Do anything more if there are nodes at next level in given perfect Binary Tree ; Create a queue and enqueue left and right children of root ; We process two nodes at a time , so we need two variables to store two front items of queue ; traversal loop ; Pop two items from queue ; Print children of first and second in reverse order ; If first and second have grandchildren , enqueue them in reverse order ; Driver program to test above functions | #include <iostream> NEW_LINE #include <queue> NEW_LINE using namespace std ; struct Node { int data ; Node * left ; Node * right ; } ; Node * newNode ( int data ) { Node * node = new Node ; node -> data = data ; node -> right = node -> left = NULL ; return node ; } void printSpecificLevelOrder ( Node * root ) { if ( root == NULL ) return ; cout << root -> data ; if ( root -> left != NULL ) cout << " β " << root -> left -> data << " β " << root -> right -> data ; if ( root -> left -> left == NULL ) return ; queue < Node * > q ; q . push ( root -> left ) ; q . push ( root -> right ) ; Node * first = NULL , * second = NULL ; while ( ! q . empty ( ) ) { first = q . front ( ) ; q . pop ( ) ; second = q . front ( ) ; q . pop ( ) ; cout << " β " << first -> left -> data << " β " << second -> right -> data ; cout << " β " << first -> right -> data << " β " << second -> left -> data ; if ( first -> left -> left != NULL ) { q . push ( first -> left ) ; q . push ( second -> right ) ; q . push ( first -> right ) ; q . push ( second -> left ) ; } } } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> left = newNode ( 6 ) ; root -> right -> right = newNode ( 7 ) ; root -> left -> left -> left = newNode ( 8 ) ; root -> left -> left -> right = newNode ( 9 ) ; root -> left -> right -> left = newNode ( 10 ) ; root -> left -> right -> right = newNode ( 11 ) ; root -> right -> left -> left = newNode ( 12 ) ; root -> right -> left -> right = newNode ( 13 ) ; root -> right -> right -> left = newNode ( 14 ) ; root -> right -> right -> right = newNode ( 15 ) ; root -> left -> left -> left -> left = newNode ( 16 ) ; root -> left -> left -> left -> right = newNode ( 17 ) ; root -> left -> left -> right -> left = newNode ( 18 ) ; root -> left -> left -> right -> right = newNode ( 19 ) ; root -> left -> right -> left -> left = newNode ( 20 ) ; root -> left -> right -> left -> right = newNode ( 21 ) ; root -> left -> right -> right -> left = newNode ( 22 ) ; root -> left -> right -> right -> right = newNode ( 23 ) ; root -> right -> left -> left -> left = newNode ( 24 ) ; root -> right -> left -> left -> right = newNode ( 25 ) ; root -> right -> left -> right -> left = newNode ( 26 ) ; root -> right -> left -> right -> right = newNode ( 27 ) ; root -> right -> right -> left -> left = newNode ( 28 ) ; root -> right -> right -> left -> right = newNode ( 29 ) ; root -> right -> right -> right -> left = newNode ( 30 ) ; root -> right -> right -> right -> right = newNode ( 31 ) ; cout << " Specific β Level β Order β traversal β of β binary β tree β is β STRNEWLINE " ; printSpecificLevelOrder ( root ) ; return 0 ; } |
Ford | C ++ program for implementation of Ford Fulkerson algorithm ; Number of vertices in given graph ; Returns true if there is a path from source ' s ' to sink ' t ' in residual graph . Also fills parent [ ] to store the path ; Create a visited array and mark all vertices as not visited ; Create a queue , enqueue source vertex and mark source vertex as visited ; Standard BFS Loop ; If we find a connection to the sink node , then there is no point in BFS anymore We just have to set its parent and can return true ; We didn 't reach sink in BFS starting from source, so return false ; Returns the maximum flow from s to t in the given graph ; Create a residual graph and fill the residual graph with given capacities in the original graph as residual capacities in residual graph ; This array is filled by BFS and to store path ; There is no flow initially ; Augment the flow while tere is path from source to sink ; Find minimum residual capacity of the edges along the path filled by BFS . Or we can say find the maximum flow through the path found . ; update residual capacities of the edges and reverse edges along the path ; Add path flow to overall flow ; Return the overall flow ; Driver program to test above functions ; Let us create a graph shown in the above example | #include <iostream> NEW_LINE #include <limits.h> NEW_LINE #include <queue> NEW_LINE #include <string.h> NEW_LINE using namespace std ; #define V 6 NEW_LINE bool bfs ( int rGraph [ V ] [ V ] , int s , int t , int parent [ ] ) { bool visited [ V ] ; memset ( visited , 0 , sizeof ( visited ) ) ; queue < int > q ; q . push ( s ) ; visited [ s ] = true ; parent [ s ] = -1 ; while ( ! q . empty ( ) ) { int u = q . front ( ) ; q . pop ( ) ; for ( int v = 0 ; v < V ; v ++ ) { if ( visited [ v ] == false && rGraph [ u ] [ v ] > 0 ) { if ( v == t ) { parent [ v ] = u ; return true ; } q . push ( v ) ; parent [ v ] = u ; visited [ v ] = true ; } } } return false ; } int fordFulkerson ( int graph [ V ] [ V ] , int s , int t ) { int u , v ; int rGraph [ V ] [ V ] ; for ( u = 0 ; u < V ; u ++ ) for ( v = 0 ; v < V ; v ++ ) rGraph [ u ] [ v ] = graph [ u ] [ v ] ; int parent [ V ] ; int max_flow = 0 ; while ( bfs ( rGraph , s , t , parent ) ) { int path_flow = INT_MAX ; for ( v = t ; v != s ; v = parent [ v ] ) { u = parent [ v ] ; path_flow = min ( path_flow , rGraph [ u ] [ v ] ) ; } for ( v = t ; v != s ; v = parent [ v ] ) { u = parent [ v ] ; rGraph [ u ] [ v ] -= path_flow ; rGraph [ v ] [ u ] += path_flow ; } max_flow += path_flow ; } return max_flow ; } int main ( ) { int graph [ V ] [ V ] = { { 0 , 16 , 13 , 0 , 0 , 0 } , { 0 , 0 , 10 , 12 , 0 , 0 } , { 0 , 4 , 0 , 0 , 14 , 0 } , { 0 , 0 , 9 , 0 , 0 , 20 } , { 0 , 0 , 0 , 7 , 0 , 4 } , { 0 , 0 , 0 , 0 , 0 , 0 } } ; cout << " The β maximum β possible β flow β is β " << fordFulkerson ( graph , 0 , 5 ) ; return 0 ; } |
Find maximum number of edge disjoint paths between two vertices | C ++ program to find maximum number of edge disjoint paths ; Number of vertices in given graph ; Returns true if there is a path from source ' s ' to sink ' t ' in residual graph . Also fills parent [ ] to store the path ; Create a visited array and mark all vertices as not visited ; Create a queue , enqueue source vertex and mark source vertex as visited ; Standard BFS Loop ; If we reached sink in BFS starting from source , then return true , else false ; Returns tne maximum number of edge - disjoint paths from s to t . goo . gl / wtQ4Ks This function is copy of forFulkerson ( ) discussed at http : ; Create a residual graph and fill the residual graph with given capacities in the original graph as residual capacities in residual graph Residual graph where rGraph [ i ] [ j ] indicates residual capacity of edge from i to j ( if there is an edge . If rGraph [ i ] [ j ] is 0 , then there is not ) ; This array is filled by BFS and to store path ; There is no flow initially ; Augment the flow while tere is path from source to sink ; Find minimum residual capacity of the edges along the path filled by BFS . Or we can say find the maximum flow through the path found . ; update residual capacities of the edges and reverse edges along the path ; Add path flow to overall flow ; Return the overall flow ( max_flow is equal to maximum number of edge - disjoint paths ) ; Driver program to test above functions ; Let us create a graph shown in the above example | #include <iostream> NEW_LINE #include <limits.h> NEW_LINE #include <string.h> NEW_LINE #include <queue> NEW_LINE using namespace std ; #define V 8 NEW_LINE bool bfs ( int rGraph [ V ] [ V ] , int s , int t , int parent [ ] ) { bool visited [ V ] ; memset ( visited , 0 , sizeof ( visited ) ) ; queue < int > q ; q . push ( s ) ; visited [ s ] = true ; parent [ s ] = -1 ; while ( ! q . empty ( ) ) { int u = q . front ( ) ; q . pop ( ) ; for ( int v = 0 ; v < V ; v ++ ) { if ( visited [ v ] == false && rGraph [ u ] [ v ] > 0 ) { q . push ( v ) ; parent [ v ] = u ; visited [ v ] = true ; } } } return ( visited [ t ] == true ) ; } int findDisjointPaths ( int graph [ V ] [ V ] , int s , int t ) { int u , v ; int rGraph [ V ] [ V ] ; for ( u = 0 ; u < V ; u ++ ) for ( v = 0 ; v < V ; v ++ ) rGraph [ u ] [ v ] = graph [ u ] [ v ] ; int parent [ V ] ; int max_flow = 0 ; while ( bfs ( rGraph , s , t , parent ) ) { int path_flow = INT_MAX ; for ( v = t ; v != s ; v = parent [ v ] ) { u = parent [ v ] ; path_flow = min ( path_flow , rGraph [ u ] [ v ] ) ; } for ( v = t ; v != s ; v = parent [ v ] ) { u = parent [ v ] ; rGraph [ u ] [ v ] -= path_flow ; rGraph [ v ] [ u ] += path_flow ; } max_flow += path_flow ; } return max_flow ; } int main ( ) { int graph [ V ] [ V ] = { { 0 , 1 , 1 , 1 , 0 , 0 , 0 , 0 } , { 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 1 , 0 , 0 , 1 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 } , { 0 , 0 , 1 , 0 , 0 , 0 , 0 , 1 } , { 0 , 1 , 0 , 0 , 0 , 0 , 0 , 1 } , { 0 , 0 , 0 , 0 , 0 , 1 , 0 , 1 } , { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } } ; int s = 0 ; int t = 7 ; cout << " There β can β be β maximum β " << findDisjointPaths ( graph , s , t ) << " β edge - disjoint β paths β from β " << s << " β to β " << t ; return 0 ; } |
Perfect Binary Tree Specific Level Order Traversal | Set 2 | C ++ program for special order traversal ; A binary tree node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Function body ; Create a queue and enqueue left and right children of root ; We process two nodes at a time , so we need two variables to store two front items of queue ; traversal loop ; Pop two items from queue ; Push first and second node 's chilren in reverse order ; If first and second have grandchildren , enqueue them in specific order ; Given a perfect binary tree , print its nodes in specific level order ; create a stack and push root ; Push level 1 and level 2 nodes in stack ; Since it is perfect Binary Tree , right is not checked ; Do anything more if there are nodes at next level in given perfect Binary Tree ; Finally pop all Nodes from stack and prints them . ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int data ) { Node * node = new Node ; node -> data = data ; node -> right = node -> left = NULL ; return node ; } void printSpecificLevelOrderUtil ( Node * root , stack < Node * > & s ) { if ( root == NULL ) return ; queue < Node * > q ; q . push ( root -> left ) ; q . push ( root -> right ) ; Node * first = NULL , * second = NULL ; while ( ! q . empty ( ) ) { first = q . front ( ) ; q . pop ( ) ; second = q . front ( ) ; q . pop ( ) ; s . push ( second -> left ) ; s . push ( first -> right ) ; s . push ( second -> right ) ; s . push ( first -> left ) ; if ( first -> left -> left != NULL ) { q . push ( first -> right ) ; q . push ( second -> left ) ; q . push ( first -> left ) ; q . push ( second -> right ) ; } } } void printSpecificLevelOrder ( Node * root ) { stack < Node * > s ; s . push ( root ) ; if ( root -> left != NULL ) { s . push ( root -> right ) ; s . push ( root -> left ) ; } if ( root -> left -> left != NULL ) printSpecificLevelOrderUtil ( root , s ) ; while ( ! s . empty ( ) ) { cout << s . top ( ) -> data << " β " ; s . pop ( ) ; } } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; cout << " Specific β Level β Order β traversal β of β binary β " " tree β is β STRNEWLINE " ; printSpecificLevelOrder ( root ) ; return 0 ; } |
Prim 's algorithm using priority_queue in STL | If v is not in MST and weight of ( u , v ) is smaller than current key of v ; Updating key of v | if ( inMST [ v ] == false && key [ v ] > weight ) { key [ v ] = weight ; pq . push ( make_pair ( key [ v ] , v ) ) ; parent [ v ] = u ; } |
Graph implementation using STL for competitive programming | Set 2 ( Weighted graph ) | C ++ program to represent undirected and weighted graph using STL . The program basically prints adjacency list representation of graph ; To add an edge ; Print adjacency list representaion ot graph ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void addEdge ( vector < pair < int , int > > adj [ ] , int u , int v , int wt ) { adj [ u ] . push_back ( make_pair ( v , wt ) ) ; adj [ v ] . push_back ( make_pair ( u , wt ) ) ; } void printGraph ( vector < pair < int , int > > adj [ ] , int V ) { int v , w ; for ( int u = 0 ; u < V ; u ++ ) { cout << " Node β " << u << " β makes β an β edge β with β STRNEWLINE " ; for ( auto it = adj [ u ] . begin ( ) ; it != adj [ u ] . end ( ) ; it ++ ) { v = it -> first ; w = it -> second ; cout << " TABSYMBOL Node β " << v << " β with β edge β weight β = " << w << " STRNEWLINE " ; } cout << " STRNEWLINE " ; } } int main ( ) { int V = 5 ; vector < pair < int , int > > adj [ V ] ; addEdge ( adj , 0 , 1 , 10 ) ; addEdge ( adj , 0 , 4 , 20 ) ; addEdge ( adj , 1 , 2 , 30 ) ; addEdge ( adj , 1 , 3 , 40 ) ; addEdge ( adj , 1 , 4 , 50 ) ; addEdge ( adj , 2 , 3 , 60 ) ; addEdge ( adj , 3 , 4 , 70 ) ; printGraph ( adj , V ) ; return 0 ; } |
K Centers Problem | Set 1 ( Greedy Approximate Algorithm ) | C ++ program for the above approach ; index of city having the maximum distance to it 's closest center ; updating the distance of the cities to their closest centers ; updating the index of the city with the maximum distance to it 's closest center ; Printing the maximum distance of a city to a center that is our answer ; Printing the cities that were chosen to be made centers ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxindex ( int * dist , int n ) { int mi = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( dist [ i ] > dist [ mi ] ) mi = i ; } return mi ; } void selectKcities ( int n , int weights [ 4 ] [ 4 ] , int k ) { int * dist = new int [ n ] ; vector < int > centers ; for ( int i = 0 ; i < n ; i ++ ) { dist [ i ] = INT_MAX ; } int max = 0 ; for ( int i = 0 ; i < k ; i ++ ) { centers . push_back ( max ) ; for ( int j = 0 ; j < n ; j ++ ) { dist [ j ] = min ( dist [ j ] , weights [ max ] [ j ] ) ; } max = maxindex ( dist , n ) ; } cout << endl << dist [ max ] << endl ; for ( int i = 0 ; i < centers . size ( ) ; i ++ ) { cout << centers [ i ] << " β " ; } cout << endl ; } int main ( ) { int n = 4 ; int weights [ 4 ] [ 4 ] = { { 0 , 4 , 8 , 5 } , { 4 , 0 , 10 , 7 } , { 8 , 10 , 0 , 9 } , { 5 , 7 , 9 , 0 } } ; int k = 2 ; selectKcities ( n , weights , k ) ; } |
Hierholzer 's Algorithm for directed graph | A C ++ program to print Eulerian circuit in given directed graph using Hierholzer algorithm ; adj represents the adjacency list of the directed graph edge_count represents the number of edges emerging from a vertex ; find the count of edges to keep track of unused edges ; Maintain a stack to keep vertices ; vector to store final circuit ; start from any vertex ; Current vertex ; If there 's remaining edge ; Push the vertex ; Find the next vertex using an edge ; and remove that edge ; Move to next vertex ; back - track to find remaining circuit ; Back - tracking ; we 've got the circuit, now print it in reverse ; Driver program to check the above function ; Input Graph 1 ; Build the edges ; Input Graph 2 | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printCircuit ( vector < vector < int > > adj ) { unordered_map < int , int > edge_count ; for ( int i = 0 ; i < adj . size ( ) ; i ++ ) { edge_count [ i ] = adj [ i ] . size ( ) ; } if ( ! adj . size ( ) ) return ; stack < int > curr_path ; vector < int > circuit ; curr_path . push ( 0 ) ; int curr_v = 0 ; while ( ! curr_path . empty ( ) ) { if ( edge_count [ curr_v ] ) { curr_path . push ( curr_v ) ; int next_v = adj [ curr_v ] . back ( ) ; edge_count [ curr_v ] -- ; adj [ curr_v ] . pop_back ( ) ; curr_v = next_v ; } else { circuit . push_back ( curr_v ) ; curr_v = curr_path . top ( ) ; curr_path . pop ( ) ; } } for ( int i = circuit . size ( ) - 1 ; i >= 0 ; i -- ) { cout << circuit [ i ] ; if ( i ) cout << " β - > β " ; } } int main ( ) { vector < vector < int > > adj1 , adj2 ; adj1 . resize ( 3 ) ; adj1 [ 0 ] . push_back ( 1 ) ; adj1 [ 1 ] . push_back ( 2 ) ; adj1 [ 2 ] . push_back ( 0 ) ; printCircuit ( adj1 ) ; cout << endl ; adj2 . resize ( 7 ) ; adj2 [ 0 ] . push_back ( 1 ) ; adj2 [ 0 ] . push_back ( 6 ) ; adj2 [ 1 ] . push_back ( 2 ) ; adj2 [ 2 ] . push_back ( 0 ) ; adj2 [ 2 ] . push_back ( 3 ) ; adj2 [ 3 ] . push_back ( 4 ) ; adj2 [ 4 ] . push_back ( 2 ) ; adj2 [ 4 ] . push_back ( 5 ) ; adj2 [ 5 ] . push_back ( 0 ) ; adj2 [ 6 ] . push_back ( 4 ) ; printCircuit ( adj2 ) ; return 0 ; } |
Perfect Binary Tree Specific Level Order Traversal | Set 2 | C ++ program for special order traversal ; A binary tree node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Given a perfect binary tree , print its nodes in specific level order ; for level order traversal ; stack to print reverse ; vector to store the level ; considering size of the level ; push data of the node of a particular level to vector ; push vector containing a level in stack ; print the stack ; Finally pop all Nodes from stack and prints them . ; finally print root ; ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * left ; Node * right ; Node ( int value ) { data = value ; left = NULL ; right = NULL ; } } ; void specific_level_order_traversal ( Node * root ) { queue < Node * > q ; stack < vector < int > > s ; q . push ( root ) ; int sz ; while ( ! q . empty ( ) ) { vector < int > v ; sz = q . size ( ) ; for ( int i = 0 ; i < sz ; ++ i ) { Node * temp = q . front ( ) ; q . pop ( ) ; v . push_back ( temp -> data ) ; if ( temp -> left != NULL ) q . push ( temp -> left ) ; if ( temp -> right != NULL ) q . push ( temp -> right ) ; } s . push ( v ) ; } while ( ! s . empty ( ) ) { vector < int > v = s . top ( ) ; s . pop ( ) ; for ( int i = 0 , j = v . size ( ) - 1 ; i < j ; ++ i ) { cout << v [ i ] << " β " << v [ j ] << " β " ; j -- ; } } cout << root -> data ; } int main ( ) { Node * root = new Node ( 1 ) ; root -> left = new Node ( 2 ) ; root -> right = new Node ( 3 ) ; cout << " Specific β Level β Order β traversal β of β binary β " " tree β is β STRNEWLINE " ; specific_level_order_traversal ( root ) ; return 0 ; } |
Number of Triangles in an Undirected Graph | A C ++ program for finding number of triangles in an Undirected Graph . The program is for adjacency matrix representation of the graph ; Number of vertices in the graph ; Utility function for matrix multiplication ; Utility function to calculate trace of a matrix ( sum ofdiagnonal elements ) ; Utility function for calculating number of triangles in graph ; To Store graph ^ 2 ; To Store graph ^ 3 ; Initialising aux matrices with 0 ; aux2 is graph ^ 2 now printMatrix ( aux2 ) ; ; after this multiplication aux3 is graph ^ 3 printMatrix ( aux3 ) ; ; driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define V 4 NEW_LINE void multiply ( int A [ ] [ V ] , int B [ ] [ V ] , int C [ ] [ V ] ) { for ( int i = 0 ; i < V ; i ++ ) { for ( int j = 0 ; j < V ; j ++ ) { C [ i ] [ j ] = 0 ; for ( int k = 0 ; k < V ; k ++ ) C [ i ] [ j ] += A [ i ] [ k ] * B [ k ] [ j ] ; } } } int getTrace ( int graph [ ] [ V ] ) { int trace = 0 ; for ( int i = 0 ; i < V ; i ++ ) trace += graph [ i ] [ i ] ; return trace ; } int triangleInGraph ( int graph [ ] [ V ] ) { int aux2 [ V ] [ V ] ; int aux3 [ V ] [ V ] ; for ( int i = 0 ; i < V ; ++ i ) for ( int j = 0 ; j < V ; ++ j ) aux2 [ i ] [ j ] = aux3 [ i ] [ j ] = 0 ; multiply ( graph , graph , aux2 ) ; multiply ( graph , aux2 , aux3 ) ; int trace = getTrace ( aux3 ) ; return trace / 6 ; } int main ( ) { int graph [ V ] [ V ] = { { 0 , 1 , 1 , 0 } , { 1 , 0 , 1 , 1 } , { 1 , 1 , 0 , 1 } , { 0 , 1 , 1 , 0 } } ; printf ( " Total β number β of β Triangle β in β Graph β : β % d STRNEWLINE " , triangleInGraph ( graph ) ) ; return 0 ; } |
Count subsequences in first string which are anagrams of the second string | C ++ implementation to count subsequences in first string which are anagrams of the second string ; Returns value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- -- * 1 ] ; function to count subsequences in first string which are anagrams of the second string ; hash tables to store frequencies of each character ; store frequency of each character of ' str1' ; store frequency of each character of ' str2' ; to store the total count of subsequences ; if character ( i + ' a ' ) exists in ' str2' ; if this character ' s β frequency β β in β ' str2 ' β in β less β than β or β β equal β to β its β frequency β in β β ' str1 ' β then β accumulate β its β β contribution β to β the β count β β of β subsequences . β If β its β β frequency β in β ' str1 ' β is β ' n ' β β and β in β ' str2 ' β is β ' r ', then its contribution will be nCr, where C is the binomial coefficient. ; else return 0 as there could be no subsequence which is an anagram of ' str2' ; required count of subsequences ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define SIZE 26 NEW_LINE int binomialCoeff ( int n , int k ) { int res = 1 ; if ( k > n - k ) k = n - k ; for ( int i = 0 ; i < k ; ++ i ) { res *= ( n - i ) ; res /= ( i + 1 ) ; } return res ; } int countSubsequences ( string str1 , string str2 ) { int freq1 [ SIZE ] , freq2 [ SIZE ] ; int n1 = str1 . size ( ) ; int n2 = str2 . size ( ) ; memset ( freq1 , 0 , sizeof ( freq1 ) ) ; memset ( freq2 , 0 , sizeof ( freq2 ) ) ; for ( int i = 0 ; i < n1 ; i ++ ) freq1 [ str1 [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < n2 ; i ++ ) freq2 [ str2 [ i ] - ' a ' ] ++ ; int count = 1 ; for ( int i = 0 ; i < SIZE ; i ++ ) if ( freq2 [ i ] != 0 ) { if ( freq2 [ i ] <= freq1 [ i ] ) count = count * binomialCoeff ( freq1 [ i ] , freq2 [ i ] ) ; else return 0 ; } return count ; } int main ( ) { string str1 = " abacd " ; string str2 = " abc " ; cout << " Count β = β " << countSubsequences ( str1 , str2 ) ; return 0 ; } |
Subsequence queries after removing substrings | CPP program for answering queries to check whether a string subsequence or not after removing a substring . ; arrays to store results of preprocessing ; function to preprocess the strings ; initialize it as 0. ; store subsequence count in forward direction ; store number of matches till now ; store subsequence count in backward direction ; store number of matches till now ; function that gives the output ; length of remaining string A is less than B 's length ; driver function ; two queries | #include <bits/stdc++.h> NEW_LINE using namespace std ; int * fwd , * bwd ; void preProcess ( string a , string b ) { int n = a . size ( ) ; fwd = new int [ n ] ( ) ; bwd = new int [ n ] ( ) ; int j = 0 ; for ( int i = 1 ; i <= a . size ( ) ; i ++ ) { if ( j < b . size ( ) && a [ i - 1 ] == b [ j ] ) j ++ ; fwd [ i ] = j ; } j = 0 ; for ( int i = a . size ( ) ; i >= 1 ; i -- ) { if ( j < b . size ( ) && a [ i - 1 ] == b [ b . size ( ) - j - 1 ] ) j ++ ; bwd [ i ] = j ; } } void query ( string a , string b , int x , int y ) { if ( ( x - 1 + a . size ( ) - y ) < b . size ( ) ) { cout << " No STRNEWLINE " ; return ; } if ( fwd [ x - 1 ] + bwd [ y + 1 ] >= b . size ( ) ) cout << " Yes STRNEWLINE " ; else cout << " No STRNEWLINE " ; } int main ( ) { string a = " abcabcxy " , b = " acy " ; preProcess ( a , b ) ; int x = 2 , y = 5 ; query ( a , b , x , y ) ; x = 3 , y = 6 ; query ( a , b , x , y ) ; return 0 ; } |
Count subsequence of length three in a given string | C ++ program to find number of occurrences of a subsequence of length 3 ; Function to find number of occurrences of a subsequence of length three in a string ; variable to store no of occurrences ; loop to find first character ; loop to find 2 nd character ; loop to find 3 rd character ; increment count if subsequence is found ; Driver code | #include <iostream> NEW_LINE using namespace std ; int findOccurrences ( string str , string substr ) { int counter = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] == substr [ 0 ] ) { for ( int j = i + 1 ; j < str . length ( ) ; j ++ ) { if ( str [ j ] == substr [ 1 ] ) { for ( int k = j + 1 ; k < str . length ( ) ; k ++ ) { if ( str [ k ] == substr [ 2 ] ) counter ++ ; } } } } } return counter ; } int main ( ) { string str = " GFGFGYSYIOIWIN " ; string substr = " GFG " ; cout << findOccurrences ( str , substr ) ; return 0 ; } |
Count subsequence of length three in a given string | C ++ program to find number of occurrences of a subsequence of length 3 ; Function to find number of occurrences of a subsequence of length three in a string ; calculate length of string ; auxiliary array to store occurrences of first character ; auxiliary array to store occurrences of third character ; calculate occurrences of first character upto ith index from left ; calculate occurrences of third character upto ith index from right ; variable to store total number of occurrences ; loop to find the occurrences of middle element ; if middle character of subsequence is found in the string ; multiply the total occurrences of first character before middle character with the total occurrences of third character after middle character ; Driver code | #include <iostream> NEW_LINE using namespace std ; int findOccurrences ( string str , string substr ) { int n = str . length ( ) ; int preLeft [ n ] = { 0 } ; int preRight [ n ] = { 0 } ; if ( str [ 0 ] == substr [ 0 ] ) preLeft [ 0 ] ++ ; for ( int i = 1 ; i < n ; i ++ ) { if ( str [ i ] == substr [ 0 ] ) preLeft [ i ] = preLeft [ i - 1 ] + 1 ; else preLeft [ i ] = preLeft [ i - 1 ] ; } if ( str [ n - 1 ] == substr [ 2 ] ) preRight [ n - 1 ] ++ ; for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( str [ i ] == substr [ 2 ] ) preRight [ i ] = preRight [ i + 1 ] + 1 ; else preRight [ i ] = preRight [ i + 1 ] ; } int counter = 0 ; for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( str [ i ] == str [ 1 ] ) { int total = preLeft [ i - 1 ] * preRight [ i + 1 ] ; counter += total ; } } return counter ; } int main ( ) { string str = " GFGFGYSYIOIWIN " ; string substr = " GFG " ; cout << findOccurrences ( str , substr ) ; return 0 ; } |
Form the largest palindromic number using atmost two swaps | C ++ implementation to form the largest palindromic number using atmost two swaps ; function to form the largest palindromic number using atmost two swaps ; if length of number is less than '3' then no higher palindromic number can be formed ; find the index of last digit in the 1 st half of ' num ' ; as only the first half of ' num [ ] ' is being considered , therefore for the rightmost digit in the first half of ' num [ ] ' , there will be no greater right digit ; index of the greatest right digit till the current index from the right direction ; traverse the array from second right element in the first half of ' num [ ] ' up to the left element ; if ' num [ i ] ' is less than the greatest digit encountered so far ; there is no greater right digit for ' num [ i ] ' ; update ' right ' index ; traverse the ' rightMax [ ] ' array from left to right ; if for the current digit , greater right digit exists then swap it with its greater right digit and also perform the required swap operation in the right halft of ' num [ ] ' to maintain palindromic property , then break ; performing the required swap operations ; Driver program to test above ; required largest palindromic number | #include <bits/stdc++.h> NEW_LINE using namespace std ; void largestPalin ( char num [ ] , int n ) { if ( n <= 3 ) return ; int mid = n / 2 - 1 ; int rightMax [ mid + 1 ] , right ; rightMax [ mid ] = -1 ; right = mid ; for ( int i = mid - 1 ; i >= 0 ; i -- ) { if ( num [ i ] < num [ right ] ) rightMax [ i ] = right ; else { rightMax [ i ] = -1 ; right = i ; } } for ( int i = 0 ; i <= mid ; i ++ ) { if ( rightMax [ i ] != -1 ) { swap ( num [ i ] , num [ rightMax [ i ] ] ) ; swap ( num [ n - i - 1 ] , num [ n - rightMax [ i ] - 1 ] ) ; break ; } } } int main ( ) { char num [ ] = "4697557964" ; int n = strlen ( num ) ; largestPalin ( num , n ) ; cout << " Largest β Palindrome : β " << num ; return 0 ; } |
Mirror characters of a string | C ++ code to find the reverse alphabetical order from a given position ; Function which take the given string and the position from which the reversing shall be done and returns the modified string ; Creating a string having reversed alphabetical order ; The string up to the point specified in the question , the string remains unchanged and from the point up to the length of the string , we reverse the alphabetical order ; Driver function | #include <iostream> NEW_LINE #include <string> NEW_LINE using namespace std ; string compute ( string str , int n ) { string reverseAlphabet = " zyxwvutsrqponmlkjihgfedcba " ; int l = str . length ( ) ; for ( int i = n ; i < l ; i ++ ) str [ i ] = reverseAlphabet [ str [ i ] - ' a ' ] ; return str ; } int main ( ) { string str = " pneumonia " ; int n = 4 ; string answer = compute ( str , n - 1 ) ; cout << answer ; return 0 ; } |
Check whether a given graph is Bipartite or not | ; ; vector to store colour of vertex assiging all to - 1 i . e . uncoloured colours are either 0 or 1 for understanding take 0 as red and 1 as blue ; queue for BFS storing { vertex , colour } ; loop incase graph is not connected ; if not coloured ; colouring with 0 i . e . red ; current vertex ; colour of current vertex ; traversing vertexes connected to current vertex ; if already coloured with parent vertex color then bipartite graph is not possible ; if uncooloured ; colouring with opposite color to that of parent ; if all vertexes are coloured such that no two connected vertex have same colours ; { Driver Code Starts . ; adjacency list for storing graph ; returns 1 if bipatite graph is possible ; returns 0 if bipartite graph is not possible | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isBipartite ( int V , vector < int > adj [ ] ) { vector < int > col ( V , -1 ) ; queue < pair < int , int > > q ; for ( int i = 0 ; i < V ; i ++ ) { if ( col [ i ] == -1 ) { q . push ( { i , 0 } ) ; col [ i ] = 0 ; while ( ! q . empty ( ) ) { pair < int , int > p = q . front ( ) ; q . pop ( ) ; int v = p . first ; int c = p . second ; for ( int j : adj [ v ] ) { if ( col [ j ] == c ) return 0 ; if ( col [ j ] == -1 ) { col [ j ] = ( c ) ? 0 : 1 ; q . push ( { j , col [ j ] } ) ; } } } } } return 1 ; } int main ( ) { int V , E ; V = 4 , E = 8 ; vector < int > adj [ V ] ; adj [ 0 ] = { 1 , 3 } ; adj [ 1 ] = { 0 , 2 } ; adj [ 2 ] = { 1 , 3 } ; adj [ 3 ] = { 0 , 2 } ; bool ans = isBipartite ( V , adj ) ; if ( ans ) cout << " Yes STRNEWLINE " ; else cout << " No STRNEWLINE " ; return 0 ; } |
Lexicographically smallest string whose hamming distance from given string is exactly K | CPP program to find Lexicographically smallest string whose hamming distance from given string is exactly K ; function to find Lexicographically smallest string with hamming distance k ; If k is 0 , output input string ; Copying input string into output string ; Traverse all the character of the string ; If current character is not ' a ' ; copy character ' a ' to output string ; If hamming distance became k , break ; ; If k is less than p ; Traversing string in reverse order ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findString ( string str , int n , int k ) { if ( k == 0 ) { cout << str << endl ; return ; } string str2 = str ; int p = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str2 [ i ] != ' a ' ) { str2 [ i ] = ' a ' ; p ++ ; if ( p == k ) break ; } } if ( p < k ) { for ( int i = n - 1 ; i >= 0 ; i -- ) if ( str [ i ] == ' a ' ) { str2 [ i ] = ' b ' ; p ++ ; if ( p == k ) break ; } } cout << str2 << endl ; } int main ( ) { string str = " pqrs " ; int n = str . length ( ) ; int k = 2 ; findString ( str , n , k ) ; return 0 ; } |
Lexicographically first alternate vowel and consonant string | C ++ implementation of lexicographically first alternate vowel and consonant string ; ' ch ' is vowel or not ; create alternate vowel and consonant string str1 [ 0. . . l1 - 1 ] and str2 [ start ... l2 - 1 ] ; first adding character of vowel / consonant then adding character of consonant / vowel ; function to find the required lexicographically first alternate vowel and consonant string ; hash table to store frequencies of each character in ' str ' ; initialize all elements of char_freq [ ] to 0 ; count vowels ; count consonants ; update frequency of ' ch ' in char_freq [ ] ; no such string can be formed ; form the vowel string ' vstr ' and consonant string ' cstr ' which contains characters in lexicographical order ; remove first character of vowel string then create alternate string with cstr [ 0. . . nc - 1 ] and vstr [ 1. . . nv - 1 ] ; remove first character of consonant string then create alternate string with vstr [ 0. . . nv - 1 ] and cstr [ 1. . . nc - 1 ] ; if both vowel and consonant strings are of equal length start creating string with consonant ; start creating string with vowel ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define SIZE 26 NEW_LINE bool isVowel ( char ch ) { if ( ch == ' a ' ch == ' e ' ch == ' i ' ch == ' o ' ch == ' u ' ) return true ; return false ; } string createAltStr ( string str1 , string str2 , int start , int l ) { string finalStr = " " ; for ( int i = 0 , j = start ; j < l ; i ++ , j ++ ) finalStr = ( finalStr + str1 . at ( i ) ) + str2 . at ( j ) ; return finalStr ; } string findAltStr ( string str ) { int char_freq [ SIZE ] ; memset ( char_freq , 0 , sizeof ( char_freq ) ) ; int nv = 0 , nc = 0 ; string vstr = " " , cstr = " " ; int l = str . size ( ) ; for ( int i = 0 ; i < l ; i ++ ) { char ch = str . at ( i ) ; if ( isVowel ( ch ) ) nv ++ ; else nc ++ ; char_freq [ ch - 97 ] ++ ; } if ( abs ( nv - nc ) >= 2 ) return " no β such β string " ; for ( int i = 0 ; i < SIZE ; i ++ ) { char ch = ( char ) ( i + 97 ) ; for ( int j = 1 ; j <= char_freq [ i ] ; j ++ ) { if ( isVowel ( ch ) ) vstr += ch ; else cstr += ch ; } } if ( nv > nc ) return ( vstr . at ( 0 ) + createAltStr ( cstr , vstr , 1 , nv ) ) ; if ( nc > nv ) return ( cstr . at ( 0 ) + createAltStr ( vstr , cstr , 1 , nc ) ) ; if ( cstr . at ( 0 ) < vstr . at ( 0 ) ) return createAltStr ( cstr , vstr , 0 , nv ) ; return createAltStr ( vstr , cstr , 0 , nc ) ; } int main ( ) { string str = " aeroplane " ; cout << findAltStr ( str ) ; return 0 ; } |
Decode an Encoded Base 64 String to ASCII String | C ++ Program to decode a base64 Encoded string back to ASCII string ; char_set = " ABCDEFGHIJKLMNOPQRSTUVWXYZ β abcdefghijklmnopqrstuvwxyz0123456789 + / " ; stores the bitstream . ; count_bits stores current number of bits in num . ; selects 4 characters from encoded string at a time . find the position of each encoded character in char_set and stores in num . ; make space for 6 bits . ; encoded [ i + j ] = ' E ' , ' E ' - ' A ' = 5 ' E ' has 5 th position in char_set . ; encoded [ i + j ] = ' e ' , ' e ' - ' a ' = 5 , 5 + 26 = 31 , ' e ' has 31 st position in char_set . ; encoded [ i + j ] = '8' , '8' - '0' = 8 8 + 52 = 60 , '8' has 60 th position in char_set . ; ' + ' occurs in 62 nd position in char_set . ; ' / ' occurs in 63 rd position in char_set . ; ( str [ i + j ] == ' = ' ) remove 2 bits to delete appended bits during encoding . ; 255 in binary is 11111111 ; Driver code ; Do not count last NULL character . | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define SIZE 100 NEW_LINE char * base64Decoder ( char encoded [ ] , int len_str ) { char * decoded_string ; decoded_string = ( char * ) malloc ( sizeof ( char ) * SIZE ) ; int i , j , k = 0 ; int num = 0 ; int count_bits = 0 ; for ( i = 0 ; i < len_str ; i += 4 ) { num = 0 , count_bits = 0 ; for ( j = 0 ; j < 4 ; j ++ ) { if ( encoded [ i + j ] != ' = ' ) { num = num << 6 ; count_bits += 6 ; } if ( encoded [ i + j ] >= ' A ' && encoded [ i + j ] <= ' Z ' ) num = num | ( encoded [ i + j ] - ' A ' ) ; else if ( encoded [ i + j ] >= ' a ' && encoded [ i + j ] <= ' z ' ) num = num | ( encoded [ i + j ] - ' a ' + 26 ) ; else if ( encoded [ i + j ] >= '0' && encoded [ i + j ] <= '9' ) num = num | ( encoded [ i + j ] - '0' + 52 ) ; else if ( encoded [ i + j ] == ' + ' ) num = num | 62 ; else if ( encoded [ i + j ] == ' / ' ) num = num | 63 ; else { num = num >> 2 ; count_bits -= 2 ; } } while ( count_bits != 0 ) { count_bits -= 8 ; decoded_string [ k ++ ] = ( num >> count_bits ) & 255 ; } } decoded_string [ k ] = ' \0' ; return decoded_string ; } int main ( ) { char encoded_string [ ] = " TUVOT04 = " ; int len_str = sizeof ( encoded_string ) / sizeof ( encoded_string [ 0 ] ) ; len_str -= 1 ; cout << " Encoded β string β : β " << encoded_string << endl ; cout << " Decoded β string β : β " << base64Decoder ( encoded_string , len_str ) << endl ; return 0 ; } |
Print all possible strings that can be made by placing spaces | C ++ program to print all strings that can be made by placing spaces ; Function to print all subsequences ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printSubsequences ( string str ) { int n = str . length ( ) ; unsigned int opsize = pow ( 2 , n - 1 ) ; for ( int counter = 0 ; counter < opsize ; counter ++ ) { for ( int j = 0 ; j < n ; j ++ ) { cout << str [ j ] ; if ( counter & ( 1 << j ) ) cout << " β " ; } cout << endl ; } } int main ( ) { string str = " ABC " ; printSubsequences ( str ) ; return 0 ; } |
Find n | C ++ program to print n - th permutation ; Utility for calculating factorials ; Function for nth permutation ; Length of given string ; Count frequencies of all characters ; Out string for output string ; Iterate till sum equals n ; We update both n and sum in this loop . ; Check for characters present in freq [ ] ; Remove character ; Calculate sum after fixing a particular char ; if sum > n fix that char as present char and update sum and required nth after fixing char at that position ; if sum < n , add character back ; if sum == n means this char will provide its greatest permutation as nth permutation ; append string termination character and print result ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE const int MAX_CHAR = 26 ; const int MAX_FACT = 20 ; ll fact [ MAX_FACT ] ; void precomputeFactorials ( ) { fact [ 0 ] = 1 ; for ( int i = 1 ; i < MAX_FACT ; i ++ ) fact [ i ] = fact [ i - 1 ] * i ; } void nPermute ( char str [ ] , int n ) { precomputeFactorials ( ) ; int len = strlen ( str ) ; int freq [ MAX_CHAR ] = { 0 } ; for ( int i = 0 ; i < len ; i ++ ) freq [ str [ i ] - ' a ' ] ++ ; char out [ MAX_CHAR ] ; int sum = 0 ; int k = 0 ; while ( sum != n ) { sum = 0 ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) { if ( freq [ i ] == 0 ) continue ; freq [ i ] -- ; int xsum = fact [ len - 1 - k ] ; for ( int j = 0 ; j < MAX_CHAR ; j ++ ) xsum /= fact [ freq [ j ] ] ; sum += xsum ; if ( sum >= n ) { out [ k ++ ] = i + ' a ' ; n -= ( sum - xsum ) ; break ; } if ( sum < n ) freq [ i ] ++ ; } } for ( int i = MAX_CHAR - 1 ; k < len && i >= 0 ; i -- ) if ( freq [ i ] ) { out [ k ++ ] = i + ' a ' ; freq [ i ++ ] -- ; } out [ k ] = ' \0' ; cout << out ; } int main ( ) { int n = 2 ; char str [ ] = " geeksquiz " ; nPermute ( str , n ) ; return 0 ; } |
Minimum number of deletions so that no two consecutive are same | CPP code to count minimum deletions required so that there are no consecutive characters left ; Function for counting deletions ; If two consecutive characters are the same , delete one of them . ; Driver code ; Function call to print answer | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countDeletions ( string str ) { int ans = 0 ; for ( int i = 0 ; i < str . length ( ) - 1 ; i ++ ) if ( str [ i ] == str [ i + 1 ] ) ans ++ ; return ans ; } int main ( ) { string str = " AAABBB " ; cout << countDeletions ( str ) ; return 0 ; } |
Count words that appear exactly two times in an array of words | C ++ program to count all words with count exactly 2. ; Returns count of words with frequency exactly 2. ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countWords ( string str [ ] , int n ) { unordered_map < string , int > m ; for ( int i = 0 ; i < n ; i ++ ) m [ str [ i ] ] += 1 ; int res = 0 ; for ( auto it = m . begin ( ) ; it != m . end ( ) ; it ++ ) if ( ( it -> second == 2 ) ) res ++ ; return res ; } int main ( ) { string s [ ] = { " hate " , " love " , " peace " , " love " , " peace " , " hate " , " love " , " peace " , " love " , " peace " } ; int n = sizeof ( s ) / sizeof ( s [ 0 ] ) ; cout << countWords ( s , n ) ; return 0 ; } |
Check whether a given graph is Bipartite or not | C ++ program to find out whether a given graph is Bipartite or not . Using recursion . ; color this pos as c and all its neighbours and 1 - c ; start is vertex 0 ; ; two colors 1 and 0 ; Driver Code | #include <iostream> NEW_LINE using namespace std ; #define V 4 NEW_LINE bool colorGraph ( int G [ ] [ V ] , int color [ ] , int pos , int c ) { if ( color [ pos ] != -1 && color [ pos ] != c ) return false ; color [ pos ] = c ; bool ans = true ; for ( int i = 0 ; i < V ; i ++ ) { if ( G [ pos ] [ i ] ) { if ( color [ i ] == -1 ) ans &= colorGraph ( G , color , i , 1 - c ) ; if ( color [ i ] != -1 && color [ i ] != 1 - c ) return false ; } if ( ! ans ) return false ; } return true ; } bool isBipartite ( int G [ ] [ V ] ) { int color [ V ] ; for ( int i = 0 ; i < V ; i ++ ) color [ i ] = -1 ; int pos = 0 ; return colorGraph ( G , color , pos , 1 ) ; } int main ( ) { int G [ ] [ V ] = { { 0 , 1 , 0 , 1 } , { 1 , 0 , 1 , 0 } , { 0 , 1 , 0 , 1 } , { 1 , 0 , 1 , 0 } } ; isBipartite ( G ) ? cout << " Yes " : cout << " No " ; return 0 ; } |
Nth Even length Palindrome | C ++ program to find n = th even length string . ; Function to find nth even length Palindrome ; string r to store resultant palindrome . Initialize same as s ; In this loop string r stores reverse of string s after the string s in consecutive manner . ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; string evenlength ( string n ) { string res = n ; for ( int j = n . length ( ) - 1 ; j >= 0 ; -- j ) res += n [ j ] ; return res ; } int main ( ) { string n = "10" ; cout << evenlength ( n ) ; return 0 ; } |
Program for First Fit algorithm in Memory Management | C ++ implementation of First - Fit algorithm ; Function to allocate memory to blocks as per First fit algorithm ; Stores block id of the block allocated to a process ; Initially no block is assigned to any process ; pick each process and find suitable blocks according to its size ad assign to it ; allocate block j to p [ i ] process ; Reduce available memory in this block . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void firstFit ( int blockSize [ ] , int m , int processSize [ ] , int n ) { int allocation [ n ] ; memset ( allocation , -1 , sizeof ( allocation ) ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( blockSize [ j ] >= processSize [ i ] ) { allocation [ i ] = j ; blockSize [ j ] -= processSize [ i ] ; break ; } } } cout << " Process No . Process Size Block no . " ; for ( int i = 0 ; i < n ; i ++ ) { cout << " β " << i + 1 << " TABSYMBOL TABSYMBOL " << processSize [ i ] << " TABSYMBOL TABSYMBOL " ; if ( allocation [ i ] != -1 ) cout << allocation [ i ] + 1 ; else cout << " Not β Allocated " ; cout << endl ; } } int main ( ) { int blockSize [ ] = { 100 , 500 , 200 , 300 , 600 } ; int processSize [ ] = { 212 , 417 , 112 , 426 } ; int m = sizeof ( blockSize ) / sizeof ( blockSize [ 0 ] ) ; int n = sizeof ( processSize ) / sizeof ( processSize [ 0 ] ) ; firstFit ( blockSize , m , processSize , n ) ; return 0 ; } |
Determine if a string has all Unique Characters | C ++ program to illustrate string with unique characters using brute force technique ; If at any time we encounter 2 same characters , return false ; If no duplicate characters encountered , return true ; driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool uniqueCharacters ( string str ) { for ( int i = 0 ; i < str . length ( ) - 1 ; i ++ ) { for ( int j = i + 1 ; j < str . length ( ) ; j ++ ) { if ( str [ i ] == str [ j ] ) { return false ; } } } return true ; } int main ( ) { string str = " GeeksforGeeks " ; if ( uniqueCharacters ( str ) ) { cout << " The β String β " << str << " β has β all β unique β characters STRNEWLINE " ; } else { cout << " The β String β " << str << " β has β duplicate β characters STRNEWLINE " ; } return 0 ; } |
Check if given string can be split into four distinct strings | C ++ program to check if we can break a string into four distinct strings . ; Return if the given string can be split or not . ; We can always break a string of size 10 or more into four distinct strings . ; Brute Force ; Making 4 string from the given string ; Checking if they are distinct or not . ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( string s ) { if ( s . size ( ) >= 10 ) return true ; for ( int i = 1 ; i < s . size ( ) ; i ++ ) { for ( int j = i + 1 ; j < s . size ( ) ; j ++ ) { for ( int k = j + 1 ; k < s . size ( ) ; k ++ ) { string s1 = s . substr ( 0 , i ) ; string s2 = s . substr ( i , j - i ) ; string s3 = s . substr ( j , k - j ) ; string s4 = s . substr ( k , s . size ( ) - k ) ; if ( s1 != s2 && s1 != s3 && s1 != s4 && s2 != s3 && s2 != s4 && s3 != s4 ) return true ; } } } return false ; } int main ( ) { string str = " aaabb " ; ( check ( str ) ) ? ( cout << " Yes " << endl ) : ( cout << " No " << endl ) ; return 0 ; } |
Multiply Large Numbers represented as Strings | C ++ program to multiply two numbers represented as strings . ; Multiplies str1 and str2 , and prints result . ; will keep the result number in vector in reverse order ; Below two indexes are used to find positions in result . ; Go from right to left in num1 ; To shift position to left after every multiplication of a digit in num2 ; Go from right to left in num2 ; Take current digit of second number ; Multiply with current digit of first number and add result to previously stored result at current position . ; Carry for next iteration ; Store result ; store carry in next cell ; To shift position to left after every multiplication of a digit in num1 . ; ignore '0' s from the right ; If all were '0' s - means either both or one of num1 or num2 were '0' ; generate the result string ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string multiply ( string num1 , string num2 ) { int len1 = num1 . size ( ) ; int len2 = num2 . size ( ) ; if ( len1 == 0 len2 == 0 ) return "0" ; vector < int > result ( len1 + len2 , 0 ) ; int i_n1 = 0 ; int i_n2 = 0 ; for ( int i = len1 - 1 ; i >= 0 ; i -- ) { int carry = 0 ; int n1 = num1 [ i ] - '0' ; i_n2 = 0 ; for ( int j = len2 - 1 ; j >= 0 ; j -- ) { int n2 = num2 [ j ] - '0' ; int sum = n1 * n2 + result [ i_n1 + i_n2 ] + carry ; carry = sum / 10 ; result [ i_n1 + i_n2 ] = sum % 10 ; i_n2 ++ ; } if ( carry > 0 ) result [ i_n1 + i_n2 ] += carry ; i_n1 ++ ; } int i = result . size ( ) - 1 ; while ( i >= 0 && result [ i ] == 0 ) i -- ; if ( i == -1 ) return "0" ; string s = " " ; while ( i >= 0 ) s += std :: to_string ( result [ i -- ] ) ; return s ; } int main ( ) { string str1 = "1235421415454545454545454544" ; string str2 = "1714546546546545454544548544544545" ; if ( ( str1 . at ( 0 ) == ' - ' || str2 . at ( 0 ) == ' - ' ) && ( str1 . at ( 0 ) != ' - ' || str2 . at ( 0 ) != ' - ' ) ) cout << " - " ; if ( str1 . at ( 0 ) == ' - ' ) str1 = str1 . substr ( 1 ) ; if ( str2 . at ( 0 ) == ' - ' ) str2 = str2 . substr ( 1 ) ; cout << multiply ( str1 , str2 ) ; return 0 ; } |
Find an equal point in a string of brackets | C ++ program to find an index k which decides the number of opening brackets is equal to the number of closing brackets ; Function to find an equal index ; Store the number of opening brackets at each index ; Store the number of closing brackets at each index ; check if there is no opening or closing brackets ; check if there is any index at which both brackets are equal ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findIndex ( string str ) { int len = str . length ( ) ; int open [ len + 1 ] , close [ len + 1 ] ; int index = -1 ; memset ( open , 0 , sizeof ( open ) ) ; memset ( close , 0 , sizeof ( close ) ) ; open [ 0 ] = 0 ; close [ len ] = 0 ; if ( str [ 0 ] == ' ( ' ) open [ 1 ] = 1 ; if ( str [ len - 1 ] == ' ) ' ) close [ len - 1 ] = 1 ; for ( int i = 1 ; i < len ; i ++ ) { if ( str [ i ] == ' ( ' ) open [ i + 1 ] = open [ i ] + 1 ; else open [ i + 1 ] = open [ i ] ; } for ( int i = len - 2 ; i >= 0 ; i -- ) { if ( str [ i ] == ' ) ' ) close [ i ] = close [ i + 1 ] + 1 ; else close [ i ] = close [ i + 1 ] ; } if ( open [ len ] == 0 ) return len ; if ( close [ 0 ] == 0 ) return 0 ; for ( int i = 0 ; i <= len ; i ++ ) if ( open [ i ] == close [ i ] ) index = i ; return index ; } int main ( ) { string str = " ( ( ) ) ) ( ( ) ( ) ( ) ) ) ) " ; cout << findIndex ( str ) ; return 0 ; } |
Convert decimal fraction to binary number | C ++ program to convert fractional decimal to binary number ; Function to convert decimal to binary upto k - precision after decimal point ; Fetch the integral part of decimal number ; Fetch the fractional part decimal number ; Conversion of integral part to binary equivalent ; Append 0 in binary ; Reverse string to get original binary equivalent ; Append point before conversion of fractional part ; Conversion of fractional part to binary equivalent ; Find next bit in fraction ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string decimalToBinary ( double num , int k_prec ) { string binary = " " ; int Integral = num ; double fractional = num - Integral ; while ( Integral ) { int rem = Integral % 2 ; binary . push_back ( rem + '0' ) ; Integral /= 2 ; } reverse ( binary . begin ( ) , binary . end ( ) ) ; binary . push_back ( ' . ' ) ; while ( k_prec -- ) { fractional *= 2 ; int fract_bit = fractional ; if ( fract_bit == 1 ) { fractional -= fract_bit ; binary . push_back ( 1 + '0' ) ; } else binary . push_back ( 0 + '0' ) ; } return binary ; } int main ( ) { double n = 4.47 ; int k = 3 ; cout << decimalToBinary ( n , k ) << " STRNEWLINE " ; n = 6.986 , k = 5 ; cout << decimalToBinary ( n , k ) ; return 0 ; } |
Difference of two large numbers | C ++ program to find difference of two large numbers . ; Returns true if str1 is smaller than str2 , else false . ; Calculate lengths of both string ; Function for finding difference of larger numbers ; Before proceeding further , make sure str1 is not smaller ; Take an empty string for storing result ; Calculate lengths of both string ; Initially take carry zero ; Traverse from end of both strings ; Do school mathematics , compute difference of current digits and carry ; subtract remaining digits of str1 [ ] ; if ( i > 0 sub > 0 ) remove preceding 0 's ; reverse resultant string ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isSmaller ( string str1 , string str2 ) { int n1 = str1 . length ( ) , n2 = str2 . length ( ) ; if ( n1 < n2 ) return true ; if ( n2 < n1 ) return false ; for ( int i = 0 ; i < n1 ; i ++ ) { if ( str1 [ i ] < str2 [ i ] ) return true ; else if ( str1 [ i ] > str2 [ i ] ) return false ; } return false ; } string findDiff ( string str1 , string str2 ) { if ( isSmaller ( str1 , str2 ) ) swap ( str1 , str2 ) ; string str = " " ; int n1 = str1 . length ( ) , n2 = str2 . length ( ) ; int diff = n1 - n2 ; int carry = 0 ; for ( int i = n2 - 1 ; i >= 0 ; i -- ) { int sub = ( ( str1 [ i + diff ] - '0' ) - ( str2 [ i ] - '0' ) - carry ) ; if ( sub < 0 ) { sub = sub + 10 ; carry = 1 ; } else carry = 0 ; str . push_back ( sub + '0' ) ; } for ( int i = n1 - n2 - 1 ; i >= 0 ; i -- ) { if ( str1 [ i ] == '0' && carry ) { str . push_back ( '9' ) ; continue ; } int sub = ( ( str1 [ i ] - '0' ) - carry ) ; str . push_back ( sub + '0' ) ; carry = 0 ; } reverse ( str . begin ( ) , str . end ( ) ) ; return str ; } int main ( ) { string str1 = "88" ; string str2 = "1079" ; cout << findDiff ( str1 , str2 ) ; return 0 ; } |
Efficiently check if a string has all unique characters without using any additional data structure | Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool unique ( string s ) { sort ( s . begin ( ) , s . end ( ) ) ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { if ( s [ i ] == s [ i + 1 ] ) { return false ; break ; } } return true ; } int main ( ) { if ( unique ( " abcdd " ) == true ) { cout << " String β is β Unique " << endl ; } else { cout << " String β is β not β Unique " << endl ; } return 0 ; } |
Check if two strings are k | Optimized C ++ program to check if two strings are k anagram or not . ; Function to check if str1 and str2 are k - anagram or not ; If both strings are not of equal length then return false ; Store the occurrence of all characters in a hash_array ; Store the occurrence of all characters in a hash_array ; Return true if count is less than or equal to k ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; bool areKAnagrams ( string str1 , string str2 , int k ) { int n = str1 . length ( ) ; if ( str2 . length ( ) != n ) return false ; int hash_str1 [ MAX_CHAR ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) hash_str1 [ str1 [ i ] - ' a ' ] ++ ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( hash_str1 [ str2 [ i ] - ' a ' ] > 0 ) hash_str1 [ str2 [ i ] - ' a ' ] -- ; else count ++ ; if ( count > k ) return false ; } return true ; } int main ( ) { string str1 = " fodr " ; string str2 = " gork " ; int k = 2 ; if ( areKAnagrams ( str1 , str2 , k ) == true ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Nth character in Concatenated Decimal String | C ++ program to get Nth character in concatenated Decimal String ; Utility method to get dth digit of number N ; Method to return Nth character in concatenated decimal string ; sum will store character escaped till now ; dist will store numbers escaped till now ; loop for number lengths ; nine * len will be incremented characters and nine will be incremented numbers ; restore variables to previous correct state ; get distance from last one digit less maximum number ; d will store dth digit of current number ; method will return dth numbered digit of ( dist + diff ) number ; Driver code to test above methods | #include <bits/stdc++.h> NEW_LINE using namespace std ; char getDigit ( int N , int d ) { string str ; stringstream ss ; ss << N ; ss >> str ; return str [ d - 1 ] ; } char getNthChar ( int N ) { int sum = 0 , nine = 9 ; int dist = 0 , len ; for ( len = 1 ; ; len ++ ) { sum += nine * len ; dist += nine ; if ( sum >= N ) { sum -= nine * len ; dist -= nine ; N -= sum ; break ; } nine *= 10 ; } int diff = ceil ( ( double ) N / len ) ; int d = N % len ; if ( d == 0 ) d = len ; return getDigit ( dist + diff , d ) ; } int main ( ) { int N = 251 ; cout << getNthChar ( N ) << endl ; return 0 ; } |
Minimum characters to be added at front to make string palindrome | C ++ program for getting minimum character to be added at front to make string palindrome ; function for checking string is palindrome or not ; Driver code ; if string becomes palindrome then break ; erase the last element of the string ; print the number of insertion at front | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool ispalindrome ( string s ) { int l = s . length ( ) ; int j ; for ( int i = 0 , j = l - 1 ; i <= j ; i ++ , j -- ) { if ( s [ i ] != s [ j ] ) return false ; } return true ; } int main ( ) { string s = " BABABAA " ; int cnt = 0 ; int flag = 0 ; while ( s . length ( ) > 0 ) { if ( ispalindrome ( s ) ) { flag = 1 ; break ; } else { cnt ++ ; s . erase ( s . begin ( ) + s . length ( ) - 1 ) ; } } s . erase ( s . begin ( ) + s . length ( ) - 1 ) ; if ( flag ) cout << cnt ; } |
Count characters at same position as in English alphabet | C ++ program to find number of characters at same position as in English alphabets ; Traverse input string ; Check that index of characters of string is same as of English alphabets by using ASCII values and the fact that all lower case alphabetic characters come together in same order in ASCII table . And same is true for upper case . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findCount ( string str ) { int result = 0 ; for ( int i = 0 ; i < str . size ( ) ; i ++ ) if ( i == ( str [ i ] - ' a ' ) || i == ( str [ i ] - ' A ' ) ) result ++ ; return result ; } int main ( ) { string str = " AbgdeF " ; cout << findCount ( str ) ; return 0 ; } |
Remove a character from a string to make it a palindrome | C / C ++ program to check whether it is possible to make string palindrome by removing one character ; Utility method to check if substring from low to high is palindrome or not . ; This method returns - 1 if it is not possible to make string a palindrome . It returns - 2 if string is already a palindrome . Otherwise it returns index of character whose removal can make the whole string palindrome . ; Initialize low and right by both the ends of the string ; loop until low and high cross each other ; If both characters are equal then move both pointer towards end ; If removing str [ low ] makes the whole string palindrome . We basically check if substring str [ low + 1. . high ] is palindrome or not . ; If removing str [ high ] makes the whole string palindrome We basically check if substring str [ low + 1. . high ] is palindrome or not . ; We reach here when complete string will be palindrome if complete string is palindrome then return mid character ; Driver code to test above methods | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( string :: iterator low , string :: iterator high ) { while ( low < high ) { if ( * low != * high ) return false ; low ++ ; high -- ; } return true ; } int possiblePalinByRemovingOneChar ( string str ) { int low = 0 , high = str . length ( ) - 1 ; while ( low < high ) { if ( str [ low ] == str [ high ] ) { low ++ ; high -- ; } else { if ( isPalindrome ( str . begin ( ) + low + 1 , str . begin ( ) + high ) ) return low ; if ( isPalindrome ( str . begin ( ) + low , str . begin ( ) + high - 1 ) ) return high ; return -1 ; } } return -2 ; } int main ( ) { string str = " abecbea " ; int idx = possiblePalinByRemovingOneChar ( str ) ; if ( idx == -1 ) cout << " Not β Possible β STRNEWLINE " ; else if ( idx == -2 ) cout << " Possible β without β removing β any β character " ; else cout << " Possible β by β removing β character " << " β at β index β " << idx << " STRNEWLINE " ; return 0 ; } |
Count number of unique ways to paint a N x 3 grid | C ++ program for the above approach ; Function to count the number of ways to paint N * 3 grid based on given conditions ; Count of ways to pain a row with same colored ends ; Count of ways to pain a row with different colored ends ; Traverse up to ( N - 1 ) th row ; For same colored ends ; For different colored ends ; Print the total number of ways ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void waysToPaint ( int n ) { int same = 6 ; int diff = 6 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { long sameTmp = 3 * same + 2 * diff ; long diffTmp = 2 * same + 2 * diff ; same = sameTmp ; diff = diffTmp ; } cout << ( same + diff ) ; } int main ( ) { int N = 2 ; waysToPaint ( N ) ; } |
Print all words matching a pattern in CamelCase Notation Dictionary | C ++ program to print all words in the CamelCase dictionary that matches with a given pattern ; Alphabet size ( # of upper - Case characters ) ; A Trie node ; isLeaf is true if the node represents end of a word ; vector to store list of complete words in leaf node ; Function to insert word into the Trie ; consider only uppercase characters ; get current character position ; mark last node as leaf ; push word into vector associated with leaf node ; Function to print all children of Trie node root ; if current node is leaf ; recurse for all children of root node ; search for pattern in Trie and print all words matching that pattern ; Invalid pattern ; print all words matching that pattern ; Main function to print all words in the CamelCase dictionary that matches with a given pattern ; construct Trie root node ; Construct Trie from given dict ; search for pattern in Trie ; Driver function ; dictionary of words where each word follows CamelCase notation ; pattern consisting of uppercase characters only | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ALPHABET_SIZE 26 NEW_LINE struct TrieNode { TrieNode * children [ ALPHABET_SIZE ] ; bool isLeaf ; list < string > word ; } ; TrieNode * getNewTrieNode ( void ) { TrieNode * pNode = new TrieNode ; if ( pNode ) { pNode -> isLeaf = false ; for ( int i = 0 ; i < ALPHABET_SIZE ; i ++ ) pNode -> children [ i ] = NULL ; } return pNode ; } void insert ( TrieNode * root , string word ) { int index ; TrieNode * pCrawl = root ; for ( int level = 0 ; level < word . length ( ) ; level ++ ) { if ( islower ( word [ level ] ) ) continue ; index = int ( word [ level ] ) - ' A ' ; if ( ! pCrawl -> children [ index ] ) pCrawl -> children [ index ] = getNewTrieNode ( ) ; pCrawl = pCrawl -> children [ index ] ; } pCrawl -> isLeaf = true ; ( pCrawl -> word ) . push_back ( word ) ; } void printAllWords ( TrieNode * root ) { if ( root -> isLeaf ) { for ( string str : root -> word ) cout << str << endl ; } for ( int i = 0 ; i < ALPHABET_SIZE ; i ++ ) { TrieNode * child = root -> children [ i ] ; if ( child ) printAllWords ( child ) ; } } bool search ( TrieNode * root , string pattern ) { int index ; TrieNode * pCrawl = root ; for ( int level = 0 ; level < pattern . length ( ) ; level ++ ) { index = int ( pattern [ level ] ) - ' A ' ; if ( ! pCrawl -> children [ index ] ) return false ; pCrawl = pCrawl -> children [ index ] ; } printAllWords ( pCrawl ) ; return true ; } void findAllWords ( vector < string > dict , string pattern ) { TrieNode * root = getNewTrieNode ( ) ; for ( string word : dict ) insert ( root , word ) ; if ( ! search ( root , pattern ) ) cout << " No β match β found " ; } int main ( ) { vector < string > dict = { " Hi " , " Hello " , " HelloWorld " , " HiTech " , " HiGeek " , " HiTechWorld " , " HiTechCity " , " HiTechLab " } ; string pattern = " HT " ; findAllWords ( dict , pattern ) ; return 0 ; } |
Generate all binary strings from given pattern | Recursive C ++ program to generate all binary strings formed by replacing each wildcard character by 0 or 1 ; Recursive function to generate all binary strings formed by replacing each wildcard character by 0 or 1 ; replace ' ? ' by '0' and recurse ; replace ' ? ' by '1' and recurse ; No need to backtrack as string is passed by value to the function ; Driver code to test above function | #include <iostream> NEW_LINE using namespace std ; void print ( string str , int index ) { if ( index == str . size ( ) ) { cout << str << endl ; return ; } if ( str [ index ] == ' ? ' ) { str [ index ] = '0' ; print ( str , index + 1 ) ; str [ index ] = '1' ; print ( str , index + 1 ) ; } else print ( str , index + 1 ) ; } int main ( ) { string str = "1 ? ? 0?101" ; print ( str , 0 ) ; return 0 ; } |
Rearrange array by interchanging positions of even and odd elements in the given array | C ++ program for the above approach ; Function to replace each even element by odd and vice - versa in a given array ; Traverse array ; If current element is even then swap it with odd ; Perform Swap ; Change the sign ; If current element is odd then swap it with even ; Perform Swap ; Change the sign ; Marked element positive ; Print final array ; Driver Code ; Given array arr [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void replace ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( arr [ i ] >= 0 && arr [ j ] >= 0 && arr [ i ] % 2 == 0 && arr [ j ] % 2 != 0 ) { int tmp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = tmp ; arr [ j ] = - arr [ j ] ; break ; } else if ( arr [ i ] >= 0 && arr [ j ] >= 0 && arr [ i ] % 2 != 0 && arr [ j ] % 2 == 0 ) { int tmp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = tmp ; arr [ j ] = - arr [ j ] ; break ; } } } for ( int i = 0 ; i < n ; i ++ ) arr [ i ] = abs ( arr [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; } int main ( ) { int arr [ ] = { 1 , 3 , 2 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; replace ( arr , n ) ; } |
Find the most frequent digit without using array / string | Finds maximum occurring digit without using any array / string ; Simple function to count occurrences of digit d in x ; int count = 0 ; Initialize count of digit d ; Increment count if current digit is same as d ; Returns the max occurring digit in x ; Handle negative number ; Traverse through all digits ; Count occurrences of current digit ; Update max_count and result if needed ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countOccurrences ( long int x , int d ) { while ( x ) { if ( x % 10 == d ) count ++ ; x = x / 10 ; } return count ; } int maxOccurring ( long int x ) { if ( x < 0 ) x = - x ; for ( int d = 0 ; d <= 9 ; d ++ ) { int count = countOccurrences ( x , d ) ; if ( count >= max_count ) { max_count = count ; result = d ; } } return result ; } int main ( ) { long int x = 1223355 ; cout << " Max β occurring β digit β is β " << maxOccurring ( x ) ; return 0 ; } |
Remove recurring digits in a given number | C ++ program to remove recurring digits from a given number ; Removes recurring digits in num [ ] ; Traverse digits of given number one by one ; Copy the first occurrence of new digit ; Remove repeating occurrences of digit ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void removeRecurringDigits ( char num [ ] ) { int len = strlen ( num ) ; for ( int i = 0 ; i < len ; i ++ ) { num [ j ++ ] = num [ i ] ; while ( i + 1 < len && num [ i ] == num [ i + 1 ] ) i ++ ; } int main ( ) { char num [ ] = "1299888833" ; removeRecurringDigits ( num ) ; cout << " Modified β number β is β " << num ; return 0 ; } |
Find the maximum subarray XOR in a given array | A simple C ++ program to find max subarray XOR ; Initialize result ; Pick starting points of subarrays ; Pick ending points of subarrays starting with i ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSubarrayXOR ( int arr [ ] , int n ) { int ans = INT_MIN ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { curr_xor = curr_xor ^ arr [ j ] ; ans = max ( ans , curr_xor ) ; } } return ans ; } int main ( ) { int arr [ ] = { 8 , 1 , 2 , 12 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Max β subarray β XOR β is β " << maxSubarrayXOR ( arr , n ) ; return 0 ; } |
Recursive Implementation of atoi ( ) | Recursive C program to compute atoi ( ) ; Recursive function to compute atoi ( ) ; Base case ( Only one digit ) ; If more than 1 digits , recur for ( n - 1 ) , multiplu result with 10 and add last digit ; Driver Program | #include <stdio.h> NEW_LINE #include <string.h> NEW_LINE int myAtoiRecursive ( char * str , int n ) { if ( n == 1 ) return * str - '0' ; return ( 10 * myAtoiRecursive ( str , n - 1 ) + str [ n - 1 ] - '0' ) ; } int main ( void ) { char str [ ] = "112" ; int n = strlen ( str ) ; printf ( " % d " , myAtoiRecursive ( str , n ) ) ; return 0 ; } |
Print string of odd length in ' X ' format | C ++ program to print the given pattern ; Function to print the given string in respective pattern ; Print characters at corresponding places satisfying the two conditions ; Print blank space at rest of places ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printPattern ( string str , int len ) { for ( int i = 0 ; i < len ; i ++ ) { for ( int j = 0 ; j < len ; j ++ ) { if ( ( i == j ) || ( i + j == len - 1 ) ) cout << str [ j ] ; else cout << " β " ; } cout << endl ; } } int main ( ) { string str = " geeksforgeeks " ; int len = str . size ( ) ; printPattern ( str , len ) ; return 0 ; } |
Find the longest substring with k unique characters in a given string | C ++ program to find the longest substring with k unique characters in a given string ; This function calculates number of unique characters using a associative array count [ ] . Returns true if no . of characters are less than required else returns false . ; Return true if k is greater than or equal to val ; Finds the maximum substring with exactly k unique chars ; Associative array to store the count of characters ; Traverse the string , Fills the associative array count [ ] and count number of unique characters ; If there are not enough unique characters , show an error message . ; Otherwise take a window with first element in it . start and end variables . ; Also initialize values for result longest window ; Initialize associative array count [ ] with zero ; put the first character ; Start from the second character and add characters in window according to above explanation ; Add the character ' s [ i ] ' to current window ; If there are more than k unique characters in current window , remove from left side ; Update the max window size if required ; Driver function | #include <iostream> NEW_LINE #include <cstring> NEW_LINE #define MAX_CHARS 26 NEW_LINE using namespace std ; bool isValid ( int count [ ] , int k ) { int val = 0 ; for ( int i = 0 ; i < MAX_CHARS ; i ++ ) if ( count [ i ] > 0 ) val ++ ; return ( k >= val ) ; } void kUniques ( string s , int k ) { int count [ MAX_CHARS ] ; memset ( count , 0 , sizeof ( count ) ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( count [ s [ i ] - ' a ' ] == 0 ) u ++ ; count [ s [ i ] - ' a ' ] ++ ; } if ( u < k ) { cout << " Not β enough β unique β characters " ; return ; } int curr_start = 0 , curr_end = 0 ; int max_window_size = 1 , max_window_start = 0 ; memset ( count , 0 , sizeof ( count ) ) ; count [ s [ 0 ] - ' a ' ] ++ ; for ( int i = 1 ; i < n ; i ++ ) { count [ s [ i ] - ' a ' ] ++ ; curr_end ++ ; while ( ! isValid ( count , k ) ) { count [ s [ curr_start ] - ' a ' ] -- ; curr_start ++ ; } if ( curr_end - curr_start + 1 > max_window_size ) { max_window_size = curr_end - curr_start + 1 ; max_window_start = curr_start ; } } cout << " Max β substring β is β : β " << s . substr ( max_window_start , max_window_size ) << " β with β length β " << max_window_size << endl ; } int main ( ) { string s = " aabacbebebe " ; int k = 3 ; kUniques ( s , k ) ; return 0 ; } |
Function to find Number of customers who could not get a computer | C ++ program to find number of customers who couldn 't get a resource. ; n is number of computers in cafe . ' seq ' is given sequence of customer entry , exit events ; seen [ i ] = 0 , indicates that customer ' i ' is not in cafe seen [ 1 ] = 1 , indicates that customer ' i ' is in cafe but computer is not assigned yet . seen [ 2 ] = 2 , indicates that customer ' i ' is in cafe and has occupied a computer . ; Initialize result which is number of customers who could not get any computer . ; Traverse the input sequence ; Find index of current character in seen [ 0. . .25 ] ; If First occurrence of ' seq [ i ] ' ; set the current character as seen ; If number of occupied computers is less than n , then assign a computer to new customer ; Set the current character as occupying a computer ; Else this customer cannot get a computer , increment result ; If this is second occurrence of ' seq [ i ] ' ; Decrement occupied only if this customer was using a computer ; Driver program | #include <iostream> NEW_LINE #include <cstring> NEW_LINE using namespace std ; #define MAX_CHAR 26 NEW_LINE int runCustomerSimulation ( int n , const char * seq ) { char seen [ MAX_CHAR ] = { 0 } ; int res = 0 ; for ( int i = 0 ; seq [ i ] ; i ++ ) { int ind = seq [ i ] - ' A ' ; if ( seen [ ind ] == 0 ) { seen [ ind ] = 1 ; if ( occupied < n ) { occupied ++ ; seen [ ind ] = 2 ; } else res ++ ; } else { if ( seen [ ind ] == 2 ) occupied -- ; seen [ ind ] = 0 ; } } return res ; } int main ( ) { cout << runCustomerSimulation ( 2 , " ABBAJJKZKZ " ) << endl ; cout << runCustomerSimulation ( 3 , " GACCBDDBAGEE " ) << endl ; cout << runCustomerSimulation ( 3 , " GACCBGDDBAEE " ) << endl ; cout << runCustomerSimulation ( 1 , " ABCBCA " ) << endl ; cout << runCustomerSimulation ( 1 , " ABCBCADEED " ) << endl ; return 0 ; } |
Check if characters of a given string can be rearranged to form a palindrome | C ++ Implementation of the above approach ; bitvector to store the record of which character appear odd and even number of times ; Driver Code | # include <bits/stdc++.h> NEW_LINE using namespace std ; bool canFormPalindrome ( string a ) { int bitvector = 0 , mask = 0 ; for ( int i = 0 ; a [ i ] != ' \0' ; i ++ ) { int x = a [ i ] - ' a ' ; mask = 1 << x ; bitvector = bitvector ^ mask ; } return ( bitvector & ( bitvector - 1 ) ) == 0 ; } int main ( ) { if ( canFormPalindrome ( " geeksforgeeks " ) ) cout << ( " Yes " ) << endl ; else cout << ( " No " ) << endl ; return 0 ; } |
Print all pairs of anagrams in a given array of strings | C ++ program to Print all pairs of anagrams in a given array of strings ; function to check whether two strings are anagram of each other ; Create two count arrays and initialize all values as 0 ; For each character in input strings , increment count in the corresponding count array ; If both strings are of different length . Removing this condition will make the program fail for strings like " aaca " and " aca " ; See if there is any non - zero value in count array ; This function prints all anagram pairs in a given array of strings ; Driver program to test to pront printDups | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define NO_OF_CHARS 256 NEW_LINE bool areAnagram ( string str1 , string str2 ) { int count [ NO_OF_CHARS ] = { 0 } ; int i ; for ( i = 0 ; str1 [ i ] && str2 [ i ] ; i ++ ) { count [ str1 [ i ] ] ++ ; count [ str2 [ i ] ] -- ; } if ( str1 [ i ] str2 [ i ] ) return false ; for ( i = 0 ; i < NO_OF_CHARS ; i ++ ) if ( count [ i ] ) return false ; return true ; } void findAllAnagrams ( string arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( areAnagram ( arr [ i ] , arr [ j ] ) ) cout << arr [ i ] << " β is β anagram β of β " << arr [ j ] << endl ; } int main ( ) { string arr [ ] = { " geeksquiz " , " geeksforgeeks " , " abcd " , " forgeeksgeeks " , " zuiqkeegs " } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findAllAnagrams ( arr , n ) ; return 0 ; } |
Program to print all palindromes in a given range | A function to check if n is palindrome ; Find reverse of n ; If n and rev are same , then n is palindrome ; prints palindrome between min and max ; Driver program to test above function | #include <iostream> NEW_LINE using namespace std ; int isPalindrome ( int n ) { int rev = 0 ; for ( int i = n ; i > 0 ; i /= 10 ) rev = rev * 10 + i % 10 ; return ( n == rev ) ; } void countPal ( int min , int max ) { for ( int i = min ; i <= max ; i ++ ) if ( isPalindrome ( i ) ) cout << i << " β " ; } int main ( ) { countPal ( 100 , 2000 ) ; return 0 ; } |
Length of the longest substring without repeating characters | C ++ program to find the length of the longest substring without repeating characters ; result ; Note : Default values in visited are false ; If current character is visited Break the loop ; Else update the result if this window is larger , and mark current character as visited . ; Remove the first character of previous window ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int longestUniqueSubsttr ( string str ) { int n = str . size ( ) ; int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { vector < bool > visited ( 256 ) ; for ( int j = i ; j < n ; j ++ ) { if ( visited [ str [ j ] ] == true ) break ; else { res = max ( res , j - i + 1 ) ; visited [ str [ j ] ] = true ; } } visited [ str [ i ] ] = false ; } return res ; } int main ( ) { string str = " geeksforgeeks " ; cout << " The β input β string β is β " << str << endl ; int len = longestUniqueSubsttr ( str ) ; cout << " The β length β of β the β longest β non - repeating β " " character β substring β is β " << len ; return 0 ; } |
Length of the longest substring without repeating characters | Creating a set to store the last positions of occurrence ; Starting the initial point of window to index 0 ; Checking if we have already seen the element or not ; If we have seen the number , move the start pointer to position after the last occurrence ; Updating the last seen value of the character ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int longestUniqueSubsttr ( string s ) { map < char , int > seen ; int maximum_length = 0 ; int start = 0 ; for ( int end = 0 ; end < s . length ( ) ; end ++ ) { if ( seen . find ( s [ end ] ) != seen . end ( ) ) { start = max ( start , seen [ s [ end ] ] + 1 ) ; } seen [ s [ end ] ] = end ; maximum_length = max ( maximum_length , end - start + 1 ) ; } return maximum_length ; } int main ( ) { string s = " geeksforgeeks " ; cout << " The β input β String β is β " << s << endl ; int length = longestUniqueSubsttr ( s ) ; cout << " The β length β of β the β longest β non - repeating β character β " << " substring β is β " << length ; } |
Find the smallest window in a string containing all characters of another string | Function ; Answer length of ans ; starting index of ans ; creating map ; References of Window ; Traversing the window ; Calculations ; Condition matching ; Sorting ans ; Sliding I Calculation for removing I ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string Minimum_Window ( string s , string t ) { int m [ 256 ] = { 0 } ; int ans = INT_MAX ; int start = 0 ; int count = 0 ; for ( int i = 0 ; i < t . length ( ) ; i ++ ) { if ( m [ t [ i ] ] == 0 ) count ++ ; m [ t [ i ] ] ++ ; } int i = 0 ; int j = 0 ; while ( j < s . length ( ) ) { m [ s [ j ] ] -- ; if ( m [ s [ j ] ] == 0 ) count -- ; if ( count == 0 ) { while ( count == 0 ) { if ( ans > j - i + 1 ) { ans = min ( ans , j - i + 1 ) ; start = i ; } m [ s [ i ] ] ++ ; if ( m [ s [ i ] ] > 0 ) count ++ ; i ++ ; } } j ++ ; } if ( ans != INT_MAX ) return s . substr ( start , ans ) ; else return " - 1" ; } main ( ) { string s = " ADOBECODEBANC " ; string t = " ABC " ; cout << " - - > Smallest β window β that β contain β all β character β : β " << endl ; cout << Minimum_Window ( s , t ) ; } |
Run Length Encoding | CPP program to implement run length encoding ; Count occurrences of current character ; Print character and its count ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printRLE ( string str ) { int n = str . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int count = 1 ; while ( i < n - 1 && str [ i ] == str [ i + 1 ] ) { count ++ ; i ++ ; } cout << str [ i ] << count ; } } int main ( ) { string str = " wwwwaaadexxxxxxywww " ; printRLE ( str ) ; return 0 ; } |
Print list items containing all characters of a given word | C ++ program to print all strings that contain all characters of a word ; prints list items having all characters of word ; Since calloc is used , map [ ] is initialized as 0 ; Set the values in map ; Get the length of given word ; Check each item of list if has all characters of word ; unset the bit so that strings like sss not printed ; Set the values in map for next item ; Driver code | #include <bits/stdc++.h> NEW_LINE #include <stdio.h> NEW_LINE #include <string.h> NEW_LINE using namespace std ; # define NO_OF_CHARS 256 NEW_LINE void print ( char list [ ] [ 50 ] , char * word , int list_size ) { int * map = new int [ ( sizeof ( int ) * NO_OF_CHARS ) ] ; int i , j , count , word_size ; for ( i = 0 ; * ( word + i ) ; i ++ ) map [ * ( word + i ) ] = 1 ; word_size = strlen ( word ) ; for ( i = 0 ; i < list_size ; i ++ ) { for ( j = 0 , count = 0 ; * ( list [ i ] + j ) ; j ++ ) { if ( map [ * ( list [ i ] + j ) ] ) { count ++ ; map [ * ( list [ i ] + j ) ] = 0 ; } } if ( count == word_size ) cout << list [ i ] << endl ; for ( j = 0 ; * ( word + j ) ; j ++ ) map [ * ( word + j ) ] = 1 ; } } int main ( ) { char str [ ] = " sun " ; char list [ ] [ 50 ] = { " geeksforgeeks " , " unsorted " , " sunday " , " just " , " sss " } ; print ( list , str , 5 ) ; return 0 ; } |
Given a string , find its first non | C ++ program to find first non - repeating character ; Returns an array of size 256 containing count of characters in the passed char array ; The function returns index of first non - repeating character in a string . If all characters are repeating then returns - 1 ; To avoid memory leak ; Driver program to test above function | #include <iostream> NEW_LINE using namespace std ; #define NO_OF_CHARS 256 NEW_LINE int * getCharCountArray ( char * str ) { int * count = ( int * ) calloc ( sizeof ( int ) , NO_OF_CHARS ) ; int i ; for ( i = 0 ; * ( str + i ) ; i ++ ) count [ * ( str + i ) ] ++ ; return count ; } int firstNonRepeating ( char * str ) { int * count = getCharCountArray ( str ) ; int index = -1 , i ; for ( i = 0 ; * ( str + i ) ; i ++ ) { if ( count [ * ( str + i ) ] == 1 ) { index = i ; break ; } } free ( count ) ; return index ; } int main ( ) { char str [ ] = " geeksforgeeks " ; int index = firstNonRepeating ( str ) ; if ( index == -1 ) cout << " Either β all β characters β are β repeating β or β " " string β is β empty " ; else cout << " First β non - repeating β character β is β " << str [ index ] ; getchar ( ) ; return 0 ; } |
Divide a string in N equal parts | C ++ program to divide a string in n equal parts ; Function to print n equal parts of str ; Check if string can be divided in n equal parts ; Calculate the size of parts to find the division points ; Driver code ; length od string is 28 ; Print 4 equal parts of the string | #include <iostream> NEW_LINE #include <string.h> NEW_LINE using namespace std ; class gfg { public : void divideString ( char str [ ] , int n ) { int str_size = strlen ( str ) ; int i ; int part_size ; if ( str_size % n != 0 ) { cout << " Invalid β Input : β String β size " ; cout << " β is β not β divisible β by β n " ; return ; } part_size = str_size / n ; for ( i = 0 ; i < str_size ; i ++ ) { if ( i % part_size == 0 ) cout << endl ; cout << str [ i ] ; } } } ; int main ( ) { gfg g ; char str [ ] = " a _ simple _ divide _ string _ quest " ; g . divideString ( str , 4 ) ; return 0 ; } |
Boggle ( Find all possible words in a board of characters ) | Set 1 | C ++ program for Boggle game ; Let the given dictionary be following ; A given function to check if a given string is present in dictionary . The implementation is naive for simplicity . As per the question dictionary is given to us . ; Linearly search all words ; A recursive function to print all words present on boggle ; Mark current cell as visited and append current character to str ; If str is present in dictionary , then print it ; Traverse 8 adjacent cells of boggle [ i ] [ j ] ; Erase current character from string and mark visited of current cell as false ; Prints all words present in dictionary . ; Mark all characters as not visited ; Initialize current string ; Consider every character and look for all words starting with this character ; Driver program to test above function | #include <cstring> NEW_LINE #include <iostream> NEW_LINE using namespace std ; #define M 3 NEW_LINE #define N 3 NEW_LINE string dictionary [ ] = { " GEEKS " , " FOR " , " QUIZ " , " GO " } ; int n = sizeof ( dictionary ) / sizeof ( dictionary [ 0 ] ) ; bool isWord ( string & str ) { for ( int i = 0 ; i < n ; i ++ ) if ( str . compare ( dictionary [ i ] ) == 0 ) return true ; return false ; } void findWordsUtil ( char boggle [ M ] [ N ] , bool visited [ M ] [ N ] , int i , int j , string & str ) { visited [ i ] [ j ] = true ; str = str + boggle [ i ] [ j ] ; if ( isWord ( str ) ) cout << str << endl ; for ( int row = i - 1 ; row <= i + 1 && row < M ; row ++ ) for ( int col = j - 1 ; col <= j + 1 && col < N ; col ++ ) if ( row >= 0 && col >= 0 && ! visited [ row ] [ col ] ) findWordsUtil ( boggle , visited , row , col , str ) ; str . erase ( str . length ( ) - 1 ) ; visited [ i ] [ j ] = false ; } void findWords ( char boggle [ M ] [ N ] ) { bool visited [ M ] [ N ] = { { false } } ; string str = " " ; for ( int i = 0 ; i < M ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) findWordsUtil ( boggle , visited , i , j , str ) ; } int main ( ) { char boggle [ M ] [ N ] = { { ' G ' , ' I ' , ' Z ' } , { ' U ' , ' E ' , ' K ' } , { ' Q ' , ' S ' , ' E ' } } ; cout << " Following β words β of β dictionary β are β present STRNEWLINE " ; findWords ( boggle ) ; return 0 ; } |
Print all paths from a source point to all the 4 corners of a Matrix | C ++ program for the above approach ; Function to check if we reached on of the entry / exit ( corner ) point . ; Function to check if the index is within the matrix boundary . ; Recursive helper function ; If any corner is reached push the string t into ans and return ; For all the four directions ; The new ith index ; The new jth index ; The direction R / L / U / D ; If the new cell is within the matrix boundary and it is not previously visited in same path ; Mark the new cell as visited ; Store the direction ; Recur ; Backtrack to explore other paths ; Function to find all possible paths ; Create a direction array for all the four directions ; Stores the result ; Driver Code ; Initializing the variables ; Function Call ; Print the result | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct direction { int x , y ; char c ; } ; bool isCorner ( int i , int j , int M , int N ) { if ( ( i == 0 && j == 0 ) || ( i == 0 && j == N - 1 ) || ( i == M - 1 && j == N - 1 ) || ( i == M - 1 && j == 0 ) ) return true ; return false ; } bool isValid ( int i , int j , int M , int N ) { if ( i < 0 i > = M j < 0 j > = N ) return false ; return true ; } void solve ( int i , int j , int M , int N , direction dir [ ] , vector < vector < int > > & maze , string & t , vector < string > & ans ) { if ( isCorner ( i , j , M , N ) ) { ans . push_back ( t ) ; return ; } for ( int k = 0 ; k < 4 ; k ++ ) { int x = i + dir [ k ] . x ; int y = j + dir [ k ] . y ; char c = dir [ k ] . c ; if ( isValid ( x , y , M , N ) && maze [ x ] [ y ] == 1 ) { maze [ x ] [ y ] = 0 ; t . push_back ( c ) ; solve ( x , y , M , N , dir , maze , t , ans ) ; t . pop_back ( ) ; maze [ x ] [ y ] = 1 ; } } return ; } vector < string > possiblePaths ( vector < int > src , vector < vector < int > > & maze ) { direction dir [ 4 ] = { { -1 , 0 , ' U ' } , { 0 , 1 , ' R ' } , { 1 , 0 , ' D ' } , { 0 , -1 , ' L ' } } ; string temp ; vector < string > ans ; solve ( src [ 0 ] , src [ 1 ] , maze . size ( ) , maze [ 0 ] . size ( ) , dir , maze , temp , ans ) ; return ans ; } int main ( ) { vector < vector < int > > maze = { { 1 , 0 , 0 , 1 , 0 , 0 , 1 , 1 } , { 1 , 1 , 1 , 0 , 0 , 0 , 1 , 0 } , { 1 , 0 , 1 , 1 , 1 , 1 , 1 , 0 } , { 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 } , { 1 , 0 , 1 , 0 , 1 , 0 , 0 , 1 } , { 0 , 1 , 1 , 1 , 1 , 0 , 0 , 1 } , { 0 , 1 , 0 , 0 , 1 , 1 , 1 , 1 } , { 1 , 1 , 0 , 0 , 0 , 0 , 0 , 1 } , } ; vector < int > src = { 4 , 2 } ; vector < string > paths = possiblePaths ( src , maze ) ; if ( paths . size ( ) == 0 ) { cout << " No β Possible β Paths " ; return 0 ; } for ( int i = 0 ; i < paths . size ( ) ; i ++ ) cout << paths [ i ] << endl ; return 0 ; } |
Solve Sudoku on the basis of the given irregular regions | C ++ program for the above approach ; Grid dimension ; Function to check if the number to be present in the current cell is safe or not ; Check if the number is present in i - th row or j - th column or not ; Check if the number to be filled is safe in current region or not ; Initialize the queue for the BFS ; Insert the current cell into queue ; Check if the neighbours cell is visited or not ; Initialize visited to 0 ; Mark current cell is visited ; Performing the BFS technique Checking for 4 neighbours at a time ; Stores front element of the queue ; Pop top element of the queue ; Check for neighbours cell ; If already contains the same number ; Mark as neighbour cell as visited ; Checking for 2 nd neighbours ; If neighbours contains the same number ; Insert neighbour cell into queue ; Mark neighbour cell as visited ; Checking for 3 rd neighbours ; If neighbours contains the same number ; Insert neighbour cell into queue ; Mark neighbour cell as visited ; Checking for 4 th neighbours ; If neighbours contains the same number ; Insert neighbour cell into queue ; Mark neighbour cell as visited ; Recursive function to solve the sudoku ; If the given sudoku already solved ; Print the solution of sudoku ; If the numbers in the current row already filled ; If current cell is not empty ; Iterate over all possible value of numbers ; If placing the current number is safe in the current cell ; Update sudoku [ i ] [ j ] ; Fill the ramining cells of the sudoku ; If remaining cells has been filled ; Otherwise No Solution ; Driver Code ; Given sudoku array ; Given region array ; Function call ; No answer exist | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 2 ; bool issafe ( int sudoku [ N ] [ N ] , int i , int j , int n , int number , char region [ N ] [ N ] ) { for ( int x = 0 ; x < n ; x ++ ) { if ( sudoku [ x ] [ j ] == number sudoku [ i ] [ x ] == number ) { return false ; } } char r = region [ i ] [ j ] ; queue < pair < int , int > > q ; q . push ( make_pair ( i , j ) ) ; int visited [ N ] [ N ] ; memset ( visited , 0 , sizeof visited ) ; visited [ i ] [ j ] = 1 ; while ( ! q . empty ( ) ) { pair < int , int > front = q . front ( ) ; q . pop ( ) ; if ( front . first + 1 < N && region [ front . first + 1 ] [ front . second ] == r && ! visited [ front . first + 1 ] [ front . second ] ) { if ( sudoku [ front . first + 1 ] [ front . second ] == number ) { return false ; } q . push ( make_pair ( front . first + 1 , front . second ) ) ; visited [ front . first + 1 ] [ front . second ] = 1 ; } if ( front . first - 1 >= 0 && region [ front . first - 1 ] [ front . second ] == r && ! visited [ front . first - 1 ] [ front . second ] ) { if ( sudoku [ front . first - 1 ] [ front . second ] == number ) { return false ; } q . push ( make_pair ( front . first - 1 , front . second ) ) ; visited [ front . first - 1 ] [ front . second ] = 1 ; } if ( front . second + 1 < N && region [ front . first ] [ front . second + 1 ] == r && ! visited [ front . first ] [ front . second + 1 ] ) { if ( sudoku [ front . first ] [ front . second + 1 ] == number ) { return false ; } q . push ( make_pair ( front . first , front . second + 1 ) ) ; visited [ front . first ] [ front . second + 1 ] = 1 ; } if ( front . second - 1 >= 0 && region [ front . first ] [ front . second - 1 ] == r && ! visited [ front . first ] [ front . second - 1 ] ) { if ( sudoku [ front . first ] [ front . second - 1 ] == number ) { return false ; } q . push ( make_pair ( front . first , front . second - 1 ) ) ; visited [ front . first ] [ front . second - 1 ] = 1 ; } } return true ; } bool solveSudoku ( int sudoku [ N ] [ N ] , int i , int j , int n , char region [ N ] [ N ] ) { if ( i == n ) { for ( int a = 0 ; a < n ; a ++ ) { for ( int b = 0 ; b < n ; b ++ ) { cout << sudoku [ a ] [ b ] << " β " ; } cout << endl ; } return true ; } if ( j == n ) { return solveSudoku ( sudoku , i + 1 , 0 , n , region ) ; } if ( sudoku [ i ] [ j ] != 0 ) { return solveSudoku ( sudoku , i , j + 1 , n , region ) ; } else { for ( int number = 1 ; number <= n ; number ++ ) { if ( issafe ( sudoku , i , j , n , number , region ) ) { sudoku [ i ] [ j ] = number ; bool rest = solveSudoku ( sudoku , i , j + 1 , n , region ) ; if ( rest == true ) { return true ; } } } sudoku [ i ] [ j ] = 0 ; return false ; } } int main ( ) { int sudoku [ N ] [ N ] = { { 0 , 1 } , { 0 , 0 } } ; char region [ N ] [ N ] = { { ' r ' , ' r ' } , { ' b ' , ' b ' } } ; int ans = solveSudoku ( sudoku , 0 , 0 , N , region ) ; if ( ans == 0 ) { cout << " - 1" ; } return 0 ; } |
Remove all subtrees consisting only of even valued nodes from a Binary Tree | C ++ program for the above approach ; Node of the tree ; Function to create a new node ; Function to print tree level wise ; Base Case ; Create an empty queue for level order traversal ; Enqueue Root ; Print front of queue and remove it from queue ; If left child is present ; Otherwise ; If right child is present ; Otherwise ; Function to remove subtrees ; Base Case ; Search for required condition in left and right half ; If the node is even and leaf node ; Driver Code ; Function Call ; Print answer | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int data ; struct node * left , * right ; } ; node * newNode ( int key ) { node * temp = new node ; temp -> data = key ; temp -> left = temp -> right = NULL ; return ( temp ) ; } void printLevelOrder ( node * root ) { if ( ! root ) return ; queue < node * > q ; q . push ( root ) ; while ( ! q . empty ( ) ) { node * temp = q . front ( ) ; cout << temp -> data << " β " ; q . pop ( ) ; if ( temp -> left != NULL ) { q . push ( temp -> left ) ; } else if ( temp -> right != NULL ) { cout << " NULL β " ; } if ( temp -> right != NULL ) { q . push ( temp -> right ) ; } else if ( temp -> left != NULL ) { cout << " NULL β " ; } } } node * pruneTree ( node * root ) { if ( ! root ) { return NULL ; } root -> left = pruneTree ( root -> left ) ; root -> right = pruneTree ( root -> right ) ; if ( root -> data % 2 == 0 && ! root -> right && ! root -> left ) return NULL ; return root ; } int main ( ) { struct node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> left -> left = newNode ( 8 ) ; root -> left -> right = newNode ( 10 ) ; root -> right = newNode ( 7 ) ; root -> right -> left = newNode ( 12 ) ; root -> right -> right = newNode ( 5 ) ; node * newRoot = pruneTree ( root ) ; printLevelOrder ( newRoot ) ; return 0 ; } |
Count total ways to reach destination from source in an undirected Graph | C ++ program to count total number of ways to reach destination in a graph ; Utility Function to count total ways ; Base condition When reach to the destination ; Make vertex visited ; Recursive function , for count ways ; Backtracking Make vertex unvisited ; Return total ways ; Function to count total ways to reach destination ; Loop to make all vertex unvisited , Initially ; Make source visited ; Print total ways | #include <iostream> NEW_LINE using namespace std ; int countWays ( int mtrx [ ] [ 11 ] , int vrtx , int i , int dest , bool visited [ ] ) { if ( i == dest ) { return 1 ; } int total = 0 ; for ( int j = 0 ; j < vrtx ; j ++ ) { if ( mtrx [ i ] [ j ] == 1 && ! visited [ j ] ) { visited [ j ] = true ; total += countWays ( mtrx , vrtx , j , dest , visited ) ; visited [ j ] = false ; } } return total ; } int totalWays ( int mtrx [ ] [ 11 ] , int vrtx , int src , int dest ) { bool visited [ vrtx ] ; for ( int i = 0 ; i < vrtx ; i ++ ) { visited [ i ] = false ; } visited [ src ] = true ; return countWays ( mtrx , vrtx , src , dest , visited ) ; } int main ( ) { int vrtx = 11 ; int mtrx [ 11 ] [ 11 ] = { { 0 , 1 , 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 } , { 1 , 0 , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 1 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 1 , 0 } , { 0 , 0 , 0 , 0 , 1 , 0 , 1 , 0 , 0 , 1 , 0 } , { 1 , 0 , 0 , 0 , 0 , 1 , 0 , 1 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 , 1 , 0 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 , 1 , 0 } , { 0 , 0 , 0 , 0 , 1 , 1 , 0 , 0 , 1 , 0 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 } } ; int src = 3 ; int dest = 9 ; cout << totalWays ( mtrx , vrtx , src - 1 , dest - 1 ) ; return 0 ; } |
Print path from given Source to Destination in 2 | C ++ program for printing a path from given source to destination ; Function to print the path ; Base condition ; Pop stores elements ; Recursive call for printing stack In reverse order ; Function to store the path into The stack , if path exist ; Base condition ; Push current elements ; Condition to check whether reach to the Destination or not ; Increment ' x ' ordinate of source by ( 2 * x + y ) Keeping ' y ' constant ; Increment ' y ' ordinate of source by ( 2 * y + x ) Keeping ' x ' constant ; Pop current elements form stack ; If no path exists ; Utility function to check whether path exist or not ; To store x co - ordinate ; To store y co - ordinate ; Function to find the path ; Print - 1 , if path doesn 't exist ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printExistPath ( stack < int > sx , stack < int > sy , int last ) { if ( sx . empty ( ) || sy . empty ( ) ) { return ; } int x = sx . top ( ) ; int y = sy . top ( ) ; sx . pop ( ) ; sy . pop ( ) ; printExistPath ( sx , sy , last ) ; if ( sx . size ( ) == last - 1 ) { cout << " ( " << x << " , β " << y << " ) " ; } else { cout << " ( " << x << " , β " << y << " ) β - > β " ; } } bool storePath ( int srcX , int srcY , int destX , int destY , stack < int > & sx , stack < int > & sy ) { if ( srcX > destX srcY > destY ) { return false ; } sx . push ( srcX ) ; sy . push ( srcY ) ; if ( srcX == destX && srcY == destY ) { printExistPath ( sx , sy , sx . size ( ) ) ; return true ; } if ( storePath ( ( 2 * srcX ) + srcY , srcY , destX , destY , sx , sy ) ) { return true ; } if ( storePath ( srcX , ( 2 * srcY ) + srcX , destX , destY , sx , sy ) ) { return true ; } sx . pop ( ) ; sy . pop ( ) ; return false ; } bool isPathExist ( int srcX , int srcY , int destX , int destY ) { stack < int > sx ; stack < int > sy ; return storePath ( srcX , srcY , destX , destY , sx , sy ) ; } void printPath ( int srcX , int srcY , int destX , int destY ) { if ( ! isPathExist ( srcX , srcY , destX , destY ) ) { cout << " - 1" ; } } int main ( ) { int srcX = 5 , srcY = 8 ; int destX = 83 , destY = 21 ; printPath ( srcX , srcY , destX , destY ) ; } |
Count even paths in Binary Tree | C ++ program for the above approach ; A Tree node ; Utility function to create a new node ; Utility function to count the even path in a given Binary tree ; Base Condition , when node pointer becomes null or node value is odd ; Increment count when encounter leaf node with all node value even ; Left recursive call , and save the value of count ; Right recursive call , and return value of count ; Function to count the even paths in a given Binary tree ; Function call with count = 0 ; Driver Code ; Tree ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * left , * right ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return ( temp ) ; } int evenPaths ( struct Node * node , int count ) { if ( node == NULL || ( node -> key % 2 != 0 ) ) { return count ; } if ( ! node -> left && ! node -> right ) { count ++ ; } count = evenPaths ( node -> left , count ) ; return evenPaths ( node -> right , count ) ; } int countEvenPaths ( struct Node * node ) { return evenPaths ( node , 0 ) ; } int main ( ) { Node * root = newNode ( 12 ) ; root -> left = newNode ( 13 ) ; root -> right = newNode ( 12 ) ; root -> right -> left = newNode ( 14 ) ; root -> right -> right = newNode ( 16 ) ; root -> right -> left -> left = newNode ( 21 ) ; root -> right -> left -> right = newNode ( 22 ) ; root -> right -> right -> left = newNode ( 22 ) ; root -> right -> right -> right = newNode ( 24 ) ; root -> right -> right -> right -> left = newNode ( 8 ) ; cout << countEvenPaths ( root ) ; return 0 ; } |
Sum of subsets of all the subsets of an array | O ( 3 ^ N ) | C ++ implementation of the approach ; To store the final ans ; Function to sum of all subsets of a given array ; Base case ; Recursively calling subsetSum ; 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 | #include <bits/stdc++.h> NEW_LINE using namespace std ; int ans = 0 ; vector < int > c ; subsetGen ( arr , 0 , n , ans , c ) ; cout << ans ; return 0 ; } void subsetSum ( vector < int > & c , int i , int & ans , int curr ) { if ( i == c . size ( ) ) { ans += curr ; return ; } subsetSum ( c , i + 1 , ans , curr + c [ i ] ) ; subsetSum ( c , i + 1 , ans , curr ) ; } void subsetGen ( int * arr , int i , int n , int & ans , vector < int > & c ) { if ( i == n ) { subsetSum ( c , 0 , ans , 0 ) ; return ; } subsetGen ( arr , i + 1 , n , ans , c ) ; c . push_back ( arr [ i ] ) ; subsetGen ( arr , i + 1 , n , ans , c ) ; c . pop_back ( ) ; } int main ( ) { int arr [ ] = { 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( int ) ; |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.