text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
0 | A dynamic programming based solution for 0 - 1 Knapsack problem ; A utility function that returns maximum of two integers ; Returns the maximum value that can be put in a knapsack of capacity W ; Build table K [ ] [ ] in bottom up manner ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int max ( int a , int b ) { return ( a > b ) ? a : b ; } int knapSack ( int W , int wt [ ] , int val [ ] , int n ) { int i , w ; int K [ n + 1 ] [ W + 1 ] ; for ( i = 0 ; i <= n ; i ++ ) { for ( w = 0 ; w <= W ; w ++ ) { if ( i == 0 w == 0 ) K [ i ] [ w ] = 0 ; else if ( wt [ i - 1 ] <= w ) K [ i ] [ w ] = max ( val [ i - 1 ] + K [ i - 1 ] [ w - wt [ i - 1 ] ] , K [ i - 1 ] [ w ] ) ; else K [ i ] [ w ] = K [ i - 1 ] [ w ] ; } } return K [ n ] [ W ] ; } int main ( ) { int val [ ] = { 60 , 100 , 120 } ; int wt [ ] = { 10 , 20 , 30 } ; int W = 50 ; int n = sizeof ( val ) / sizeof ( val [ 0 ] ) ; cout << knapSack ( W , wt , val , n ) ; return 0 ; } |
Egg Dropping Puzzle | DP | ; A utility function to get maximum of two integers ; Function to get minimum number of trials needed in worst case with n eggs and k floors ; If there are no floors , then no trials needed . OR if there is one floor , one trial needed . ; We need k trials for one egg and k floors ; Consider all droppings from 1 st floor to kth floor and return the minimum of these values plus 1. ; Driver program to test to pront printDups | #include <bits/stdc++.h> NEW_LINE using namespace std ; int max ( int a , int b ) { return ( a > b ) ? a : b ; } int eggDrop ( int n , int k ) { if ( k == 1 k == 0 ) return k ; if ( n == 1 ) return k ; int min = INT_MAX , x , res ; for ( x = 1 ; x <= k ; x ++ ) { res = max ( eggDrop ( n - 1 , x - 1 ) , eggDrop ( n , k - x ) ) ; if ( res < min ) min = res ; } return min + 1 ; } int main ( ) { int n = 2 , k = 10 ; cout << " Minimum β number β of β trials β " " in β worst β case β with β " << n << " β eggs β and β " << k << " β floors β is β " << eggDrop ( n , k ) << endl ; return 0 ; } |
Egg Dropping Puzzle | DP | A Dynamic Programming based for the Egg Dropping Puzzle ; A utility function to get maximum of two integers ; Function to get minimum number of trials needed in worst case with n eggs and k floors ; A 2D table where entry eggFloor [ i ] [ j ] will represent minimum number of trials needed for i eggs and j floors . ; We need one trial for one floor and 0 trials for 0 floors ; We always need j trials for one egg and j floors . ; Fill rest of the entries in table using optimal substructure property ; eggFloor [ n ] [ k ] holds the result ; Driver program to test to pront printDups | #include <limits.h> NEW_LINE #include <stdio.h> NEW_LINE int max ( int a , int b ) { return ( a > b ) ? a : b ; } int eggDrop ( int n , int k ) { int eggFloor [ n + 1 ] [ k + 1 ] ; int res ; int i , j , x ; for ( i = 1 ; i <= n ; i ++ ) { eggFloor [ i ] [ 1 ] = 1 ; eggFloor [ i ] [ 0 ] = 0 ; } for ( j = 1 ; j <= k ; j ++ ) eggFloor [ 1 ] [ j ] = j ; for ( i = 2 ; i <= n ; i ++ ) { for ( j = 2 ; j <= k ; j ++ ) { eggFloor [ i ] [ j ] = INT_MAX ; for ( x = 1 ; x <= j ; x ++ ) { res = 1 + max ( eggFloor [ i - 1 ] [ x - 1 ] , eggFloor [ i ] [ j - x ] ) ; if ( res < eggFloor [ i ] [ j ] ) eggFloor [ i ] [ j ] = res ; } } } return eggFloor [ n ] [ k ] ; } int main ( ) { int n = 2 , k = 36 ; printf ( " Minimum number of trials " STRNEWLINE TABSYMBOL TABSYMBOL " in worst case with % d eggs and " STRNEWLINE TABSYMBOL TABSYMBOL " % d floors is % d " , n , k , eggDrop ( n , k ) ) ; return 0 ; } |
Longest Palindromic Subsequence | DP | C ++ program of above approach ; A utility function to get max of two integers ; Returns the length of the longest palindromic subsequence in seq ; Base Case 1 : If there is only 1 character ; Base Case 2 : If there are only 2 characters and both are same ; If the first and last characters match ; If the first and last characters do not match ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; int max ( int x , int y ) { return ( x > y ) ? x : y ; } int lps ( char * seq , int i , int j ) { if ( i == j ) return 1 ; if ( seq [ i ] == seq [ j ] && i + 1 == j ) return 2 ; if ( seq [ i ] == seq [ j ] ) return lps ( seq , i + 1 , j - 1 ) + 2 ; return max ( lps ( seq , i , j - 1 ) , lps ( seq , i + 1 , j ) ) ; } int main ( ) { char seq [ ] = " GEEKSFORGEEKS " ; int n = strlen ( seq ) ; cout << " The β length β of β the β LPS β is β " << lps ( seq , 0 , n - 1 ) ; return 0 ; } |
Longest Palindromic Subsequence | DP | A Dynamic Programming based C ++ program for LPS problem Returns the length of the longest palindromic subsequence in seq ; A utility function to get max of two integers ; Returns the length of the longest palindromic subsequence in seq ; Create a table to store results of subproblems ; Strings of length 1 are palindrome of lentgh 1 ; Build the table . Note that the lower diagonal values of table are useless and not filled in the process . The values are filled in a manner similar to Matrix Chain Multiplication DP solution ( Seewww . geeksforgeeks . org / matrix - chain - multiplication - dp - 8 / ) . cl is length of https : substring ; Driver program to test above functions | #include <stdio.h> NEW_LINE #include <string.h> NEW_LINE int max ( int x , int y ) { return ( x > y ) ? x : y ; } int lps ( char * str ) { int n = strlen ( str ) ; int i , j , cl ; int L [ n ] [ n ] ; for ( i = 0 ; i < n ; i ++ ) L [ i ] [ i ] = 1 ; for ( cl = 2 ; cl <= n ; cl ++ ) { for ( i = 0 ; i < n - cl + 1 ; i ++ ) { j = i + cl - 1 ; if ( str [ i ] == str [ j ] && cl == 2 ) L [ i ] [ j ] = 2 ; else if ( str [ i ] == str [ j ] ) L [ i ] [ j ] = L [ i + 1 ] [ j - 1 ] + 2 ; else L [ i ] [ j ] = max ( L [ i ] [ j - 1 ] , L [ i + 1 ] [ j ] ) ; } } return L [ 0 ] [ n - 1 ] ; } int main ( ) { char seq [ ] = " GEEKS β FOR β GEEKS " ; int n = strlen ( seq ) ; printf ( " The β length β of β the β LPS β is β % d " , lps ( seq ) ) ; getchar ( ) ; return 0 ; } |
Longest Bitonic Subsequence | DP | Dynamic Programming implementation of longest bitonic subsequence problem ; lbs ( ) returns the length of the Longest Bitonic Subsequence in arr [ ] of size n . The function mainly creates two temporary arrays lis [ ] and lds [ ] and returns the maximum lis [ i ] + lds [ i ] - 1. lis [ i ] == > Longest Increasing subsequence ending with arr [ i ] lds [ i ] == > Longest decreasing subsequence starting with arr [ i ] ; Allocate memory for LIS [ ] and initialize LIS values as 1 for all indexes ; Compute LIS values from left to right ; Allocate memory for lds and initialize LDS values for all indexes ; Compute LDS values from right to left ; Return the maximum value of lis [ i ] + lds [ i ] - 1 ; Driver program to test above function | #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int lbs ( int arr [ ] , int n ) { int i , j ; int * lis = new int [ n ] ; for ( i = 0 ; i < n ; i ++ ) lis [ i ] = 1 ; for ( i = 1 ; i < n ; i ++ ) for ( j = 0 ; j < i ; j ++ ) if ( arr [ i ] > arr [ j ] && lis [ i ] < lis [ j ] + 1 ) lis [ i ] = lis [ j ] + 1 ; int * lds = new int [ n ] ; for ( i = 0 ; i < n ; i ++ ) lds [ i ] = 1 ; for ( i = n - 2 ; i >= 0 ; i -- ) for ( j = n - 1 ; j > i ; j -- ) if ( arr [ i ] > arr [ j ] && lds [ i ] < lds [ j ] + 1 ) lds [ i ] = lds [ j ] + 1 ; int max = lis [ 0 ] + lds [ 0 ] - 1 ; for ( i = 1 ; i < n ; i ++ ) if ( lis [ i ] + lds [ i ] - 1 > max ) max = lis [ i ] + lds [ i ] - 1 ; return max ; } int main ( ) { int arr [ ] = { 0 , 8 , 4 , 12 , 2 , 10 , 6 , 14 , 1 , 9 , 5 , 13 , 3 , 11 , 7 , 15 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Length β of β LBS β is β % d STRNEWLINE " , lbs ( arr , n ) ) ; return 0 ; } |
Palindrome Partitioning | DP | C ++ Code for Palindrome Partitioning Problem ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( string String , int i , int j ) { while ( i < j ) { if ( String [ i ] != String [ j ] ) return false ; i ++ ; j -- ; } return true ; } int minPalPartion ( string String , int i , int j ) { if ( i >= j || isPalindrome ( String , i , j ) ) return 0 ; int ans = INT_MAX , count ; for ( int k = i ; k < j ; k ++ ) { count = minPalPartion ( String , i , k ) + minPalPartion ( String , k + 1 , j ) + 1 ; ans = min ( ans , count ) ; } return ans ; } int main ( ) { string str = " ababbbabbababa " ; cout << " Min β cuts β needed β for β " << " Palindrome β Partitioning β is β " << minPalPartion ( str , 0 , str . length ( ) - 1 ) << endl ; return 0 ; } |
Palindrome Partitioning | DP | ; minCut function ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minCut ( string a ) { int cut [ a . length ( ) ] ; bool palindrome [ a . length ( ) ] [ a . length ( ) ] ; memset ( palindrome , false , sizeof ( palindrome ) ) ; for ( int i = 0 ; i < a . length ( ) ; i ++ ) { int minCut = i ; for ( int j = 0 ; j <= i ; j ++ ) { if ( a [ i ] == a [ j ] && ( i - j < 2 palindrome [ j + 1 ] [ i - 1 ] ) ) { palindrome [ j ] [ i ] = true ; minCut = min ( minCut , j == 0 ? 0 : ( cut [ j - 1 ] + 1 ) ) ; } } cut [ i ] = minCut ; } return cut [ a . length ( ) - 1 ] ; } int main ( ) { cout << minCut ( " aab " ) << endl ; cout << minCut ( " aabababaxx " ) << endl ; return 0 ; } |
Palindrome Partitioning | DP | Using memoizatoin to solve the partition problem . ; Function to check if input string is pallindrome or not ; Using two pointer technique to check pallindrome ; Function to find keys for the Hashmap ; Returns the minimum number of cuts needed to partition a string such that every part is a palindrome ; Key for the Input String ; If the no of partitions for string " ij " is already calculated then return the calculated value using the Hashmap ; Every String of length 1 is a pallindrome ; Make a cut at every possible location starting from i to j ; If left cut is found already ; If right cut is found already ; Recursively calculating for left and right strings ; Taking minimum of all k possible cuts ; Return the min cut value for complete string . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool ispallindrome ( string input , int start , int end ) { while ( start < end ) { if ( input [ start ] != input [ end ] ) return false ; start ++ ; end -- ; } return true ; } string convert ( int a , int b ) { return to_string ( a ) + " " + to_string ( b ) ; } int minpalparti_memo ( string input , int i , int j , unordered_map < string , int > & memo ) { if ( i > j ) return 0 ; string ij = convert ( i , j ) ; if ( memo . find ( ij ) != memo . end ( ) ) { return memo [ ij ] ; } if ( i == j ) { memo [ ij ] = 0 ; return 0 ; } if ( ispallindrome ( input , i , j ) ) { memo [ ij ] = 0 ; return 0 ; } int minimum = INT_MAX ; for ( int k = i ; k < j ; k ++ ) { int left_min = INT_MAX ; int right_min = INT_MAX ; string left = convert ( i , k ) ; string right = convert ( k + 1 , j ) ; if ( memo . find ( left ) != memo . end ( ) ) { left_min = memo [ left ] ; } if ( memo . find ( right ) != memo . end ( ) ) { right_min = memo [ right ] ; } if ( left_min == INT_MAX ) left_min = minpalparti_memo ( input , i , k , memo ) ; if ( right_min == INT_MAX ) right_min = minpalparti_memo ( input , k + 1 , j , memo ) ; minimum = min ( minimum , left_min + 1 + right_min ) ; } memo [ ij ] = minimum ; return memo [ ij ] ; } int main ( ) { string input = " ababbbabbababa " ; unordered_map < string , int > memo ; cout << minpalparti_memo ( input , 0 , input . length ( ) - 1 , memo ) << endl ; return 0 ; } |
Word Wrap Problem | DP | A Dynamic programming solution for Word Wrap Problem ; A utility function to print the solution ; l [ ] represents lengths of different words in input sequence . For example , l [ ] = { 3 , 2 , 2 , 5 } is for a sentence like " aaa β bb β cc β ddddd " . n is size of l [ ] and M is line width ( maximum no . of characters that can fit in a line ) ; For simplicity , 1 extra space is used in all below arrays extras [ i ] [ j ] will have number of extra spaces if words from i to j are put in a single line ; lc [ i ] [ j ] will have cost of a line which has words from i to j ; c [ i ] will have total cost of optimal arrangement of words from 1 to i ; p [ ] is used to print the solution . ; calculate extra spaces in a single line . The value extra [ i ] [ j ] indicates extra spaces if words from word number i to j are placed in a single line ; Calculate line cost corresponding to the above calculated extra spaces . The value lc [ i ] [ j ] indicates cost of putting words from word number i to j in a single line ; Calculate minimum cost and find minimum cost arrangement . The value c [ j ] indicates optimized cost to arrange words from word number 1 to j . ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define INF INT_MAX NEW_LINE int printSolution ( int p [ ] , int n ) ; int printSolution ( int p [ ] , int n ) { int k ; if ( p [ n ] == 1 ) k = 1 ; else k = printSolution ( p , p [ n ] - 1 ) + 1 ; cout << " Line β number β " << k << " : β From β word β no . β " << p [ n ] << " β to β " << n << endl ; return k ; } void solveWordWrap ( int l [ ] , int n , int M ) { int extras [ n + 1 ] [ n + 1 ] ; int lc [ n + 1 ] [ n + 1 ] ; int c [ n + 1 ] ; int p [ n + 1 ] ; int i , j ; for ( i = 1 ; i <= n ; i ++ ) { extras [ i ] [ i ] = M - l [ i - 1 ] ; for ( j = i + 1 ; j <= n ; j ++ ) extras [ i ] [ j ] = extras [ i ] [ j - 1 ] - l [ j - 1 ] - 1 ; } for ( i = 1 ; i <= n ; i ++ ) { for ( j = i ; j <= n ; j ++ ) { if ( extras [ i ] [ j ] < 0 ) lc [ i ] [ j ] = INF ; else if ( j == n && extras [ i ] [ j ] >= 0 ) lc [ i ] [ j ] = 0 ; else lc [ i ] [ j ] = extras [ i ] [ j ] * extras [ i ] [ j ] ; } } c [ 0 ] = 0 ; for ( j = 1 ; j <= n ; j ++ ) { c [ j ] = INF ; for ( i = 1 ; i <= j ; i ++ ) { if ( c [ i - 1 ] != INF && lc [ i ] [ j ] != INF && ( c [ i - 1 ] + lc [ i ] [ j ] < c [ j ] ) ) { c [ j ] = c [ i - 1 ] + lc [ i ] [ j ] ; p [ j ] = i ; } } } printSolution ( p , n ) ; } int main ( ) { int l [ ] = { 3 , 2 , 2 , 5 } ; int n = sizeof ( l ) / sizeof ( l [ 0 ] ) ; int M = 6 ; solveWordWrap ( l , n , M ) ; return 0 ; } |
Ugly Numbers | CPP program to find nth ugly number ; This function divides a by greatest divisible power of b ; Function to check if a number is ugly or not ; Function to get the nth ugly number ; ugly number count ; Check for all integers untill ugly count becomes n ; Driver Code | #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int maxDivide ( int a , int b ) { while ( a % b == 0 ) a = a / b ; return a ; } int isUgly ( int no ) { no = maxDivide ( no , 2 ) ; no = maxDivide ( no , 3 ) ; no = maxDivide ( no , 5 ) ; return ( no == 1 ) ? 1 : 0 ; } int getNthUglyNo ( int n ) { int i = 1 ; int count = 1 ; while ( n > count ) { i ++ ; if ( isUgly ( i ) ) count ++ ; } return i ; } int main ( ) { unsigned no = getNthUglyNo ( 150 ) ; printf ( "150th β ugly β no . β is β % d β " , no ) ; getchar ( ) ; return 0 ; } |
Longest Palindromic Substring | Set 1 | A C ++ solution for longest palindrome ; Function to print a substring str [ low . . high ] ; This function prints the longest palindrome substring It also returns the length of the longest palindrome ; get length of input string ; All substrings of length 1 are palindromes ; Nested loop to mark start and end index ; Check palindrome ; Palindrome ; return length of LPS ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printSubStr ( string str , int low , int high ) { for ( int i = low ; i <= high ; ++ i ) cout << str [ i ] ; } int longestPalSubstr ( string str ) { int n = str . size ( ) ; int maxLength = 1 , start = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { for ( int j = i ; j < str . length ( ) ; j ++ ) { int flag = 1 ; for ( int k = 0 ; k < ( j - i + 1 ) / 2 ; k ++ ) if ( str [ i + k ] != str [ j - k ] ) flag = 0 ; if ( flag && ( j - i + 1 ) > maxLength ) { start = i ; maxLength = j - i + 1 ; } } } cout << " Longest β palindrome β substring β is : β " ; printSubStr ( str , start , start + maxLength - 1 ) ; return maxLength ; } int main ( ) { string str = " forgeeksskeegfor " ; cout << " Length is : " << longestPalSubstr ( str ) ; return 0 ; } |
Longest Palindromic Substring | Set 1 | A C ++ dynamic programming solution for longest palindrome ; Function to print a substring str [ low . . high ] ; This function prints the longest palindrome substring It also returns the length of the longest palindrome ; get length of input string ; table [ i ] [ j ] will be false if substring str [ i . . j ] is not palindrome . Else table [ i ] [ j ] will be true ; All substrings of length 1 are palindromes ; check for sub - string of length 2. ; Check for lengths greater than 2. k is length of substring ; Fix the starting index ; Get the ending index of substring from starting index i and length k ; checking for sub - string from ith index to jth index iff str [ i + 1 ] to str [ j - 1 ] is a palindrome ; return length of LPS ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printSubStr ( string str , int low , int high ) { for ( int i = low ; i <= high ; ++ i ) cout << str [ i ] ; } int longestPalSubstr ( string str ) { int n = str . size ( ) ; bool table [ n ] [ n ] ; memset ( table , 0 , sizeof ( table ) ) ; int maxLength = 1 ; for ( int i = 0 ; i < n ; ++ i ) table [ i ] [ i ] = true ; int start = 0 ; for ( int i = 0 ; i < n - 1 ; ++ i ) { if ( str [ i ] == str [ i + 1 ] ) { table [ i ] [ i + 1 ] = true ; start = i ; maxLength = 2 ; } } for ( int k = 3 ; k <= n ; ++ k ) { for ( int i = 0 ; i < n - k + 1 ; ++ i ) { int j = i + k - 1 ; if ( table [ i + 1 ] [ j - 1 ] && str [ i ] == str [ j ] ) { table [ i ] [ j ] = true ; if ( k > maxLength ) { start = i ; maxLength = k ; } } } } cout << " Longest β palindrome β substring β is : β " ; printSubStr ( str , start , start + maxLength - 1 ) ; return maxLength ; } int main ( ) { string str = " forgeeksskeegfor " ; cout << " Length is : " << longestPalSubstr ( str ) ; return 0 ; } |
Optimal Binary Search Tree | DP | A naive recursive implementation of optimal binary search tree problem ; A utility function to get sum of array elements freq [ i ] to freq [ j ] ; A recursive function to calculate cost of optimal binary search tree ; Base cases no elements in this subarray ; one element in this subarray ; Get sum of freq [ i ] , freq [ i + 1 ] , ... freq [ j ] ; Initialize minimum value ; One by one consider all elements as root and recursively find cost of the BST , compare the cost with min and update min if needed ; Return minimum value ; The main function that calculates minimum cost of a Binary Search Tree . It mainly uses optCost ( ) to find the optimal cost . ; Here array keys [ ] is assumed to be sorted in increasing order . If keys [ ] is not sorted , then add code to sort keys , and rearrange freq [ ] accordingly . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sum ( int freq [ ] , int i , int j ) { int s = 0 ; for ( int k = i ; k <= j ; k ++ ) s += freq [ k ] ; return s ; } int optCost ( int freq [ ] , int i , int j ) { if ( j < i ) return 0 ; if ( j == i ) return freq [ i ] ; int fsum = sum ( freq , i , j ) ; int min = INT_MAX ; for ( int r = i ; r <= j ; ++ r ) { int cost = optCost ( freq , i , r - 1 ) + optCost ( freq , r + 1 , j ) ; if ( cost < min ) min = cost ; } return min + fsum ; } int optimalSearchTree ( int keys [ ] , int freq [ ] , int n ) { return optCost ( freq , 0 , n - 1 ) ; } int main ( ) { int keys [ ] = { 10 , 12 , 20 } ; int freq [ ] = { 34 , 8 , 50 } ; int n = sizeof ( keys ) / sizeof ( keys [ 0 ] ) ; cout << " Cost β of β Optimal β BST β is β " << optimalSearchTree ( keys , freq , n ) ; return 0 ; } |
Optimal Binary Search Tree | DP | Dynamic Programming code for Optimal Binary Search Tree Problem ; A utility function to get sum of array elements freq [ i ] to freq [ j ] ; A Dynamic Programming based function that calculates minimum cost of a Binary Search Tree . ; Create an auxiliary 2D matrix to store results of subproblems ; For a single key , cost is equal to frequency of the key ; Now we need to consider chains of length 2 , 3 , ... . L is chain length . ; i is row number in cost [ ] [ ] ; Get column number j from row number i and chain length L ; Try making all keys in interval keys [ i . . j ] as root ; c = cost when keys [ r ] becomes root of this subtree ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sum ( int freq [ ] , int i , int j ) { int s = 0 ; for ( int k = i ; k <= j ; k ++ ) s += freq [ k ] ; return s ; } int optimalSearchTree ( int keys [ ] , int freq [ ] , int n ) { int cost [ n ] [ n ] ; for ( int i = 0 ; i < n ; i ++ ) cost [ i ] [ i ] = freq [ i ] ; for ( int L = 2 ; L <= n ; L ++ ) { for ( int i = 0 ; i <= n - L + 1 ; i ++ ) { int j = i + L - 1 ; cost [ i ] [ j ] = INT_MAX ; for ( int r = i ; r <= j ; r ++ ) { int c = ( ( r > i ) ? cost [ i ] [ r - 1 ] : 0 ) + ( ( r < j ) ? cost [ r + 1 ] [ j ] : 0 ) + sum ( freq , i , j ) ; if ( c < cost [ i ] [ j ] ) cost [ i ] [ j ] = c ; } } } return cost [ 0 ] [ n - 1 ] ; } int main ( ) { int keys [ ] = { 10 , 12 , 20 } ; int freq [ ] = { 34 , 8 , 50 } ; int n = sizeof ( keys ) / sizeof ( keys [ 0 ] ) ; cout << " Cost β of β Optimal β BST β is β " << optimalSearchTree ( keys , freq , n ) ; return 0 ; } |
Largest Independent Set Problem | DP | A naive recursive implementation of Largest Independent Set problem ; A utility function to find max of two integers ; A binary tree node has data , pointer to left child and a pointer to right child ; The function returns size of the largest independent set in a given binary tree ; Calculate size excluding the current node ; Calculate size including the current node ; Return the maximum of two sizes ; A utility function to create a node ; Driver Code ; Let us construct the tree given in the above diagram | #include <bits/stdc++.h> NEW_LINE using namespace std ; int max ( int x , int y ) { return ( x > y ) ? x : y ; } class node { public : int data ; node * left , * right ; } ; int LISS ( node * root ) { if ( root == NULL ) return 0 ; int size_excl = LISS ( root -> left ) + LISS ( root -> right ) ; int size_incl = 1 ; if ( root -> left ) size_incl += LISS ( root -> left -> left ) + LISS ( root -> left -> right ) ; if ( root -> right ) size_incl += LISS ( root -> right -> left ) + LISS ( root -> right -> right ) ; return max ( size_incl , size_excl ) ; } node * newNode ( int data ) { node * temp = new node ( ) ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } int main ( ) { node * root = newNode ( 20 ) ; root -> left = newNode ( 8 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 12 ) ; root -> left -> right -> left = newNode ( 10 ) ; root -> left -> right -> right = newNode ( 14 ) ; root -> right = newNode ( 22 ) ; root -> right -> right = newNode ( 25 ) ; cout << " Size β of β the β Largest " << " β Independent β Set β is β " << LISS ( root ) ; return 0 ; } |
Boolean Parenthesization Problem | DP | ; Returns count of all possible parenthesizations that lead to result true for a boolean expression with symbols like true and false and operators like & , | and ^ filled between symbols ; Fill diaginal entries first All diagonal entries in T [ i ] [ i ] are 1 if symbol [ i ] is T ( true ) . Similarly , all F [ i ] [ i ] entries are 1 if symbol [ i ] is F ( False ) ; Now fill T [ i ] [ i + 1 ] , T [ i ] [ i + 2 ] , T [ i ] [ i + 3 ] ... in order And F [ i ] [ i + 1 ] , F [ i ] [ i + 2 ] , F [ i ] [ i + 3 ] ... in order ; Find place of parenthesization using current value of gap ; Store Total [ i ] [ k ] and Total [ k + 1 ] [ j ] ; Follow the recursive formulas according to the current operator ; Driver code ; There are 4 ways ( ( T T ) & ( F ^ T ) ) , ( T | ( T & ( F ^ T ) ) ) , ( ( ( T T ) & F ) ^ T ) and ( T | ( ( T & F ) ^ T ) ) | #include <cstring> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int countParenth ( char symb [ ] , char oper [ ] , int n ) { int F [ n ] [ n ] , T [ n ] [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { F [ i ] [ i ] = ( symb [ i ] == ' F ' ) ? 1 : 0 ; T [ i ] [ i ] = ( symb [ i ] == ' T ' ) ? 1 : 0 ; } for ( int gap = 1 ; gap < n ; ++ gap ) { for ( int i = 0 , j = gap ; j < n ; ++ i , ++ j ) { T [ i ] [ j ] = F [ i ] [ j ] = 0 ; for ( int g = 0 ; g < gap ; g ++ ) { int k = i + g ; int tik = T [ i ] [ k ] + F [ i ] [ k ] ; int tkj = T [ k + 1 ] [ j ] + F [ k + 1 ] [ j ] ; if ( oper [ k ] == ' & ' ) { T [ i ] [ j ] += T [ i ] [ k ] * T [ k + 1 ] [ j ] ; F [ i ] [ j ] += ( tik * tkj - T [ i ] [ k ] * T [ k + 1 ] [ j ] ) ; } if ( oper [ k ] == ' β ' ) { F [ i ] [ j ] += F [ i ] [ k ] * F [ k + 1 ] [ j ] ; T [ i ] [ j ] += ( tik * tkj - F [ i ] [ k ] * F [ k + 1 ] [ j ] ) ; } if ( oper [ k ] == ' ^ ' ) { T [ i ] [ j ] += F [ i ] [ k ] * T [ k + 1 ] [ j ] + T [ i ] [ k ] * F [ k + 1 ] [ j ] ; F [ i ] [ j ] += T [ i ] [ k ] * T [ k + 1 ] [ j ] + F [ i ] [ k ] * F [ k + 1 ] [ j ] ; } } } } return T [ 0 ] [ n - 1 ] ; } int main ( ) { char symbols [ ] = " TTFT " ; char operators [ ] = " | & ^ " ; int n = strlen ( symbols ) ; cout << countParenth ( symbols , operators , n ) ; return 0 ; } |
Mobile Numeric Keypad Problem | A Dynamic Programming based C program to count number of possible numbers of given length ; Return count of all possible numbers of length n in a given numeric keyboard ; left , up , right , down move from current location ; taking n + 1 for simplicity - count [ i ] [ j ] will store number count starting with digit i and length j ; count numbers starting with digit i and of lengths 0 and 1 ; Bottom up - Get number count of length 2 , 3 , 4 , ... , n ; Loop on keypad row ; Loop on keypad column ; Process for 0 to 9 digits ; Here we are counting the numbers starting with digit keypad [ i ] [ j ] and of length k keypad [ i ] [ j ] will become 1 st digit , and we need to look for ( k - 1 ) more digits ; move left , up , right , down from current location and if new location is valid , then get number count of length ( k - 1 ) from that new digit and add in count we found so far ; Get count of all possible numbers of length " n " starting with digit 0 , 1 , 2 , ... , 9 ; Driver program to test above function | #include <stdio.h> NEW_LINE int getCount ( char keypad [ ] [ 3 ] , int n ) { if ( keypad == NULL n <= 0 ) return 0 ; if ( n == 1 ) return 10 ; int row [ ] = { 0 , 0 , -1 , 0 , 1 } ; int col [ ] = { 0 , -1 , 0 , 1 , 0 } ; int count [ 10 ] [ n + 1 ] ; int i = 0 , j = 0 , k = 0 , move = 0 , ro = 0 , co = 0 , num = 0 ; int nextNum = 0 , totalCount = 0 ; for ( i = 0 ; i <= 9 ; i ++ ) { count [ i ] [ 0 ] = 0 ; count [ i ] [ 1 ] = 1 ; } for ( k = 2 ; k <= n ; k ++ ) { for ( i = 0 ; i < 4 ; i ++ ) { for ( j = 0 ; j < 3 ; j ++ ) { if ( keypad [ i ] [ j ] != ' * ' && keypad [ i ] [ j ] != ' # ' ) { num = keypad [ i ] [ j ] - '0' ; count [ num ] [ k ] = 0 ; for ( move = 0 ; move < 5 ; move ++ ) { ro = i + row [ move ] ; co = j + col [ move ] ; if ( ro >= 0 && ro <= 3 && co >= 0 && co <= 2 && keypad [ ro ] [ co ] != ' * ' && keypad [ ro ] [ co ] != ' # ' ) { nextNum = keypad [ ro ] [ co ] - '0' ; count [ num ] [ k ] += count [ nextNum ] [ k - 1 ] ; } } } } } } totalCount = 0 ; for ( i = 0 ; i <= 9 ; i ++ ) totalCount += count [ i ] [ n ] ; return totalCount ; } int main ( int argc , char * argv [ ] ) { char keypad [ 4 ] [ 3 ] = { { '1' , '2' , '3' } , { '4' , '5' , '6' } , { '7' , '8' , '9' } , { ' * ' , '0' , ' # ' } } ; printf ( " Count β for β numbers β of β length β % d : β % dn " , 1 , getCount ( keypad , 1 ) ) ; printf ( " Count β for β numbers β of β length β % d : β % dn " , 2 , getCount ( keypad , 2 ) ) ; printf ( " Count β for β numbers β of β length β % d : β % dn " , 3 , getCount ( keypad , 3 ) ) ; printf ( " Count β for β numbers β of β length β % d : β % dn " , 4 , getCount ( keypad , 4 ) ) ; printf ( " Count β for β numbers β of β length β % d : β % dn " , 5 , getCount ( keypad , 5 ) ) ; return 0 ; } |
Mobile Numeric Keypad Problem | A Space Optimized C ++ program to count number of possible numbers of given length ; Return count of all possible numbers of length n in a given numeric keyboard ; odd [ i ] , even [ i ] arrays represent count of numbers starting with digit i for any length j ; for j = 1 ; Bottom Up calculation from j = 2 to n ; Here we are explicitly writing lines for each number 0 to 9. But it can always be written as DFS on 4 X3 grid using row , column array valid moves ; Get count of all possible numbers of length " n " starting with digit 0 , 1 , 2 , ... , 9 ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getCount ( char keypad [ ] [ 3 ] , int n ) { if ( keypad == NULL n <= 0 ) return 0 ; if ( n == 1 ) return 10 ; int odd [ 10 ] , even [ 10 ] ; int i = 0 , j = 0 , useOdd = 0 , totalCount = 0 ; for ( i = 0 ; i <= 9 ; i ++ ) odd [ i ] = 1 ; for ( j = 2 ; j <= n ; j ++ ) { useOdd = 1 - useOdd ; if ( useOdd == 1 ) { even [ 0 ] = odd [ 0 ] + odd [ 8 ] ; even [ 1 ] = odd [ 1 ] + odd [ 2 ] + odd [ 4 ] ; even [ 2 ] = odd [ 2 ] + odd [ 1 ] + odd [ 3 ] + odd [ 5 ] ; even [ 3 ] = odd [ 3 ] + odd [ 2 ] + odd [ 6 ] ; even [ 4 ] = odd [ 4 ] + odd [ 1 ] + odd [ 5 ] + odd [ 7 ] ; even [ 5 ] = odd [ 5 ] + odd [ 2 ] + odd [ 4 ] + odd [ 8 ] + odd [ 6 ] ; even [ 6 ] = odd [ 6 ] + odd [ 3 ] + odd [ 5 ] + odd [ 9 ] ; even [ 7 ] = odd [ 7 ] + odd [ 4 ] + odd [ 8 ] ; even [ 8 ] = odd [ 8 ] + odd [ 0 ] + odd [ 5 ] + odd [ 7 ] + odd [ 9 ] ; even [ 9 ] = odd [ 9 ] + odd [ 6 ] + odd [ 8 ] ; } else { odd [ 0 ] = even [ 0 ] + even [ 8 ] ; odd [ 1 ] = even [ 1 ] + even [ 2 ] + even [ 4 ] ; odd [ 2 ] = even [ 2 ] + even [ 1 ] + even [ 3 ] + even [ 5 ] ; odd [ 3 ] = even [ 3 ] + even [ 2 ] + even [ 6 ] ; odd [ 4 ] = even [ 4 ] + even [ 1 ] + even [ 5 ] + even [ 7 ] ; odd [ 5 ] = even [ 5 ] + even [ 2 ] + even [ 4 ] + even [ 8 ] + even [ 6 ] ; odd [ 6 ] = even [ 6 ] + even [ 3 ] + even [ 5 ] + even [ 9 ] ; odd [ 7 ] = even [ 7 ] + even [ 4 ] + even [ 8 ] ; odd [ 8 ] = even [ 8 ] + even [ 0 ] + even [ 5 ] + even [ 7 ] + even [ 9 ] ; odd [ 9 ] = even [ 9 ] + even [ 6 ] + even [ 8 ] ; } } totalCount = 0 ; if ( useOdd == 1 ) { for ( i = 0 ; i <= 9 ; i ++ ) totalCount += even [ i ] ; } else { for ( i = 0 ; i <= 9 ; i ++ ) totalCount += odd [ i ] ; } return totalCount ; } int main ( ) { char keypad [ 4 ] [ 3 ] = { { '1' , '2' , '3' } , { '4' , '5' , '6' } , { '7' , '8' , '9' } , { ' * ' , '0' , ' # ' } } ; cout << " Count β for β numbers β of β length β 1 : β " << getCount ( keypad , 1 ) << endl ; cout << " Count β for β numbers β of β length β 2 : β " << getCount ( keypad , 2 ) << endl ; cout << " Count β for β numbers β of β length β 3 : β " << getCount ( keypad , 3 ) << endl ; cout << " Count β for β numbers β of β length β 4 : β " << getCount ( keypad , 4 ) << endl ; cout << " Count β for β numbers β of β length β 5 : β " << getCount ( keypad , 5 ) << endl ; return 0 ; } |
Count of n digit numbers whose sum of digits equals to given sum | A C ++ program using recursive to count numbers with sum of digits as given ' sum ' ; Recursive function to count ' n ' digit numbers with sum of digits as ' sum ' . This function considers leading 0 's also as digits, that is why not directly called ; Base case ; Initialize answer ; Traverse through every digit and count numbers beginning with it using recursion ; This is mainly a wrapper over countRec . It explicitly handles leading digit and calls countRec ( ) for remaining digits . ; Initialize final answer ; Traverse through every digit from 1 to 9 and count numbers beginning with it ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned long long int countRec ( int n , int sum ) { if ( n == 0 ) return sum == 0 ; if ( sum == 0 ) return 1 ; unsigned long long int ans = 0 ; for ( int i = 0 ; i <= 9 ; i ++ ) if ( sum - i >= 0 ) ans += countRec ( n - 1 , sum - i ) ; return ans ; } unsigned long long int finalCount ( int n , int sum ) { unsigned long long int ans = 0 ; for ( int i = 1 ; i <= 9 ; i ++ ) if ( sum - i >= 0 ) ans += countRec ( n - 1 , sum - i ) ; return ans ; } int main ( ) { int n = 2 , sum = 5 ; cout << finalCount ( n , sum ) ; return 0 ; } |
Count of n digit numbers whose sum of digits equals to given sum | A C ++ memoization based recursive program to count numbers with sum of n as given ' sum ' ; A lookup table used for memoization ; Memoization based implementation of recursive function ; Base case ; If this subproblem is already evaluated , return the evaluated value ; Initialize answer ; Traverse through every digit and recursively count numbers beginning with it ; This is mainly a wrapper over countRec . It explicitly handles leading digit and calls countRec ( ) for remaining n . ; Initialize all entries of lookup table ; Initialize final answer ; Traverse through every digit from 1 to 9 and count numbers beginning with it ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned long long int lookup [ 101 ] [ 501 ] ; unsigned long long int countRec ( int n , int sum ) { if ( n == 0 ) return sum == 0 ; if ( lookup [ n ] [ sum ] != -1 ) return lookup [ n ] [ sum ] ; unsigned long long int ans = 0 ; for ( int i = 0 ; i < 10 ; i ++ ) if ( sum - i >= 0 ) ans += countRec ( n - 1 , sum - i ) ; return lookup [ n ] [ sum ] = ans ; } unsigned long long int finalCount ( int n , int sum ) { memset ( lookup , -1 , sizeof lookup ) ; unsigned long long int ans = 0 ; for ( int i = 1 ; i <= 9 ; i ++ ) if ( sum - i >= 0 ) ans += countRec ( n - 1 , sum - i ) ; return ans ; } int main ( ) { int n = 3 , sum = 5 ; cout << finalCount ( n , sum ) ; return 0 ; } |
Count of n digit numbers whose sum of digits equals to given sum | C ++ program to Count of n digit numbers whose sum of digits equals to given sum ; in case n = 2 start is 10 and end is ( 100 - 1 ) = 99 ; Driver Code | #include <bits/stdc++.h> NEW_LINE #include <iostream> NEW_LINE using namespace std ; void findCount ( int n , int sum ) { int start = pow ( 10 , n - 1 ) ; int end = pow ( 10 , n ) - 1 ; int count = 0 ; int i = start ; while ( i <= end ) { int cur = 0 ; int temp = i ; while ( temp != 0 ) { cur += temp % 10 ; temp = temp / 10 ; } if ( cur == sum ) { count ++ ; i += 9 ; } else i ++ ; } cout << count ; } int main ( ) { int n = 3 ; int sum = 5 ; findCount ( n , sum ) ; return 0 ; } |
Total number of non | C ++ program to count non - decreasing number with n digits ; dp [ i ] [ j ] contains total count of non decreasing numbers ending with digit i and of length j ; Fill table for non decreasing numbers of length 1 Base cases 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ; Fill the table in bottom - up manner ; Compute total numbers of non decreasing numbers of length ' len ' ; sum of all numbers of length of len - 1 in which last digit x is <= ' digit ' ; There total nondecreasing numbers of length n wiint be dp [ 0 ] [ n ] + dp [ 1 ] [ n ] . . + dp [ 9 ] [ n ] ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long int countNonDecreasing ( int n ) { long long int dp [ 10 ] [ n + 1 ] ; memset ( dp , 0 , sizeof dp ) ; for ( int i = 0 ; i < 10 ; i ++ ) dp [ i ] [ 1 ] = 1 ; for ( int digit = 0 ; digit <= 9 ; digit ++ ) { for ( int len = 2 ; len <= n ; len ++ ) { for ( int x = 0 ; x <= digit ; x ++ ) dp [ digit ] [ len ] += dp [ x ] [ len - 1 ] ; } } long long int count = 0 ; for ( int i = 0 ; i < 10 ; i ++ ) count += dp [ i ] [ n ] ; return count ; } int main ( ) { int n = 3 ; cout << countNonDecreasing ( n ) ; return 0 ; } |
Total number of non | C ++ program to count non - decreasing numner with n digits ; Compute value of N * ( N + 1 ) / 2 * ( N + 2 ) / 3 * ... . * ( N + n - 1 ) / n ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long int countNonDecreasing ( int n ) { int N = 10 ; long long count = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { count *= ( N + i - 1 ) ; count /= i ; } return count ; } int main ( ) { int n = 3 ; cout << countNonDecreasing ( n ) ; return 0 ; } |
Minimum number of squares whose sum equals to given number n | A naive recursive C ++ program to find minimum number of squares whose sum is equal to a given number ; Returns count of minimum squares that sum to n ; base cases if n is perfect square then Minimum squares required is 1 ( 144 = 12 ^ 2 ) ; getMinSquares rest of the table using recursive formula Maximum squares required is n ( 1 * 1 + 1 * 1 + . . ) ; Go through all smaller numbers to recursively find minimum ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getMinSquares ( unsigned int n ) { if ( sqrt ( n ) - floor ( sqrt ( n ) ) == 0 ) return 1 ; if ( n <= 3 ) return n ; int res = n ; for ( int x = 1 ; x <= n ; x ++ ) { int temp = x * x ; if ( temp > n ) break ; else res = min ( res , 1 + getMinSquares ( n - temp ) ) ; } return res ; } int main ( ) { cout << getMinSquares ( 6 ) ; return 0 ; } |
Minimum number of squares whose sum equals to given number n | A dynamic programming based C ++ program to find minimum number of squares whose sum is equal to a given number ; Returns count of minimum squares that sum to n ; We need to check base case for n i . e . 0 , 1 , 2 the below array creation will go OutOfBounds . ; Create a dynamic programming table to store sq ; getMinSquares table for base case entries ; getMinSquares rest of the table using recursive formula ; max value is i as i can always be represented as 1 * 1 + 1 * 1 + ... ; Go through all smaller numbers to to recursively find minimum ; Store result and free dp [ ] ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getMinSquares ( int n ) { if ( n <= 3 ) return n ; int * dp = new int [ n + 1 ] ; dp [ 0 ] = 0 ; dp [ 1 ] = 1 ; dp [ 2 ] = 2 ; dp [ 3 ] = 3 ; for ( int i = 4 ; i <= n ; i ++ ) { dp [ i ] = i ; for ( int x = 1 ; x <= ceil ( sqrt ( i ) ) ; x ++ ) { int temp = x * x ; if ( temp > i ) break ; else dp [ i ] = min ( dp [ i ] , 1 + dp [ i - temp ] ) ; } } int res = dp [ n ] ; delete [ ] dp ; return res ; } int main ( ) { cout << getMinSquares ( 6 ) ; return 0 ; } |
Minimum number of squares whose sum equals to given number n | C ++ program for the above approach ; Function to count minimum squares that sum to n ; Creating visited vector of size n + 1 ; Queue of pair to store node and number of steps ; Initially ans variable is initialized with inf ; Push starting node with 0 0 indicate current number of step to reach n ; Mark starting node visited ; If node reaches its destination 0 update it with answer ; Loop for all possible path from 1 to i * i <= current node ( p . first ) ; If we are standing at some node then next node it can jump to will be current node - ( some square less than or equal n ) ; Check if it is valid and not visited yet ; Mark visited ; Push it it Queue ; Return ans to calling function ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int numSquares ( int n ) { vector < int > visited ( n + 1 , 0 ) ; queue < pair < int , int > > q ; int ans = INT_MAX ; q . push ( { n , 0 } ) ; visited [ n ] = 1 ; while ( ! q . empty ( ) ) { pair < int , int > p ; p = q . front ( ) ; q . pop ( ) ; if ( p . first == 0 ) ans = min ( ans , p . second ) ; for ( int i = 1 ; i * i <= p . first ; i ++ ) { int path = ( p . first - ( i * i ) ) ; if ( path >= 0 && ( ! visited [ path ] path == 0 ) ) { visited [ path ] = 1 ; q . push ( { path , p . second + 1 } ) ; } } } return ans ; } int main ( ) { cout << numSquares ( 12 ) ; return 0 ; } |
Find minimum number of coins that make a given value | A Naive recursive C ++ program to find minimum of coins to make a given change V ; m is size of coins array ( number of different coins ) ; base case ; Initialize result ; Try every coin that has smaller value than V ; Check for INT_MAX to avoid overflow and see if result can minimized ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minCoins ( int coins [ ] , int m , int V ) { if ( V == 0 ) return 0 ; int res = INT_MAX ; for ( int i = 0 ; i < m ; i ++ ) { if ( coins [ i ] <= V ) { int sub_res = minCoins ( coins , m , V - coins [ i ] ) ; if ( sub_res != INT_MAX && sub_res + 1 < res ) res = sub_res + 1 ; } } return res ; } int main ( ) { int coins [ ] = { 9 , 6 , 5 , 1 } ; int m = sizeof ( coins ) / sizeof ( coins [ 0 ] ) ; int V = 11 ; cout << " Minimum β coins β required β is β " << minCoins ( coins , m , V ) ; return 0 ; } |
Find minimum number of coins that make a given value | A Dynamic Programming based C ++ program to find minimum of coins to make a given change V ; m is size of coins array ( number of different coins ) ; table [ i ] will be storing the minimum number of coins required for i value . So table [ V ] will have result ; Base case ( If given value V is 0 ) ; Initialize all table values as Infinite ; Compute minimum coins required for all values from 1 to V ; Go through all coins smaller than i ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minCoins ( int coins [ ] , int m , int V ) { int table [ V + 1 ] ; table [ 0 ] = 0 ; for ( int i = 1 ; i <= V ; i ++ ) table [ i ] = INT_MAX ; for ( int i = 1 ; i <= V ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) if ( coins [ j ] <= i ) { int sub_res = table [ i - coins [ j ] ] ; if ( sub_res != INT_MAX && sub_res + 1 < table [ i ] ) table [ i ] = sub_res + 1 ; } } if ( table [ V ] == INT_MAX ) return -1 ; return table [ V ] ; } int main ( ) { int coins [ ] = { 9 , 6 , 5 , 1 } ; int m = sizeof ( coins ) / sizeof ( coins [ 0 ] ) ; int V = 11 ; cout << " Minimum β coins β required β is β " << minCoins ( coins , m , V ) ; return 0 ; } |
Shortest Common Supersequence | A Naive recursive C ++ program to find length of the shortest supersequence ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int superSeq ( char * X , char * Y , int m , int n ) { if ( ! m ) return n ; if ( ! n ) return m ; if ( X [ m - 1 ] == Y [ n - 1 ] ) return 1 + superSeq ( X , Y , m - 1 , n - 1 ) ; return 1 + min ( superSeq ( X , Y , m - 1 , n ) , superSeq ( X , Y , m , n - 1 ) ) ; } int main ( ) { char X [ ] = " AGGTAB " ; char Y [ ] = " GXTXAYB " ; cout << " Length β of β the β shortest β supersequence β is β " << superSeq ( X , Y , strlen ( X ) , strlen ( Y ) ) ; return 0 ; } |
Shortest Common Supersequence | A dynamic programming based C program to find length of the shortest supersequence ; Returns length of the shortest supersequence of X and Y ; Fill table in bottom up manner ; Below steps follow above recurrence ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int superSeq ( char * X , char * Y , int m , int n ) { int dp [ m + 1 ] [ n + 1 ] ; for ( int i = 0 ; i <= m ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { if ( ! i ) dp [ i ] [ j ] = j ; else if ( ! j ) dp [ i ] [ j ] = i ; else if ( X [ i - 1 ] == Y [ j - 1 ] ) dp [ i ] [ j ] = 1 + dp [ i - 1 ] [ j - 1 ] ; else dp [ i ] [ j ] = 1 + min ( dp [ i - 1 ] [ j ] , dp [ i ] [ j - 1 ] ) ; } } return dp [ m ] [ n ] ; } int main ( ) { char X [ ] = " AGGTAB " ; char Y [ ] = " GXTXAYB " ; cout << " Length β of β the β shortest β supersequence β is β " << superSeq ( X , Y , strlen ( X ) , strlen ( Y ) ) ; return 0 ; } |
Compute sum of digits in all numbers from 1 to n | A Simple C ++ program to compute sum of digits in numbers from 1 to n ; Returns sum of all digits in numbers from 1 to n ; initialize result ; One by one compute sum of digits in every number from 1 to n ; A utility function to compute sum of digits in a given number x ; Driver Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfDigits ( int ) ; int sumOfDigitsFrom1ToN ( int n ) { int result = 0 ; for ( int x = 1 ; x <= n ; x ++ ) result += sumOfDigits ( x ) ; return result ; } int sumOfDigits ( int x ) { int sum = 0 ; while ( x != 0 ) { sum += x % 10 ; x = x / 10 ; } return sum ; } int main ( ) { int n = 328 ; cout << " Sum β of β digits β in β numbers β from β 1 β to β " << n << " β is β " << sumOfDigitsFrom1ToN ( n ) ; return 0 ; } |
Compute sum of digits in all numbers from 1 to n | C ++ program to compute sum of digits in numbers from 1 to n ; Function to computer sum of digits in numbers from 1 to n Comments use example of 328 to explain the code ; base case : if n < 10 return sum of first n natural numbers ; d = number of digits minus one in n . For 328 , d is 2 ; computing sum of digits from 1 to 10 ^ d - 1 , d = 1 a [ 0 ] = 0 ; d = 2 a [ 1 ] = sum of digit from 1 to 9 = 45 d = 3 a [ 2 ] = sum of digit from 1 to 99 = a [ 1 ] * 10 + 45 * 10 ^ 1 = 900 d = 4 a [ 3 ] = sum of digit from 1 to 999 = a [ 2 ] * 10 + 45 * 10 ^ 2 = 13500 ; computing 10 ^ d ; Most significant digit ( msd ) of n , For 328 , msd is 3 which can be obtained using 328 / 100 ; EXPLANATION FOR FIRST and SECOND TERMS IN BELOW LINE OF CODE First two terms compute sum of digits from 1 to 299 ( sum of digits in range 1 - 99 stored in a [ d ] ) + ( sum of digits in range 100 - 199 , can be calculated as 1 * 100 + a [ d ] ( sum of digits in range 200 - 299 , can be calculated as 2 * 100 + a [ d ] The above sum can be written as 3 * a [ d ] + ( 1 + 2 ) * 100 EXPLANATION FOR THIRD AND FOURTH TERMS IN BELOW LINE OF CODE The last two terms compute sum of digits in number from 300 to 328 The third term adds 3 * 29 to sum as digit 3 occurs in all numbers from 300 to 328 The fourth term recursively calls for 28 ; Driver Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfDigitsFrom1ToN ( int n ) { if ( n < 10 ) return n * ( n + 1 ) / 2 ; int d = log10 ( n ) ; int * a = new int [ d + 1 ] ; a [ 0 ] = 0 , a [ 1 ] = 45 ; for ( int i = 2 ; i <= d ; i ++ ) a [ i ] = a [ i - 1 ] * 10 + 45 * ceil ( pow ( 10 , i - 1 ) ) ; int p = ceil ( pow ( 10 , d ) ) ; int msd = n / p ; return msd * a [ d ] + ( msd * ( msd - 1 ) / 2 ) * p + msd * ( 1 + n % p ) + sumOfDigitsFrom1ToN ( n % p ) ; } int main ( ) { int n = 328 ; cout << " Sum β of β digits β in β numbers β from β 1 β to β " << n << " β is β " << sumOfDigitsFrom1ToN ( n ) ; return 0 ; } |
Compute sum of digits in all numbers from 1 to n | C ++ program to compute sum of digits in numbers from 1 to n ; Function to computer sum of digits in numbers from 1 to n ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfDigitsFrom1ToNUtil ( int n , int a [ ] ) { if ( n < 10 ) return ( n * ( n + 1 ) / 2 ) ; int d = ( int ) ( log10 ( n ) ) ; int p = ( int ) ( ceil ( pow ( 10 , d ) ) ) ; int msd = n / p ; return ( msd * a [ d ] + ( msd * ( msd - 1 ) / 2 ) * p + msd * ( 1 + n % p ) + sumOfDigitsFrom1ToNUtil ( n % p , a ) ) ; } int sumOfDigitsFrom1ToN ( int n ) { int d = ( int ) ( log10 ( n ) ) ; int a [ d + 1 ] ; a [ 0 ] = 0 ; a [ 1 ] = 45 ; for ( int i = 2 ; i <= d ; i ++ ) a [ i ] = a [ i - 1 ] * 10 + 45 * ( int ) ( ceil ( pow ( 10 , i - 1 ) ) ) ; return sumOfDigitsFrom1ToNUtil ( n , a ) ; } int main ( ) { int n = 328 ; cout << " Sum β of β digits β in β numbers β from β 1 β to β " << n << " β is β " << sumOfDigitsFrom1ToN ( n ) ; } |
Count possible ways to construct buildings | C ++ program to count all possible way to construct buildings ; Returns count of possible ways for N sections ; Base case ; 2 for one side and 4 for two sides ; countB is count of ways with a building at the end countS is count of ways with a space at the end prev_countB and prev_countS are previous values of countB and countS respectively . Initialize countB and countS for one side ; Use the above recursive formula for calculating countB and countS using previous values ; Result for one side is sum of ways ending with building and ending with space ; Result for 2 sides is square of result for one side ; Driver program | #include <iostream> NEW_LINE using namespace std ; int countWays ( int N ) { if ( N == 1 ) return 4 ; int countB = 1 , countS = 1 , prev_countB , prev_countS ; for ( int i = 2 ; i <= N ; i ++ ) { prev_countB = countB ; prev_countS = countS ; countS = prev_countB + prev_countS ; countB = prev_countS ; } int result = countS + countB ; return ( result * result ) ; } int main ( ) { int N = 3 ; cout << " Count β of β ways β for β " << N << " β sections β is β " << countWays ( N ) ; return 0 ; } |
Count number of ways to reach a given score in a game | A C ++ program to count number of possible ways to a given score can be reached in a game where a move can earn 3 or 5 or 10 ; Returns number of ways to reach score n ; table [ i ] will store count of solutions for value i . ; Initialize all table values as 0 ; Base case ( If given value is 0 ) ; One by one consider given 3 moves and update the table [ ] values after the index greater than or equal to the value of the picked move ; Driver Code | #include <iostream> NEW_LINE using namespace std ; int count ( int n ) { int table [ n + 1 ] , i ; for ( int j = 0 ; j < n + 1 ; j ++ ) table [ j ] = 0 ; table [ 0 ] = 1 ; for ( i = 3 ; i <= n ; i ++ ) table [ i ] += table [ i - 3 ] ; for ( i = 5 ; i <= n ; i ++ ) table [ i ] += table [ i - 5 ] ; for ( i = 10 ; i <= n ; i ++ ) table [ i ] += table [ i - 10 ] ; return table [ n ] ; } int main ( void ) { int n = 20 ; cout << " Count β for β " << n << " β is β " << count ( n ) << endl ; n = 13 ; cout << " Count β for β " << n << " β is β " << count ( n ) << endl ; return 0 ; } |
Naive algorithm for Pattern Searching | C ++ program for Naive Pattern Searching algorithm ; A loop to slide pat [ ] one by one ; For current index i , check for pattern match ; if pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void search ( char * pat , char * txt ) { int M = strlen ( pat ) ; int N = strlen ( txt ) ; for ( int i = 0 ; i <= N - M ; i ++ ) { int j ; for ( j = 0 ; j < M ; j ++ ) if ( txt [ i + j ] != pat [ j ] ) break ; if ( j == M ) cout << " Pattern β found β at β index β " << i << endl ; } } int main ( ) { char txt [ ] = " AABAACAADAABAAABAA " ; char pat [ ] = " AABA " ; search ( pat , txt ) ; return 0 ; } |
Rabin | Following program is a C ++ implementation of Rabin Karp Algorithm given in the CLRS book ; d is the number of characters in the input alphabet ; pat -> pattern txt -> text q -> A prime number ; hash value for pattern ; hash value for txt ; The value of h would be " pow ( d , β M - 1 ) % q " ; Calculate the hash value of pattern and first window of text ; Slide the pattern over text one by one ; Check the hash values of current window of text and pattern . If the hash values match then only check for characters on by one ; Check for characters one by one ; if p == t and pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; Calculate hash value for next window of text : Remove leading digit , add trailing digit ; We might get negative value of t , converting it to positive ; Driver code ; A prime number ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define d 256 NEW_LINE void search ( char pat [ ] , char txt [ ] , int q ) { int M = strlen ( pat ) ; int N = strlen ( txt ) ; int i , j ; int p = 0 ; int t = 0 ; int h = 1 ; for ( i = 0 ; i < M - 1 ; i ++ ) h = ( h * d ) % q ; for ( i = 0 ; i < M ; i ++ ) { p = ( d * p + pat [ i ] ) % q ; t = ( d * t + txt [ i ] ) % q ; } for ( i = 0 ; i <= N - M ; i ++ ) { if ( p == t ) { for ( j = 0 ; j < M ; j ++ ) { if ( txt [ i + j ] != pat [ j ] ) break ; } if ( j == M ) cout << " Pattern β found β at β index β " << i << endl ; } if ( i < N - M ) { t = ( d * ( t - txt [ i ] * h ) + txt [ i + M ] ) % q ; if ( t < 0 ) t = ( t + q ) ; } } } int main ( ) { char txt [ ] = " GEEKS β FOR β GEEKS " ; char pat [ ] = " GEEK " ; int q = 101 ; search ( pat , txt , q ) ; return 0 ; } |
Optimized Naive Algorithm for Pattern Searching | C ++ program for A modified Naive Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different ; A modified Naive Pettern Searching algorithn that is optimized for the cases when all characters of pattern are different ; For current index i , check for pattern match ; if pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; slide the pattern by j ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void search ( string pat , string txt ) { int M = pat . size ( ) ; int N = txt . size ( ) ; int i = 0 ; while ( i <= N - M ) { int j ; for ( j = 0 ; j < M ; j ++ ) if ( txt [ i + j ] != pat [ j ] ) break ; if ( j == M ) { cout << " Pattern β found β at β index β " << i << endl ; i = i + M ; } else if ( j == 0 ) i = i + 1 ; else i = i + j ; } } int main ( ) { string txt = " ABCEABCDABCEABCD " ; string pat = " ABCD " ; search ( pat , txt ) ; return 0 ; } |
Finite Automata algorithm for Pattern Searching | CPP program for Finite Automata Pattern searching Algorithm ; If the character c is same as next character in pattern , then simply increment state ; ns stores the result which is next state ; ns finally contains the longest prefix which is also suffix in " pat [ 0 . . state - 1 ] c " Start from the largest possible value and stop when you find a prefix which is also suffix ; This function builds the TF table which represents4 Finite Automata for a given pattern ; Prints all occurrences of pat in txt ; Process txt over FA . ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define NO_OF_CHARS 256 NEW_LINE int getNextState ( string pat , int M , int state , int x ) { if ( state < M && x == pat [ state ] ) return state + 1 ; int ns , i ; for ( ns = state ; ns > 0 ; ns -- ) { if ( pat [ ns - 1 ] == x ) { for ( i = 0 ; i < ns - 1 ; i ++ ) if ( pat [ i ] != pat [ state - ns + 1 + i ] ) break ; if ( i == ns - 1 ) return ns ; } } return 0 ; } void computeTF ( string pat , int M , int TF [ ] [ NO_OF_CHARS ] ) { int state , x ; for ( state = 0 ; state <= M ; ++ state ) for ( x = 0 ; x < NO_OF_CHARS ; ++ x ) TF [ state ] [ x ] = getNextState ( pat , M , state , x ) ; } void search ( string pat , string txt ) { int M = pat . size ( ) ; int N = txt . size ( ) ; int TF [ M + 1 ] [ NO_OF_CHARS ] ; computeTF ( pat , M , TF ) ; int i , state = 0 ; for ( i = 0 ; i < N ; i ++ ) { state = TF [ state ] [ txt [ i ] ] ; if ( state == M ) cout << " β Pattern β found β at β index β " << i - M + 1 << endl ; } } int main ( ) { string txt = " AABAACAADAABAAABAA " ; string pat = " AABA " ; search ( pat , txt ) ; return 0 ; } |
Boyer Moore Algorithm for Pattern Searching | C ++ Program for Bad Character Heuristic of Boyer Moore String Matching Algorithm ; The preprocessing function for Boyer Moore 's bad character heuristic ; Initialize all occurrences as - 1 ; Fill the actual value of last occurrence of a character ; A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm ; Fill the bad character array by calling the preprocessing function badCharHeuristic ( ) for given pattern ; s is shift of the pattern with respect to text ; there are n - m + 1 potential allignments ; Keep reducing index j of pattern while characters of pattern and text are matching at this shift s ; If the pattern is present at current shift , then index j will become - 1 after the above loop ; Shift the pattern so that the next character in text aligns with the last occurrence of it in pattern . The condition s + m < n is necessary for the case when pattern occurs at the end of text ; Shift the pattern so that the bad character in text aligns with the last occurrence of it in pattern . The max function is used to make sure that we get a positive shift . We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; # define NO_OF_CHARS 256 NEW_LINE void badCharHeuristic ( string str , int size , int badchar [ NO_OF_CHARS ] ) { int i ; for ( i = 0 ; i < NO_OF_CHARS ; i ++ ) badchar [ i ] = -1 ; for ( i = 0 ; i < size ; i ++ ) badchar [ ( int ) str [ i ] ] = i ; } void search ( string txt , string pat ) { int m = pat . size ( ) ; int n = txt . size ( ) ; int badchar [ NO_OF_CHARS ] ; badCharHeuristic ( pat , m , badchar ) ; int s = 0 ; while ( s <= ( n - m ) ) { int j = m - 1 ; while ( j >= 0 && pat [ j ] == txt [ s + j ] ) j -- ; if ( j < 0 ) { cout << " pattern β occurs β at β shift β = β " << s << endl ; s += ( s + m < n ) ? m - badchar [ txt [ s + m ] ] : 1 ; } else s += max ( 1 , j - badchar [ txt [ s + j ] ] ) ; } } int main ( ) { string txt = " ABAAABCD " ; string pat = " ABC " ; search ( txt , pat ) ; return 0 ; } |
Anagram Substring Search ( Or Search for all permutations ) | C ++ program to search all anagrams of a pattern in a text ; This function returns true if contents of arr1 [ ] and arr2 [ ] are same , otherwise false . ; This function search for all permutations of pat [ ] in txt [ ] ; countP [ ] : Store count of all characters of pattern countTW [ ] : Store count of current window of text ; Traverse through remaining characters of pattern ; Compare counts of current window of text with counts of pattern [ ] ; Add current character to current window ; Remove the first character of previous window ; Check for the last window in text ; Driver program to test above function | #include <iostream> NEW_LINE #include <cstring> NEW_LINE #define MAX 256 NEW_LINE using namespace std ; bool compare ( char arr1 [ ] , char arr2 [ ] ) { for ( int i = 0 ; i < MAX ; i ++ ) if ( arr1 [ i ] != arr2 [ i ] ) return false ; return true ; } void search ( char * pat , char * txt ) { int M = strlen ( pat ) , N = strlen ( txt ) ; char countP [ MAX ] = { 0 } , countTW [ MAX ] = { 0 } ; for ( int i = 0 ; i < M ; i ++ ) { ( countP [ pat [ i ] ] ) ++ ; ( countTW [ txt [ i ] ] ) ++ ; } for ( int i = M ; i < N ; i ++ ) { if ( compare ( countP , countTW ) ) cout << " Found β at β Index β " << ( i - M ) << endl ; ( countTW [ txt [ i ] ] ) ++ ; countTW [ txt [ i - M ] ] -- ; } if ( compare ( countP , countTW ) ) cout << " Found β at β Index β " << ( N - M ) << endl ; } int main ( ) { char txt [ ] = " BACDGABCDA " ; char pat [ ] = " ABCD " ; search ( pat , txt ) ; return 0 ; } |
Manacher 's Algorithm | A C program to implement Manachers Algorithm ; Position count ; LPS Length Array ; centerPosition ; centerRightPosition ; currentRightPosition ; currentLeftPosition ; Uncomment it to print LPS Length array printf ( " % d β % d β " , L [ 0 ] , L [ 1 ] ) ; ; get currentLeftPosition iMirror for currentRightPosition i ; If currentRightPosition i is within centerRightPosition R ; Attempt to expand palindrome centered at currentRightPosition i Here for odd positions , we compare characters and if match then increment LPS Length by ONE If even position , we just increment LPS by ONE without any character comparison ; Track maxLPSLength ; If palindrome centered at currentRightPosition i expand beyond centerRightPosition R , adjust centerPosition C based on expanded palindrome . ; Uncomment it to print LPS Length array printf ( " % d β " , L [ i ] ) ; ; printf ( " \n " ) ; | #include <stdio.h> NEW_LINE #include <string.h> NEW_LINE char text [ 100 ] ; int min ( int a , int b ) { int res = a ; if ( b < a ) res = b ; return res ; } void findLongestPalindromicString ( ) { int N = strlen ( text ) ; if ( N == 0 ) return ; N = 2 * N + 1 ; int L [ N ] ; L [ 0 ] = 0 ; L [ 1 ] = 1 ; int C = 1 ; int R = 2 ; int i = 0 ; int iMirror ; int maxLPSLength = 0 ; int maxLPSCenterPosition = 0 ; int start = -1 ; int end = -1 ; int diff = -1 ; for ( i = 2 ; i < N ; i ++ ) { iMirror = 2 * C - i ; L [ i ] = 0 ; diff = R - i ; if ( diff > 0 ) L [ i ] = min ( L [ iMirror ] , diff ) ; while ( ( ( i + L [ i ] ) < N && ( i - L [ i ] ) > 0 ) && ( ( ( i + L [ i ] + 1 ) % 2 == 0 ) || ( text [ ( i + L [ i ] + 1 ) / 2 ] == text [ ( i - L [ i ] - 1 ) / 2 ] ) ) ) { L [ i ] ++ ; } if ( L [ i ] > maxLPSLength ) { maxLPSLength = L [ i ] ; maxLPSCenterPosition = i ; } if ( i + L [ i ] > R ) { C = i ; R = i + L [ i ] ; } } start = ( maxLPSCenterPosition - maxLPSLength ) / 2 ; end = start + maxLPSLength - 1 ; printf ( " LPS β of β string β is β % s β : β " , text ) ; for ( i = start ; i <= end ; i ++ ) printf ( " % c " , text [ i ] ) ; printf ( " STRNEWLINE " ) ; } int main ( int argc , char * argv [ ] ) { strcpy ( text , " babcbabcbaccba " ) ; findLongestPalindromicString ( ) ; strcpy ( text , " abaaba " ) ; findLongestPalindromicString ( ) ; strcpy ( text , " abababa " ) ; findLongestPalindromicString ( ) ; strcpy ( text , " abcbabcbabcba " ) ; findLongestPalindromicString ( ) ; strcpy ( text , " forgeeksskeegfor " ) ; findLongestPalindromicString ( ) ; strcpy ( text , " caba " ) ; findLongestPalindromicString ( ) ; strcpy ( text , " abacdfgdcaba " ) ; findLongestPalindromicString ( ) ; strcpy ( text , " abacdfgdcabba " ) ; findLongestPalindromicString ( ) ; strcpy ( text , " abacdedcaba " ) ; findLongestPalindromicString ( ) ; return 0 ; } |
Print all possible strings that can be made by placing spaces | C ++ program to print permutations of a given string with spaces . ; Function recursively prints the strings having space pattern . i and j are indices in ' str [ ] ' and ' buff [ ] ' respectively ; Either put the character ; Or put a space followed by next character ; This function creates buf [ ] to store individual output string and uses printPatternUtil ( ) to print all permutations . ; Buffer to hold the string containing spaces 2 n - 1 characters and 1 string terminator ; Copy the first character as it is , since it will be always at first position ; Driver program to test above functions | #include <cstring> NEW_LINE #include <iostream> NEW_LINE using namespace std ; void printPatternUtil ( const char str [ ] , char buff [ ] , int i , int j , int n ) { if ( i == n ) { buff [ j ] = ' \0' ; cout << buff << endl ; return ; } buff [ j ] = str [ i ] ; printPatternUtil ( str , buff , i + 1 , j + 1 , n ) ; buff [ j ] = ' β ' ; buff [ j + 1 ] = str [ i ] ; printPatternUtil ( str , buff , i + 1 , j + 2 , n ) ; } void printPattern ( const char * str ) { int n = strlen ( str ) ; char buf [ 2 * n ] ; buf [ 0 ] = str [ 0 ] ; printPatternUtil ( str , buf , 1 , 1 , n ) ; } int main ( ) { const char * str = " ABCD " ; printPattern ( str ) ; return 0 ; } |
Subset Sum | Backtracking | ; Prints subset found ; inputs s - set vector t - tuplet vector s_size - set size t_size - tuplet size so far sum - sum so far ite - nodes count target_sum - sum to be found ; We found subset ; Exclude previously added item and consider next candidate ; Generate nodes along the breadth ; Consider next level node ( along depth ) ; Wrapper to print subsets that sum to target_sum input is weights vector and target_sum ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ARRAYSIZE ( a ) (sizeof(a)) / (sizeof(a[0])) NEW_LINE #define mx 200 NEW_LINE static int total_nodes ; void printSubset ( int A [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) { cout << A [ i ] << " β " ; } cout << " STRNEWLINE β " ; } void subset_sum ( int s [ ] , int t [ ] , int s_size , int t_size , int sum , int ite , int const target_sum ) { total_nodes ++ ; if ( target_sum == sum ) { printSubset ( t , t_size ) ; subset_sum ( s , t , s_size , t_size - 1 , sum - s [ ite ] , ite + 1 , target_sum ) ; return ; } else { for ( int i = ite ; i < s_size ; i ++ ) { t [ t_size ] = s [ i ] ; subset_sum ( s , t , s_size , t_size + 1 , sum + s [ i ] , i + 1 , target_sum ) ; } } } void generateSubsets ( int s [ ] , int size , int target_sum ) { int * tuplet_vector = new int [ mx ] ; subset_sum ( s , tuplet_vector , size , 0 , 0 , 0 , target_sum ) ; free ( tuplet_vector ) ; } int main ( ) { int weights [ ] = { 10 , 7 , 5 , 18 , 12 , 20 , 15 } ; int size = ARRAYSIZE ( weights ) ; generateSubsets ( weights , size , 35 ) ; cout << " Nodes β generated β " << total_nodes << " STRNEWLINE " ; return 0 ; } |
Subset Sum | Backtracking | ; prints subset found ; qsort compare function ; inputs s - set vector t - tuplet vector s_size - set size t_size - tuplet size so far sum - sum so far ite - nodes count target_sum - sum to be found ; We found sum ; constraint check ; Exclude previous added item and consider next candidate ; constraint check ; generate nodes along the breadth ; consider next level node ( along depth ) ; Wrapper that prints subsets that sum to target_sum ; sort the set ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ARRAYSIZE ( a ) (sizeof(a))/(sizeof(a[0])) NEW_LINE static int total_nodes ; void printSubset ( int A [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) { cout << " β " << A [ i ] ; } cout << " STRNEWLINE " ; } int comparator ( const void * pLhs , const void * pRhs ) { int * lhs = ( int * ) pLhs ; int * rhs = ( int * ) pRhs ; return * lhs > * rhs ; } void subset_sum ( int s [ ] , int t [ ] , int s_size , int t_size , int sum , int ite , int const target_sum ) { total_nodes ++ ; if ( target_sum == sum ) { printSubset ( t , t_size ) ; if ( ite + 1 < s_size && sum - s [ ite ] + s [ ite + 1 ] <= target_sum ) { subset_sum ( s , t , s_size , t_size - 1 , sum - s [ ite ] , ite + 1 , target_sum ) ; } return ; } else { if ( ite < s_size && sum + s [ ite ] <= target_sum ) { for ( int i = ite ; i < s_size ; i ++ ) { t [ t_size ] = s [ i ] ; if ( sum + s [ i ] <= target_sum ) { subset_sum ( s , t , s_size , t_size + 1 , sum + s [ i ] , i + 1 , target_sum ) ; } } } } } void generateSubsets ( int s [ ] , int size , int target_sum ) { int * tuplet_vector = ( int * ) malloc ( size * sizeof ( int ) ) ; int total = 0 ; qsort ( s , size , sizeof ( int ) , & comparator ) ; for ( int i = 0 ; i < size ; i ++ ) { total += s [ i ] ; } if ( s [ 0 ] <= target_sum && total >= target_sum ) { subset_sum ( s , tuplet_vector , size , 0 , 0 , 0 , target_sum ) ; } free ( tuplet_vector ) ; } int main ( ) { int weights [ ] = { 15 , 22 , 14 , 26 , 32 , 9 , 16 , 8 } ; int target = 53 ; int size = ARRAYSIZE ( weights ) ; generateSubsets ( weights , size , target ) ; cout << " Nodes β generated β " << total_nodes ; return 0 ; } |
Sudoku | Backtracking | ; N is the size of the 2D matrix N * N ; A utility function to print grid ; Checks whether it will be legal to assign num to the given row , col ; Check if we find the same num in the similar row , we return false ; Check if we find the same num in the similar column , we return false ; Check if we find the same num in the particular 3 * 3 matrix , we return false ; Takes a partially filled - in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution ( non - duplication across rows , columns , and boxes ) ; Check if we have reached the 8 th row and 9 th column ( 0 indexed matrix ) , we are returning true to avoid further backtracking ; Check if column value becomes 9 , we move to next row and column start from 0 ; Check if the current position of the grid already contains value > 0 , we iterate for next column ; Check if it is safe to place the num ( 1 - 9 ) in the given row , col -> we move to next column ; Assigning the num in the current ( row , col ) position of the grid and assuming our assined num in the position is correct ; Checking for next possibility with next column ; Removing the assigned num , since our assumption was wrong , and we go for next assumption with diff num value ; Driver Code | #include <iostream> NEW_LINE using namespace std ; #define N 9 NEW_LINE void print ( int arr [ N ] [ N ] ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) cout << arr [ i ] [ j ] << " β " ; cout << endl ; } } bool isSafe ( int grid [ N ] [ N ] , int row , int col , int num ) { for ( int x = 0 ; x <= 8 ; x ++ ) if ( grid [ row ] [ x ] == num ) return false ; for ( int x = 0 ; x <= 8 ; x ++ ) if ( grid [ x ] [ col ] == num ) return false ; int startRow = row - row % 3 , startCol = col - col % 3 ; for ( int i = 0 ; i < 3 ; i ++ ) for ( int j = 0 ; j < 3 ; j ++ ) if ( grid [ i + startRow ] [ j + startCol ] == num ) return false ; return true ; } bool solveSuduko ( int grid [ N ] [ N ] , int row , int col ) { if ( row == N - 1 && col == N ) return true ; if ( col == N ) { row ++ ; col = 0 ; } if ( grid [ row ] [ col ] > 0 ) return solveSuduko ( grid , row , col + 1 ) ; for ( int num = 1 ; num <= N ; num ++ ) { if ( isSafe ( grid , row , col , num ) ) { grid [ row ] [ col ] = num ; if ( solveSuduko ( grid , row , col + 1 ) ) return true ; } grid [ row ] [ col ] = 0 ; } return false ; } int main ( ) { int grid [ N ] [ N ] = { { 3 , 0 , 6 , 5 , 0 , 8 , 4 , 0 , 0 } , { 5 , 2 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 8 , 7 , 0 , 0 , 0 , 0 , 3 , 1 } , { 0 , 0 , 3 , 0 , 1 , 0 , 0 , 8 , 0 } , { 9 , 0 , 0 , 8 , 6 , 3 , 0 , 0 , 5 } , { 0 , 5 , 0 , 0 , 9 , 0 , 6 , 0 , 0 } , { 1 , 3 , 0 , 0 , 0 , 0 , 2 , 5 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 7 , 4 } , { 0 , 0 , 5 , 2 , 0 , 6 , 3 , 0 , 0 } } ; if ( solveSuduko ( grid , 0 , 0 ) ) print ( grid ) ; else cout << " no β solution β exists β " << endl ; return 0 ; } |
Median of two sorted arrays of same size | A Simple Merge based O ( n ) solution to find median of two sorted arrays ; This function returns median of ar1 [ ] and ar2 [ ] . Assumptions in this function : Both ar1 [ ] and ar2 [ ] are sorted arrays Both have n elements ; Since there are 2 n elements , median will be average of elements at index n - 1 and n in the array obtained after merging ar1 and ar2 ; Below is to handle case where all elements of ar1 [ ] are smaller than smallest ( or first ) element of ar2 [ ] ; Below is to handle case where all elements of ar2 [ ] are smaller than smallest ( or first ) element of ar1 [ ] ; equals sign because if two arrays have some common elements ; Store the prev median ; Store the prev median ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getMedian ( int ar1 [ ] , int ar2 [ ] , int n ) { int i = 0 ; int j = 0 ; int count ; int m1 = -1 , m2 = -1 ; for ( count = 0 ; count <= n ; count ++ ) { if ( i == n ) { m1 = m2 ; m2 = ar2 [ 0 ] ; break ; } else if ( j == n ) { m1 = m2 ; m2 = ar1 [ 0 ] ; break ; } if ( ar1 [ i ] <= ar2 [ j ] ) { m1 = m2 ; m2 = ar1 [ i ] ; i ++ ; } else { m1 = m2 ; m2 = ar2 [ j ] ; j ++ ; } } return ( m1 + m2 ) / 2 ; } int main ( ) { int ar1 [ ] = { 1 , 12 , 15 , 26 , 38 } ; int ar2 [ ] = { 2 , 13 , 17 , 30 , 45 } ; int n1 = sizeof ( ar1 ) / sizeof ( ar1 [ 0 ] ) ; int n2 = sizeof ( ar2 ) / sizeof ( ar2 [ 0 ] ) ; if ( n1 == n2 ) cout << " Median β is β " << getMedian ( ar1 , ar2 , n1 ) ; else cout << " Doesn ' t β work β for β arrays " << " β of β unequal β size " ; getchar ( ) ; return 0 ; } |
Median of two sorted arrays of same size | A divide and conquer based efficient solution to find median of two sorted arrays of same size . ; to get median of a sorted array ; This function returns median of ar1 [ ] and ar2 [ ] . Assumptions in this function : Both ar1 [ ] and ar2 [ ] are sorted arrays Both have n elements ; get the median of the first array ; get the median of the second array ; If medians are equal then return either m1 or m2 ; if m1 < m2 then median must exist in ar1 [ m1 ... . ] and ar2 [ ... . m2 ] ; if m1 > m2 then median must exist in ar1 [ ... . m1 ] and ar2 [ m2 ... ] ; Function to get median of a sorted array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int median ( int [ ] , int ) ; int getMedian ( int ar1 [ ] , int ar2 [ ] , int n ) { if ( n <= 0 ) return -1 ; if ( n == 1 ) return ( ar1 [ 0 ] + ar2 [ 0 ] ) / 2 ; if ( n == 2 ) return ( max ( ar1 [ 0 ] , ar2 [ 0 ] ) + min ( ar1 [ 1 ] , ar2 [ 1 ] ) ) / 2 ; int m1 = median ( ar1 , n ) ; int m2 = median ( ar2 , n ) ; if ( m1 == m2 ) return m1 ; if ( m1 < m2 ) { if ( n % 2 == 0 ) return getMedian ( ar1 + n / 2 - 1 , ar2 , n - n / 2 + 1 ) ; return getMedian ( ar1 + n / 2 , ar2 , n - n / 2 ) ; } if ( n % 2 == 0 ) return getMedian ( ar2 + n / 2 - 1 , ar1 , n - n / 2 + 1 ) ; return getMedian ( ar2 + n / 2 , ar1 , n - n / 2 ) ; } int median ( int arr [ ] , int n ) { if ( n % 2 == 0 ) return ( arr [ n / 2 ] + arr [ n / 2 - 1 ] ) / 2 ; else return arr [ n / 2 ] ; } int main ( ) { int ar1 [ ] = { 1 , 2 , 3 , 6 } ; int ar2 [ ] = { 4 , 6 , 8 , 10 } ; int n1 = sizeof ( ar1 ) / sizeof ( ar1 [ 0 ] ) ; int n2 = sizeof ( ar2 ) / sizeof ( ar2 [ 0 ] ) ; if ( n1 == n2 ) cout << " Median β is β " << getMedian ( ar1 , ar2 , n1 ) ; else cout << " Doesn ' t β work β for β arrays β " << " of β unequal β size " ; return 0 ; } |
Median of two sorted arrays of same size | CPP program for the above approach ; This function returns median of ar1 [ ] and ar2 [ ] . Assumptions in this function : Both ar1 [ ] and ar2 [ ] are sorted arrays Both have n elements ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getMedian ( int ar1 [ ] , int ar2 [ ] , int n ) { int j = 0 ; int i = n - 1 ; while ( ar1 [ i ] > ar2 [ j ] && j < n && i > - 1 ) swap ( ar1 [ i -- ] , ar2 [ j ++ ] ) ; sort ( ar1 , ar1 + n ) ; sort ( ar2 , ar2 + n ) ; return ( ar1 [ n - 1 ] + ar2 [ 0 ] ) / 2 ; } int main ( ) { int ar1 [ ] = { 1 , 12 , 15 , 26 , 38 } ; int ar2 [ ] = { 2 , 13 , 17 , 30 , 45 } ; int n1 = sizeof ( ar1 ) / sizeof ( ar1 [ 0 ] ) ; int n2 = sizeof ( ar2 ) / sizeof ( ar2 [ 0 ] ) ; if ( n1 == n2 ) cout << " Median β is β " << getMedian ( ar1 , ar2 , n1 ) ; else cout << " Doesn ' t β work β for β arrays " << " β of β unequal β size " ; getchar ( ) ; return 0 ; } |
Closest Pair of Points using Divide and Conquer algorithm | A divide and conquer program in C ++ to find the smallest distance from a given set of points . ; A structure to represent a Point in 2D plane ; Needed to sort array of points according to X coordinate ; Needed to sort array of points according to Y coordinate ; A utility function to find the distance between two points ; A Brute Force method to return the smallest distance between two points in P [ ] of size n ; A utility function to find minimum of two float values ; A utility function to find the distance beween the closest points of strip of given size . All points in strip [ ] are sorted accordint to y coordinate . They all have an upper bound on minimum distance as d . Note that this method seems to be a O ( n ^ 2 ) method , but it 's a O(n) method as the inner loop runs at most 6 times ; Initialize the minimum distance as d ; Pick all points one by one and try the next points till the difference between y coordinates is smaller than d . This is a proven fact that this loop runs at most 6 times ; A recursive function to find the smallest distance . The array P contains all points sorted according to x coordinate ; If there are 2 or 3 points , then use brute force ; Find the middle point ; Consider the vertical line passing through the middle point calculate the smallest distance dl on left of middle point and dr on right side ; Find the smaller of two distances ; Build an array strip [ ] that contains points close ( closer than d ) to the line passing through the middle point ; Find the closest points in strip . Return the minimum of d and closest distance is strip [ ] ; The main function that finds the smallest distance This method mainly uses closestUtil ( ) ; Use recursive function closestUtil ( ) to find the smallest distance ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; class Point { public : int x , y ; } ; int compareX ( const void * a , const void * b ) { Point * p1 = ( Point * ) a , * p2 = ( Point * ) b ; return ( p1 -> x - p2 -> x ) ; } int compareY ( const void * a , const void * b ) { Point * p1 = ( Point * ) a , * p2 = ( Point * ) b ; return ( p1 -> y - p2 -> y ) ; } float dist ( Point p1 , Point p2 ) { return sqrt ( ( p1 . x - p2 . x ) * ( p1 . x - p2 . x ) + ( p1 . y - p2 . y ) * ( p1 . y - p2 . y ) ) ; } float bruteForce ( Point P [ ] , int n ) { float min = FLT_MAX ; for ( int i = 0 ; i < n ; ++ i ) for ( int j = i + 1 ; j < n ; ++ j ) if ( dist ( P [ i ] , P [ j ] ) < min ) min = dist ( P [ i ] , P [ j ] ) ; return min ; } float min ( float x , float y ) { return ( x < y ) ? x : y ; } float stripClosest ( Point strip [ ] , int size , float d ) { float min = d ; qsort ( strip , size , sizeof ( Point ) , compareY ) ; for ( int i = 0 ; i < size ; ++ i ) for ( int j = i + 1 ; j < size && ( strip [ j ] . y - strip [ i ] . y ) < min ; ++ j ) if ( dist ( strip [ i ] , strip [ j ] ) < min ) min = dist ( strip [ i ] , strip [ j ] ) ; return min ; } float closestUtil ( Point P [ ] , int n ) { if ( n <= 3 ) return bruteForce ( P , n ) ; int mid = n / 2 ; Point midPoint = P [ mid ] ; float dl = closestUtil ( P , mid ) ; float dr = closestUtil ( P + mid , n - mid ) ; float d = min ( dl , dr ) ; Point strip [ n ] ; int j = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( abs ( P [ i ] . x - midPoint . x ) < d ) strip [ j ] = P [ i ] , j ++ ; return min ( d , stripClosest ( strip , j , d ) ) ; } float closest ( Point P [ ] , int n ) { qsort ( P , n , sizeof ( Point ) , compareX ) ; return closestUtil ( P , n ) ; } int main ( ) { Point P [ ] = { { 2 , 3 } , { 12 , 30 } , { 40 , 50 } , { 5 , 1 } , { 12 , 10 } , { 3 , 4 } } ; int n = sizeof ( P ) / sizeof ( P [ 0 ] ) ; cout << " The β smallest β distance β is β " << closest ( P , n ) ; return 0 ; } |
How to check if two given line segments intersect ? | A C ++ program to check if two given line segments intersect ; Given three colinear points p , q , r , the function checks if point q lies on line segment ' pr ' ; To find orientation of ordered triplet ( p , q , r ) . The function returns following values 0 -- > p , q and r are colinear 1 -- > Clockwise 2 -- > Counterclockwise ; www . geeksforgeeks . org / orientation - 3 - ordered - points / See https : for details of below formula . ; colinear ; clock or counterclock wise ; The main function that returns true if line segment ' p1q1' and ' p2q2' intersect . ; Find the four orientations needed for general and special cases ; General case ; Special Cases p1 , q1 and p2 are colinear and p2 lies on segment p1q1 ; p1 , q1 and q2 are colinear and q2 lies on segment p1q1 ; p2 , q2 and p1 are colinear and p1 lies on segment p2q2 ; p2 , q2 and q1 are colinear and q1 lies on segment p2q2 ; Doesn 't fall in any of the above cases ; Driver program to test above functions | #include <iostream> NEW_LINE using namespace std ; struct Point { int x ; int y ; } ; bool onSegment ( Point p , Point q , Point r ) { if ( q . x <= max ( p . x , r . x ) && q . x >= min ( p . x , r . x ) && q . y <= max ( p . y , r . y ) && q . y >= min ( p . y , r . y ) ) return true ; return false ; } int orientation ( Point p , Point q , Point r ) { int val = ( q . y - p . y ) * ( r . x - q . x ) - ( q . x - p . x ) * ( r . y - q . y ) ; if ( val == 0 ) return 0 ; return ( val > 0 ) ? 1 : 2 ; } bool doIntersect ( Point p1 , Point q1 , Point p2 , Point q2 ) { int o1 = orientation ( p1 , q1 , p2 ) ; int o2 = orientation ( p1 , q1 , q2 ) ; int o3 = orientation ( p2 , q2 , p1 ) ; int o4 = orientation ( p2 , q2 , q1 ) ; if ( o1 != o2 && o3 != o4 ) return true ; if ( o1 == 0 && onSegment ( p1 , p2 , q1 ) ) return true ; if ( o2 == 0 && onSegment ( p1 , q2 , q1 ) ) return true ; if ( o3 == 0 && onSegment ( p2 , p1 , q2 ) ) return true ; if ( o4 == 0 && onSegment ( p2 , q1 , q2 ) ) return true ; return false ; } int main ( ) { struct Point p1 = { 1 , 1 } , q1 = { 10 , 1 } ; struct Point p2 = { 1 , 2 } , q2 = { 10 , 2 } ; doIntersect ( p1 , q1 , p2 , q2 ) ? cout << " Yes STRNEWLINE " : cout << " No STRNEWLINE " ; p1 = { 10 , 0 } , q1 = { 0 , 10 } ; p2 = { 0 , 0 } , q2 = { 10 , 10 } ; doIntersect ( p1 , q1 , p2 , q2 ) ? cout << " Yes STRNEWLINE " : cout << " No STRNEWLINE " ; p1 = { -5 , -5 } , q1 = { 0 , 0 } ; p2 = { 1 , 1 } , q2 = { 10 , 10 } ; doIntersect ( p1 , q1 , p2 , q2 ) ? cout << " Yes STRNEWLINE " : cout << " No STRNEWLINE " ; return 0 ; } |
Check whether a given point lies inside a triangle or not | ; A utility function to calculate area of triangle formed by ( x1 , y1 ) , ( x2 , y2 ) and ( x3 , y3 ) ; A function to check whether point P ( x , y ) lies inside the triangle formed by A ( x1 , y1 ) , B ( x2 , y2 ) and C ( x3 , y3 ) ; Calculate area of triangle ABC ; Calculate area of triangle PBC ; Calculate area of triangle PAC ; Calculate area of triangle PAB ; Check if sum of A1 , A2 and A3 is same as A ; Driver program to test above function ; Let us check whether the point P ( 10 , 15 ) lies inside the triangle formed by A ( 0 , 0 ) , B ( 20 , 0 ) and C ( 10 , 30 ) | #include <bits/stdc++.h> NEW_LINE using namespace std ; float area ( int x1 , int y1 , int x2 , int y2 , int x3 , int y3 ) { return abs ( ( x1 * ( y2 - y3 ) + x2 * ( y3 - y1 ) + x3 * ( y1 - y2 ) ) / 2.0 ) ; } bool isInside ( int x1 , int y1 , int x2 , int y2 , int x3 , int y3 , int x , int y ) { float A = area ( x1 , y1 , x2 , y2 , x3 , y3 ) ; float A1 = area ( x , y , x2 , y2 , x3 , y3 ) ; float A2 = area ( x1 , y1 , x , y , x3 , y3 ) ; float A3 = area ( x1 , y1 , x2 , y2 , x , y ) ; return ( A == A1 + A2 + A3 ) ; } int main ( ) { if ( isInside ( 0 , 0 , 20 , 0 , 10 , 30 , 10 , 15 ) ) printf ( " Inside " ) ; else printf ( " Not β Inside " ) ; return 0 ; } |
Lucky Numbers | C ++ program for Lucky Numbers ; Returns 1 if n is a lucky no . otherwise returns 0 ; variable next_position is just for readability of the program we can remove it and use n only ; calculate next position of input no ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define bool int NEW_LINE bool isLucky ( int n ) { static int counter = 2 ; int next_position = n ; if ( counter > n ) return 1 ; if ( n % counter == 0 ) return 0 ; next_position -= next_position / counter ; counter ++ ; return isLucky ( next_position ) ; } int main ( ) { int x = 5 ; if ( isLucky ( x ) ) cout << x << " β is β a β lucky β no . " ; else cout << x << " β is β not β a β lucky β no . " ; } |
Write you own Power without using multiplication ( * ) and division ( / ) operators | C ++ code for power function ; Works only if a >= 0 and b >= 0 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int pow ( int a , int b ) { if ( b == 0 ) return 1 ; int answer = a ; int increment = a ; int i , j ; for ( i = 1 ; i < b ; i ++ ) { for ( j = 1 ; j < a ; j ++ ) { answer += increment ; } increment = answer ; } return answer ; } int main ( ) { cout << pow ( 5 , 3 ) ; return 0 ; } |
Write you own Power without using multiplication ( * ) and division ( / ) operators | ; A recursive function to get x * y ; A recursive function to get a ^ b Works only if a >= 0 and b >= 0 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int multiply ( int x , int y ) { if ( y ) return ( x + multiply ( x , y - 1 ) ) ; else return 0 ; } int pow ( int a , int b ) { if ( b ) return multiply ( a , pow ( a , b - 1 ) ) ; else return 1 ; } int main ( ) { cout << pow ( 5 , 3 ) ; getchar ( ) ; return 0 ; } |
Count numbers that don 't contain 3 | ; returns count of numbers which are in range from 1 to n and don 't contain 3 as a digit ; Base cases ( Assuming n is not negative ) ; Calculate 10 ^ ( d - 1 ) ( 10 raise to the power d - 1 ) where d is number of digits in n . po will be 100 for n = 578 ; find the most significant digit ( msd is 5 for 578 ) ; For 578 , total will be 4 * count ( 10 ^ 2 - 1 ) + 4 + count ( 78 ) ; For 35 , total will be equal to count ( 29 ) ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int count ( int n ) { if ( n < 3 ) return n ; if ( n >= 3 && n < 10 ) return n - 1 ; int po = 1 ; while ( n / po > 9 ) po = po * 10 ; int msd = n / po ; if ( msd != 3 ) return count ( msd ) * count ( po - 1 ) + count ( msd ) + count ( n % po ) ; else return count ( msd * po - 1 ) ; } int main ( ) { cout << count ( 578 ) << " β " ; return 0 ; } |
Number which has the maximum number of distinct prime factors in the range M to N | C ++ program to print the Number which has the maximum number of distinct prime factors of numbers in range m to n ; Function to return the maximum number ; array to store the number of distinct primes ; true if index ' i ' is a prime ; initializing the number of factors to 0 and ; Used in Sieve ; condition works only when ' i ' is prime , hence for factors of all prime number , the prime status is changed to false ; Number is prime ; number of factor of a prime number is 1 ; incrementing factorCount all the factors of i ; and changing prime status to false ; Initialize the max and num ; Gets the maximum number ; Gets the maximum number ; Driver code ; Calling function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumNumberDistinctPrimeRange ( int m , int n ) { long long factorCount [ n + 1 ] ; bool prime [ n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) { factorCount [ i ] = 0 ; prime [ i ] = true ; } for ( int i = 2 ; i <= n ; i ++ ) { if ( prime [ i ] == true ) { factorCount [ i ] = 1 ; for ( int j = i * 2 ; j <= n ; j += i ) { factorCount [ j ] ++ ; prime [ j ] = false ; } } } int max = factorCount [ m ] ; int num = m ; for ( int i = m ; i <= n ; i ++ ) { if ( factorCount [ i ] > max ) { max = factorCount [ i ] ; num = i ; } } return num ; } int main ( ) { int m = 4 , n = 6 ; cout << maximumNumberDistinctPrimeRange ( m , n ) ; return 0 ; } |
Lexicographic rank of a string | C ++ program to find lexicographic rank of a string ; A utility function to find factorial of n ; A utility function to count smaller characters on right of arr [ low ] ; A function to find rank of a string in all permutations of characters ; count number of chars smaller than str [ i ] from str [ i + 1 ] to str [ len - 1 ] ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE #include <string.h> NEW_LINE using namespace std ; int fact ( int n ) { return ( n <= 1 ) ? 1 : n * fact ( n - 1 ) ; } int findSmallerInRight ( char * str , int low , int high ) { int countRight = 0 , i ; for ( i = low + 1 ; i <= high ; ++ i ) if ( str [ i ] < str [ low ] ) ++ countRight ; return countRight ; } int findRank ( char * str ) { int len = strlen ( str ) ; int mul = fact ( len ) ; int rank = 1 ; int countRight ; int i ; for ( i = 0 ; i < len ; ++ i ) { mul /= len - i ; countRight = findSmallerInRight ( str , i , len - 1 ) ; rank += countRight * mul ; } return rank ; } int main ( ) { char str [ ] = " string " ; cout << findRank ( str ) ; return 0 ; } |
Lexicographic rank of a string | A O ( n ) solution for finding rank of string ; all elements of count [ ] are initialized with 0 ; A utility function to find factorial of n ; Construct a count array where value at every index contains count of smaller characters in whole string ; Removes a character ch from count [ ] array constructed by populateAndIncreaseCount ( ) ; A function to find rank of a string in all permutations of characters ; Populate the count array such that count [ i ] contains count of characters which are present in str and are smaller than i ; count number of chars smaller than str [ i ] fron str [ i + 1 ] to str [ len - 1 ] ; Reduce count of characters greater than str [ i ] ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX_CHAR 256 NEW_LINE int count [ MAX_CHAR ] = { 0 } ; int fact ( int n ) { return ( n <= 1 ) ? 1 : n * fact ( n - 1 ) ; } void populateAndIncreaseCount ( int * count , char * str ) { int i ; for ( i = 0 ; str [ i ] ; ++ i ) ++ count [ str [ i ] ] ; for ( i = 1 ; i < MAX_CHAR ; ++ i ) count [ i ] += count [ i - 1 ] ; } void updatecount ( int * count , char ch ) { int i ; for ( i = ch ; i < MAX_CHAR ; ++ i ) -- count [ i ] ; } int findRank ( char * str ) { int len = strlen ( str ) ; int mul = fact ( len ) ; int rank = 1 , i ; populateAndIncreaseCount ( count , str ) ; for ( i = 0 ; i < len ; ++ i ) { mul /= len - i ; rank += count [ str [ i ] - 1 ] * mul ; updatecount ( count , str [ i ] ) ; } return rank ; } int main ( ) { char str [ ] = " string " ; cout << findRank ( str ) ; return 0 ; } |
Print all permutations in sorted ( lexicographic ) order | C ++ Program to print all permutations of a string in sorted order . ; Following function is needed for library function qsort ( ) . Refer http : www . cplusplus . com / reference / clibrary / cstdlib / qsort / ; A utility function two swap two characters a and b ; This function finds the index of the smallest character which is greater than ' first ' and is present in str [ l . . h ] ; initialize index of ceiling element ; Now iterate through rest of the elements and find the smallest character greater than ' first ' ; Print all permutations of str in sorted order ; Get size of string ; Sort the string in increasing order ; Print permutations one by one ; print this permutation ; Find the rightmost character which is smaller than its next character . Let us call it ' first β char ' ; If there is no such character , all are sorted in decreasing order , means we just printed the last permutation and we are done . ; Find the ceil of ' first β char ' in right of first character . Ceil of a character is the smallest character greater than it ; Swap first and second characters ; Sort the string on right of ' first β char ' ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int compare ( const void * a , const void * b ) { return ( * ( char * ) a - * ( char * ) b ) ; } void swap ( char * a , char * b ) { char t = * a ; * a = * b ; * b = t ; } int findCeil ( char str [ ] , char first , int l , int h ) { int ceilIndex = l ; for ( int i = l + 1 ; i <= h ; i ++ ) if ( str [ i ] > first && str [ i ] < str [ ceilIndex ] ) ceilIndex = i ; return ceilIndex ; } void sortedPermutations ( char str [ ] ) { int size = strlen ( str ) ; qsort ( str , size , sizeof ( str [ 0 ] ) , compare ) ; bool isFinished = false ; while ( ! isFinished ) { cout << str << endl ; int i ; for ( i = size - 2 ; i >= 0 ; -- i ) if ( str [ i ] < str [ i + 1 ] ) break ; if ( i == -1 ) isFinished = true ; else { int ceilIndex = findCeil ( str , str [ i ] , i + 1 , size - 1 ) ; swap ( & str [ i ] , & str [ ceilIndex ] ) ; qsort ( str + i + 1 , size - i - 1 , sizeof ( str [ 0 ] ) , compare ) ; } } } int main ( ) { char str [ ] = " ABCD " ; sortedPermutations ( str ) ; return 0 ; } |
Print all permutations in sorted ( lexicographic ) order | ; An optimized version that uses reverse instead of sort for finding the next permutation A utility function to reverse a string str [ l . . h ] ; ; ; Print all permutations of str in sorted order ; Get size of string ; Sort the string in increasing order ; Print permutations one by one ; print this permutation ; Find the rightmost character which is smaller than its next character . Let us call it ' first β char ' ; If there is no such character , all are sorted in decreasing order , means we just printed the last permutation and we are done . ; Find the ceil of ' first β char ' in right of first character . Ceil of a character is the smallest character greater than it ; Swap first and second characters ; reverse the string on right of ' first β char ' | #include <bits/stdc++.h> NEW_LINE using namespace std ; void reverse ( char str [ ] , int l , int h ) { while ( l < h ) { swap ( & str [ l ] , & str [ h ] ) ; l ++ ; h -- ; } } void swap ( char * a , char * b ) { char t = * a ; * a = * b ; * b = t ; } int compare ( const void * a , const void * b ) { return ( * ( char * ) a - * ( char * ) b ) ; } int findCeil ( char str [ ] , char first , int l , int h ) { int ceilIndex = l ; for ( int i = l + 1 ; i <= h ; i ++ ) if ( str [ i ] > first && str [ i ] < str [ ceilIndex ] ) ceilIndex = i ; return ceilIndex ; } void sortedPermutations ( char str [ ] ) { int size = strlen ( str ) ; qsort ( str , size , sizeof ( str [ 0 ] ) , compare ) ; bool isFinished = false ; while ( ! isFinished ) { cout << str << endl ; int i ; for ( i = size - 2 ; i >= 0 ; -- i ) if ( str [ i ] < str [ i + 1 ] ) break ; if ( i == -1 ) isFinished = true ; else { int ceilIndex = findCeil ( str , str [ i ] , i + 1 , size - 1 ) ; swap ( & str [ i ] , & str [ ceilIndex ] ) ; reverse ( str , i + 1 , size - 1 ) ; } } } |
Efficient program to calculate e ^ x | C ++ Efficient program to calculate e raise to the power x ; Returns approximate value of e ^ x using sum of first n terms of Taylor Series ; initialize sum of series ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; float exponential ( int n , float x ) { float sum = 1.0f ; for ( int i = n - 1 ; i > 0 ; -- i ) sum = 1 + x * sum / i ; return sum ; } int main ( ) { int n = 10 ; float x = 1.0f ; cout << " e ^ x β = β " << fixed << setprecision ( 5 ) << exponential ( n , x ) ; return 0 ; } |
Measure one litre using two vessels and infinite water supply | Sample run of the Algo for V1 with capacity 3 and V2 with capacity 7 1. Fill V1 : V1 = 3 , V2 = 0 2. Transfer from V1 to V2 , and fill V1 : V1 = 3 , V2 = 3 2. Transfer from V1 to V2 , and fill V1 : V1 = 3 , V2 = 6 3. Transfer from V1 to V2 , and empty V2 : V1 = 2 , V2 = 0 4. Transfer from V1 to V2 , and fill V1 : V1 = 3 , V2 = 2 5. Transfer from V1 to V2 , and fill V1 : V1 = 3 , V2 = 5 6. Transfer from V1 to V2 , and empty V2 : V1 = 1 , V2 = 0 7. Stop as V1 now contains 1 litre . Note that V2 was made empty in steps 3 and 6 because it became full ; A utility function to get GCD of two numbers ; Class to represent a Vessel ; A vessel has capacity , and current amount of water in it ; Constructor : initializes capacity as given , and current as 0 ; The main function to fill one litre in this vessel . Capacity of V2 must be greater than this vessel and two capacities must be co - prime ; Fills vessel with given amount and returns the amount of water transferred to it . If the vessel becomes full , then the vessel is made empty . ; The main function to fill one litre in this vessel . Capacity of V2 must be greater than this vessel and two capacities must be coprime ; solution exists iff a and b are co - prime ; fill A ( smaller vessel ) ; Transfer water from V1 to V2 and reduce current of V1 by the amount equal to transferred water ; Finally , there will be 1 litre in vessel 1 ; Fills vessel with given amount and returns the amount of water transferred to it . If the vessel becomes full , then the vessel is made empty ; If the vessel can accommodate the given amount ; If the vessel cannot accommodate the given amount , then store the amount of water transferred ; Since the vessel becomes full , make the vessel empty so that it can be filled again ; Driver program to test above function ; a must be smaller than b ; Create two vessels of capacities a and b ; Get 1 litre in first vessel | #include <iostream> NEW_LINE using namespace std ; int gcd ( int a , int b ) { return b ? gcd ( b , a % b ) : a ; } class Vessel { int capacity , current ; public : Vessel ( int capacity ) { this -> capacity = capacity ; current = 0 ; } void makeOneLitre ( Vessel & V2 ) ; int transfer ( int amount ) ; } ; void Vessel :: makeOneLitre ( Vessel & V2 ) { if ( gcd ( capacity , V2 . capacity ) != 1 ) return ; while ( current != 1 ) { if ( current == 0 ) current = capacity ; cout << " Vessel β 1 : β " << current << " β Vessel β 2 : β " << V2 . current << endl ; current = current - V2 . transfer ( current ) ; } cout << " Vessel β 1 : β " << current << " β Vessel β 2 : β " << V2 . current << endl ; } int Vessel :: transfer ( int amount ) { if ( current + amount < capacity ) { current += amount ; return amount ; } int transferred = capacity - current ; current = 0 ; return transferred ; } int main ( ) { int a = 3 , b = 7 ; Vessel V1 ( a ) , V2 ( b ) ; V1 . makeOneLitre ( V2 ) ; return 0 ; } |
Random number generator in arbitrary probability distribution fashion | C ++ program to generate random numbers according to given frequency distribution ; Utility function to find ceiling of r in arr [ l . . h ] ; Same as mid = ( l + h ) / 2 ; The main function that returns a random number from arr [ ] according to distribution array defined by freq [ ] . n is size of arrays . ; Create and fill prefix array ; prefix [ n - 1 ] is sum of all frequencies . Generate a random number with value from 1 to this sum ; Find index of ceiling of r in prefix arrat ; Driver code ; Use a different seed value for every run . ; Let us generate 10 random numbers accroding to given distribution | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findCeil ( int arr [ ] , int r , int l , int h ) { int mid ; while ( l < h ) { mid = l + ( ( h - l ) >> 1 ) ; ( r > arr [ mid ] ) ? ( l = mid + 1 ) : ( h = mid ) ; } return ( arr [ l ] >= r ) ? l : -1 ; } int myRand ( int arr [ ] , int freq [ ] , int n ) { int prefix [ n ] , i ; prefix [ 0 ] = freq [ 0 ] ; for ( i = 1 ; i < n ; ++ i ) prefix [ i ] = prefix [ i - 1 ] + freq [ i ] ; int r = ( rand ( ) % prefix [ n - 1 ] ) + 1 ; int indexc = findCeil ( prefix , r , 0 , n - 1 ) ; return arr [ indexc ] ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int freq [ ] = { 10 , 5 , 20 , 100 } ; int i , n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; srand ( time ( NULL ) ) ; for ( i = 0 ; i < 5 ; i ++ ) cout << myRand ( arr , freq , n ) << endl ; return 0 ; } |
How to check if a given number is Fibonacci number ? | C ++ program to check if x is a perfect square ; A utility function that returns true if x is perfect square ; Returns true if n is a Fibinacci Number , else false ; n is Fibinacci if one of 5 * n * n + 4 or 5 * n * n - 4 or both is a perferct square ; A utility function to test above functions | #include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; bool isPerfectSquare ( int x ) { int s = sqrt ( x ) ; return ( s * s == x ) ; } bool isFibonacci ( int n ) { return isPerfectSquare ( 5 * n * n + 4 ) || isPerfectSquare ( 5 * n * n - 4 ) ; } int main ( ) { for ( int i = 1 ; i <= 10 ; i ++ ) isFibonacci ( i ) ? cout << i << " β is β a β Fibonacci β Number β STRNEWLINE " : cout << i << " β is β a β not β Fibonacci β Number β STRNEWLINE " ; return 0 ; } |
Count trailing zeroes in factorial of a number | C ++ program to count trailing 0 s in n ! ; Function to return trailing 0 s in factorial of n ; Initialize result ; Keep dividing n by powers of 5 and update count ; Driver Code | #include <iostream> NEW_LINE using namespace std ; int findTrailingZeros ( int n ) { int count = 0 ; for ( int i = 5 ; n / i >= 1 ; i *= 5 ) count += n / i ; return count ; } int main ( ) { int n = 100 ; cout << " Count β of β trailing β 0s β in β " << 100 << " ! β is β " << findTrailingZeros ( n ) ; return 0 ; } |
Program for nth Catalan Number | ; A recursive function to find nth catalan number ; Base case ; catalan ( n ) is sum of catalan ( i ) * catalan ( n - i - 1 ) ; Driver code | #include <iostream> NEW_LINE using namespace std ; unsigned long int catalan ( unsigned int n ) { if ( n <= 1 ) return 1 ; unsigned long int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) res += catalan ( i ) * catalan ( n - i - 1 ) ; return res ; } int main ( ) { for ( int i = 0 ; i < 10 ; i ++ ) cout << catalan ( i ) << " β " ; return 0 ; } |
Program for nth Catalan Number | A dynamic programming based function to find nth Catalan number ; Table to store results of subproblems ; Initialize first two values in table ; Fill entries in catalan [ ] using recursive formula ; Return last entry ; Driver code | #include <iostream> NEW_LINE using namespace std ; unsigned long int catalanDP ( unsigned int n ) { unsigned long int catalan [ n + 1 ] ; catalan [ 0 ] = catalan [ 1 ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { catalan [ i ] = 0 ; for ( int j = 0 ; j < i ; j ++ ) catalan [ i ] += catalan [ j ] * catalan [ i - j - 1 ] ; } return catalan [ n ] ; } int main ( ) { for ( int i = 0 ; i < 10 ; i ++ ) cout << catalanDP ( i ) << " β " ; return 0 ; } |
Program for nth Catalan Number | C ++ program for nth Catalan Number ; 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 ] ; A Binomial coefficient based function to find nth catalan number in O ( n ) time ; Calculate value of 2 nCn ; return 2 nCn / ( n + 1 ) ; Driver code | #include <iostream> NEW_LINE using namespace std ; unsigned long int binomialCoeff ( unsigned int n , unsigned int k ) { unsigned long 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 ; } unsigned long int catalan ( unsigned int n ) { unsigned long int c = binomialCoeff ( 2 * n , n ) ; return c / ( n + 1 ) ; } int main ( ) { for ( int i = 0 ; i < 10 ; i ++ ) cout << catalan ( i ) << " β " ; return 0 ; } |
Program for nth Catalan Number | ; Function to print the number ; For the first number C ( 0 ) ; Iterate till N ; Calculate the number and print it ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE #include <boost/multiprecision/cpp_int.hpp> NEW_LINE using boost :: multiprecision :: cpp_int ; using namespace std ; void catalan ( int n ) { cpp_int cat_ = 1 ; cout << cat_ << " β " ; for ( cpp_int i = 1 ; i < n ; i ++ ) { cat_ *= ( 4 * i - 2 ) ; cat_ /= ( i + 1 ) ; cout << cat_ << " β " ; } } int main ( ) { int n = 5 ; catalan ( n ) ; return 0 ; } |
Find Excel column name from a given column number | C ++ program to find Excel column name from a given column number ; Function to print Excel column name for a given column number ; To store current index in str which is result ; Find remainder ; If remainder is 0 , then a ' Z ' must be there in output ; If remainder is non - zero ; Reverse the string and print result ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE #define MAX 50 NEW_LINE using namespace std ; void printString ( int n ) { char str [ MAX ] ; int i = 0 ; while ( n > 0 ) { int rem = n % 26 ; if ( rem == 0 ) { str [ i ++ ] = ' Z ' ; n = ( n / 26 ) - 1 ; } else { str [ i ++ ] = ( rem - 1 ) + ' A ' ; n = n / 26 ; } } str [ i ] = ' \0' ; reverse ( str , str + strlen ( str ) ) ; cout << str << endl ; return ; } int main ( ) { printString ( 26 ) ; printString ( 51 ) ; printString ( 52 ) ; printString ( 80 ) ; printString ( 676 ) ; printString ( 702 ) ; printString ( 705 ) ; return 0 ; } |
Find Excel column name from a given column number | ; Step 1 : Converting to number assuming 0 in number system ; Step 2 : Getting rid of 0 , as 0 is not part of number system ; Driver program to test above function | #include <iostream> NEW_LINE using namespace std ; void printString ( int n ) { int arr [ 10000 ] ; int i = 0 ; while ( n ) { arr [ i ] = n % 26 ; n = n / 26 ; i ++ ; } for ( int j = 0 ; j < i - 1 ; j ++ ) { if ( arr [ j ] <= 0 ) { arr [ j ] += 26 ; arr [ j + 1 ] = arr [ j + 1 ] - 1 ; } } for ( int j = i ; j >= 0 ; j -- ) { if ( arr [ j ] > 0 ) cout << char ( ' A ' + arr [ j ] - 1 ) ; } cout << endl ; } int main ( ) { printString ( 26 ) ; printString ( 51 ) ; printString ( 52 ) ; printString ( 80 ) ; printString ( 676 ) ; printString ( 702 ) ; printString ( 705 ) ; return 0 ; } |
Calculate the angle between hour hand and minute hand | C ++ program to find angle between hour and minute hands ; Utility function to find minimum of two integers ; Function to calculate the angle ; validate the input ; Calculate the angles moved by hour and minute hands with reference to 12 : 00 ; Find the difference between two angles ; Return the smaller angle of two possible angles ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int min ( int x , int y ) { return ( x < y ) ? x : y ; } int calcAngle ( double h , double m ) { if ( h < 0 m < 0 h > 12 m > 60 ) printf ( " Wrong β input " ) ; if ( h == 12 ) h = 0 ; if ( m == 60 ) { m = 0 ; h += 1 ; if ( h > 12 ) h = h - 12 ; } float hour_angle = 0.5 * ( h * 60 + m ) ; float minute_angle = 6 * m ; float angle = abs ( hour_angle - minute_angle ) ; angle = min ( 360 - angle , angle ) ; return angle ; } int main ( ) { cout << calcAngle ( 9 , 60 ) << endl ; cout << calcAngle ( 3 , 30 ) << endl ; return 0 ; } |
How to check if an instance of 8 puzzle is solvable ? | C ++ program to check if a given instance of 8 puzzle is solvable or not ; A utility function to count inversions in given array ' arr [ ] ' ; Value 0 is used for empty space ; This function returns true if given 8 puzzle is solvable . ; Count inversions in given 8 puzzle ; return true if inversion count is even . ; Driver progra to test above functions | #include <iostream> NEW_LINE using namespace std ; int getInvCount ( int arr [ ] ) { int inv_count = 0 ; for ( int i = 0 ; i < 9 - 1 ; i ++ ) for ( int j = i + 1 ; j < 9 ; j ++ ) if ( arr [ j ] && arr [ i ] && arr [ i ] > arr [ j ] ) inv_count ++ ; return inv_count ; } bool isSolvable ( int puzzle [ 3 ] [ 3 ] ) { int invCount = getInvCount ( ( int * ) puzzle ) ; return ( invCount % 2 == 0 ) ; } int main ( int argv , char * * args ) { int puzzle [ 3 ] [ 3 ] = { { 1 , 8 , 2 } , { 0 , 4 , 3 } , { 7 , 6 , 5 } } ; isSolvable ( puzzle ) ? cout << " Solvable " : cout << " Not β Solvable " ; return 0 ; } |
Birthday Paradox | C ++ program to approximate number of people in Birthday Paradox problem ; Returns approximate number of people for a given probability ; Driver code | #include <cmath> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int find ( double p ) { return ceil ( sqrt ( 2 * 365 * log ( 1 / ( 1 - p ) ) ) ) ; } int main ( ) { cout << find ( 0.70 ) ; } |
Count Distinct Non | ; This function counts number of pairs ( x , y ) that satisfy the inequality x * x + y * y < n . ; Driver program to test above function | #include <iostream> NEW_LINE using namespace std ; int countSolutions ( int n ) { int res = 0 ; for ( int x = 0 ; x * x < n ; x ++ ) for ( int y = 0 ; x * x + y * y < n ; y ++ ) res ++ ; return res ; } int main ( ) { cout << " Total β Number β of β distinct β Non - Negative β pairs β is β " << countSolutions ( 6 ) << endl ; return 0 ; } |
Count Distinct Non | An efficient C program to find different ( x , y ) pairs that satisfy x * x + y * y < n . ; This function counts number of pairs ( x , y ) that satisfy the inequality x * x + y * y < n . ; Find the count of different y values for x = 0. ; One by one increase value of x , and find yCount for current x . If yCount becomes 0 , then we have reached maximum possible value of x . ; Add yCount ( count of different possible values of y for current x ) to result ; Increment x ; Update yCount for current x . Keep reducing yCount while the inequality is not satisfied . ; Driver program to test above function | #include <iostream> NEW_LINE using namespace std ; int countSolutions ( int n ) { int x = 0 , yCount , res = 0 ; for ( yCount = 0 ; yCount * yCount < n ; yCount ++ ) ; while ( yCount != 0 ) { res += yCount ; x ++ ; while ( yCount != 0 && ( x * x + ( yCount - 1 ) * ( yCount - 1 ) >= n ) ) yCount -- ; } return res ; } int main ( ) { cout << " Total β Number β of β distinct β Non - Negative β pairs β is β " << countSolutions ( 6 ) << endl ; return 0 ; } |
Program for Method Of False Position | C ++ program for implementation of Bisection Method for solving equations ; An example function whose solution is determined using Bisection Method . The function is x ^ 3 - x ^ 2 + 2 ; Prints root of func ( x ) in interval [ a , b ] ; Initialize result ; Find the point that touches x axis ; Check if the above found point is root ; Decide the side to repeat the steps ; Driver program to test above function ; Initial values assumed | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX_ITER 1000000 NEW_LINE double func ( double x ) { return x * x * x - x * x + 2 ; } void regulaFalsi ( double a , double b ) { if ( func ( a ) * func ( b ) >= 0 ) { cout << " You β have β not β assumed β right β a β and β b STRNEWLINE " ; return ; } double c = a ; for ( int i = 0 ; i < MAX_ITER ; i ++ ) { c = ( a * func ( b ) - b * func ( a ) ) / ( func ( b ) - func ( a ) ) ; if ( func ( c ) == 0 ) break ; else if ( func ( c ) * func ( a ) < 0 ) b = c ; else a = c ; } cout << " The β value β of β root β is β : β " << c ; } int main ( ) { double a = -200 , b = 300 ; regulaFalsi ( a , b ) ; return 0 ; } |
Program for Newton Raphson Method | C ++ program for implementation of Newton Raphson Method for solving equations ; An example function whose solution is determined using Bisection Method . The function is x ^ 3 - x ^ 2 + 2 ; Derivative of the above function which is 3 * x ^ x - 2 * x ; Function to find the root ; x ( i + 1 ) = x ( i ) - f ( x ) / f '(x) ; Driver program to test above ; Initial values assumed | #include <bits/stdc++.h> NEW_LINE #define EPSILON 0.001 NEW_LINE using namespace std ; double func ( double x ) { return x * x * x - x * x + 2 ; } double derivFunc ( double x ) { return 3 * x * x - 2 * x ; } void newtonRaphson ( double x ) { double h = func ( x ) / derivFunc ( x ) ; while ( abs ( h ) >= EPSILON ) { h = func ( x ) / derivFunc ( x ) ; x = x - h ; } cout << " The β value β of β the β root β is β : β " << x ; } int main ( ) { double x0 = -20 ; newtonRaphson ( x0 ) ; return 0 ; } |
Find the element that appears once | C ++ program to find the element that occur only once ; Method to find the element that occur only once ; The expression " one β & β arr [ i ] " gives the bits that are there in both ' ones ' and new element from arr [ ] . We add these bits to ' twos ' using bitwise OR Value of ' twos ' will be set as 0 , 3 , 3 and 1 after 1 st , 2 nd , 3 rd and 4 th iterations respectively ; XOR the new bits with previous ' ones ' to get all bits appearing odd number of times Value of ' ones ' will be set as 3 , 0 , 2 and 3 after 1 st , 2 nd , 3 rd and 4 th iterations respectively ; The common bits are those bits which appear third time So these bits should not be there in both ' ones ' and ' twos ' . common_bit_mask contains all these bits as 0 , so that the bits can be removed from ' ones ' and ' twos ' Value of ' common _ bit _ mask ' will be set as 00 , 00 , 01 and 10 after 1 st , 2 nd , 3 rd and 4 th iterations respectively ; Remove common bits ( the bits that appear third time ) from ' ones ' Value of ' ones ' will be set as 3 , 0 , 0 and 2 after 1 st , 2 nd , 3 rd and 4 th iterations respectively ; Remove common bits ( the bits that appear third time ) from ' twos ' Value of ' twos ' will be set as 0 , 3 , 1 and 0 after 1 st , 2 nd , 3 rd and 4 th itearations respectively ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getSingle ( int arr [ ] , int n ) { int ones = 0 , twos = 0 ; int common_bit_mask ; for ( int i = 0 ; i < n ; i ++ ) { twos = twos | ( ones & arr [ i ] ) ; ones = ones ^ arr [ i ] ; common_bit_mask = ~ ( ones & twos ) ; ones &= common_bit_mask ; twos &= common_bit_mask ; } return ones ; } int main ( ) { int arr [ ] = { 3 , 3 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " The β element β with β single β occurrence β is β " << getSingle ( arr , n ) ; return 0 ; } |
Find the element that appears once | C ++ program to find the element that occur only once ; Initialize result ; Iterate through every bit ; Find sum of set bits at ith position in all array elements ; The bits with sum not multiple of 3 , are the bits of element with single occurrence . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define INT_SIZE 32 NEW_LINE int getSingle ( int arr [ ] , int n ) { int result = 0 ; int x , sum ; for ( int i = 0 ; i < INT_SIZE ; i ++ ) { sum = 0 ; x = ( 1 << i ) ; for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ j ] & x ) sum ++ ; } if ( ( sum % 3 ) != 0 ) result |= x ; } return result ; } int main ( ) { int arr [ ] = { 12 , 1 , 12 , 3 , 12 , 1 , 1 , 2 , 3 , 2 , 2 , 3 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " The β element β with β single β occurrence β is β " << getSingle ( arr , n ) ; return 0 ; } |
Detect if two integers have opposite signs | C ++ Program to Detect if two integers have opposite signs . ; Function to detect signs ; Driver Code | #include <stdbool.h> NEW_LINE #include <stdio.h> NEW_LINE bool oppositeSigns ( int x , int y ) { return ( ( x ^ y ) < 0 ) ; } int main ( ) { int x = 100 , y = -100 ; if ( oppositeSigns ( x , y ) == true ) printf ( " Signs β are β opposite " ) ; else printf ( " Signs β are β not β opposite " ) ; return 0 ; } |
Count total set bits in all numbers from 1 to n | A simple program to count set bits in all numbers from 1 to n . ; A utility function to count set bits in a number x ; Returns count of set bits present in all numbers from 1 to n ; initialize the result ; A utility function to count set bits in a number x ; Driver program to test above functions | #include <stdio.h> NEW_LINE unsigned int countSetBitsUtil ( unsigned int x ) ; unsigned int countSetBits ( unsigned int n ) { int bitCount = 0 ; for ( int i = 1 ; i <= n ; i ++ ) bitCount += countSetBitsUtil ( i ) ; return bitCount ; } unsigned int countSetBitsUtil ( unsigned int x ) { if ( x <= 0 ) return 0 ; return ( x % 2 == 0 ? 0 : 1 ) + countSetBitsUtil ( x / 2 ) ; } int main ( ) { int n = 4 ; printf ( " Total β set β bit β count β is β % d " , countSetBits ( n ) ) ; return 0 ; } |
Count total set bits in all numbers from 1 to n | ; ans store sum of set bits from 0 to n ; while n greater than equal to 2 ^ i ; This k will get flipped after 2 ^ i iterations ; change is iterator from 2 ^ i to 1 ; This will loop from 0 to n for every bit position ; When change = 1 flip the bit ; again set change to 2 ^ i ; increment the position ; Main Function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSetBits ( int n ) { int i = 0 ; int ans = 0 ; while ( ( 1 << i ) <= n ) { bool k = 0 ; int change = 1 << i ; for ( int j = 0 ; j <= n ; j ++ ) { ans += k ; if ( change == 1 ) { k = ! k ; change = 1 << i ; } else { change -- ; } } i ++ ; } return ans ; } int main ( ) { int n = 17 ; cout << countSetBits ( n ) << endl ; return 0 ; } |
Count total set bits in all numbers from 1 to n | A O ( Logn ) complexity program to count set bits in all numbers from 1 to n ; Returns position of leftmost set bit . The rightmost position is considered as 0 ; Given the position of previous leftmost set bit in n ( or an upper bound onleftmost position ) returns the new position of leftmost set bit in n ; The main recursive function used by countSetBits ( ) ; Get the position of leftmost set bit in n . This will be used as an upper bound for next set bit function ; Use the position ; Base Case : if n is 0 , then set bit count is 0 ; get position of next leftmost set bit ; If n is of the form 2 ^ x - 1 , i . e . , if n is like 1 , 3 , 7 , 15 , 31 , . . etc , then we are done . Since positions are considered starting from 0 , 1 is added to m ; update n for next recursive call ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned int getLeftmostBit ( int n ) { int m = 0 ; while ( n > 1 ) { n = n >> 1 ; m ++ ; } return m ; } unsigned int getNextLeftmostBit ( int n , int m ) { unsigned int temp = 1 << m ; while ( n < temp ) { temp = temp >> 1 ; m -- ; } return m ; } unsigned int _countSetBits ( unsigned int n , int m ) ; unsigned int countSetBits ( unsigned int n ) { int m = getLeftmostBit ( n ) ; return _countSetBits ( n , m ) ; } unsigned int _countSetBits ( unsigned int n , int m ) { if ( n == 0 ) return 0 ; m = getNextLeftmostBit ( n , m ) ; if ( n == ( ( unsigned int ) 1 << ( m + 1 ) ) - 1 ) return ( unsigned int ) ( m + 1 ) * ( 1 << m ) ; n = n - ( 1 << m ) ; return ( n + 1 ) + countSetBits ( n ) + m * ( 1 << ( m - 1 ) ) ; } int main ( ) { int n = 17 ; cout << " Total β set β bit β count β is β " << countSetBits ( n ) ; return 0 ; } |
Count total set bits in all numbers from 1 to n | | int getSetBitsFromOneToN ( int N ) { int two = 2 , ans = 0 ; int n = N ; while ( n ) { ans += ( N / two ) * ( two >> 1 ) ; if ( ( N & ( two - 1 ) ) > ( two >> 1 ) - 1 ) ans += ( N & ( two - 1 ) ) - ( two >> 1 ) + 1 ; two <<= 1 ; n >>= 1 ; } return ans ; } |
Swap bits in a given number | C ++ Program to swap bits in a given number ; Move all bits of first set to rightmost side ; Move all bits of second set to rightmost side ; Xor the two sets ; Put the Xor bits back to their original positions ; Xor the ' Xor ' with the original number so that the two sets are swapped ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int swapBits ( unsigned int x , unsigned int p1 , unsigned int p2 , unsigned int n ) { unsigned int set1 = ( x >> p1 ) & ( ( 1U << n ) - 1 ) ; unsigned int set2 = ( x >> p2 ) & ( ( 1U << n ) - 1 ) ; unsigned int Xor = ( set1 ^ set2 ) ; Xor = ( Xor << p1 ) | ( Xor << p2 ) ; unsigned int result = x ^ Xor ; return result ; } int main ( ) { int res = swapBits ( 28 , 0 , 3 , 2 ) ; cout << " Result β = β " << res ; return 0 ; } |
Swap bits in a given number | ; Setting bit at p1 position to 1 ; Setting bit at p2 position to 1 ; value1 and value2 will have 0 if num at the respective positions - p1 and p2 is 0. ; check if value1 and value2 are different i . e . at one position bit is set and other it is not ; if bit at p1 position is set ; unset bit at p1 position ; set bit at p2 position ; if bit at p2 position is set ; set bit at p2 position ; unset bit at p2 position ; return final result ; Driver code | #include <iostream> NEW_LINE using namespace std ; int swapBits ( unsigned int num , unsigned int p1 , unsigned int p2 , unsigned int n ) { int shift1 , shift2 , value1 , value2 ; while ( n -- ) { shift1 = 1 << p1 ; shift2 = 1 << p2 ; value1 = ( ( num & shift1 ) ) ; value2 = ( ( num & shift2 ) ) ; if ( ( ! value1 && value2 ) || ( ! value2 && value1 ) ) { if ( value1 ) { num = num & ( ~ shift1 ) ; num = num | shift2 ; } else { num = num & ( ~ shift2 ) ; num = num | shift1 ; } } p1 ++ ; p2 ++ ; } return num ; } int main ( ) { int res = swapBits ( 28 , 0 , 3 , 2 ) ; cout << " Result β = β " << res ; return 0 ; } |
Smallest of three integers without comparison operators | C ++ program to find Smallest of three integers without comparison operators ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int smallest ( int x , int y , int z ) { int c = 0 ; while ( x && y && z ) { x -- ; y -- ; z -- ; c ++ ; } return c ; } int main ( ) { int x = 12 , y = 15 , z = 5 ; cout << " Minimum β of β 3 β numbers β is β " << smallest ( x , y , z ) ; return 0 ; } |
Smallest of three integers without comparison operators | C ++ implementation of above approach ; Function to find minimum of x and y ; Function to find minimum of 3 numbers x , y and z ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define CHAR_BIT 8 NEW_LINE int min ( int x , int y ) { return y + ( ( x - y ) & ( ( x - y ) >> ( sizeof ( int ) * CHAR_BIT - 1 ) ) ) ; } int smallest ( int x , int y , int z ) { return min ( x , min ( y , z ) ) ; } int main ( ) { int x = 12 , y = 15 , z = 5 ; cout << " Minimum β of β 3 β numbers β is β " << smallest ( x , y , z ) ; return 0 ; } |
Smallest of three integers without comparison operators | C ++ implementation of above approach ; Using division operator to find minimum of three numbers ; Same as " if β ( y β < β x ) " ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int smallest ( int x , int y , int z ) { if ( ! ( y / x ) ) return ( ! ( y / z ) ) ? y : z ; return ( ! ( x / z ) ) ? x : z ; } int main ( ) { int x = 78 , y = 88 , z = 68 ; cout << " Minimum β of β 3 β numbers β is β " << smallest ( x , y , z ) ; return 0 ; } |
A Boolean Array Puzzle | ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void changeToZero ( int a [ 2 ] ) { a [ a [ 1 ] ] = a [ ! a [ 1 ] ] ; } int main ( ) { int a [ ] = { 1 , 0 } ; changeToZero ( a ) ; cout << " arr [ 0 ] β = β " << a [ 0 ] << endl ; cout << " β arr [ 1 ] β = β " << a [ 1 ] ; return 0 ; } |
Program to count number of set bits in an ( big ) array | ; Size of array 64 K ; GROUP_A - When combined with META_LOOK_UP generates count for 4 x4 elements ; GROUP_B - When combined with META_LOOK_UP generates count for 4 x4x4 elements ; GROUP_C - When combined with META_LOOK_UP generates count for 4 x4x4x4 elements ; Provide appropriate letter to generate the table ; A static table will be much faster to access ; No shifting funda ( for better readability ) ; It is fine , bypass the type system ; Count set bits in individual bytes ; Driver program , generates table of random 64 K numbers ; Seed to the random - number generator ; Generate random numbers . | #include <bits/stdc++.h> NEW_LINE #include <time.h> NEW_LINE using namespace std ; #define SIZE (1 << 16) NEW_LINE #define GROUP_A ( x ) x, x + 1, x + 1, x + 2 NEW_LINE #define GROUP_B ( x ) GROUP_A(x), GROUP_A(x+1), GROUP_A(x+1), GROUP_A(x+2) NEW_LINE #define GROUP_C ( x ) GROUP_B(x), GROUP_B(x+1), GROUP_B(x+1), GROUP_B(x+2) NEW_LINE #define META_LOOK_UP ( PARAMETER ) \NEW_LINEGROUP_##PARAMETER(0),\NEW_LINEGROUP_##PARAMETER(1),\NEW_LINEGROUP_##PARAMETER(1),\NEW_LINEGROUP_##PARAMETER(2)\NEW_LINEint countSetBits(int array[], size_t array_size) NEW_LINE { int count = 0 ; static unsigned char const look_up [ ] = { META_LOOK_UP ( C ) } ; unsigned char * pData = NULL ; for ( size_t index = 0 ; index < array_size ; index ++ ) { pData = ( unsigned char * ) & array [ index ] ; count += look_up [ pData [ 0 ] ] ; count += look_up [ pData [ 1 ] ] ; count += look_up [ pData [ 2 ] ] ; count += look_up [ pData [ 3 ] ] ; } return count ; } int main ( ) { int index ; int random [ SIZE ] ; srand ( ( unsigned ) time ( 0 ) ) ; for ( index = 0 ; index < SIZE ; index ++ ) { random [ index ] = rand ( ) ; } cout << " Total β number β of β bits β = β " << countSetBits ( random , SIZE ) ; return 0 ; } |
Next higher number with same number of set bits | ; this function returns next higher number with same number of set bits as x . ; right most set bit ; reset the pattern and set next higher bit left part of x will be here ; nextHigherOneBit is now part [ D ] of the above explanation . isolate the pattern ; right adjust pattern ; correction factor ; rightOnesPattern is now part [ A ] of the above explanation . integrate new pattern ( Add [ D ] and [ A ] ) ; Driver code | #include <iostream> NEW_LINE using namespace std ; typedef unsigned int uint_t ; uint_t snoob ( uint_t x ) { uint_t rightOne ; uint_t nextHigherOneBit ; uint_t rightOnesPattern ; uint_t next = 0 ; if ( x ) { rightOne = x & - ( signed ) x ; nextHigherOneBit = x + rightOne ; rightOnesPattern = x ^ nextHigherOneBit ; rightOnesPattern = ( rightOnesPattern ) / rightOne ; rightOnesPattern >>= 2 ; next = nextHigherOneBit | rightOnesPattern ; } return next ; } int main ( ) { int x = 156 ; cout << " Next β higher β number β with β same β number β of β set β bits β is β " << snoob ( x ) ; getchar ( ) ; return 0 ; } |
Add 1 to a given number | C ++ code to add add one to a given number ; Flip all the set bits until we find a 0 ; flip the rightmost 0 bit ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; int addOne ( int x ) { int m = 1 ; while ( x & m ) { x = x ^ m ; m <<= 1 ; } x = x ^ m ; return x ; } int main ( ) { cout << addOne ( 13 ) ; return 0 ; } |
Add 1 to a given number | ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int addOne ( int x ) { return ( - ( ~ x ) ) ; } int main ( ) { cout << addOne ( 13 ) ; return 0 ; } |
Multiply a given Integer with 3.5 | C ++ program to multiply a number with 3.5 ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE int multiplyWith3Point5 ( int x ) { return ( x << 1 ) + x + ( x >> 1 ) ; } int main ( ) { int x = 4 ; printf ( " % d " , multiplyWith3Point5 ( x ) ) ; getchar ( ) ; return 0 ; } |
Multiply a given Integer with 3.5 | C ++ program for above approach ; Function to multiple number with 3.5 ; The 3.5 is 7 / 2 , so multiply by 7 ( x * 7 ) then divide the result by 2 ( result / 2 ) x * 7 -> 7 is 0111 so by doing mutiply by 7 it means we do 2 shifting for the number but since we doing multiply we need to take care of carry one . ; Then divide by 2 r / 2 ; Driver Code | #include <iostream> NEW_LINE using namespace std ; int multiplyWith3Point5 ( int x ) { int r = 0 ; int x1Shift = x << 1 ; int x2Shifts = x << 2 ; r = ( x ^ x1Shift ) ^ x2Shifts ; int c = ( x & x1Shift ) | ( x & x2Shifts ) | ( x1Shift & x2Shifts ) ; while ( c > 0 ) { c <<= 1 ; int t = r ; r ^= c ; c &= t ; } r = r >> 1 ; return r ; } int main ( ) { cout << ( multiplyWith3Point5 ( 5 ) ) ; return 0 ; } |
Turn off the rightmost set bit | ; unsets the rightmost set bit of n and returns the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int fun ( unsigned int n ) { return n & ( n - 1 ) ; } int main ( ) { int n = 7 ; cout << " The β number β after β unsetting β the " ; cout << " β rightmost β set β bit β " << fun ( n ) ; return 0 ; } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.