text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Minimum removal of subsequences of distinct consecutive characters required to empty a given string | C ++ program to implement the above approach ; Function to count minimum operations required to make the string an empty string ; Stores count of 1 s by removing consecutive distinct subsequence ; Stores count of 0 s by removing consecutive distinct subsequence ; Stores length of str ; Traverse the string ; If current character is 0 ; Update cntOne ; Update cntZero ; If current character is 1 ; Update cntZero ; Update cntOne ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinOperationsReqEmpStr ( string str ) { int cntOne = 0 ; int cntZero = 0 ; int N = str . length ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( str [ i ] == '0' ) { if ( cntOne ) { cntOne -- ; } cntZero ++ ; } else { if ( cntZero ) { cntZero -- ; } cntOne ++ ; } } return ( cntOne + cntZero ) ; } int main ( ) { string str = "0100100111" ; cout << findMinOperationsReqEmpStr ( str ) ; }
Minimum number of flips required such that the last cell of matrix can be reached from any other cell | C ++ program for the above approach ; Function to calculate the minimum number of flips required ; Dimensions of mat [ ] [ ] ; Initialize answer ; Count all ' D ' s in the last row ; Count all ' R ' s in the last column ; Print answer ; Driver Code ; Given matrix ; Function call ; Print answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countChanges ( vector < vector < char > > mat ) { int n = mat . size ( ) ; int m = mat [ 0 ] . size ( ) ; int ans = 0 ; for ( int j = 0 ; j < m - 1 ; j ++ ) { if ( mat [ n - 1 ] [ j ] != ' R ' ) ans ++ ; } for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( mat [ i ] [ m - 1 ] != ' D ' ) ans ++ ; } return ans ; } int main ( ) { vector < vector < char > > arr = { { ' R ' , ' R ' , ' R ' , ' D ' } , { ' D ' , ' D ' , ' D ' , ' R ' } , { ' R ' , ' D ' , ' R ' , ' F ' } } ; int cnt = countChanges ( arr ) ; cout << cnt << endl ; return 0 ; }
Check if a binary tree is sorted level | CPP program to determine whether binary tree is level sorted or not . ; Structure of a tree node . ; Function to create new tree node . ; Function to determine if given binary tree is level sorted or not . ; to store maximum value of previous level . ; to store minimum value of current level . ; to store maximum value of current level . ; to store number of nodes in current level . ; queue to perform level order traversal . ; find number of nodes in current level . ; traverse current level and find minimum and maximum value of this level . ; if minimum value of this level is not greater than maximum value of previous level then given tree is not level sorted . ; maximum value of this level is previous maximum value for next level . ; Driver program ; 1 / 4 \ 6 / \ 8 9 / \ 12 10
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; Node * left , * right ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return temp ; } int isSorted ( Node * root ) { int prevMax = INT_MIN ; int minval ; int maxval ; int levelSize ; queue < Node * > q ; q . push ( root ) ; while ( ! q . empty ( ) ) { levelSize = q . size ( ) ; minval = INT_MAX ; maxval = INT_MIN ; while ( levelSize > 0 ) { root = q . front ( ) ; q . pop ( ) ; levelSize -- ; minval = min ( minval , root -> key ) ; maxval = max ( maxval , root -> key ) ; if ( root -> left ) q . push ( root -> left ) ; if ( root -> right ) q . push ( root -> right ) ; } if ( minval <= prevMax ) return 0 ; prevMax = maxval ; } return 1 ; } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 6 ) ; root -> left -> right -> left = newNode ( 8 ) ; root -> left -> right -> right = newNode ( 9 ) ; root -> left -> right -> left -> left = newNode ( 12 ) ; root -> left -> right -> right -> right = newNode ( 10 ) ; if ( isSorted ( root ) ) cout << " Sorted " ; else cout << " Not ▁ sorted " ; return 0 ; }
Smallest subsequence having GCD equal to GCD of given array | C ++ program to implement the above approach ; Function to print the smallest subsequence that satisfies the condition ; Stores gcd of the array . ; Traverse the given array ; Update gcdArr ; Traverse the given array . ; If current element equal to gcd of array . ; Generate all possible pairs . ; If gcd of current pair equal to gcdArr ; Print current pair of the array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printSmallSub ( int arr [ ] , int N ) { int gcdArr = 0 ; for ( int i = 0 ; i < N ; i ++ ) { gcdArr = __gcd ( gcdArr , arr [ i ] ) ; } for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == gcdArr ) { cout << arr [ i ] << " ▁ " ; return ; } } for ( int i = 0 ; i < N ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { if ( __gcd ( arr [ i ] , arr [ j ] ) == gcdArr ) { cout << arr [ i ] << " ▁ " << arr [ j ] ; return ; } } } } int main ( ) { int arr [ ] = { 4 , 6 , 12 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printSmallSub ( arr , N ) ; }
Count pairs in an array whose product is composite number | C ++ program to implement the above approach ; Function to get all the prime numbers in the range [ 1 , X ] ; Stores the boolean value to check if a number is prime or not ; Mark all non prime numbers as false ; If i is prime number ; Mark j as a composite number ; Function to get the count of pairs whose product is a composite number ; Stores the boolean value to check if a number is prime or not ; Stores the count of 1 s ; Stores the count of prime numbers ; Traverse the given array . ; Stores count of pairs whose product is not a composite number ; Stores the count of pairs whose product is composite number ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define X 1000000 NEW_LINE vector < bool > getPrimeNum ( ) { vector < bool > isPrime ( X , true ) ; isPrime [ 0 ] = false ; isPrime [ 1 ] = false ; for ( int i = 2 ; i * i <= X ; i ++ ) { if ( isPrime [ i ] == true ) { for ( int j = i * i ; j < X ; j += i ) { isPrime [ j ] = false ; } } } return isPrime ; } int cntPairs ( int arr [ ] , int N ) { vector < bool > isPrime = getPrimeNum ( ) ; int cntOne = 0 ; int cntPrime = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == 1 ) { cntOne += 1 ; } else if ( isPrime [ i ] ) { cntPrime += 1 ; } } int cntNonComp = 0 ; cntNonComp = cntPrime * cntOne + cntOne * ( cntOne - 1 ) / 2 ; int res = 0 ; res = N * ( N - 1 ) / 2 - cntNonComp ; return res ; } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 2 , 8 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << cntPairs ( arr , N ) ; }
Find the greater number closest to N having at most one non | C ++ program to implement the above approach ; Function to calculate X ^ n in log ( n ) ; Stores the value of X ^ n ; If N is odd ; Function to find the closest number > N having at most 1 non - zero digit ; Stores the count of digits in N ; Stores the power of 10 ^ ( n - 1 ) ; Stores the last ( n - 1 ) digits ; Store the answer ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int power ( int X , int n ) { int res = 1 ; while ( n ) { if ( n & 1 ) res = res * X ; X = X * X ; n = n >> 1 ; } return res ; } int closestgtNum ( int N ) { int n = log10 ( N ) + 1 ; int P = power ( 10 , n - 1 ) ; int Y = N % P ; int res = N + ( P - Y ) ; return res ; } int main ( ) { int N = 120 ; cout << closestgtNum ( N ) ; }
Rearrange an array to make similar indexed elements different from that of another array | C ++ program for the above approach ; Function to find the arrangement of array B [ ] such that element at each index of A [ ] and B [ ] are not equal ; Print not possible , if arrays only have single equal element ; Reverse array B ; Traverse over arrays to check if there is any index where A [ i ] and B [ i ] are equal ; Swap B [ i ] with B [ i - 1 ] ; Break the loop ; Print required arrangement of array B ; Driver Code ; Given arrays A [ ] and B [ ] ; Length of array A [ ] ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void RearrangeB ( int A [ ] , vector < int > B , int n ) { if ( n == 1 && A [ 0 ] == B [ 0 ] ) { cout << " - 1" << endl ; return ; } for ( int i = 0 ; i < n / 2 ; i ++ ) { int t = B [ i ] ; B [ i ] = B [ n - i - 1 ] ; B [ n - i - 1 ] = t ; } for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( B [ i ] == A [ i ] ) { int t = B [ i + 1 ] ; B [ i + 1 ] = B [ i ] ; B [ i ] = t ; break ; } } for ( int k : B ) cout << k << " ▁ " ; } int main ( ) { int A [ ] = { 2 , 4 , 5 , 8 } ; vector < int > B = { 2 , 4 , 5 , 8 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; RearrangeB ( A , B , n ) ; }
Swap the elements between any two given quadrants of a Matrix | C ++ program for the above approach ; Function to iterate over the X quadrant and swap its element with Y quadrant ; Iterate over X quadrant ; Swap operations ; Function to swap the elements of the two given quadrants ; For Swapping 1 st and 2 nd Quadrant ; For Swapping 1 st and 3 rd Quadrant ; For Swapping 1 st and 4 th Quadrant ; For Swapping 2 nd and 3 rd Quadrant ; For Swapping 2 nd and 4 th Quadrant ; For Swapping 3 rd and 4 th Quadrant ; Print the resultant matrix ; Function to print the matrix ; Iterate over the rows ; Iterate over the cols ; Driver Code ; Given matrix ; Given quadrants ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 6 NEW_LINE #define M 6 NEW_LINE void swap ( int mat [ N ] [ M ] , int startx_X , int starty_X , int startx_Y , int starty_Y ) { int row = 0 ; int col = 0 ; for ( int i = startx_X ; ; i ++ ) { col = 0 ; for ( int j = startx_X ; ; j ++ ) { int temp = mat [ i ] [ j ] ; mat [ i ] [ j ] = mat [ startx_Y + row ] [ starty_Y + col ] ; mat [ startx_Y + row ] [ starty_Y + col ] = temp ; col ++ ; if ( col >= M / 2 ) break ; } row ++ ; if ( row >= N / 2 ) break ; } } static void swapQuadOfMatrix ( int mat [ N ] [ M ] , int X , int Y ) { if ( X == 1 && Y == 2 ) { swap ( mat , 0 , 0 , 0 , M / 2 ) ; } else if ( X == 1 && Y == 3 ) { swap ( mat , 0 , 0 , N / 2 , 0 ) ; } else if ( X == 1 && Y == 4 ) { swap ( mat , 0 , 0 , N / 2 , M / 2 ) ; } else if ( X == 2 && Y == 3 ) { swap ( mat , 0 , M / 2 , N / 2 , 0 ) ; } else if ( X == 2 && Y == 4 ) { swap ( mat , 0 , M / 2 , N / 2 , M / 2 ) ; } else if ( X == 3 && Y == 4 ) { swap ( mat , N / 2 , 0 , N / 2 , M / 2 ) ; } printMat ( mat ) ; } void printMat ( int mat [ N ] [ M ] ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { cout << mat [ i ] [ j ] << " ▁ " ; } cout << endl ; } } int main ( ) { int mat [ ] [ M ] = { { 1 , 2 , 3 , 4 , 5 , 6 } , { 7 , 8 , 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 16 , 17 , 18 } , { 19 , 20 , 21 , 22 , 23 , 24 } , { 25 , 26 , 27 , 28 , 29 , 30 } , { 31 , 32 , 33 , 34 , 35 , 36 } } ; int X = 1 , Y = 4 ; swapQuadOfMatrix ( mat , X , Y ) ; }
Bottom View of a Binary Tree | C ++ Program to print Bottom View of Binary Tree ; Tree node class ; data of the node ; horizontal distance of the node ; left and right references ; Constructor of tree node ; Method that prints the bottom view . ; Initialize a variable ' hd ' with 0 for the root element . ; TreeMap which stores key value pair sorted on key value ; Queue to store tree nodes in level order traversal ; Assign initialized horizontal distance value to root node and add it to the queue . ; In STL , push ( ) is used enqueue an item ; Loop until the queue is empty ( standard level order loop ) ; In STL , pop ( ) is used dequeue an item ; Extract the horizontal distance value from the dequeued tree node . ; Put the dequeued tree node to TreeMap having key as horizontal distance . Every time we find a node having same horizontal distance we need to replace the data in the map . ; If the dequeued node has a left child , add it to the queue with a horizontal distance hd - 1. ; If the dequeued node has a right child , add it to the queue with a horizontal distance hd + 1. ; Traverse the map elements using the iterator . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; int hd ; Node * left , * right ; Node ( int key ) { data = key ; hd = INT_MAX ; left = right = NULL ; } } ; void bottomView ( Node * root ) { if ( root == NULL ) return ; int hd = 0 ; map < int , int > m ; queue < Node * > q ; root -> hd = hd ; q . push ( root ) ; while ( ! q . empty ( ) ) { Node * temp = q . front ( ) ; q . pop ( ) ; hd = temp -> hd ; m [ hd ] = temp -> data ; if ( temp -> left != NULL ) { temp -> left -> hd = hd - 1 ; q . push ( temp -> left ) ; } if ( temp -> right != NULL ) { temp -> right -> hd = hd + 1 ; q . push ( temp -> right ) ; } } for ( auto i = m . begin ( ) ; i != m . end ( ) ; ++ i ) cout << i -> second << " ▁ " ; } int main ( ) { Node * root = new Node ( 20 ) ; root -> left = new Node ( 8 ) ; root -> right = new Node ( 22 ) ; root -> left -> left = new Node ( 5 ) ; root -> left -> right = new Node ( 3 ) ; root -> right -> left = new Node ( 4 ) ; root -> right -> right = new Node ( 25 ) ; root -> left -> right -> left = new Node ( 10 ) ; root -> left -> right -> right = new Node ( 14 ) ; cout << " Bottom ▁ view ▁ of ▁ the ▁ given ▁ binary ▁ tree ▁ : STRNEWLINE " ; bottomView ( root ) ; return 0 ; }
Minimum increments by index value required to obtain at least two equal Array elements | C ++ Program to implement the above approach ; Function to calculate the minimum number of steps required ; Stores minimum difference ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void incrementCount ( int arr [ ] , int N ) { int mini = arr [ 0 ] - arr [ 1 ] ; for ( int i = 2 ; i < N ; i ++ ) { mini = min ( mini , arr [ i - 1 ] - arr [ i ] ) ; } cout << mini ; } int main ( ) { int N = 3 ; int arr [ N ] = { 12 , 8 , 4 } ; incrementCount ( arr , N ) ; return 0 ; }
Minimum operations required to convert all characters of a String to a given Character | C ++ program to implement the above approach ; Function to find the minimum number of operations required ; Maximum number of characters that can be changed in one operation ; If length of the string less than maximum number of characters that can be changed in an operation ; Set the last index as the index for the operation ; Otherwise ; If size of the string is equal to the maximum number of characters in an operation ; Find the number of operations required ; Find the starting position ; Print i - th index ; Shift to next index ; Otherwise ; Find the number of operations required ; If n % div exceeds k ; Print i - th index ; Shift to next index ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countOperations ( int n , int k ) { int div = 2 * k + 1 ; if ( n / 2 <= k ) { cout << 1 << " STRNEWLINE " ; if ( n > k ) cout << k + 1 ; else cout << n ; } else { if ( n % div == 0 ) { int oprn = n / div ; cout << oprn << " STRNEWLINE " ; int pos = k + 1 ; cout << pos << " ▁ " ; for ( int i = 1 ; i <= oprn ; i ++ ) { cout << pos << " ▁ " ; pos += div ; } } else { int oprn = n / div + 1 ; cout << oprn << " STRNEWLINE " ; int pos = n % div ; if ( n % div > k ) pos -= k ; for ( int i = 1 ; i <= oprn ; i ++ ) { cout << pos << " ▁ " ; pos += div ; } } } } int main ( ) { string str = " edfreqwsazxet " ; char ch = ' $ ' ; int n = str . size ( ) ; int k = 4 ; countOperations ( n , k ) ; return 0 ; }
Length of largest subsequence consisting of a pair of alternating digits | C ++ program for the above approach ; Function to find the length of the largest subsequence consisting of a pair of alternating digits ; Variable initialization ; Nested loops for iteration ; Check if i is not equal to j ; Initialize length as 0 ; Iterate from 0 till the size of the string ; Increment length ; Increment length ; Update maxi ; Check if maxi is not equal to 1 the print it otherwise print 0 ; Driver Code ; Given string ; Function call
#include <iostream> NEW_LINE using namespace std ; void largestSubsequence ( string s ) { int maxi = 0 ; char prev1 ; for ( int i = 0 ; i < 10 ; i ++ ) { for ( int j = 0 ; j < 10 ; j ++ ) { if ( i != j ) { int len = 0 ; prev1 = j + '0' ; for ( int k = 0 ; k < s . size ( ) ; k ++ ) { if ( s [ k ] == i + '0' && prev1 == j + '0' ) { prev1 = s [ k ] ; len ++ ; } else if ( s [ k ] == j + '0' && prev1 == i + '0' ) { prev1 = s [ k ] ; len ++ ; } } maxi = max ( len , maxi ) ; } } } if ( maxi != 1 ) cout << maxi << endl ; else cout << 0 << endl ; } int main ( ) { string s = "1542745249842" ; largestSubsequence ( s ) ; return 0 ; }
Bottom View of a Binary Tree | C ++ Program to print Bottom View of Binary Tree ; Tree node class ; data of the node ; horizontal distance of the node ; left and right references ; Constructor of tree node ; printBottomViewUtil function ; Base case ; If node for a particular horizontal distance is not present , add to the map . ; Compare height for already present node at similar horizontal distance ; Recur for left subtree ; Recur for right subtree ; printBottomView function ; Map to store Horizontal Distance , Height and Data . ; Prints the values stored by printBottomViewUtil ( ) ; Driver Code
#include <bits/stdc++.h> NEW_LINE #include <map> NEW_LINE using namespace std ; struct Node { int data ; int hd ; Node * left , * right ; Node ( int key ) { data = key ; hd = INT_MAX ; left = right = NULL ; } } ; void printBottomViewUtil ( Node * root , int curr , int hd , map < int , pair < int , int > > & m ) { if ( root == NULL ) return ; if ( m . find ( hd ) == m . end ( ) ) { m [ hd ] = make_pair ( root -> data , curr ) ; } else { pair < int , int > p = m [ hd ] ; if ( p . second <= curr ) { m [ hd ] . second = curr ; m [ hd ] . first = root -> data ; } } printBottomViewUtil ( root -> left , curr + 1 , hd - 1 , m ) ; printBottomViewUtil ( root -> right , curr + 1 , hd + 1 , m ) ; } void printBottomView ( Node * root ) { map < int , pair < int , int > > m ; printBottomViewUtil ( root , 0 , 0 , m ) ; map < int , pair < int , int > > :: iterator it ; for ( it = m . begin ( ) ; it != m . end ( ) ; ++ it ) { pair < int , int > p = it -> second ; cout << p . first << " ▁ " ; } } int main ( ) { Node * root = new Node ( 20 ) ; root -> left = new Node ( 8 ) ; root -> right = new Node ( 22 ) ; root -> left -> left = new Node ( 5 ) ; root -> left -> right = new Node ( 3 ) ; root -> right -> left = new Node ( 4 ) ; root -> right -> right = new Node ( 25 ) ; root -> left -> right -> left = new Node ( 10 ) ; root -> left -> right -> right = new Node ( 14 ) ; cout << " Bottom ▁ view ▁ of ▁ the ▁ given ▁ binary ▁ tree ▁ : STRNEWLINE " ; printBottomView ( root ) ; return 0 ; }
Find maximum GCD value from root to leaf in a Binary tree | C ++ program for the above approach ; Initialise to update the maximum gcd value from all the path ; Node structure ; Left & right child of the node ; Initialize constructor ; Function to find gcd of a and b ; function to find the gcd of a path ; Function to find the maximum value of gcd from root to leaf in a Binary tree ; Check if root is not null ; Find the maximum gcd of path value and store in global maxm variable ; Traverse left of binary tree ; Traverse right of the binary tree ; Driver Code ; Given Tree ; Function Call ; Print the maximum AND value
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxm = 0 ; struct Node { int val ; Node * left , * right ; Node ( int x ) { val = x ; left = NULL ; right = NULL ; } } ; int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } int find_gcd ( vector < int > arr ) { if ( arr . size ( ) == 1 ) return arr [ 0 ] ; int g = arr [ 0 ] ; for ( int i = 1 ; i < arr . size ( ) ; i ++ ) { g = gcd ( g , arr [ i ] ) ; } return g ; } void maxm_gcd ( Node * root , vector < int > ans ) { if ( ! root ) return ; if ( root -> left == NULL and root -> right == NULL ) { ans . push_back ( root -> val ) ; maxm = max ( find_gcd ( ans ) , maxm ) ; return ; } ans . push_back ( root -> val ) ; maxm_gcd ( root -> left , ans ) ; maxm_gcd ( root -> right , ans ) ; } int main ( ) { Node * root = new Node ( 15 ) ; root -> left = new Node ( 3 ) ; root -> right = new Node ( 7 ) ; root -> left -> left = new Node ( 15 ) ; root -> left -> right = new Node ( 1 ) ; root -> right -> left = new Node ( 31 ) ; root -> right -> right = new Node ( 9 ) ; maxm_gcd ( root , { } ) ; cout << maxm << endl ; return 0 ; }
Count of pairs with sum N from first N natural numbers | C ++ Program to implement the above approach ; Function to calculate the value of count ; Stores the count of pairs ; Set the two pointers ; Check if the sum of pairs is equal to N ; Increase the count of pairs ; Move to the next pair ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int numberOfPairs ( int n ) { int count = 0 ; int i = 1 , j = n - 1 ; while ( i < j ) { if ( i + j == n ) { count ++ ; } i ++ ; j -- ; } return count ; } int main ( ) { int n = 8 ; cout << numberOfPairs ( n ) ; return 0 ; }
Count of ways to generate a Matrix with product of each row and column as 1 or | C ++ implementation of the above approach ; Function to return the number of possible ways ; Check if product can be - 1 ; Driver Code
#include using namespace std ; void Solve ( int N , int M ) { int temp = ( N - 1 ) * ( M - 1 ) ; int ans = pow ( 2 , temp ) ; if ( ( N + M ) % 2 != 0 ) cout << ans ; else cout << 2 * ans ; cout << endl ; } int main ( ) { int N = 3 ; int M = 3 ; Solve ( N , M ) ; return 0 ; }
Maximum number of bridges in a path of a given graph | C ++ program to find the maximum number of bridges in any path of the given graph ; Stores the nodes and their connections ; Store the tree with Bridges as the edges ; Stores the visited nodes ; for finding bridges ; for Disjoint Set Union ; for storing actual bridges ; Stores the number of nodes and edges ; For finding bridges ; Function to find root of the component in which A lies ; Doing path compression ; Function to do union between a and b ; If both are already in the same component ; If both have same rank , then increase anyone 's rank ; Function to find bridges ; Initialize in time and low value ; Update the low value of the parent ; Perform DFS on its child updating low if the child has connection with any ancestor ; Bridge found ; Otherwise ; Find union between parent and child as they are in same component ; Function to find diameter of the tree for storing max two depth child ; Finding max two depth from its children ; Update diameter with the sum of max two depths ; Return the maximum depth ; Function to find maximum bridges bwtween any two nodes ; DFS to find bridges ; If no bridges are found ; Iterate over all bridges ; Find the endpoints ; Generate the tree with bridges as the edges ; Update the head ; Return the diameter ; Driver Code ; Graph = > 1 -- -- 2 -- -- 3 -- -- 4 | | 5 -- -- 6
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 1e5 + 5 ; vector < vector < int > > v ( N ) ; vector < vector < int > > g ( N ) ; vector < bool > vis ( N , 0 ) ; vector < int > in ( N ) , low ( N ) ; vector < int > parent ( N ) , rnk ( N ) ; vector < pair < int , int > > bridges ; int n , m ; int timer = 0 ; int find_set ( int a ) { if ( parent [ a ] == a ) return a ; return parent [ a ] = find_set ( parent [ a ] ) ; } void union_set ( int a , int b ) { int x = find_set ( a ) , y = find_set ( b ) ; if ( x == y ) return ; if ( rnk [ x ] == rnk [ y ] ) rnk [ x ] ++ ; if ( rnk [ y ] > rnk [ x ] ) swap ( x , y ) ; parent [ y ] = x ; } void dfsBridges ( int a , int par ) { vis [ a ] = 1 ; in [ a ] = low [ a ] = timer ++ ; for ( int i v [ a ] ) { if ( i == par ) continue ; if ( vis [ i ] ) low [ a ] = min ( low [ a ] , in [ i ] ) ; else { dfsBridges ( i , a ) ; low [ a ] = min ( low [ a ] , low [ i ] ) ; if ( in [ a ] < low [ i ] ) bridges . push_back ( make_pair ( i , a ) ) ; else union_set ( i , a ) ; } } } int dfsDiameter ( int a , int par , int & diameter ) { int x = 0 , y = 0 ; for ( int i g [ a ] ) { if ( i == par ) continue ; int mx = dfsDiameter ( i , a , diameter ) ; if ( mx > x ) { y = x ; x = mx ; } else if ( mx > y ) y = mx ; } diameter = max ( diameter , x + y ) ; return x + 1 ; } int findMaxBridges ( ) { for ( int i = 0 ; i <= n ; i ++ ) { parent [ i ] = i ; rnk [ i ] = 1 ; } dfsBridges ( 1 , 0 ) ; if ( bridges . empty ( ) ) return 0 ; int head = -1 ; for ( auto & i bridges ) { int a = find_set ( i . first ) ; int b = find_set ( i . second ) ; g [ a ] . push_back ( b ) ; g [ b ] . push_back ( a ) ; head = a ; } int diameter = 0 ; dfsDiameter ( head , 0 , diameter ) ; return diameter ; } int main ( ) { n = 6 , m = 6 ; v [ 1 ] . push_back ( 2 ) ; v [ 2 ] . push_back ( 1 ) ; v [ 2 ] . push_back ( 3 ) ; v [ 3 ] . push_back ( 2 ) ; v [ 2 ] . push_back ( 5 ) ; v [ 5 ] . push_back ( 2 ) ; v [ 5 ] . push_back ( 6 ) ; v [ 6 ] . push_back ( 5 ) ; v [ 6 ] . push_back ( 3 ) ; v [ 3 ] . push_back ( 6 ) ; v [ 3 ] . push_back ( 4 ) ; v [ 4 ] . push_back ( 4 ) ; int ans = findMaxBridges ( ) ; cout << ans << endl ; return 0 ; }
Program to count leaf nodes in a binary tree | C ++ implementation to find leaf count of a given Binary tree ; A binary tree node has data , pointer to left child and a pointer to right child ; Function to get the count of leaf nodes in a binary tree ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver code ; create a tree ; get leaf count of the above created tree
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int data ; struct node * left ; struct node * right ; } ; unsigned int getLeafCount ( struct node * node ) { if ( node == NULL ) return 0 ; if ( node -> left == NULL && node -> right == NULL ) return 1 ; else return getLeafCount ( node -> left ) + getLeafCount ( node -> right ) ; } struct node * newNode ( int data ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; return ( node ) ; } int main ( ) { struct node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; cout << " Leaf ▁ count ▁ of ▁ the ▁ tree ▁ is ▁ : ▁ " << getLeafCount ( root ) << endl ; return 0 ; }
Make a palindromic string from given string | C ++ Implementation to find which player can form a palindromic string first in a game ; Function to find winner of the game ; Array to Maintain frequency of the characters in S ; Initialise freq array with 0 ; Maintain count of all distinct characters ; Finding frequency of each character ; Count unique duplicate characters ; Loop to count the unique duplicate characters ; Condition for Player - 1 to be winner ; Else Player - 2 is always winner ; Driven Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int palindromeWinner ( string & S ) { int freq [ 26 ] ; memset ( freq , 0 , sizeof freq ) ; int count = 0 ; for ( int i = 0 ; i < ( int ) S . length ( ) ; ++ i ) { if ( freq [ S [ i ] - ' a ' ] == 0 ) count ++ ; freq [ S [ i ] - ' a ' ] ++ ; } int unique = 0 ; int duplicate = 0 ; for ( int i = 0 ; i < 26 ; ++ i ) { if ( freq [ i ] == 1 ) unique ++ ; else if ( freq [ i ] >= 2 ) duplicate ++ ; } if ( unique == 1 && ( unique + duplicate ) == count ) return 1 ; return 2 ; } int main ( ) { string S = " abcbc " ; cout << " Player - " << palindromeWinner ( S ) << endl ; return 0 ; }
Number of substrings with length divisible by the number of 1 's in it | C ++ program to count number of substring under given condition ; Function return count of such substring ; Selection of adequate x value ; Store where 1 's are located ; If there are no ones , then answer is 0 ; For ease of implementation ; Count storage ; Iterate on all k values less than fixed x ; Keeps a count of 1 's occured during string traversal ; Iterate on string and modify the totCount ; If this character is 1 ; Add to the final sum / count ; Increase totCount at exterior position ; Reduce totCount at index + k * n ; Slightly modified prefix sum storage ; Number of 1 's till i-1 ; Traversing over string considering each position and finding bounds and count using the inequalities ; Calculating bounds for l and r ; If valid then add to answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countOfSubstrings ( string s ) { int n = s . length ( ) ; int x = sqrt ( n ) ; vector < int > ones ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == '1' ) ones . push_back ( i ) ; } if ( ones . size ( ) == 0 ) return 0 ; ones . push_back ( n ) ; vector < int > totCount ( n * x + n ) ; int sum = 0 ; for ( int k = 0 ; k <= x ; k ++ ) { int now = 0 ; totCount [ k * n ] ++ ; for ( int j = 1 ; j <= n ; j ++ ) { if ( s [ j - 1 ] == '1' ) now ++ ; int index = j - k * now ; sum += totCount [ index + k * n ] ; totCount [ index + k * n ] ++ ; } now = 0 ; totCount [ k * n ] -- ; for ( int j = 1 ; j <= n ; j ++ ) { if ( s [ j - 1 ] == '1' ) now ++ ; int index = j - k * now ; totCount [ index + k * n ] -- ; } } int prefix_sum [ n ] ; memset ( prefix_sum , -1 , sizeof ( prefix_sum ) ) ; int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { prefix_sum [ i ] = cnt ; if ( s [ i ] == '1' ) cnt ++ ; } for ( int k = 0 ; k < n ; k ++ ) { for ( int j = 1 ; j <= ( n / x ) && prefix_sum [ k ] + j <= cnt ; j ++ ) { int l = ones [ prefix_sum [ k ] + j - 1 ] - k + 1 ; int r = ones [ prefix_sum [ k ] + j ] - k ; l = max ( l , j * ( x + 1 ) ) ; if ( l <= r ) { sum += r / j - ( l - 1 ) / j ; } } } return sum ; } int main ( ) { string S = "1111100000" ; cout << countOfSubstrings ( S ) ; return 0 ; }
Find the largest number smaller than integer N with maximum number of set bits | C ++ implementation to Find the largest number smaller than integer N with maximum number of set bits ; Function to return the largest number less than N ; Iterate through all the numbers ; Find the number of set bits for the current number ; Check if this number has the highest set bits ; Return the result ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int largestNum ( int n ) { int num = 0 ; int max_setBits = 0 ; for ( int i = 0 ; i <= n ; i ++ ) { int setBits = __builtin_popcount ( i ) ; if ( setBits >= max_setBits ) { num = i ; max_setBits = setBits ; } } return num ; } int main ( ) { int N = 345 ; cout << largestNum ( N ) ; return 0 ; }
Iterative program to count leaf nodes in a Binary Tree | C ++ program to count leaf nodes in a Binary Tree ; A binary tree Node has data , pointer to left child and a pointer to right child ; Function to get the count of leaf Nodes in a binary tree ; If tree is empty ; Initialize empty queue . ; Do level order traversal starting from root Initialize count of leaves ; Helper function that allocates a new Node with the given data and NULL left and right pointers . ; Driver program to test above functions ; 1 / \ 2 3 / \ 4 5 Let us create Binary Tree shown in above example ; get leaf count of the above created tree
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; unsigned int getLeafCount ( struct Node * node ) { if ( ! node ) return 0 ; queue < Node * > q ; int count = 0 ; q . push ( node ) ; while ( ! q . empty ( ) ) { struct Node * temp = q . front ( ) ; q . pop ( ) ; if ( temp -> left != NULL ) q . push ( temp -> left ) ; if ( temp -> right != NULL ) q . push ( temp -> right ) ; if ( temp -> left == NULL && temp -> right == NULL ) count ++ ; } return count ; } struct Node * newNode ( int data ) { struct Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } int main ( ) { struct Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; cout << getLeafCount ( root ) ; return 0 ; }
Find the Kth smallest element in the sorted generated array | C ++ implementation of the approach ; Function to return the Kth element in B [ ] ; Initialize the count Array ; Reduce N repeatedly to half its value ; Add count to start ; Subtract same count after end index ; Store each element of Array [ ] with their count ; Sort the elements wrt value ; If Kth element is in range of element [ i ] return element [ i ] ; If K is out of bound ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( int Array [ ] , int N , int K ) { int count_Arr [ N + 1 ] = { 0 } ; int factor = 1 ; int size = N ; while ( size ) { int start = 1 ; int end = size ; count_Arr [ 1 ] += factor * N ; count_Arr [ end + 1 ] -= factor * N ; factor ++ ; size /= 2 ; } for ( int i = 2 ; i <= N ; i ++ ) count_Arr [ i ] += count_Arr [ i - 1 ] ; vector < pair < int , int > > element ; for ( int i = 0 ; i < N ; i ++ ) { element . push_back ( { Array [ i ] , count_Arr [ i + 1 ] } ) ; } sort ( element . begin ( ) , element . end ( ) ) ; int start = 1 ; for ( int i = 0 ; i < N ; i ++ ) { int end = start + element [ i ] . second - 1 ; if ( K >= start && K <= end ) { return element [ i ] . first ; } start += element [ i ] . second ; } return -1 ; } int main ( ) { int arr [ ] = { 2 , 4 , 5 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 13 ; cout << solve ( arr , N , K ) ; return 0 ; }
Find the lexicographical next balanced bracket sequence | C ++ implementation of the approach ; Function to find the lexicographically next balanced bracket expression if possible ; Decrement the depth for every opening bracket ; Increment for the closing brackets ; Last opening bracket ; Generate the required string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string next_balanced_sequence ( string & s ) { string next = " - 1" ; int length = s . size ( ) ; int depth = 0 ; for ( int i = length - 1 ; i >= 0 ; -- i ) { if ( s [ i ] == ' ( ' ) depth -- ; else depth ++ ; if ( s [ i ] == ' ( ' && depth > 0 ) { depth -- ; int open = ( length - i - 1 - depth ) / 2 ; int close = length - i - 1 - open ; next = s . substr ( 0 , i ) + ' ) ' + string ( open , ' ( ' ) + string ( close , ' ) ' ) ; break ; } } return next ; } int main ( ) { string s = " ( ( ( ) ) ) " ; cout << next_balanced_sequence ( s ) ; return 0 ; }
Maximum number that can be display on Seven Segment Display using N segments | ; Function to print maximum number that can be formed using N segments ; If n is odd ; use 3 three segment to print 7 ; remaining to print 1 ; If n is even ; print n / 2 1 s . ; Driver 's Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printMaxNumber ( int n ) { if ( n & 1 ) { cout << "7" ; for ( int i = 0 ; i < ( n - 3 ) / 2 ; i ++ ) cout << "1" ; } else { for ( int i = 0 ; i < n / 2 ; i ++ ) cout << "1" ; } } int main ( ) { int n = 5 ; printMaxNumber ( n ) ; return 0 ; }
Find the sum of digits of a number at even and odd places | C ++ implementation of the approach ; Function to find the sum of the odd and even positioned digits in a number ; To store the respective sums ; Converting integer to string ; Traversing the string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void getSum ( int n ) { int sumOdd = 0 , sumEven = 0 ; string num = to_string ( n ) ; for ( int i = 0 ; i < num . size ( ) ; i ++ ) { if ( i % 2 == 0 ) sumOdd = sumOdd + ( int ( num [ i ] ) - 48 ) ; else sumEven = sumEven + ( int ( num [ i ] ) - 48 ) ; } cout << " Sum ▁ odd ▁ = ▁ " << sumOdd << " STRNEWLINE " ; cout << " Sum ▁ even ▁ = ▁ " << sumEven << " STRNEWLINE " ; } int main ( ) { int n = 457892 ; getSum ( n ) ; return 0 ; }
Iterative program to count leaf nodes in a Binary Tree | C ++ Program for above approach ; Node class ; Program to count leaves ; If the node itself is " null " return 0 , as there are no leaves ; It the node is a leaf then both right and left children will be " null " ; Now we count the leaves in the left and right subtrees and return the sum ; Class newNode of Node type ; Driver Code ; get leaf count of the above created tree
#include <iostream> NEW_LINE using namespace std ; struct node { int data ; struct node * left ; struct node * right ; } ; int countLeaves ( struct node * node ) { if ( node == NULL ) { return 0 ; } if ( node -> left == NULL && node -> right == NULL ) { return 1 ; } return countLeaves ( node -> left ) + countLeaves ( node -> right ) ; } struct node * newNode ( int data ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; return ( node ) ; } int main ( ) { struct node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; cout << countLeaves ( root ) << endl ; }
Partition an array such into maximum increasing segments | C ++ program to divide into maximum number of segments ; Returns the maximum number of sorted subarrays in a valid partition ; Find minimum value from right for every index ; Finding the shortest prefix such that all the elements in the prefix are less than or equal to the elements in the rest of the array . ; if current max is less than the right prefix min , we increase number of partitions . ; Driver code ; Find minimum value from right for every index
#include <iostream> NEW_LINE using namespace std ; int sorted_partitions ( int arr [ ] , int n ) { int right_min [ n + 1 ] ; right_min [ n ] = INT8_MAX ; for ( int i = n - 1 ; i >= 0 ; i -- ) { right_min [ i ] = min ( right_min [ i + 1 ] , arr [ i ] ) ; } int partitions = 0 ; for ( int current_max = arr [ 0 ] , i = 0 ; i < n ; i ++ ) { current_max = max ( current_max , arr [ i ] ) ; if ( current_max <= right_min [ i + 1 ] ) partitions ++ ; } return partitions ; } int main ( ) { int arr [ ] = { 3 , 1 , 2 , 4 , 100 , 7 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int ans = sorted_partitions ( arr , n ) ; cout << ans << endl ; return 0 ; }
Minimize Cost with Replacement with other allowed | C ++ Program for the above approach ; this function returns the minimum cost of the array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMinCost ( int arr [ ] , int n ) { int min_ele = * min_element ( arr , arr + n ) ; return min_ele * ( n - 1 ) ; } int main ( ) { int arr [ ] = { 4 , 2 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << getMinCost ( arr , n ) << endl ; return 0 ; }
Minimum swaps required to make a binary string alternating | C ++ implementation of the above approach ; function to count minimum swaps required to make binary string alternating ; stores total number of ones ; stores total number of zeroes ; checking impossible condition ; odd length string ; number of even positions ; stores number of zeroes and ones at even positions ; even length string ; stores number of ones at odd and even position respectively ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countMinSwaps ( string s ) { int N = s . size ( ) ; int one = 0 ; int zero = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( s [ i ] == '1' ) one ++ ; else zero ++ ; } if ( one > zero + 1 zero > one + 1 ) return -1 ; if ( N % 2 ) { int num = ( N + 1 ) / 2 ; int one_even = 0 , zero_even = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( i % 2 == 0 ) { if ( s [ i ] == '1' ) one_even ++ ; else zero_even ++ ; } } if ( one > zero ) return num - one_even ; else return num - zero_even ; } else { int one_odd = 0 , one_even = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( s [ i ] == '1' ) { if ( i % 2 ) one_odd ++ ; else one_even ++ ; } } return min ( N / 2 - one_odd , N / 2 - one_even ) ; } } int main ( ) { string s = "111000" ; cout << countMinSwaps ( s ) ; return 0 ; }
Check if it is possible to return to the starting position after moving in the given directions | C ++ implementation of above approach ; Main method ; int n = 0 ; Count of North int s = 0 ; Count of South int e = 0 ; Count of East int w = 0 ; Count of West
#include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { string st = " NNNWEWESSS " ; int len = st . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { if ( st [ i ] == ' N ' ) n += 1 ; if ( st [ i ] == ' S ' ) s += 1 ; if ( st [ i ] == ' W ' ) w += 1 ; if ( st [ i ] == ' E ' ) e += 1 ; } if ( n == s && w == e ) cout << ( " YES " ) << endl ; else cout << ( " NO " ) << endl ; }
Minimum cost to make array size 1 by removing larger of pairs | CPP program to find minimum cost to reduce array size to 1 , ; function to calculate the minimum cost ; Minimum cost is n - 1 multiplied with minimum element . ; driver code .
#include <bits/stdc++.h> NEW_LINE using namespace std ; int cost ( int a [ ] , int n ) { return ( n - 1 ) * ( * min_element ( a , a + n ) ) ; } int main ( ) { int a [ ] = { 4 , 3 , 2 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << cost ( a , n ) << endl ; return 0 ; }
Count Non | CPP program to count total number of non - leaf nodes in a binary tree ; A binary tree node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Computes the number of non - leaf nodes in a tree . ; Base cases . ; If root is Not NULL and its one of its child is also not NULL ; Driver program to test size function
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left ; struct Node * right ; } ; struct Node * newNode ( int data ) { struct Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } int countNonleaf ( struct Node * root ) { if ( root == NULL || ( root -> left == NULL && root -> right == NULL ) ) return 0 ; return 1 + countNonleaf ( root -> left ) + countNonleaf ( root -> right ) ; } int main ( ) { struct Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; cout << countNonleaf ( root ) ; return 0 ; }
Minimum cost for acquiring all coins with k extra coins allowed with every coin | C ++ program to acquire all n coins ; function to calculate min cost ; sort the coins value ; calculate no . of coins needed ; calculate sum of all selected coins ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minCost ( int coin [ ] , int n , int k ) { sort ( coin , coin + n ) ; int coins_needed = ceil ( 1.0 * n / ( k + 1 ) ) ; int ans = 0 ; for ( int i = 0 ; i <= coins_needed - 1 ; i ++ ) ans += coin [ i ] ; return ans ; } int main ( ) { int coin [ ] = { 8 , 5 , 3 , 10 , 2 , 1 , 15 , 25 } ; int n = sizeof ( coin ) / sizeof ( coin [ 0 ] ) ; int k = 3 ; cout << minCost ( coin , n , k ) ; return 0 ; }
Program for First Fit algorithm in Memory Management | C ++ implementation of First - Fit algorithm ; Function to allocate memory to blocks as per First fit algorithm ; Stores block id of the block allocated to a process ; Initially no block is assigned to any process ; pick each process and find suitable blocks according to its size ad assign to it ; allocate block j to p [ i ] process ; Reduce available memory in this block . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void firstFit ( int blockSize [ ] , int m , int processSize [ ] , int n ) { int allocation [ n ] ; memset ( allocation , -1 , sizeof ( allocation ) ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( blockSize [ j ] >= processSize [ i ] ) { allocation [ i ] = j ; blockSize [ j ] -= processSize [ i ] ; break ; } } } cout << " Process No . Process Size Block no . " ; for ( int i = 0 ; i < n ; i ++ ) { cout << " ▁ " << i + 1 << " TABSYMBOL TABSYMBOL " << processSize [ i ] << " TABSYMBOL TABSYMBOL " ; if ( allocation [ i ] != -1 ) cout << allocation [ i ] + 1 ; else cout << " Not ▁ Allocated " ; cout << endl ; } } int main ( ) { int blockSize [ ] = { 100 , 500 , 200 , 300 , 600 } ; int processSize [ ] = { 212 , 417 , 112 , 426 } ; int m = sizeof ( blockSize ) / sizeof ( blockSize [ 0 ] ) ; int n = sizeof ( processSize ) / sizeof ( processSize [ 0 ] ) ; firstFit ( blockSize , m , processSize , n ) ; return 0 ; }
Greedy Algorithm to find Minimum number of Coins | C ++ program to find minimum number of denominations ; All denominations of Indian Currency ; Initialize result ; Traverse through all denomination ; Find denominations ; Print result ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int deno [ ] = { 1 , 2 , 5 , 10 , 20 , 50 , 100 , 500 , 1000 } ; int n = sizeof ( deno ) / sizeof ( deno [ 0 ] ) ; void findMin ( int V ) { sort ( deno , deno + n ) ; vector < int > ans ; for ( int i = n - 1 ; i >= 0 ; i -- ) { while ( V >= deno [ i ] ) { V -= deno [ i ] ; ans . push_back ( deno [ i ] ) ; } } for ( int i = 0 ; i < ans . size ( ) ; i ++ ) cout << ans [ i ] << " ▁ " ; } int main ( ) { int n = 93 ; cout << " Following ▁ is ▁ minimal " << " ▁ number ▁ of ▁ change ▁ for ▁ " << n << " : ▁ " ; findMin ( n ) ; return 0 ; }
Minimize count of array elements to be removed such that at least K elements are equal to their index values | C ++ program for the above approach ; Function to minimize the removals of array elements such that atleast K elements are equal to their indices ; Store the array as 1 - based indexing Copy of first array ; Make a dp - table of ( N * N ) size ; Delete the current element ; Take the current element ; Check for the minimum removals ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MinimumRemovals ( int a [ ] , int N , int K ) { int b [ N + 1 ] ; for ( int i = 0 ; i < N ; i ++ ) { b [ i + 1 ] = a [ i ] ; } int dp [ N + 1 ] [ N + 1 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j <= i ; j ++ ) { dp [ i + 1 ] [ j ] = max ( dp [ i + 1 ] [ j ] , dp [ i ] [ j ] ) ; dp [ i + 1 ] [ j + 1 ] = max ( dp [ i + 1 ] [ j + 1 ] , dp [ i ] [ j ] + ( ( b [ i + 1 ] == j + 1 ) ? 1 : 0 ) ) ; } } for ( int j = N ; j >= 0 ; j -- ) { if ( dp [ N ] [ j ] >= K ) { return ( N - j ) ; } } return -1 ; } int main ( ) { int arr [ ] = { 5 , 1 , 3 , 2 , 3 } ; int K = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << MinimumRemovals ( arr , N , K ) ; return 0 ; }
Count of Arrays of size N having absolute difference between adjacent elements at most 1 | C ++ program of the above approach ; Function to find the count of possible arrays such that the absolute difference between any adjacent elements is atmost 1 ; Stores the dp states where dp [ i ] [ j ] represents count of arrays of length i + 1 having their last element as j ; Case where 1 st array element is missing ; All integers in range [ 1 , M ] are reachable ; Only reachable integer is arr [ 0 ] ; Iterate through all values of i ; If arr [ i ] is not missing ; Only valid value of j is arr [ i ] ; If arr [ i ] is missing ; Iterate through all possible values of j in range [ 1 , M ] ; Stores the count of valid arrays ; Calculate the total count of valid arrays ; Return answer ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countArray ( int arr [ ] , int N , int M ) { int dp [ N ] [ M + 2 ] ; memset ( dp , 0 , sizeof dp ) ; if ( arr [ 0 ] == -1 ) { for ( int j = 1 ; j <= M ; j ++ ) { dp [ 0 ] [ j ] = 1 ; } } else { dp [ 0 ] [ arr [ 0 ] ] = 1 ; } for ( int i = 1 ; i < N ; i ++ ) { if ( arr [ i ] != -1 ) { int j = arr [ i ] ; dp [ i ] [ j ] += dp [ i - 1 ] [ j - 1 ] + dp [ i - 1 ] [ j ] + dp [ i - 1 ] [ j + 1 ] ; } if ( arr [ i ] == -1 ) { for ( int j = 1 ; j <= M ; j ++ ) { dp [ i ] [ j ] += dp [ i - 1 ] [ j - 1 ] + dp [ i - 1 ] [ j ] + dp [ i - 1 ] [ j + 1 ] ; } } } int arrCount = 0 ; for ( int j = 1 ; j <= M ; j ++ ) { arrCount += dp [ N - 1 ] [ j ] ; } return arrCount ; } int main ( ) { int arr [ ] = { 4 , -1 , 2 , 1 , -1 , -1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int M = 10 ; cout << countArray ( arr , N , M ) ; return 0 ; }
Maximize sum of product of neighbouring elements of the element removed from Array | C ++ implementation for the above approach ; Stores the dp state where dp [ i ] [ j ] represents the maximum possible score in the subarray from index i to j ; Function to calculate maximum possible score using the given operations ; Iterate through all possible lengths of the subarray ; Iterate through all the possible starting indices i having length len ; Stores the rightmost index of the current subarray ; Initial dp [ i ] [ j ] will be 0. ; Iterate through all possible values of k in range [ i + 1 , j - 1 ] ; Return the answer ; Driver Code ; Function Call ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 101 ] [ 101 ] ; int maxMergingScore ( int A [ ] , int N ) { for ( int len = 1 ; len < N ; ++ len ) { for ( int i = 0 ; i + len < N ; ++ i ) { int j = i + len ; dp [ i ] [ j ] = 0 ; for ( int k = i + 1 ; k < j ; ++ k ) { dp [ i ] [ j ] = max ( dp [ i ] [ j ] , dp [ i ] [ k ] + dp [ k ] [ j ] + A [ i ] * A [ j ] ) ; } } } return dp [ 0 ] [ N - 1 ] ; } int main ( ) { int N = 4 ; int A [ ] = { 1 , 2 , 3 , 4 } ; cout << maxMergingScore ( A , N ) << endl ; N = 2 ; int B [ ] = { 1 , 55 } ; cout << maxMergingScore ( B , N ) << endl ; return 0 ; }
Longest subarray with all even or all odd elements | C ++ implementation for the above approach ; Function to calculate longest substring with odd or even elements ; Initializing dp ; Initializing dp with 1 ; ans will store the final answer ; Traversing the array from index 1 to N - 1 ; Checking both current and previous element is even or odd ; Updating dp with ( previous dp value ) + 1 ; Storing max element so far to ans ; Returning the final answer ; Driver code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int LongestOddEvenSubarray ( int A [ ] , int N ) { int dp ; dp = 1 ; int ans = 1 ; for ( int i = 1 ; i < N ; i ++ ) { if ( ( A [ i ] % 2 == 0 && A [ i - 1 ] % 2 == 0 ) || ( A [ i ] % 2 != 0 && A [ i - 1 ] % 2 != 0 ) ) { dp = dp + 1 ; ans = max ( ans , dp ) ; } else dp = 1 ; } return ans ; } int main ( ) { int A [ ] = { 2 , 5 , 7 , 2 , 4 , 6 , 8 , 3 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << LongestOddEvenSubarray ( A , N ) ; return 0 ; }
Count of N | C ++ program for the above approach ; Function to find number of ' N ' digit numbers such that the element is mean of sum of its adjacent digits ; If digit = n + 1 , a valid n - digit number has been formed ; If the state has already been computed ; If current position is 1 , then any digit from [ 1 - 9 ] can be placed . If n = 1 , 0 can be also placed . ; If current position is 2 , then any digit from [ 1 - 9 ] can be placed . ; previous digit selected is the mean . ; mean = ( current + prev2 ) / 2 current = ( 2 * mean ) - prev2 ; Check if current and current + 1 can be valid placements ; return answer ; Driver code ; Initializing dp array with - 1. ; Given Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 100 ] [ 10 ] [ 10 ] ; int countOfNumbers ( int digit , int prev1 , int prev2 , int n ) { if ( digit == n + 1 ) { return 1 ; } int & val = dp [ digit ] [ prev1 ] [ prev2 ] ; if ( val != -1 ) { return val ; } val = 0 ; if ( digit == 1 ) { for ( int i = ( n == 1 ? 0 : 1 ) ; i <= 9 ; ++ i ) { val += countOfNumbers ( digit + 1 , i , prev1 , n ) ; } } else if ( digit == 2 ) { for ( int i = 0 ; i <= 9 ; ++ i ) { val += countOfNumbers ( digit + 1 , i , prev1 , n ) ; } } else { int mean = prev1 ; int current = ( 2 * mean ) - prev2 ; if ( current >= 0 and current <= 9 ) val += countOfNumbers ( digit + 1 , current , prev1 , n ) ; if ( ( current + 1 ) >= 0 and ( current + 1 ) <= 9 ) val += countOfNumbers ( digit + 1 , current + 1 , prev1 , n ) ; } return val ; } int main ( ) { memset ( dp , -1 , sizeof dp ) ; int n = 2 ; cout << countOfNumbers ( 1 , 0 , 0 , n ) << endl ; return 0 ; }
Count half nodes in a Binary tree ( Iterative and Recursive ) | C ++ program to count half nodes in a Binary Tree ; A binary tree Node has data , pointer to left child and a pointer to right child ; Function to get the count of half Nodes in a binary tree ; If tree is empty ; Do level order traversal starting from root ; Initialize count of half nodes ; Enqueue left child ; Enqueue right child ; Helper function that allocates a new Node with the given data and NULL left and right pointers . ; Driver Program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; unsigned int gethalfCount ( struct Node * node ) { if ( ! node ) return 0 ; queue < Node * > q ; q . push ( node ) ; int count = 0 ; while ( ! q . empty ( ) ) { struct Node * temp = q . front ( ) ; q . pop ( ) ; if ( ! temp -> left && temp -> right temp -> left && ! temp -> right ) count ++ ; if ( temp -> left != NULL ) q . push ( temp -> left ) ; if ( temp -> right != NULL ) q . push ( temp -> right ) ; } return count ; } struct Node * newNode ( int data ) { struct Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } int main ( void ) { struct Node * root = newNode ( 2 ) ; root -> left = newNode ( 7 ) ; root -> right = newNode ( 5 ) ; root -> left -> right = newNode ( 6 ) ; root -> left -> right -> left = newNode ( 1 ) ; root -> left -> right -> right = newNode ( 11 ) ; root -> right -> right = newNode ( 9 ) ; root -> right -> right -> left = newNode ( 4 ) ; cout << gethalfCount ( root ) ; return 0 ; }
Count N | C ++ program for the above approach ; Function to count N digit numbers whose digits are less than or equal to the absolute difference of previous two digits ; If all digits are traversed ; If the state has already been computed ; If the current digit is 1 , any digit from [ 1 - 9 ] can be placed . If N == 1 , 0 can also be placed . ; If the current digit is 2 , any digit from [ 0 - 9 ] can be placed ; For other digits , any digit from 0 to abs ( prev1 - prev2 ) can be placed ; Return the answer ; Driver code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long dp [ 50 ] [ 10 ] [ 10 ] ; long long countOfNumbers ( int digit , int prev1 , int prev2 , int N ) { if ( digit == N + 1 ) return 1 ; if ( dp [ digit ] [ prev1 ] [ prev2 ] != -1 ) return dp [ digit ] [ prev1 ] [ prev2 ] ; dp [ digit ] [ prev1 ] [ prev2 ] = 0 ; if ( digit == 1 ) { for ( int j = ( N == 1 ? 0 : 1 ) ; j <= 9 ; ++ j ) { dp [ digit ] [ prev1 ] [ prev2 ] += countOfNumbers ( digit + 1 , j , prev1 , N ) ; } } else if ( digit == 2 ) { for ( int j = 0 ; j <= 9 ; ++ j ) { dp [ digit ] [ prev1 ] [ prev2 ] += countOfNumbers ( digit + 1 , j , prev1 , N ) ; } } else { for ( int j = 0 ; j <= abs ( prev1 - prev2 ) ; ++ j ) { dp [ digit ] [ prev1 ] [ prev2 ] += countOfNumbers ( digit + 1 , j , prev1 , N ) ; } } return dp [ digit ] [ prev1 ] [ prev2 ] ; } int main ( ) { memset ( dp , -1 , sizeof dp ) ; int N = 3 ; cout << countOfNumbers ( 1 , 0 , 0 , N ) << endl ; return 0 ; }
Length of longest subset consisting of A 0 s and B 1 s from an array of strings | C ++ program for the above approach ; Function to count number of 0 s present in the string ; Stores the count of 0 s ; Iterate over characters of string ; If current character is '0' ; Recursive Function to find the length of longest subset from given array of strings with at most A 0 s and B 1 s ; If idx is equal to N or A + B is equal to 0 ; If the state is already calculated ; Stores the count of 0 's ; Stores the count of 1 's ; Stores the length of longest by including arr [ idx ] ; If zero is less than A and one is less than B ; Stores the length of longest subset by excluding arr [ idx ] ; Assign ; Return ; Function to find the length of the longest subset of an array of strings with at most A 0 s and B 1 s ; Stores all Dp - states ; Return ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count0 ( string s ) { int count = 0 ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { if ( s [ i ] == '0' ) { count ++ ; } } return count ; } int solve ( vector < string > vec , int A , int B , int idx , vector < vector < vector < int > > > & dp ) { if ( idx == vec . size ( ) A + B == 0 ) { return 0 ; } if ( dp [ A ] [ B ] [ idx ] > 0 ) { return dp [ A ] [ B ] [ idx ] ; } int zero = count0 ( vec [ idx ] ) ; int one = vec [ idx ] . size ( ) - zero ; int inc = 0 ; if ( zero <= A && one <= B ) { inc = 1 + solve ( vec , A - zero , B - one , idx + 1 , dp ) ; } int exc = solve ( vec , A , B , idx + 1 , dp ) ; dp [ A ] [ B ] [ idx ] = max ( inc , exc ) ; return dp [ A ] [ B ] [ idx ] ; } int MaxSubsetlength ( vector < string > arr , int A , int B ) { vector < vector < vector < int > > > dp ( A + 1 , vector < vector < int > > ( B + 1 , vector < int > ( arr . size ( ) + 1 , 0 ) ) ) ; return solve ( arr , A , B , 0 , dp ) ; } int main ( ) { vector < string > arr = { "1" , "0" , "10" } ; int A = 1 , B = 1 ; cout << MaxSubsetlength ( arr , A , B ) ; return 0 ; }
Check if a given pattern exists in a given string or not | C ++ program for the above approach ; Function to check if the pattern consisting of ' * ' , ' . ' and lowercase characters matches the text or not ; Base Case ; Stores length of text ; Stores length of pattern ; dp [ i ] [ j ] : Check if { text [ 0 ] , . . text [ i ] } matches { pattern [ 0 ] , ... pattern [ j ] } or not ; Base Case ; Iterate over the characters of the string pattern ; Update dp [ 0 ] [ i + 1 ] ; Iterate over the characters of both the strings ; If current character in the pattern is ' . ' ; Update dp [ i + 1 ] [ j + 1 ] ; If current character in both the strings are equal ; Update dp [ i + 1 ] [ j + 1 ] ; If current character in the pattern is ' * ' ; Update dp [ i + 1 ] [ j + 1 ] ; Update dp [ i + 1 ] [ j + 1 ] ; Return dp [ M ] [ N ] ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int isMatch ( string text , string pattern ) { if ( text == " " or pattern == " " ) return false ; int N = text . size ( ) ; int M = pattern . size ( ) ; vector < vector < bool > > dp ( N + 1 , vector < bool > ( M + 1 , false ) ) ; dp [ 0 ] [ 0 ] = true ; for ( int i = 0 ; i < M ; i ++ ) { if ( pattern [ i ] == ' * ' && dp [ 0 ] [ i - 1 ] ) { dp [ 0 ] [ i + 1 ] = true ; } } for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( pattern [ j ] == ' . ' ) { dp [ i + 1 ] [ j + 1 ] = dp [ i ] [ j ] ; } if ( pattern [ j ] == text [ i ] ) { dp [ i + 1 ] [ j + 1 ] = dp [ i ] [ j ] ; } if ( pattern [ j ] == ' * ' ) { if ( pattern [ j - 1 ] != text [ i ] && pattern [ j - 1 ] != ' . ' ) { dp [ i + 1 ] [ j + 1 ] = dp [ i + 1 ] [ j - 1 ] ; } else { dp [ i + 1 ] [ j + 1 ] = ( dp [ i + 1 ] [ j ] or dp [ i ] [ j + 1 ] or dp [ i + 1 ] [ j - 1 ] ) ; } } } } return dp [ N ] [ M ] ; } int main ( ) { string text = " geeksforgeeks " ; string pattern = " ge * ksforgeeks " ; if ( isMatch ( text , pattern ) ) cout << " Yes " ; else cout << " No " ; }
Count number of unique ways to paint a N x 3 grid | C ++ program for the above approach ; Function to count the number of ways to paint N * 3 grid based on given conditions ; Count of ways to pain a row with same colored ends ; Count of ways to pain a row with different colored ends ; Traverse up to ( N - 1 ) th row ; For same colored ends ; For different colored ends ; Print the total number of ways ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void waysToPaint ( int n ) { int same = 6 ; int diff = 6 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { long sameTmp = 3 * same + 2 * diff ; long diffTmp = 2 * same + 2 * diff ; same = sameTmp ; diff = diffTmp ; } cout << ( same + diff ) ; } int main ( ) { int N = 2 ; waysToPaint ( N ) ; }
Minimize sum of incompatibilities of K equal | C ++ program for the above approach ; Function to find the minimum incompatibility sum ; Stores the count of element ; Traverse the array ; If number i not occurs in Map ; Put the element in the Map ; Increment the count of i in the Hash Map ; If count of i in Map is greater than K then return - 1 ; Stores all total state ; Traverse over all the state ; If number of set bit is equal to N / K ; Stores the minimum value at a state ; Call the recursive function ; Recursive function to find the minimum required value ; Base Case ; Stores the minimum value of the current state ; If dp [ state ] [ index ] is already calculated ; return dp [ state ] [ index ] ; Traverse over all the bits ; If count of set bit is N / K ; Store the new state after choosing N / K elements ; Stores the minimum and maximum of current subset ; Stores if the elements have been already selected or not ; Stores if it is possible to select N / K elements ; Traverse over the array ; If not chosen already for another subset ; If already chosen for another subset or current subset ; Mark the good false ; Mark the current number visited ; Mark the current position in mask newstate ; Update the maximum and minimum ; If good is true then Update the res ; Update the current sp state ; Return the res ; Driver code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int k ; int n ; int goal ; vector < vector < int > > dp ; vector < int > bits ; int minimumIncompatibility ( vector < int > A , int K ) { n = A . size ( ) ; k = K ; goal = n / k ; map < int , int > mp ; for ( int i : A ) { if ( mp . find ( i ) != mp . end ( ) ) { mp [ i ] = 0 ; } mp [ i ] ++ ; if ( mp [ i ] > k ) return -1 ; } int state = ( 1 << n ) - 1 ; for ( int i = 0 ; i <= state ; i ++ ) { if ( __builtin_popcount ( i ) == goal ) bits . push_back ( i ) ; } dp . resize ( 1 << n , vector < int > ( k , -1 ) ) ; return dfs ( A , state , 0 ) ; } int dfs ( vector < int > A , int state , int index ) { if ( index >= k ) { return 0 ; } int res = 1000 ; if ( dp [ state ] [ index ] != -1 ) { return dp [ state ] [ index ] ; } for ( int bit : bits ) { if ( __builtin_popcount ( bit ) == goal ) { int newstate = state ; int mn = 100 , mx = -1 ; vector < bool > visit ( n + 1 , false ) ; bool good = true ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( bit & ( 1 << j ) ) != 0 ) { if ( visit [ A [ j ] ] == true || ( state & ( 1 << j ) ) == 0 ) { good = false ; break ; } visit [ A [ j ] ] = true ; newstate = newstate ^ ( 1 << j ) ; mx = max ( mx , A [ j ] ) ; mn = min ( mn , A [ j ] ) ; } } if ( good ) { res = min ( res , mx - mn + dfs ( A , newstate , index + 1 ) ) ; } } } dp [ state ] [ index ] = res ; return res ; } int main ( ) { vector < int > arr = { 1 , 2 , 1 , 4 } ; int K = 2 ; cout << ( minimumIncompatibility ( arr , K ) ) ; }
Maximize sum by selecting X different | C ++ program for the above approach ; Function to find maximum sum of at most N with different index array elements such that at most X are from A [ ] , Y are from B [ ] and Z are from C [ ] ; Base Cases ; Selecting i - th element from A [ ] ; Selecting i - th element from B [ ] ; Selecting i - th element from C [ ] ; i - th elements not selected from any of the arrays ; Select the maximum sum from all the possible calls ; Driver Code ; Given X , Y and Z ; Given A [ ] ; Given B [ ] ; Given C [ ] ; Given Size ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int FindMaxS ( int X , int Y , int Z , int n , vector < int > & A , vector < int > & B , vector < int > & C ) { if ( X < 0 or Y < 0 or Z < 0 ) return INT_MIN ; if ( n < 0 ) return 0 ; int ch = A [ n ] + FindMaxS ( X - 1 , Y , Z , n - 1 , A , B , C ) ; int ca = B [ n ] + FindMaxS ( X , Y - 1 , Z , n - 1 , A , B , C ) ; int co = C [ n ] + FindMaxS ( X , Y , Z - 1 , n - 1 , A , B , C ) ; int no = FindMaxS ( X , Y , Z , n - 1 , A , B , C ) ; int maximum = max ( ch , max ( ca , max ( co , no ) ) ) ; return maximum ; } int main ( ) { int X = 1 ; int Y = 1 ; int Z = 1 ; vector < int > A = { 10 , 0 , 5 } ; vector < int > B = { 5 , 10 , 0 } ; vector < int > C = { 0 , 5 , 10 } ; int n = B . size ( ) ; cout << FindMaxS ( X , Y , Z , n - 1 , A , B , C ) ; }
Rearrange array by interchanging positions of even and odd elements in the given array | C ++ program for the above approach ; Function to replace each even element by odd and vice - versa in a given array ; Traverse array ; If current element is even then swap it with odd ; Perform Swap ; Change the sign ; If current element is odd then swap it with even ; Perform Swap ; Change the sign ; Marked element positive ; Print final array ; Driver Code ; Given array arr [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void replace ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( arr [ i ] >= 0 && arr [ j ] >= 0 && arr [ i ] % 2 == 0 && arr [ j ] % 2 != 0 ) { int tmp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = tmp ; arr [ j ] = - arr [ j ] ; break ; } else if ( arr [ i ] >= 0 && arr [ j ] >= 0 && arr [ i ] % 2 != 0 && arr [ j ] % 2 == 0 ) { int tmp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = tmp ; arr [ j ] = - arr [ j ] ; break ; } } } for ( int i = 0 ; i < n ; i ++ ) arr [ i ] = abs ( arr [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 1 , 3 , 2 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; replace ( arr , n ) ; }
Count half nodes in a Binary tree ( Iterative and Recursive ) | C ++ program to count half nodes in a Binary Tree ; A binary tree Node has data , pointer to left child and a pointer to right child ; Function to get the count of half Nodes in a binary tree ; Helper function that allocates a new Node with the given data and NULL left and right pointers . ; Driver program ; 2 / \ 7 5 \ \ 6 9 / \ / 1 11 4 Let us create Binary Tree shown in above example
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; unsigned int gethalfCount ( struct Node * root ) { if ( root == NULL ) return 0 ; int res = 0 ; if ( ( root -> left == NULL && root -> right != NULL ) || ( root -> left != NULL && root -> right == NULL ) ) res ++ ; res += ( gethalfCount ( root -> left ) + gethalfCount ( root -> right ) ) ; return res ; } struct Node * newNode ( int data ) { struct Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } int main ( void ) { struct Node * root = newNode ( 2 ) ; root -> left = newNode ( 7 ) ; root -> right = newNode ( 5 ) ; root -> left -> right = newNode ( 6 ) ; root -> left -> right -> left = newNode ( 1 ) ; root -> left -> right -> right = newNode ( 11 ) ; root -> right -> right = newNode ( 9 ) ; root -> right -> right -> left = newNode ( 4 ) ; cout << gethalfCount ( root ) ; return 0 ; }
Minimize cost to reduce array to a single element by replacing K consecutive elements by their sum | C ++ program to implement the above approach ; Function to find the minimum cost to reduce given array to a single element by replacing consecutive K array elements ; If ( N - 1 ) is not multiple of ( K - 1 ) ; Store prefix sum of the array ; Iterate over the range [ 1 , N ] ; Update prefixSum [ i ] ; dp [ i ] [ j ] : Store minimum cost to merge array elements interval [ i , j ] ; L : Stores length of interval [ i , j ] ; Iterate over each interval [ i , j ] of length L in in [ 0 , N ] ; Stores index of last element of the interval [ i , j ] ; If L is greater than K ; Update dp [ i ] [ j ] ; If ( L - 1 ) is multiple of ( K - 1 ) ; Update dp [ i ] [ j ] ; Return dp [ 0 ] [ N - 1 ] ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumCostToMergeK ( int arr [ ] , int K , int N ) { if ( ( N - 1 ) % ( K - 1 ) != 0 ) { return -1 ; } int prefixSum [ N + 1 ] = { 0 } ; for ( int i = 1 ; i < ( N + 1 ) ; i ++ ) { prefixSum [ i ] = ( prefixSum [ i - 1 ] + arr [ i - 1 ] ) ; } int dp [ N ] [ N ] ; memset ( dp , 0 , sizeof ( dp ) ) ; for ( int L = K ; L < ( N + 1 ) ; L ++ ) { for ( int i = 0 ; i < ( N - L + 1 ) ; i ++ ) { int j = i + L - 1 ; if ( L > K ) { int temp = INT_MAX ; for ( int x = i ; x < j ; x += K - 1 ) { temp = min ( temp , dp [ i ] [ x ] + dp [ x + 1 ] [ j ] ) ; } dp [ i ] [ j ] = temp ; } if ( ( L - 1 ) % ( K - 1 ) == 0 ) { dp [ i ] [ j ] += ( prefixSum [ j + 1 ] - prefixSum [ i ] ) ; } } } return dp [ 0 ] [ N - 1 ] ; } int main ( ) { int arr [ ] = { 3 , 5 , 1 , 2 , 6 } ; int K = 3 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minimumCostToMergeK ( arr , K , N ) ; }
Check if end of a sorted Array can be reached by repeated jumps of one more , one less or same number of indices as previous jump | C ++ program for the above approach ; Utility function to check if it is possible to move from index 1 to N - 1 ; Successfully reached end index ; memo [ i ] [ j ] is already calculated ; Check if there is any index having value of A [ i ] + j - 1 , A [ i ] + j or A [ i ] + j + 1 ; If A [ k ] > A [ i ] + j + 1 , can 't make a move further ; It 's possible to move A[k] ; Check is it possible to move from index k having previously taken A [ k ] - A [ i ] steps ; If yes then break the loop ; Store value of flag in memo ; Return memo [ i ] [ j ] ; Function to check if it is possible to move from index 1 to N - 1 ; Stores the memoized state ; Initialize all values as - 1 ; Initially , starting index = 1 ; Function call ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 8 NEW_LINE int check ( int memo [ ] [ N ] , int i , int j , int * A ) { if ( i == N - 1 ) return 1 ; if ( memo [ i ] [ j ] != -1 ) return memo [ i ] [ j ] ; int flag = 0 , k ; for ( k = i + 1 ; k < N ; k ++ ) { if ( A [ k ] - A [ i ] > j + 1 ) break ; if ( A [ k ] - A [ i ] >= j - 1 && A [ k ] - A [ i ] <= j + 1 ) flag = check ( memo , k , A [ k ] - A [ i ] , A ) ; if ( flag ) break ; } memo [ i ] [ j ] = flag ; return memo [ i ] [ j ] ; } void checkEndReach ( int A [ ] , int K ) { int memo [ N ] [ N ] ; memset ( memo , -1 , sizeof ( memo ) ) ; int startIndex = 1 ; if ( check ( memo , startIndex , K , A ) ) cout << " Yes " ; else cout << " No " ; } int main ( ) { int A [ ] = { 0 , 1 , 3 , 5 , 6 , 8 , 12 , 17 } ; int K = 1 ; checkEndReach ( A , K ) ; return 0 ; }
Maximum subsequence sum such that no K elements are consecutive | C ++ program for the above approach ; Function to find the maximum sum of a subsequence consisting of no K consecutive array elements ; Stores states of dp ; Initialise dp state ; Stores the prefix sum ; Update the prefix sum ; Base case for i < K ; For indices less than k take all the elements ; For i >= K case ; Skip each element from i to ( i - K + 1 ) to ensure that no K elements are consecutive ; Update the current dp state ; dp [ N ] stores the maximum sum ; Driver Code ; Given array arr [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Max_Sum ( int arr [ ] , int K , int N ) { int dp [ N + 1 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; int prefix [ N + 1 ] ; prefix [ 0 ] = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { prefix [ i ] = prefix [ i - 1 ] + arr [ i - 1 ] ; } dp [ 0 ] = 0 ; for ( int i = 1 ; i < K ; i ++ ) { dp [ i ] = prefix [ i ] ; } for ( int i = K ; i <= N ; ++ i ) { for ( int j = i ; j >= ( i - K + 1 ) ; j -- ) { dp [ i ] = max ( dp [ i ] , dp [ j - 1 ] + prefix [ i ] - prefix [ j ] ) ; } } return dp [ N ] ; } int main ( ) { int arr [ ] = { 4 , 12 , 22 , 18 , 34 , 12 , 25 } ; int N = sizeof ( arr ) / sizeof ( int ) ; int K = 5 ; cout << Max_Sum ( arr , K , N ) ; return 0 ; }
Count possible splits of sum N into K integers such that the minimum is at least P | C ++ program for the above approach ; Function that finds the value of the Binomial Coefficient C ( n , k ) ; Stores the value of Binomial Coefficient in bottom up manner ; Base Case ; Find the value using previously stored values ; Return the value of C ( N , K ) ; Function that count the number of ways to divide N into K integers >= P such that their sum is N ; Update the value of N ; Find the binomial coefficient recursively ; Driver Code ; Given K , N , and P
#include <bits/stdc++.h> NEW_LINE using namespace std ; int binomialCoeff ( int n , int k ) { int C [ n + 1 ] [ k + 1 ] ; int i , j ; for ( i = 0 ; i <= n ; i ++ ) { for ( j = 0 ; j <= min ( i , k ) ; j ++ ) { if ( j == 0 j == i ) C [ i ] [ j ] = 1 ; else C [ i ] [ j ] = C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] ; } } return C [ n ] [ k ] ; } int waysToSplitN ( int k , int n , int P ) { int new_N = n - k * P ; return binomialCoeff ( new_N + k - 1 , new_N ) ; } int main ( ) { int K = 3 , N = 8 , P = 2 ; cout << waysToSplitN ( K , N , P ) ; return 0 ; }
Minimum pair merge operations required to make Array non | C ++ program to implement the above approach ; Function to find the minimum operations to make the array Non - increasing ; Size of the array ; Dp table initialization ; dp [ i ] : Stores minimum number of operations required to make subarray { A [ i ] , ... , A [ N ] } non - increasing ; Increment the value of j ; Add current value to sum ; Update the dp tables ; Return the answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( vector < int > & a ) { int n = a . size ( ) ; vector < int > dp ( n + 1 , 0 ) , val ( n + 1 , 0 ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { long long sum = a [ i ] ; int j = i ; while ( j + 1 < n and sum < val [ j + 1 ] ) { j ++ ; sum += a [ j ] ; } dp [ i ] = ( j - i ) + dp [ j + 1 ] ; val [ i ] = sum ; } return dp [ 0 ] ; } int main ( ) { vector < int > arr = { 1 , 5 , 3 , 9 , 1 } ; cout << solve ( arr ) ; }
Count full nodes in a Binary tree ( Iterative and Recursive ) | C ++ program to count full nodes in a Binary Tree ; A binary tree Node has data , pointer to left child and a pointer to right child ; Function to get the count of full Nodes in a binary tree ; If tree is empty ; Initialize empty queue . ; Do level order traversal starting from root ; Initialize count of full nodes ; Enqueue left child ; Enqueue right child ; Helper function that allocates a new Node with the given data and NULL left and right pointers . ; Driver program ; 2 / \ 7 5 \ \ 6 9 / \ / 1 11 4 Let us create Binary Tree as shown
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; unsigned int getfullCount ( struct Node * node ) { if ( ! node ) return 0 ; queue < Node * > q ; q . push ( node ) ; int count = 0 ; while ( ! q . empty ( ) ) { struct Node * temp = q . front ( ) ; q . pop ( ) ; if ( temp -> left && temp -> right ) count ++ ; if ( temp -> left != NULL ) q . push ( temp -> left ) ; if ( temp -> right != NULL ) q . push ( temp -> right ) ; } return count ; } struct Node * newNode ( int data ) { struct Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } int main ( void ) { struct Node * root = newNode ( 2 ) ; root -> left = newNode ( 7 ) ; root -> right = newNode ( 5 ) ; root -> left -> right = newNode ( 6 ) ; root -> left -> right -> left = newNode ( 1 ) ; root -> left -> right -> right = newNode ( 11 ) ; root -> right -> right = newNode ( 9 ) ; root -> right -> right -> left = newNode ( 4 ) ; cout << getfullCount ( root ) ; return 0 ; }
Count of Distinct Substrings occurring consecutively in a given String | C ++ Program to implement the above approach ; Function to count the distinct substrings placed consecutively in the given string ; Length of the string ; If length of the string does not exceed 1 ; Initialize a DP - table ; Stores the distinct substring ; Iterate from end of the string ; Iterate backward until dp table is all computed ; If character at i - th index is same as character at j - th index ; Update dp [ i ] [ j ] based on previously computed value ; Otherwise ; Condition for consecutively placed similar substring ; Return the count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int distinctSimilarSubstrings ( string str ) { int n = str . size ( ) ; if ( n <= 1 ) { return 0 ; } vector < vector < int > > dp ( n + 1 , vector < int > ( n + 1 , 0 ) ) ; unordered_set < string > substrings ; for ( int j = n - 1 ; j >= 0 ; j -- ) { for ( int i = j - 1 ; i >= 0 ; i -- ) { if ( str [ i ] == str [ j ] ) { dp [ i ] [ j ] = dp [ i + 1 ] [ j + 1 ] + 1 ; } else { dp [ i ] [ j ] = 0 ; } if ( dp [ i ] [ j ] >= j - i ) { substrings . insert ( str . substr ( i , j - i ) ) ; } } } return substrings . size ( ) ; } int main ( ) { string str = " geeksgeeksforgeeks " ; cout << distinctSimilarSubstrings ( str ) ; return 0 ; }
Finding shortest path between any two nodes using Floyd Warshall Algorithm | C ++ program to find the shortest path between any two nodes using Floyd Warshall Algorithm . ; Infinite value for array ; Initializing the distance and Next array ; No edge between node i and j ; Function construct the shortest path between u and v ; If there 's no path between node u and v, simply return an empty array ; Storing the path in a vector ; Standard Floyd Warshall Algorithm with little modification Now if we find that dis [ i ] [ j ] > dis [ i ] [ k ] + dis [ k ] [ j ] then we modify next [ i ] [ j ] = next [ i ] [ k ] ; We cannot travel through edge that doesn 't exist ; Print the shortest path ; Driver code ; Function to initialise the distance and Next array ; Calling Floyd Warshall Algorithm , this will update the shortest distance as well as Next array ; Path from node 1 to 3 ; Path from node 0 to 2 ; path from node 3 to 2
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAXN 100 NEW_LINE const int INF = 1e7 ; int dis [ MAXN ] [ MAXN ] ; int Next [ MAXN ] [ MAXN ] ; void initialise ( int V , vector < vector < int > > & graph ) { for ( int i = 0 ; i < V ; i ++ ) { for ( int j = 0 ; j < V ; j ++ ) { dis [ i ] [ j ] = graph [ i ] [ j ] ; if ( graph [ i ] [ j ] == INF ) Next [ i ] [ j ] = -1 ; else Next [ i ] [ j ] = j ; } } } vector < int > constructPath ( int u , int v ) { if ( Next [ u ] [ v ] == -1 ) return { } ; vector < int > path = { u } ; while ( u != v ) { u = Next [ u ] [ v ] ; path . push_back ( u ) ; } return path ; } void floydWarshall ( int V ) { for ( int k = 0 ; k < V ; k ++ ) { for ( int i = 0 ; i < V ; i ++ ) { for ( int j = 0 ; j < V ; j ++ ) { if ( dis [ i ] [ k ] == INF dis [ k ] [ j ] == INF ) continue ; if ( dis [ i ] [ j ] > dis [ i ] [ k ] + dis [ k ] [ j ] ) { dis [ i ] [ j ] = dis [ i ] [ k ] + dis [ k ] [ j ] ; Next [ i ] [ j ] = Next [ i ] [ k ] ; } } } } } void printPath ( vector < int > & path ) { int n = path . size ( ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) cout << path [ i ] << " ▁ - > ▁ " ; cout << path [ n - 1 ] << endl ; } int main ( ) { int V = 4 ; vector < vector < int > > graph = { { 0 , 3 , INF , 7 } , { 8 , 0 , 2 , INF } , { 5 , INF , 0 , 1 } , { 2 , INF , INF , 0 } } ; initialise ( V , graph ) ; floydWarshall ( V ) ; vector < int > path ; cout << " Shortest ▁ path ▁ from ▁ 1 ▁ to ▁ 3 : ▁ " ; path = constructPath ( 1 , 3 ) ; printPath ( path ) ; cout << " Shortest ▁ path ▁ from ▁ 0 ▁ to ▁ 2 : ▁ " ; path = constructPath ( 0 , 2 ) ; printPath ( path ) ; cout << " Shortest ▁ path ▁ from ▁ 3 ▁ to ▁ 2 : ▁ " ; path = constructPath ( 3 , 2 ) ; printPath ( path ) ; return 0 ; }
Count sequences of length K having each term divisible by its preceding term | C ++ Program to implement the above approach ; Stores the factors of i - th element in v [ i ] ; Function to find all the factors of N ; Iterate upto sqrt ( N ) ; Function to return the count of sequences of length K having all terms divisible by its preceding term ; Calculate factors of i ; Initialize dp [ 0 ] [ i ] = 0 : No subsequence of length 0 ending with i - th element exists ; Initialize dp [ 0 ] [ i ] = 1 : Only 1 subsequence of length 1 ending with i - th element exists ; Iterate [ 2 , K ] to obtain sequences of each length ; Calculate sum of all dp [ i - 1 ] [ vp [ j ] [ k ] ] ; vp [ j ] [ k ] stores all factors of j ; Store the sum in A [ i ] [ j ] ; Sum of all dp [ K ] [ j ] obtain all K length sequences ending with j ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long NEW_LINE vector < ll int > vp [ 2009 ] ; void finding_factors ( ll int n ) { ll int i , a ; for ( i = 1 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { if ( i * i == n ) { vp [ n ] . push_back ( i ) ; } else { vp [ n ] . push_back ( i ) ; vp [ n ] . push_back ( n / i ) ; } } } } ll int countSeq ( ll int N , ll int K ) { ll int i , j , k ; ll int dp [ 109 ] [ 109 ] = { 0 } ; for ( i = 1 ; i <= N ; i ++ ) { finding_factors ( i ) ; dp [ 0 ] [ i ] = 0 ; dp [ 1 ] [ i ] = 1 ; } for ( i = 2 ; i <= K ; i ++ ) { for ( j = 1 ; j <= N ; j ++ ) { ll int sum = 0 ; for ( k = 0 ; k < vp [ j ] . size ( ) ; k ++ ) { sum = ( sum + dp [ i - 1 ] [ vp [ j ] [ k ] ] ) ; } dp [ i ] [ j ] = sum ; } } ll int ans = 0 ; for ( j = 1 ; j <= N ; j ++ ) { ans = ( ans + dp [ K ] [ j ] ) ; } return ans ; } int main ( ) { ll int N , K ; N = 3 ; K = 2 ; cout << countSeq ( N , K ) << endl ; return 0 ; }
Largest possible square submatrix with maximum AND value | C ++ program to find the length of longest possible square submatrix with maximum AND value from the given matrix ; Function to calculate and return the length of square submatrix with maximum AND value ; Extract dimensions ; Auxiliary array ; c : Stores the maximum value in the matrix p : Stores the number of elements in the submatrix having maximum AND value ; Iterate over the matrix to fill the auxiliary matrix ; Find the max element in the matrix side by side ; Fill first row and column with 1 's ; For every cell , check if the elements at the left , top and top left cells from the current cell are equal or not ; Store the minimum possible submatrix size these elements are part of ; Store 1 otherwise ; checking maximum value ; If the maximum AND value occurs more than once ; Update the maximum size of submatrix ; final output ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MAX_value ( vector < vector < int > > arr ) { int row = arr . size ( ) ; int col = arr [ 0 ] . size ( ) ; int dp [ row ] [ col ] ; memset ( dp , sizeof ( dp ) , 0 ) ; int i = 0 , j = 0 ; int c = arr [ 0 ] [ 0 ] , p = 0 ; int d = row ; for ( i = 0 ; i < d ; i ++ ) { for ( j = 0 ; j < d ; j ++ ) { if ( c < arr [ i ] [ j ] ) { c = arr [ i ] [ j ] ; } if ( i == 0 j == 0 ) { dp [ i ] [ j ] = 1 ; } else { if ( arr [ i - 1 ] [ j - 1 ] == arr [ i ] [ j ] && arr [ i - 1 ] [ j ] == arr [ i ] [ j ] && arr [ i ] [ j - 1 ] == arr [ i ] [ j ] ) { dp [ i ] [ j ] = min ( dp [ i - 1 ] [ j - 1 ] , min ( dp [ i - 1 ] [ j ] , dp [ i ] [ j - 1 ] ) ) + 1 ; } else { dp [ i ] [ j ] = 1 ; } } } } for ( i = 0 ; i < d ; i ++ ) { for ( j = 0 ; j < d ; j ++ ) { if ( arr [ i ] [ j ] == c ) { if ( p < dp [ i ] [ j ] ) { p = dp [ i ] [ j ] ; } } } } return p * p ; } int main ( ) { vector < vector < int > > arr = { { 9 , 9 , 3 , 3 , 4 , 4 } , { 9 , 9 , 7 , 7 , 7 , 4 } , { 1 , 2 , 7 , 7 , 7 , 4 } , { 4 , 4 , 7 , 7 , 7 , 4 } , { 5 , 5 , 1 , 1 , 2 , 7 } , { 2 , 7 , 1 , 1 , 4 , 4 } } ; cout << MAX_value ( arr ) << endl ; return 0 ; }
Smallest power of 2 consisting of N digits | C ++ Program to implement the above approach ; Function to return smallest power of 2 with N digits ; Iterate through all powers of 2 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int smallestNum ( int n ) { int res = 1 ; for ( int i = 2 ; ; i *= 2 ) { int length = log10 ( i ) + 1 ; if ( length == n ) return log ( i ) / log ( 2 ) ; } } int main ( ) { int n = 4 ; cout << smallestNum ( n ) ; return 0 ; }
Maximum weighted edge in path between two nodes in an N | C ++ implementation to find the maximum weighted edge in the simple path between two nodes in N - ary Tree ; Depths of Nodes ; Parent at every 2 ^ i level ; Maximum node at every 2 ^ i level ; Graph that stores destinations and its weight ; Function to traverse the nodes using the Depth - First Search Traversal ; Condition to check if its equal to its parent then skip ; DFS Recursive Call ; Function to find the ansector ; Loop to set every 2 ^ i distance ; Loop to calculate for each node in the N - ary tree ; Storing maximum edge ; Swaping if node a is at more depth than node b because we will always take at more depth ; Difference between the depth of the two given nodes ; Changing Node B to its parent at 2 ^ i distance ; Subtracting distance by 2 ^ i ; Take both a , b to its lca and find maximum ; Loop to find the 2 ^ ith parent that is different for both a and b i . e below the lca ; Updating ans ; Changing value to its parent ; Function to compute the Least common Ansector ; Driver Code ; Undirected tree ; Computing LCA
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 100005 ; vector < int > level ( N ) ; const int LG = 20 ; vector < vector < int > > dp ( LG , vector < int > ( N ) ) ; vector < vector < int > > mx ( LG , vector < int > ( N ) ) ; vector < vector < pair < int , int > > > v ( N ) ; int n ; void dfs_lca ( int a , int par , int lev ) { dp [ 0 ] [ a ] = par ; level [ a ] = lev ; for ( auto i : v [ a ] ) { if ( i . first == par ) continue ; mx [ 0 ] [ i . first ] = i . second ; dfs_lca ( i . first , a , lev + 1 ) ; } } void find_ancestor ( ) { for ( int i = 1 ; i < LG ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { dp [ i ] [ j ] = dp [ i - 1 ] [ dp [ i - 1 ] [ j ] ] ; mx [ i ] [ j ] = max ( mx [ i - 1 ] [ j ] , mx [ i - 1 ] [ dp [ i - 1 ] [ j ] ] ) ; } } } int getMax ( int a , int b ) { if ( level [ b ] < level [ a ] ) swap ( a , b ) ; int ans = 0 ; int diff = level [ b ] - level [ a ] ; while ( diff > 0 ) { int log = log2 ( diff ) ; ans = max ( ans , mx [ log ] [ b ] ) ; b = dp [ log ] [ b ] ; diff -= ( 1 << log ) ; } while ( a != b ) { int i = log2 ( level [ a ] ) ; while ( i > 0 && dp [ i ] [ a ] == dp [ i ] [ b ] ) i -- ; ans = max ( ans , mx [ i ] [ a ] ) ; ans = max ( ans , mx [ i ] [ b ] ) ; a = dp [ i ] [ a ] ; b = dp [ i ] [ b ] ; } return ans ; } void compute_lca ( ) { dfs_lca ( 1 , 0 , 0 ) ; find_ancestor ( ) ; } int main ( ) { n = 5 ; v [ 1 ] . push_back ( make_pair ( 2 , 2 ) ) ; v [ 2 ] . push_back ( make_pair ( 1 , 2 ) ) ; v [ 1 ] . push_back ( make_pair ( 3 , 5 ) ) ; v [ 3 ] . push_back ( make_pair ( 1 , 5 ) ) ; v [ 3 ] . push_back ( make_pair ( 4 , 3 ) ) ; v [ 4 ] . push_back ( make_pair ( 3 , 4 ) ) ; v [ 3 ] . push_back ( make_pair ( 5 , 1 ) ) ; v [ 5 ] . push_back ( make_pair ( 3 , 1 ) ) ; compute_lca ( ) ; int queries [ ] [ 2 ] = { { 3 , 5 } , { 2 , 3 } , { 2 , 4 } } ; int q = 3 ; for ( int i = 0 ; i < q ; i ++ ) { int max_edge = getMax ( queries [ i ] [ 0 ] , queries [ i ] [ 1 ] ) ; cout << max_edge << endl ; } return 0 ; }
Count full nodes in a Binary tree ( Iterative and Recursive ) | C ++ program to count full nodes in a Binary Tree ; A binary tree Node has data , pointer to left child and a pointer to right child ; Function to get the count of full Nodes in a binary tree ; Helper function that allocates a new Node with the given data and NULL left and right pointers . ; Driver program ; 2 / \ 7 5 \ \ 6 9 / \ / 1 11 4 Let us create Binary Tree as shown
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; unsigned int getfullCount ( struct Node * root ) { if ( root == NULL ) return 0 ; int res = 0 ; if ( root -> left && root -> right ) res ++ ; res += ( getfullCount ( root -> left ) + getfullCount ( root -> right ) ) ; return res ; } struct Node * newNode ( int data ) { struct Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } int main ( void ) { struct Node * root = newNode ( 2 ) ; root -> left = newNode ( 7 ) ; root -> right = newNode ( 5 ) ; root -> left -> right = newNode ( 6 ) ; root -> left -> right -> left = newNode ( 1 ) ; root -> left -> right -> right = newNode ( 11 ) ; root -> right -> right = newNode ( 9 ) ; root -> right -> right -> left = newNode ( 4 ) ; cout << getfullCount ( root ) ; return 0 ; }
Count Possible Decodings of a given Digit Sequence in O ( N ) time and Constant Auxiliary space | C ++ implementation to count decodings ; A Dynamic Programming based function to count decodings in digit sequence ; For base condition "01123" should return 0 ; Using last two calculated values , calculate for ith index ; Change bool to int ; Return the required answer ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countDecodingDP ( string digits , int n ) { if ( digits [ 0 ] == '0' ) return 0 ; int count0 = 1 , count1 = 1 , count2 ; for ( int i = 2 ; i <= n ; i ++ ) { count2 = ( ( int ) ( digits [ i - 1 ] != '0' ) * count1 ) + ( int ) ( ( digits [ i - 2 ] == '1' ) or ( digits [ i - 2 ] == '2' and digits [ i - 1 ] < '7' ) ) * count0 ; count0 = count1 ; count1 = count2 ; } return count1 ; } int main ( ) { string digits = "1234" ; int n = digits . size ( ) ; cout << countDecodingDP ( digits , n ) ; return 0 ; }
Maximum of all distances to the nearest 1 cell from any 0 cell in a Binary matrix | C ++ Program to find the maximum distance from a 0 - cell to a 1 - cell ; Function to find the maximum distance ; Set up top row and left column ; Pass one : top left to bottom right ; Check if there was no " One " Cell ; Set up top row and left column ; Past two : bottom right to top left ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxDistance ( vector < vector < int > > & grid ) { if ( ! grid . size ( ) ) return -1 ; int N = grid . size ( ) ; int INF = 1000000 ; vector < vector < int > > dp ( N , vector < int > ( N , 0 ) ) ; grid [ 0 ] [ 0 ] = grid [ 0 ] [ 0 ] == 1 ? 0 : INF ; for ( int i = 1 ; i < N ; i ++ ) grid [ 0 ] [ i ] = grid [ 0 ] [ i ] == 1 ? 0 : grid [ 0 ] [ i - 1 ] + 1 ; for ( int i = 1 ; i < N ; i ++ ) grid [ i ] [ 0 ] = grid [ i ] [ 0 ] == 1 ? 0 : grid [ i - 1 ] [ 0 ] + 1 ; for ( int i = 1 ; i < N ; i ++ ) { for ( int j = 1 ; j < N ; j ++ ) { grid [ i ] [ j ] = grid [ i ] [ j ] == 1 ? 0 : min ( grid [ i - 1 ] [ j ] , grid [ i ] [ j - 1 ] ) + 1 ; } } if ( grid [ N - 1 ] [ N - 1 ] >= INF ) return -1 ; int maxi = grid [ N - 1 ] [ N - 1 ] ; for ( int i = N - 2 ; i >= 0 ; i -- ) { grid [ N - 1 ] [ i ] = min ( grid [ N - 1 ] [ i ] , grid [ N - 1 ] [ i + 1 ] + 1 ) ; maxi = max ( grid [ N - 1 ] [ i ] , maxi ) ; } for ( int i = N - 2 ; i >= 0 ; i -- ) { grid [ i ] [ N - 1 ] = min ( grid [ i ] [ N - 1 ] , grid [ i + 1 ] [ N - 1 ] + 1 ) ; maxi = max ( grid [ i ] [ N - 1 ] , maxi ) ; } for ( int i = N - 2 ; i >= 0 ; i -- ) { for ( int j = N - 2 ; j >= 0 ; j -- ) { grid [ i ] [ j ] = min ( grid [ i ] [ j ] , min ( grid [ i + 1 ] [ j ] + 1 , grid [ i ] [ j + 1 ] + 1 ) ) ; maxi = max ( grid [ i ] [ j ] , maxi ) ; } } return ! maxi ? -1 : maxi ; } int main ( ) { vector < vector < int > > arr = { { 0 , 0 , 1 } , { 0 , 0 , 0 } , { 0 , 0 , 0 } } ; cout << maxDistance ( arr ) << endl ; return 0 ; }
Minimize total cost without repeating same task in two consecutive iterations | C ++ implementation of the above approach ; Function to return the minimum cost for N iterations ; Construct the dp table ; 1 st row of dp table will be equal to the 1 st of cost matrix ; Iterate through all the rows ; To iterate through the columns of current row ; Initialize val as infinity ; To iterate through the columns of previous row ; Fill the dp matrix ; Returning the minimum value ; Driver code ; Number of iterations ; Number of tasks ; Cost matrix
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findCost ( vector < vector < int > > cost_mat , int N , int M ) { vector < vector < int > > dp ( N , vector < int > ( M , 0 ) ) ; for ( int i = 0 ; i < M ; i ++ ) dp [ 0 ] [ i ] = cost_mat [ 0 ] [ i ] ; for ( int row = 1 ; row < N ; row ++ ) { for ( int curr_col = 0 ; curr_col < M ; curr_col ++ ) { int val = 999999999 ; for ( int prev_col = 0 ; prev_col < M ; prev_col ++ ) { if ( curr_col != prev_col ) val = min ( val , dp [ row - 1 ] [ prev_col ] ) ; } dp [ row ] [ curr_col ] = val + cost_mat [ row ] [ curr_col ] ; } } int ans = INT_MAX ; for ( int i = 0 ; i < M ; i ++ ) ans = min ( ans , dp [ N - 1 ] [ i ] ) ; return ans ; } int main ( ) { int N = 4 ; int M = 4 ; vector < vector < int > > cost_mat ; cost_mat = { { 4 , 5 , 3 , 2 } , { 6 , 2 , 8 , 1 } , { 6 , 2 , 2 , 1 } , { 0 , 5 , 5 , 1 } } ; cout << findCost ( cost_mat , N , M ) ; return 0 ; }
Split the given string into Primes : Digit DP | C ++ implementation of the above approach ; Function to precompute all the primes upto 1000000 and store it in a set using Sieve of Eratosthenes ; Here to_string ( ) is used for converting int to string ; A function to find the minimum number of segments the given string can be divided such that every segment is a prime ; Declare a splitdp [ ] array and initialize to - 1 ; Call sieve function to store primes in primes array ; Build the DP table in a bottom - up manner ; If the prefix is prime then the prefix will be found in the prime set ; If the Given Prefix can be split into Primes then for the remaining string from i to j Check if Prime . If yes calculate the minimum split till j ; To check if the substring from i to j is a prime number or not ; If it is a prime , then update the dp array ; Return the minimum number of splits for the entire string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void getPrimesFromSeive ( set < string > & primes ) { bool prime [ 1000001 ] ; memset ( prime , true , sizeof ( prime ) ) ; prime [ 0 ] = prime [ 1 ] = false ; for ( int i = 2 ; i * i <= 1000000 ; i ++ ) { if ( prime [ i ] == true ) { for ( int j = i * i ; j <= 1000000 ; j += i ) prime [ j ] = false ; } } for ( int i = 2 ; i <= 1000000 ; i ++ ) { if ( prime [ i ] == true ) primes . insert ( to_string ( i ) ) ; } } int splitIntoPrimes ( string number ) { int numLen = number . length ( ) ; int splitDP [ numLen + 1 ] ; memset ( splitDP , -1 , sizeof ( splitDP ) ) ; set < string > primes ; getPrimesFromSeive ( primes ) ; for ( int i = 1 ; i <= numLen ; i ++ ) { if ( i <= 6 && ( primes . find ( number . substr ( 0 , i ) ) != primes . end ( ) ) ) splitDP [ i ] = 1 ; if ( splitDP [ i ] != -1 ) { for ( int j = 1 ; j <= 6 && i + j <= numLen ; j ++ ) { if ( primes . find ( number . substr ( i , j ) ) != primes . end ( ) ) { if ( splitDP [ i + j ] == -1 ) splitDP [ i + j ] = 1 + splitDP [ i ] ; else splitDP [ i + j ] = min ( splitDP [ i + j ] , 1 + splitDP [ i ] ) ; } } } } return splitDP [ numLen ] ; } int main ( ) { cout << splitIntoPrimes ( "13499315" ) << " STRNEWLINE " ; cout << splitIntoPrimes ( "43" ) << " STRNEWLINE " ; return 0 ; }
Connect Nodes at same Level ( Level Order Traversal ) | Connect nodes at same level using level order traversal . ; Node structure ; Sets nextRight of all nodes of a tree ; null marker to represent end of current level ; Do Level order of tree using NULL markers ; next element in queue represents next node at current Level ; push left and right children of current node ; if queue is not empty , push NULL to mark nodes at this level are visited ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver program to test above functions ; Constructed binary tree is 10 / \ 8 2 / \ 3 90 ; Populates nextRight pointer in all nodes ; Let us check the values of nextRight pointers
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right , * nextRight ; } ; void connect ( struct Node * root ) { queue < Node * > q ; q . push ( root ) ; q . push ( NULL ) ; while ( ! q . empty ( ) ) { Node * p = q . front ( ) ; q . pop ( ) ; if ( p != NULL ) { p -> nextRight = q . front ( ) ; if ( p -> left ) q . push ( p -> left ) ; if ( p -> right ) q . push ( p -> right ) ; } else if ( ! q . empty ( ) ) q . push ( NULL ) ; } } struct Node * newnode ( int data ) { struct Node * node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; node -> data = data ; node -> left = node -> right = node -> nextRight = NULL ; return ( node ) ; } int main ( ) { struct Node * root = newnode ( 10 ) ; root -> left = newnode ( 8 ) ; root -> right = newnode ( 2 ) ; root -> left -> left = newnode ( 3 ) ; root -> right -> right = newnode ( 90 ) ; connect ( root ) ; printf ( " Following ▁ are ▁ populated ▁ nextRight ▁ pointers ▁ in ▁ STRNEWLINE " " the ▁ tree ▁ ( -1 ▁ is ▁ printed ▁ if ▁ there ▁ is ▁ no ▁ nextRight ) ▁ STRNEWLINE " ) ; printf ( " nextRight ▁ of ▁ % d ▁ is ▁ % d ▁ STRNEWLINE " , root -> data , root -> nextRight ? root -> nextRight -> data : -1 ) ; printf ( " nextRight ▁ of ▁ % d ▁ is ▁ % d ▁ STRNEWLINE " , root -> left -> data , root -> left -> nextRight ? root -> left -> nextRight -> data : -1 ) ; printf ( " nextRight ▁ of ▁ % d ▁ is ▁ % d ▁ STRNEWLINE " , root -> right -> data , root -> right -> nextRight ? root -> right -> nextRight -> data : -1 ) ; printf ( " nextRight ▁ of ▁ % d ▁ is ▁ % d ▁ STRNEWLINE " , root -> left -> left -> data , root -> left -> left -> nextRight ? root -> left -> left -> nextRight -> data : -1 ) ; printf ( " nextRight ▁ of ▁ % d ▁ is ▁ % d ▁ STRNEWLINE " , root -> right -> right -> data , root -> right -> right -> nextRight ? root -> right -> right -> nextRight -> data : -1 ) ; return 0 ; }
Number of ways to convert a character X to a string Y | C ++ implementation of the approach ; Function to find the modular - inverse ; While power > 1 ; Updating s and a ; Updating power ; Return the final answer ; Function to return the count of ways ; To store the final answer ; To store pre - computed factorials ; Computing factorials ; Loop to find the occurrences of x and update the ans ; Multiplying the answer by ( n - 1 ) ! ; Return the final answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MOD = 1000000007 ; long long modInv ( long long a , long long p = MOD - 2 ) { long long s = 1 ; while ( p != 1 ) { if ( p % 2 ) s = ( s * a ) % MOD ; a = ( a * a ) % MOD ; p /= 2 ; } return ( a * s ) % MOD ; } long long findCnt ( char x , string y ) { long long ans = 0 ; long long fact [ y . size ( ) + 1 ] = { 1 } ; for ( long long i = 1 ; i <= y . size ( ) ; i ++ ) fact [ i ] = ( fact [ i - 1 ] * i ) % MOD ; for ( long long i = 0 ; i < y . size ( ) ; i ++ ) { if ( y [ i ] == x ) { ans += ( modInv ( fact [ i ] ) * modInv ( fact [ y . size ( ) - i - 1 ] ) ) % MOD ; ans %= MOD ; } } ans *= fact [ ( y . size ( ) - 1 ) ] ; ans %= MOD ; return ans ; } int main ( ) { char x = ' a ' ; string y = " xxayy " ; cout << findCnt ( x , y ) ; return 0 ; }
Find the Largest divisor Subset in the Array | C ++ implementation of the approach ; Function to find the required subsequence ; Sort the array ; Keep a count of the length of the subsequence and the previous element ; Set the initial values ; Maximum length of the subsequence and the last element ; Run a loop for every element ; Check for all the divisors ; If the element is a divisor and the length of subsequence will increase by adding j as previous element of i ; Increase the count ; Update the max count ; Get the last index of the subsequence ; Print the element ; Move the index to the previous element ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findSubSeq ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int count [ n ] = { 1 } ; int prev [ n ] = { -1 } ; memset ( count , 1 , sizeof ( count ) ) ; memset ( prev , -1 , sizeof ( prev ) ) ; int max = 0 ; int maxprev = -1 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i - 1 ; j >= 0 ; j -- ) { if ( arr [ i ] % arr [ j ] == 0 && count [ j ] + 1 > count [ i ] ) { count [ i ] = count [ j ] + 1 ; prev [ i ] = j ; } } if ( max < count [ i ] ) { max = count [ i ] ; maxprev = i ; } } int i = maxprev ; while ( i >= 0 ) { if ( arr [ i ] != -1 ) cout << arr [ i ] << " ▁ " ; i = prev [ i ] ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( int ) ; findSubSeq ( arr , n ) ; return 0 ; }
Minimum number of integers required such that each Segment contains at least one of them | C ++ program for the above approach ; function to sort the 2D vector on basis of second element . ; Function to compute minimum number of points which cover all segments ; Sort the list of tuples by their second element . ; To store the solution ; Iterate over all the segments ; Get the start point of next segment ; Loop over all those segments whose start point is less than the end point of current segment ; Print the possibles values of M ; Driver code ; Starting points of segments ; Ending points of segments ; Insert ranges in points [ ] ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool sortcol ( const pair < int , int > p1 , const pair < int , int > p2 ) { return p1 . second < p2 . second ; } void minPoints ( pair < int , int > points [ ] , int n ) { sort ( points , points + n , sortcol ) ; vector < int > coordinates ; int i = 0 ; while ( i < n ) { int seg = points [ i ] . second ; coordinates . push_back ( seg ) ; int p = i + 1 ; if ( p >= n ) break ; int arrived = points [ p ] . first ; while ( seg >= arrived ) { p += 1 ; if ( p >= n ) break ; arrived = points [ p ] . first ; } i = p ; } for ( auto point : coordinates ) cout << point << " ▁ " ; } int main ( ) { int n = 4 ; int start [ ] = { 4 , 1 , 2 , 5 } ; int end [ ] = { 7 , 3 , 5 , 6 } ; pair < int , int > points [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { points [ i ] = { start [ i ] , end [ i ] } ; } minPoints ( points , n ) ; return 0 ; }
Optimally accommodate 0 s and 1 s from a Binary String into K buckets | C ++ implementation of the approach ; Function to find the minimum required sum using dynamic programming ; dp [ i ] [ j ] = minimum val of accommodation till j 'th index of the string using i+1 number of buckets. Final ans will be in dp[n-1][K-1] ; Corner cases ; Filling first row , if only 1 bucket then simple count number of zeros and ones and do the multiplication ; If k = 0 then this arrangement is not possible ; If no arrangement is possible then our answer will remain INT_MAX so return - 1 ; Driver code ; K buckets
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( string str , int K ) { int n = str . length ( ) ; long long dp [ K ] [ n ] ; memset ( dp , 0 , sizeof dp ) ; if ( n < K ) return -1 ; else if ( n == K ) return 0 ; long long zeroes = 0 , ones = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == '0' ) zeroes ++ ; else ones ++ ; dp [ 0 ] [ i ] = ones * zeroes ; } for ( int s = 1 ; s < K ; s ++ ) { for ( int i = 0 ; i < n ; i ++ ) { dp [ s ] [ i ] = INT_MAX ; ones = 0 ; zeroes = 0 ; for ( int k = i ; k >= 0 ; k -- ) { if ( str [ k ] == '0' ) zeroes ++ ; else ones ++ ; dp [ s ] [ i ] = min ( dp [ s ] [ i ] , + ( ( k - 1 >= 0 ) ? ones * zeroes + dp [ s - 1 ] [ k - 1 ] : INT_MAX ) ) ; } } } return ( dp [ K - 1 ] [ n - 1 ] == INT_MAX ) ? -1 : dp [ K - 1 ] [ n - 1 ] ; } int main ( ) { string S = "0101" ; int K = 2 ; cout << solve ( S , K ) << endl ; return 0 ; }
Queries for bitwise AND in the index range [ L , R ] of the given array | C ++ implementation of the approach ; Array to store bit - wise prefix count ; Function to find the prefix sum ; Loop for each bit ; Loop to find prefix count ; Function to answer query ; To store the answer ; Loop for each bit ; To store the number of variables with ith bit set ; Condition for ith bit of answer to be set ; Driver code
#include <bits/stdc++.h> NEW_LINE #define MAX 100000 NEW_LINE #define bitscount 32 NEW_LINE using namespace std ; int prefix_count [ bitscount ] [ MAX ] ; void findPrefixCount ( int arr [ ] , int n ) { for ( int i = 0 ; i < bitscount ; i ++ ) { prefix_count [ i ] [ 0 ] = ( ( arr [ 0 ] >> i ) & 1 ) ; for ( int j = 1 ; j < n ; j ++ ) { prefix_count [ i ] [ j ] = ( ( arr [ j ] >> i ) & 1 ) ; prefix_count [ i ] [ j ] += prefix_count [ i ] [ j - 1 ] ; } } } int rangeAnd ( int l , int r ) { int ans = 0 ; for ( int i = 0 ; i < bitscount ; i ++ ) { int x ; if ( l == 0 ) x = prefix_count [ i ] [ r ] ; else x = prefix_count [ i ] [ r ] - prefix_count [ i ] [ l - 1 ] ; if ( x == r - l + 1 ) ans = ( ans | ( 1 << i ) ) ; } return ans ; } int main ( ) { int arr [ ] = { 7 , 5 , 3 , 5 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( int ) ; findPrefixCount ( arr , n ) ; int queries [ ] [ 2 ] = { { 1 , 3 } , { 4 , 5 } } ; int q = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; for ( int i = 0 ; i < q ; i ++ ) cout << rangeAnd ( queries [ i ] [ 0 ] , queries [ i ] [ 1 ] ) << endl ; return 0 ; }
Longest path in a directed Acyclic graph | Dynamic Programming | C ++ program to find the longest path in the DAG ; Function to traverse the DAG and apply Dynamic Programming to find the longest path ; Mark as visited ; Traverse for all its children ; If not visited ; Store the max of the paths ; Function to add an edge ; Function that returns the longest path ; Dp array ; Visited array to know if the node has been visited previously or not ; Call DFS for every unvisited vertex ; Traverse and find the maximum of all dp [ i ] ; Driver Code ; Example - 1
#include <bits/stdc++.h> NEW_LINE using namespace std ; void dfs ( int node , vector < int > adj [ ] , int dp [ ] , bool vis [ ] ) { vis [ node ] = true ; for ( int i = 0 ; i < adj [ node ] . size ( ) ; i ++ ) { if ( ! vis [ adj [ node ] [ i ] ] ) dfs ( adj [ node ] [ i ] , adj , dp , vis ) ; dp [ node ] = max ( dp [ node ] , 1 + dp [ adj [ node ] [ i ] ] ) ; } } void addEdge ( vector < int > adj [ ] , int u , int v ) { adj [ u ] . push_back ( v ) ; } int findLongestPath ( vector < int > adj [ ] , int n ) { int dp [ n + 1 ] ; memset ( dp , 0 , sizeof dp ) ; bool vis [ n + 1 ] ; memset ( vis , false , sizeof vis ) ; for ( int i = 1 ; i <= n ; i ++ ) { if ( ! vis [ i ] ) dfs ( i , adj , dp , vis ) ; } int ans = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { ans = max ( ans , dp [ i ] ) ; } return ans ; } int main ( ) { int n = 5 ; vector < int > adj [ n + 1 ] ; addEdge ( adj , 1 , 2 ) ; addEdge ( adj , 1 , 3 ) ; addEdge ( adj , 3 , 2 ) ; addEdge ( adj , 2 , 4 ) ; addEdge ( adj , 3 , 4 ) ; cout << findLongestPath ( adj , n ) ; return 0 ; }
Largest subset of rectangles such that no rectangle fit in any other rectangle | C ++ implementation of the approach ; Recursive function to get the largest subset ; Base case when it exceeds ; If the state has been visited previously ; Initialize ; No elements in subset yet ; First state which includes current index ; Second state which does not include current index ; If the rectangle fits in , then do not include the current index in subset ; First state which includes current index ; Second state which does not include current index ; Function to get the largest subset ; Initialize the DP table with - 1 ; Sort the array ; Get the answer ; Driver code ; ( height , width ) pairs
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 10 NEW_LINE int dp [ N ] [ N ] ; int findLongest ( pair < int , int > a [ ] , int n , int present , int previous ) { if ( present == n ) { return 0 ; } else if ( previous != -1 ) { if ( dp [ present ] [ previous ] != -1 ) return dp [ present ] [ previous ] ; } int ans = 0 ; if ( previous == -1 ) { ans = 1 + findLongest ( a , n , present + 1 , present ) ; ans = max ( ans , findLongest ( a , n , present + 1 , previous ) ) ; } else { int h1 = a [ previous ] . first ; int h2 = a [ present ] . first ; int w1 = a [ previous ] . second ; int w2 = a [ present ] . second ; if ( ( h1 <= h2 && w1 <= w2 ) ) { ans = max ( ans , findLongest ( a , n , present + 1 , previous ) ) ; } else { ans = 1 + findLongest ( a , n , present + 1 , present ) ; ans = max ( ans , findLongest ( a , n , present + 1 , previous ) ) ; } } return dp [ present ] [ previous ] = ans ; } int getLongest ( pair < int , int > a [ ] , int n ) { memset ( dp , -1 , sizeof dp ) ; sort ( a , a + n ) ; int ans = findLongest ( a , n , 0 , -1 ) ; return ans ; } int main ( ) { pair < int , int > a [ ] = { { 1 , 5 } , { 2 , 4 } , { 1 , 1 } , { 3 , 3 } } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << getLongest ( a , n ) ; return 0 ; }
Maximum length subsequence such that adjacent elements in the subsequence have a common factor | C ++ implementation of the above approach ; Function to compute least prime divisor of i ; Function that returns the maximum length subsequence such that adjacent elements have a common factor . ; Initialize dp array with 1. ; p has appeared at least once . ; Update latest occurrence of prime p . ; Take maximum value as the answer . ; Driver code
#include <bits/stdc++.h> NEW_LINE #define N 100005 NEW_LINE #define MAX 10000002 NEW_LINE using namespace std ; int lpd [ MAX ] ; void preCompute ( ) { memset ( lpd , 0 , sizeof ( lpd ) ) ; lpd [ 0 ] = lpd [ 1 ] = 1 ; for ( int i = 2 ; i * i < MAX ; i ++ ) { for ( int j = i * 2 ; j < MAX ; j += i ) { if ( lpd [ j ] == 0 ) { lpd [ j ] = i ; } } } for ( int i = 2 ; i < MAX ; i ++ ) { if ( lpd [ i ] == 0 ) { lpd [ i ] = i ; } } } int maxLengthSubsequence ( int arr [ ] , int n ) { int dp [ N ] ; unordered_map < int , int > pos ; for ( int i = 0 ; i <= n ; i ++ ) dp [ i ] = 1 ; for ( int i = 0 ; i <= n ; i ++ ) { while ( arr [ i ] > 1 ) { int p = lpd [ arr [ i ] ] ; if ( pos [ p ] ) { dp [ i ] = max ( dp [ i ] , 1 + dp [ pos [ p ] ] ) ; } pos [ p ] = i ; while ( arr [ i ] % p == 0 ) arr [ i ] /= p ; } } int ans = 1 ; for ( int i = 0 ; i <= n ; i ++ ) { ans = max ( ans , dp [ i ] ) ; } return ans ; } int main ( ) { int arr [ ] = { 13 , 2 , 8 , 6 , 3 , 1 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; preCompute ( ) ; cout << maxLengthSubsequence ( arr , n ) ; return 0 ; }
Connect nodes at same level using constant extra space | Iterative CPP program to connect nodes at same level using constant extra space ; Constructor that allocates a new node with the given data and NULL left and right pointers . ; This function returns the leftmost child of nodes at the same level as p . This function is used to getNExt right of p 's right child If right child of is NULL then this can also be used for the left child ; Traverse nodes at p ' s ▁ level ▁ ▁ and ▁ find ▁ and ▁ return ▁ the ▁ first ▁ ▁ ▁ node ' s first child ; If all the nodes at p 's level are leaf nodes then return NULL ; Sets nextRight of all nodes of a tree with root as p ; Set nextRight for root ; set nextRight of all levels one by one ; Connect all childrem nodes of p and children nodes of all other nodes at same level as p ; Set the nextRight pointer for p 's left child ; If q has right child , then right child is nextRight of p and we also need to set nextRight of right child ; Set nextRight for other nodes in pre order fashion ; start from the first node of next level ; Driver code ; Constructed binary tree is 10 / \ 8 2 / \ 3 90 ; Populates nextRight pointer in all nodes ; Let us check the values of nextRight pointers
#include <bits/stdc++.h> NEW_LINE #include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int data ; node * left ; node * right ; node * nextRight ; node ( int data ) { this -> data = data ; this -> left = NULL ; this -> right = NULL ; this -> nextRight = NULL ; } } ; node * getNextRight ( node * p ) { node * temp = p -> nextRight ; while ( temp != NULL ) { if ( temp -> left != NULL ) return temp -> left ; if ( temp -> right != NULL ) return temp -> right ; temp = temp -> nextRight ; } return NULL ; } void connectRecur ( node * p ) { node * temp ; if ( ! p ) return ; p -> nextRight = NULL ; while ( p != NULL ) { node * q = p ; while ( q != NULL ) { if ( q -> left ) { if ( q -> right ) q -> left -> nextRight = q -> right ; else q -> left -> nextRight = getNextRight ( q ) ; } if ( q -> right ) q -> right -> nextRight = getNextRight ( q ) ; q = q -> nextRight ; } if ( p -> left ) p = p -> left ; else if ( p -> right ) p = p -> right ; else p = getNextRight ( p ) ; } } int main ( ) { node * root = new node ( 10 ) ; root -> left = new node ( 8 ) ; root -> right = new node ( 2 ) ; root -> left -> left = new node ( 3 ) ; root -> right -> right = new node ( 90 ) ; connectRecur ( root ) ; cout << " Following ▁ are ▁ populated ▁ nextRight ▁ pointers ▁ in ▁ the ▁ tree " " ▁ ( -1 ▁ is ▁ printed ▁ if ▁ there ▁ is ▁ no ▁ nextRight ) ▁ STRNEWLINE " ; cout << " nextRight ▁ of ▁ " << root -> data << " ▁ is ▁ " << ( root -> nextRight ? root -> nextRight -> data : -1 ) << endl ; cout << " nextRight ▁ of ▁ " << root -> left -> data << " ▁ is ▁ " << ( root -> left -> nextRight ? root -> left -> nextRight -> data : -1 ) << endl ; cout << " nextRight ▁ of ▁ " << root -> right -> data << " ▁ is ▁ " << ( root -> right -> nextRight ? root -> right -> nextRight -> data : -1 ) << endl ; cout << " nextRight ▁ of ▁ " << root -> left -> left -> data << " ▁ is ▁ " << ( root -> left -> left -> nextRight ? root -> left -> left -> nextRight -> data : -1 ) << endl ; cout << " nextRight ▁ of ▁ " << root -> right -> right -> data << " ▁ is ▁ " << ( root -> right -> right -> nextRight ? root -> right -> right -> nextRight -> data : -1 ) << endl ; return 0 ; }
Number of ways to partition a string into two balanced subsequences | C ++ implementation of the above approach ; For maximum length of input string ; Declaring the DP table ; Function to calculate the number of valid assignments ; Return 1 if both subsequences are balanced ; Increment the count if it an opening bracket ; Decrement the count if it a closing bracket ; Driver code ; Initializing the DP table ; Initial value for c_x and c_y is zero
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 10 ; int F [ MAX ] [ MAX ] [ MAX ] ; int noOfAssignments ( string & S , int & n , int i , int c_x , int c_y ) { if ( F [ i ] [ c_x ] [ c_y ] != -1 ) return F [ i ] [ c_x ] [ c_y ] ; if ( i == n ) { F [ i ] [ c_x ] [ c_y ] = ! c_x && ! c_y ; return F [ i ] [ c_x ] [ c_y ] ; } if ( S [ i ] == ' ( ' ) { F [ i ] [ c_x ] [ c_y ] = noOfAssignments ( S , n , i + 1 , c_x + 1 , c_y ) + noOfAssignments ( S , n , i + 1 , c_x , c_y + 1 ) ; return F [ i ] [ c_x ] [ c_y ] ; } F [ i ] [ c_x ] [ c_y ] = 0 ; if ( c_x ) F [ i ] [ c_x ] [ c_y ] += noOfAssignments ( S , n , i + 1 , c_x - 1 , c_y ) ; if ( c_y ) F [ i ] [ c_x ] [ c_y ] += noOfAssignments ( S , n , i + 1 , c_x , c_y - 1 ) ; return F [ i ] [ c_x ] [ c_y ] ; } int main ( ) { string S = " ( ( ) ) " ; int n = S . length ( ) ; memset ( F , -1 , sizeof ( F ) ) ; cout << noOfAssignments ( S , n , 0 , 0 , 0 ) ; return 0 ; }
Gould 's Sequence | CPP program to generate Gould 's Sequence ; Utility function to count odd numbers in ith row of Pascals 's triangle ; Initialize count as zero ; Return 2 ^ count ; Function to generate gould 's Sequence ; loop to generate gould 's Sequence up to n ; Driver code ; Get n ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countOddNumber ( int row_num ) { unsigned int count = 0 ; while ( row_num ) { count += row_num & 1 ; row_num >>= 1 ; } return ( 1 << count ) ; } void gouldSequence ( int n ) { for ( int row_num = 0 ; row_num < n ; row_num ++ ) { cout << countOddNumber ( row_num ) << " ▁ " ; } } int main ( ) { int n = 16 ; gouldSequence ( n ) ; return 0 ; }
Count numbers ( smaller than or equal to N ) with given digit sum | ; N can be max 10 ^ 18 and hence digitsum will be 162 maximum . ; If sum_so_far equals to given sum then return 1 else 0 ; Our constructed number should not become greater than N . ; If tight is true then it will also be true for ( i + 1 ) digit . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long dp [ 18 ] [ 2 ] [ 162 ] ; long long solve ( int i , bool tight , int sum_so_far , int Sum , string number , int len ) { if ( i == len ) { if ( sum_so_far == Sum ) return 1 ; else return 0 ; } long long & ans = dp [ i ] [ tight ] [ sum_so_far ] ; if ( ans != -1 ) { return ans ; } ans = 0 ; bool ntight ; int nsum_so_far ; for ( char currdigit = '0' ; currdigit <= '9' ; currdigit ++ ) { if ( ! tight && currdigit > number [ i ] ) { break ; } ntight = tight || currdigit < number [ i ] ; nsum_so_far = sum_so_far + ( currdigit - '0' ) ; ans += solve ( i + 1 , ntight , nsum_so_far , Sum , number , len ) ; } return ans ; } int main ( ) { long long count = 0 ; long long sum = 4 ; string number = "100" ; memset ( dp , -1 , sizeof dp ) ; cout << solve ( 0 , 0 , 0 , sum , number , number . size ( ) ) ; return 0 ; }
Longest dividing subsequence | Dynamic Programming C ++ implementation of lds problem ; lds ( ) returns the length of the longest dividing subsequence in arr [ ] of size n ; Compute optimized lds values in bottom up manner ; Return maximum value in lds [ ] ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int lds ( int arr [ ] , int n ) { int lds [ n ] ; lds [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { lds [ i ] = 1 ; for ( int j = 0 ; j < i ; j ++ ) if ( lds [ j ] != 0 && arr [ i ] % arr [ j ] == 0 ) lds [ i ] = max ( lds [ i ] , lds [ j ] + 1 ) ; } return * max_element ( lds , lds + n ) ; } int main ( ) { int arr [ ] = { 2 , 11 , 16 , 12 , 36 , 60 , 71 , 17 , 29 , 144 , 288 , 129 , 432 , 993 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Length ▁ of ▁ lds ▁ is ▁ % d STRNEWLINE " , lds ( arr , n ) ) ; return 0 ; }
Memoization ( 1D , 2D and 3D ) | A recursive implementation of LCS problem of three strings ; Utility function to get max of 2 integers ; Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; base case ; if equal , then check for next combination ; recursive call ; return the maximum of the three other possible states in recursion ; Driver Code
#include <bits/stdc++.h> NEW_LINE int max ( int a , int b ) ; int max ( int a , int b ) { return ( a > b ) ? a : b ; } int lcs ( char * X , char * Y , char * Z , int m , int n , int o ) { if ( m == 0 n == 0 o == 0 ) return 0 ; if ( X [ m - 1 ] == Y [ n - 1 ] and Y [ n - 1 ] == Z [ o - 1 ] ) { return 1 + lcs ( X , Y , Z , m - 1 , n - 1 , o - 1 ) ; } else { return max ( lcs ( X , Y , Z , m , n - 1 , o ) , max ( lcs ( X , Y , Z , m - 1 , n , o ) , lcs ( X , Y , Z , m , n , o - 1 ) ) ) ; } } int main ( ) { char X [ ] = " geeks " ; char Y [ ] = " geeksfor " ; char Z [ ] = " geeksforge " ; int m = strlen ( X ) ; int n = strlen ( Y ) ; int o = strlen ( Z ) ; printf ( " Length ▁ of ▁ LCS ▁ is ▁ % d " , lcs ( X , Y , Z , m , n , o ) ) ; return 0 ; }
Memoization ( 1D , 2D and 3D ) | A memoize recursive implementation of LCS problem ; Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] memoization applied in recursive solution ; base case ; if the same state has already been computed ; if equal , then we store the value of the function call ; store it in arr to avoid further repetitive work in future function calls ; store it in arr to avoid further repetitive work in future function calls ; Utility function to get max of 2 integers ; Driver Code
#include <bits/stdc++.h> NEW_LINE int arr [ 100 ] [ 100 ] [ 100 ] ; int max ( int a , int b ) ; int lcs ( char * X , char * Y , char * Z , int m , int n , int o ) { if ( m == 0 n == 0 o == 0 ) return 0 ; if ( arr [ m - 1 ] [ n - 1 ] [ o - 1 ] != -1 ) return arr [ m - 1 ] [ n - 1 ] [ o - 1 ] ; if ( X [ m - 1 ] == Y [ n - 1 ] and Y [ n - 1 ] == Z [ o - 1 ] ) { arr [ m - 1 ] [ n - 1 ] [ o - 1 ] = 1 + lcs ( X , Y , Z , m - 1 , n - 1 , o - 1 ) ; return arr [ m - 1 ] [ n - 1 ] [ o - 1 ] ; } else { arr [ m - 1 ] [ n - 1 ] [ o - 1 ] = max ( lcs ( X , Y , Z , m , n - 1 , o ) , max ( lcs ( X , Y , Z , m - 1 , n , o ) , lcs ( X , Y , Z , m , n , o - 1 ) ) ) ; return arr [ m - 1 ] [ n - 1 ] [ o - 1 ] ; } } int max ( int a , int b ) { return ( a > b ) ? a : b ; } int main ( ) { memset ( arr , -1 , sizeof ( arr ) ) ; char X [ ] = " geeks " ; char Y [ ] = " geeksfor " ; char Z [ ] = " geeksforgeeks " ; int m = strlen ( X ) ; int n = strlen ( Y ) ; int o = strlen ( Z ) ; printf ( " Length ▁ of ▁ LCS ▁ is ▁ % d " , lcs ( X , Y , Z , m , n , o ) ) ; return 0 ; }
Find the probability of reaching all points after N moves from point N | C ++ program to calculate the probability of reaching all points after N moves from point N ; Function to calculate the probabilities ; Array where row represent the pass and the column represents the points on the line ; Initially the person can reach left or right with one move ; Calculate probabilities for N - 1 moves ; when the person moves from ith index in right direction when i moves has been done ; when the person moves from ith index in left direction when i moves has been done ; Print the arr ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printProbabilities ( int n , double left ) { double right = 1 - left ; double arr [ n + 1 ] [ 2 * n + 1 ] = { { 0 } } ; arr [ 1 ] [ n + 1 ] = right ; arr [ 1 ] [ n - 1 ] = left ; for ( int i = 2 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= 2 * n ; j ++ ) arr [ i ] [ j ] += ( arr [ i - 1 ] [ j - 1 ] * right ) ; for ( int j = 2 * n - 1 ; j >= 0 ; j -- ) arr [ i ] [ j ] += ( arr [ i - 1 ] [ j + 1 ] * left ) ; } for ( int i = 0 ; i < 2 * n + 1 ; i ++ ) printf ( " % 5.4f ▁ " , arr [ n ] [ i ] ) ; } int main ( ) { int n = 2 ; double left = 0.5 ; printProbabilities ( n , left ) ; return 0 ; }
Check if it is possible to reach a number by making jumps of two given length | ; Function to perform BFS traversal to find minimum number of step needed to reach x from K ; Calculate GCD of d1 and d2 ; If position is not reachable return - 1 ; Queue for BFS ; Hash Table for marking visited positions ; we need 0 steps to reach K ; Mark starting position as visited ; stp is the number of steps to reach position s ; if position not visited add to queue and mark visited ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minStepsNeeded ( int k , int d1 , int d2 , int x ) { int gcd = __gcd ( d1 , d2 ) ; if ( ( k - x ) % gcd != 0 ) return -1 ; queue < pair < int , int > > q ; unordered_set < int > visited ; q . push ( { k , 0 } ) ; visited . insert ( k ) ; while ( ! q . empty ( ) ) { int s = q . front ( ) . first ; int stp = q . front ( ) . second ; if ( s == x ) return stp ; q . pop ( ) ; if ( visited . find ( s + d1 ) == visited . end ( ) ) { q . push ( { s + d1 , stp + 1 } ) ; visited . insert ( s + d1 ) ; } if ( visited . find ( s + d2 ) == visited . end ( ) ) { q . push ( { s + d2 , stp + 1 } ) ; visited . insert ( s + d2 ) ; } if ( visited . find ( s - d1 ) == visited . end ( ) ) { q . push ( { s - d1 , stp + 1 } ) ; visited . insert ( s - d1 ) ; } if ( visited . find ( s - d2 ) == visited . end ( ) ) { q . push ( { s - d2 , stp + 1 } ) ; visited . insert ( s - d2 ) ; } } } int main ( ) { int k = 10 , d1 = 4 , d2 = 6 , x = 8 ; cout << minStepsNeeded ( k , d1 , d2 , x ) ; return 0 ; }
Tiling with Dominoes | C ++ program to find no . of ways to fill a 3 xn board with 2 x1 dominoes . ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int countWays ( int n ) { int A [ n + 1 ] , B [ n + 1 ] ; A [ 0 ] = 1 , A [ 1 ] = 0 , B [ 0 ] = 0 , B [ 1 ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { A [ i ] = A [ i - 2 ] + 2 * B [ i - 1 ] ; B [ i ] = A [ i - 1 ] + B [ i - 2 ] ; } return A [ n ] ; } int main ( ) { int n = 8 ; cout << countWays ( n ) ; return 0 ; }
Newman | C ++ program for n - th element of Newman - Conway Sequence ; Recursive Function to find the n - th element ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sequence ( int n ) { if ( n == 1 n == 2 ) return 1 ; else return sequence ( sequence ( n - 1 ) ) + sequence ( n - sequence ( n - 1 ) ) ; } int main ( ) { int n = 10 ; cout << sequence ( n ) ; return 0 ; }
Connect nodes at same level | CPP program to connect nodes at same level using extended pre - order traversal ; Constructor that allocates a new node with the given data and NULL left and right pointers . ; Sets the nextRight of root and calls connectRecur ( ) for other nodes ; Set the nextRight for root ; Set the next right for rest of the nodes ( other than root ) ; Set next right of all descendents of p . Assumption : p is a compete binary tree ; Base case ; Set the nextRight pointer for p 's left child ; Set the nextRight pointer for p 's right child p->nextRight will be NULL if p is the right most child at its level ; Set nextRight for other nodes in pre order fashion ; Driver code ; Constructed binary tree is 10 / \ 8 2 / 3 ; Populates nextRight pointer in all nodes ; Let us check the values of nextRight pointers
#include <bits/stdc++.h> NEW_LINE #include <iostream> NEW_LINE using namespace std ; class node { public : int data ; node * left ; node * right ; node * nextRight ; node ( int data ) { this -> data = data ; this -> left = NULL ; this -> right = NULL ; this -> nextRight = NULL ; } } ; void connectRecur ( node * p ) ; void connect ( node * p ) { p -> nextRight = NULL ; connectRecur ( p ) ; } void connectRecur ( node * p ) { if ( ! p ) return ; if ( p -> left ) p -> left -> nextRight = p -> right ; if ( p -> right ) p -> right -> nextRight = ( p -> nextRight ) ? p -> nextRight -> left : NULL ; connectRecur ( p -> left ) ; connectRecur ( p -> right ) ; } int main ( ) { node * root = new node ( 10 ) ; root -> left = new node ( 8 ) ; root -> right = new node ( 2 ) ; root -> left -> left = new node ( 3 ) ; connect ( root ) ; cout << " Following ▁ are ▁ populated ▁ nextRight ▁ pointers ▁ in ▁ the ▁ tree " " ▁ ( -1 ▁ is ▁ printed ▁ if ▁ there ▁ is ▁ no ▁ nextRight ) STRNEWLINE " ; cout << " nextRight ▁ of ▁ " << root -> data << " ▁ is ▁ " << ( root -> nextRight ? root -> nextRight -> data : -1 ) << endl ; cout << " nextRight ▁ of ▁ " << root -> left -> data << " ▁ is ▁ " << ( root -> left -> nextRight ? root -> left -> nextRight -> data : -1 ) << endl ; cout << " nextRight ▁ of ▁ " << root -> right -> data << " ▁ is ▁ " << ( root -> right -> nextRight ? root -> right -> nextRight -> data : -1 ) << endl ; cout << " nextRight ▁ of ▁ " << root -> left -> left -> data << " ▁ is ▁ " << ( root -> left -> left -> nextRight ? root -> left -> left -> nextRight -> data : -1 ) << endl ; return 0 ; }
Variants of Binary Search | C ++ program to variants of Binary Search ; array size ; Sorted array ; Find if key is in array * Returns : True if key belongs to array , * False if key doesn 't belong to array ; if mid is less than key , all elements in range [ low , mid ] are also less so we now search in [ mid + 1 , high ] ; if mid is greater than key , all elements in range [ mid + 1 , high ] are also greater so we now search in [ low , mid - 1 ] ; comparison added just for the sake of clarity if mid is equal to key , we have found that key exists in array ; Find first occurrence index of key in array * Returns : an index in range [ 0 , n - 1 ] if key belongs * to array , - 1 if key doesn 't belong to array ; if mid is less than key , all elements in range [ low , mid ] are also less so we now search in [ mid + 1 , high ] ; if mid is greater than key , all elements in range [ mid + 1 , high ] are also greater so we now search in [ low , mid - 1 ] ; if mid is equal to key , we note down the last found index then we search for more in left side of mid so we now search in [ low , mid - 1 ] ; Find last occurrence index of key in array * Returns : an index in range [ 0 , n - 1 ] if key belongs to array , * - 1 if key doesn 't belong to array ; if mid is less than key , then all elements in range [ low , mid - 1 ] are also less so we now search in [ mid + 1 , high ] ; if mid is greater than key , then all elements in range [ mid + 1 , high ] are also greater so we now search in [ low , mid - 1 ] ; if mid is equal to key , we note down the last found index then we search for more in right side of mid so we now search in [ mid + 1 , high ] ; Find index of first occurrence of least element greater than key in array * Returns : an index in range [ 0 , n - 1 ] if key is not the greatest element in array , * - 1 if key is the greatest element in array ; if mid is less than key , all elements in range [ low , mid - 1 ] are <= key then we search in right side of mid so we now search in [ mid + 1 , high ] ; if mid is greater than key , all elements in range [ mid + 1 , high ] are >= key we note down the last found index , then we search in left side of mid so we now search in [ low , mid - 1 ] ; if mid is equal to key , all elements in range [ low , mid ] are <= key so we now search in [ mid + 1 , high ] ; Find index of last occurrence of greatest element less than key in array * Returns : an index in range [ 0 , n - 1 ] if key is not the least element in array , * - 1 if key is the least element in array ; if mid is less than key , all elements in range [ low , mid - 1 ] are < key we note down the last found index , then we search in right side of mid so we now search in [ mid + 1 , high ] ; if mid is greater than key , all elements in range [ mid + 1 , high ] are > key then we search in left side of mid so we now search in [ low , mid - 1 ] ; if mid is equal to key , all elements in range [ mid + 1 , high ] are >= key then we search in left side of mid so we now search in [ low , mid - 1 ] ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int n = 8 ; int a [ ] = { 2 , 3 , 3 , 5 , 5 , 5 , 6 , 6 } ; bool contains ( int low , int high , int key ) { bool ans = false ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; int midVal = a [ mid ] ; if ( midVal < key ) { low = mid + 1 ; } else if ( midVal > key ) { high = mid - 1 ; } else if ( midVal == key ) { ans = true ; break ; } } return ans ; } int first ( int low , int high , int key ) { int ans = -1 ; while ( low <= high ) { int mid = low + ( high - low + 1 ) / 2 ; int midVal = a [ mid ] ; if ( midVal < key ) { low = mid + 1 ; } else if ( midVal > key ) { high = mid - 1 ; } else if ( midVal == key ) { ans = mid ; high = mid - 1 ; } } return ans ; } int last ( int low , int high , int key ) { int ans = -1 ; while ( low <= high ) { int mid = low + ( high - low + 1 ) / 2 ; int midVal = a [ mid ] ; if ( midVal < key ) { low = mid + 1 ; } else if ( midVal > key ) { high = mid - 1 ; } else if ( midVal == key ) { ans = mid ; low = mid + 1 ; } } return ans ; } int leastgreater ( int low , int high , int key ) { int ans = -1 ; while ( low <= high ) { int mid = low + ( high - low + 1 ) / 2 ; int midVal = a [ mid ] ; if ( midVal < key ) { low = mid + 1 ; } else if ( midVal > key ) { ans = mid ; high = mid - 1 ; } else if ( midVal == key ) { low = mid + 1 ; } } return ans ; } int greatestlesser ( int low , int high , int key ) { int ans = -1 ; while ( low <= high ) { int mid = low + ( high - low + 1 ) / 2 ; int midVal = a [ mid ] ; if ( midVal < key ) { ans = mid ; low = mid + 1 ; } else if ( midVal > key ) { high = mid - 1 ; } else if ( midVal == key ) { high = mid - 1 ; } } return ans ; } int main ( ) { printf ( " Contains STRNEWLINE " ) ; for ( int i = 0 ; i < 10 ; i ++ ) printf ( " % d ▁ % d STRNEWLINE " , i , contains ( 0 , n - 1 , i ) ) ; printf ( " First ▁ occurrence ▁ of ▁ key STRNEWLINE " ) ; for ( int i = 0 ; i < 10 ; i ++ ) printf ( " % d ▁ % d STRNEWLINE " , i , first ( 0 , n - 1 , i ) ) ; printf ( " Last ▁ occurrence ▁ of ▁ key STRNEWLINE " ) ; for ( int i = 0 ; i < 10 ; i ++ ) printf ( " % d ▁ % d STRNEWLINE " , i , last ( 0 , n - 1 , i ) ) ; printf ( " Least ▁ integer ▁ greater ▁ than ▁ key STRNEWLINE " ) ; for ( int i = 0 ; i < 10 ; i ++ ) printf ( " % d ▁ % d STRNEWLINE " , i , leastgreater ( 0 , n - 1 , i ) ) ; printf ( " Greatest ▁ integer ▁ lesser ▁ than ▁ key STRNEWLINE " ) ; for ( int i = 0 ; i < 10 ; i ++ ) printf ( " % d ▁ % d STRNEWLINE " , i , greatestlesser ( 0 , n - 1 , i ) ) ; return 0 ; }
Counting pairs when a person can form pair with at most one | Number of ways in which participant can take part . ; Base condition ; A participant can choose to consider ( 1 ) Remains single . Number of people reduce to ( x - 1 ) ( 2 ) Pairs with one of the ( x - 1 ) others . For every pairing , number of people reduce to ( x - 2 ) . ; Driver code
#include <iostream> NEW_LINE using namespace std ; int numberOfWays ( int x ) { if ( x == 0 x == 1 ) return 1 ; else return numberOfWays ( x - 1 ) + ( x - 1 ) * numberOfWays ( x - 2 ) ; } int main ( ) { int x = 3 ; cout << numberOfWays ( x ) << endl ; return 0 ; }
Counting pairs when a person can form pair with at most one | Number of ways in which participant can take part . ; Driver code
#include <iostream> NEW_LINE using namespace std ; int numberOfWays ( int x ) { int dp [ x + 1 ] ; dp [ 0 ] = dp [ 1 ] = 1 ; for ( int i = 2 ; i <= x ; i ++ ) dp [ i ] = dp [ i - 1 ] + ( i - 1 ) * dp [ i - 2 ] ; return dp [ x ] ; } int main ( ) { int x = 3 ; cout << numberOfWays ( x ) << endl ; return 0 ; }
Longest Repeated Subsequence | Refer https : www . geeksforgeeks . org / longest - repeating - subsequence / for complete code . This function mainly returns LCS ( str , str ) with a condition that same characters at same index are not considered . ; Create and initialize DP table ; initializing first row and column in dp table ; Fill dp table ( similar to LCS loops ) ; If characters match and indexes are not same ; If characters do not match
int findLongestRepeatingSubSeq ( string str ) { int n = str . length ( ) ; int dp [ n + 1 ] [ n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) { dp [ i ] [ 0 ] = 0 ; dp [ 0 ] [ i ] = 0 ; } for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( str [ i - 1 ] == str [ j - 1 ] && i != j ) dp [ i ] [ j ] = 1 + dp [ i - 1 ] [ j - 1 ] ; else dp [ i ] [ j ] = max ( dp [ i ] [ j - 1 ] , dp [ i - 1 ] [ j ] ) ; } } return dp [ n ] [ n ] ; }
Number of ways to arrange N items under given constraints | C ++ program to find number of ways to arrange items under given constraint ; method returns number of ways with which items can be arranged ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; declare dp array to store result up to ith colored item ; variable to keep track of count of items considered till now ; loop over all different colors ; populate next value using current value and stated relation ; return value stored at last index ; Driver code to test above methods
#include <bits/stdc++.h> NEW_LINE using namespace std ; int waysToArrange ( int N , int K , int k [ ] ) { int C [ N + 1 ] [ N + 1 ] ; int i , j ; for ( i = 0 ; i <= N ; i ++ ) { for ( j = 0 ; j <= i ; j ++ ) { if ( j == 0 j == i ) C [ i ] [ j ] = 1 ; else C [ i ] [ j ] = ( C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] ) ; } } int dp [ K ] ; int count = 0 ; dp [ 0 ] = 1 ; for ( int i = 0 ; i < K ; i ++ ) { dp [ i + 1 ] = ( dp [ i ] * C [ count + k [ i ] - 1 ] [ k [ i ] - 1 ] ) ; count += k [ i ] ; } return dp [ K ] ; } int main ( ) { int N = 4 ; int k [ ] = { 2 , 2 } ; int K = sizeof ( k ) / sizeof ( int ) ; cout << waysToArrange ( N , K , k ) << endl ; return 0 ; }
Minimum cells required to reach destination with jumps equal to cell values | C ++ implementation to count minimum cells required to be covered to reach destination ; function to count minimum cells required to be covered to reach destination ; to store min cells required to be covered to reach a particular cell ; initially no cells can be reached ; base case ; building up the dp [ ] [ ] matrix ; dp [ i ] [ j ] != INT_MAX denotes that cell ( i , j ) can be reached from cell ( 0 , 0 ) and the other half of the condition finds the cell on the right that can be reached from ( i , j ) ; the other half of the condition finds the cell right below that can be reached from ( i , j ) ; it true then cell ( m - 1 , n - 1 ) can be reached from cell ( 0 , 0 ) and returns the minimum number of cells covered ; cell ( m - 1 , n - 1 ) cannot be reached from cell ( 0 , 0 ) ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define SIZE 100 NEW_LINE int minCells ( int mat [ SIZE ] [ SIZE ] , int m , int n ) { int dp [ m ] [ n ] ; for ( int i = 0 ; i < m ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) dp [ i ] [ j ] = INT_MAX ; dp [ 0 ] [ 0 ] = 1 ; for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( dp [ i ] [ j ] != INT_MAX && ( j + mat [ i ] [ j ] ) < n && ( dp [ i ] [ j ] + 1 ) < dp [ i ] [ j + mat [ i ] [ j ] ] ) dp [ i ] [ j + mat [ i ] [ j ] ] = dp [ i ] [ j ] + 1 ; if ( dp [ i ] [ j ] != INT_MAX && ( i + mat [ i ] [ j ] ) < m && ( dp [ i ] [ j ] + 1 ) < dp [ i + mat [ i ] [ j ] ] [ j ] ) dp [ i + mat [ i ] [ j ] ] [ j ] = dp [ i ] [ j ] + 1 ; } } if ( dp [ m - 1 ] [ n - 1 ] != INT_MAX ) return dp [ m - 1 ] [ n - 1 ] ; return -1 ; } int main ( ) { int mat [ SIZE ] [ SIZE ] = { { 2 , 3 , 2 , 1 , 4 } , { 3 , 2 , 5 , 8 , 2 } , { 1 , 1 , 2 , 2 , 1 } } ; int m = 3 , n = 5 ; cout << " Minimum ▁ number ▁ of ▁ cells ▁ = ▁ " << minCells ( mat , m , n ) ; return 0 ; }
Find longest bitonic sequence such that increasing and decreasing parts are from two different arrays | CPP to find largest bitonic sequence such that ; utility Binary search ; function to find LIS in reverse form ; int len = 1 ; it will always point to empty location ; new smallest value ; arr [ i ] wants to extend largest subsequence ; arr [ i ] wants to be a potential candidate of future subsequence It will replace ceil value in tailIndices ; put LIS into vector ; function for finding longest bitonic seq ; find LIS of array 1 in reverse form ; reverse res to get LIS of first array ; reverse array2 and find its LIS ; print result ; driver preogram
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > res ; int GetCeilIndex ( int arr [ ] , vector < int > & T , int l , int r , int key ) { while ( r - l > 1 ) { int m = l + ( r - l ) / 2 ; if ( arr [ T [ m ] ] >= key ) r = m ; else l = m ; } return r ; } void LIS ( int arr [ ] , int n ) { for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] < arr [ tailIndices [ 0 ] ] ) tailIndices [ 0 ] = i ; else if ( arr [ i ] > arr [ tailIndices [ len - 1 ] ] ) { prevIndices [ i ] = tailIndices [ len - 1 ] ; tailIndices [ len ++ ] = i ; } else { int pos = GetCeilIndex ( arr , tailIndices , -1 , len - 1 , arr [ i ] ) ; prevIndices [ i ] = tailIndices [ pos - 1 ] ; tailIndices [ pos ] = i ; } } for ( int i = tailIndices [ len - 1 ] ; i >= 0 ; i = prevIndices [ i ] ) res . push_back ( arr [ i ] ) ; } void longestBitonic ( int arr1 [ ] , int n1 , int arr2 [ ] , int n2 ) { LIS ( arr1 , n1 ) ; reverse ( res . begin ( ) , res . end ( ) ) ; reverse ( arr2 , arr2 + n2 ) ; LIS ( arr2 , n2 ) ; for ( int i = 0 ; i < res . size ( ) ; i ++ ) cout << res [ i ] << " ▁ " ; } int main ( ) { int arr1 [ ] = { 1 , 2 , 4 , 3 , 2 } ; int arr2 [ ] = { 8 , 6 , 4 , 7 , 8 , 9 } ; int n1 = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int n2 = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; longestBitonic ( arr1 , n1 , arr2 , n2 ) ; return 0 ; }
Maximize the binary matrix by filpping submatrix once | C ++ program to find maximum number of ones after one flipping in Binary Matrix ; Return number of ones in square submatrix of size k x k starting from ( x , y ) ; Return maximum number of 1 s after flipping a submatrix ; Precomputing the number of 1 s ; Finding the maximum number of 1 s after flipping ; Driver code
#include <bits/stdc++.h> NEW_LINE #define R 3 NEW_LINE #define C 3 NEW_LINE using namespace std ; int cal ( int ones [ R + 1 ] [ C + 1 ] , int x , int y , int k ) { return ones [ x + k - 1 ] [ y + k - 1 ] - ones [ x - 1 ] [ y + k - 1 ] - ones [ x + k - 1 ] [ y - 1 ] + ones [ x - 1 ] [ y - 1 ] ; } int sol ( int mat [ R ] [ C ] ) { int ans = 0 ; int ones [ R + 1 ] [ C + 1 ] = { 0 } ; for ( int i = 1 ; i <= R ; i ++ ) for ( int j = 1 ; j <= C ; j ++ ) ones [ i ] [ j ] = ones [ i - 1 ] [ j ] + ones [ i ] [ j - 1 ] - ones [ i - 1 ] [ j - 1 ] + ( mat [ i - 1 ] [ j - 1 ] == 1 ) ; for ( int k = 1 ; k <= min ( R , C ) ; k ++ ) for ( int i = 1 ; i + k - 1 <= R ; i ++ ) for ( int j = 1 ; j + k - 1 <= C ; j ++ ) ans = max ( ans , ( ones [ R ] [ C ] + k * k - 2 * cal ( ones , i , j , k ) ) ) ; return ans ; } int main ( ) { int mat [ R ] [ C ] = { { 0 , 0 , 1 } , { 0 , 0 , 1 } , { 1 , 0 , 1 } } ; cout << sol ( mat ) << endl ; return 0 ; }
Level with maximum number of nodes | C ++ implementation to find the level having maximum number of Nodes ; A binary tree Node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; function to find the level having maximum number of Nodes ; Current level ; Maximum Nodes at same level ; Level having maximum Nodes ; Count Nodes in a level ; If it is maximum till now Update level_no to current level ; Pop complete current level ; Increment for next level ; Driver program to test above ; binary tree formation ; 2 ; / \ ; 1 3 ; / \ \ ; 4 6 8 ; / ; 5
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left ; struct Node * right ; } ; struct Node * newNode ( int data ) { struct Node * node = new Node ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; return ( node ) ; } int maxNodeLevel ( Node * root ) { if ( root == NULL ) return -1 ; queue < Node * > q ; q . push ( root ) ; int level = 0 ; int max = INT_MIN ; int level_no = 0 ; while ( 1 ) { int NodeCount = q . size ( ) ; if ( NodeCount == 0 ) break ; if ( NodeCount > max ) { max = NodeCount ; level_no = level ; } while ( NodeCount > 0 ) { Node * Node = q . front ( ) ; q . pop ( ) ; if ( Node -> left != NULL ) q . push ( Node -> left ) ; if ( Node -> right != NULL ) q . push ( Node -> right ) ; NodeCount -- ; } level ++ ; } return level_no ; } int main ( ) { struct Node * root = newNode ( 2 ) ; root -> left = newNode ( 1 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 6 ) ; root -> right -> right = newNode ( 8 ) ; root -> left -> right -> left = newNode ( 5 ) ; printf ( " Level ▁ having ▁ maximum ▁ number ▁ of ▁ Nodes ▁ : ▁ % d " , maxNodeLevel ( root ) ) ; return 0 ; }
Minimum steps to minimize n as per given condition | ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMinSteps ( int n ) { int table [ n + 1 ] ; table [ 1 ] = 0 ; for ( int i = 2 ; i <= n ; i ++ ) { if ( ! ( i % 2 ) && ( i % 3 ) ) table [ i ] = 1 + min ( table [ i - 1 ] , table [ i / 2 ] ) ; else if ( ! ( i % 3 ) && ( i % 2 ) ) table [ i ] = 1 + min ( table [ i - 1 ] , table [ i / 3 ] ) ; else if ( ! ( i % 2 ) && ! ( i % 3 ) ) table [ i ] = 1 + min ( table [ i - 1 ] , min ( table [ i / 2 ] , table [ i / 3 ] ) ) ; else table [ i ] = 1 + table [ i - 1 ] ; } return table [ n ] ; } int main ( ) { int n = 14 ; cout << getMinSteps ( n ) ; return 0 ; }
How to solve a Dynamic Programming Problem ? | Returns the number of arrangements to form ' n ' ; base case
int solve ( int n ) { if ( n < 0 ) return 0 ; if ( n == 0 ) return 1 ; return solve ( n - 1 ) + solve ( n - 3 ) + solve ( n - 5 ) ; }
Maximum points collected by two persons allowed to meet once | C ++ program to find maximum points that can be collected by two persons in a matrix . ; To store points collected by Person P1 when he / she begins journy from start and from end . ; To store points collected by Person P2 when he / she begins journey from start and from end . ; Table for P1 's journey from start to meeting cell ; Table for P1 's journey from end to meet cell ; Table for P2 's journey from start to meeting cell ; Table for P2 's journey from end to meeting cell ; Now iterate over all meeting positions ( i , j ) ; Driver code ; input the calories burnt matrix
#include <bits/stdc++.h> NEW_LINE #define M 3 NEW_LINE #define N 3 NEW_LINE using namespace std ; int findMaxPoints ( int A [ ] [ M ] ) { int P1S [ M + 1 ] [ N + 1 ] , P1E [ M + 1 ] [ N + 1 ] ; memset ( P1S , 0 , sizeof ( P1S ) ) ; memset ( P1E , 0 , sizeof ( P1E ) ) ; int P2S [ M + 1 ] [ N + 1 ] , P2E [ M + 1 ] [ N + 1 ] ; memset ( P2S , 0 , sizeof ( P2S ) ) ; memset ( P2E , 0 , sizeof ( P2E ) ) ; for ( int i = 1 ; i <= N ; i ++ ) for ( int j = 1 ; j <= M ; j ++ ) P1S [ i ] [ j ] = max ( P1S [ i - 1 ] [ j ] , P1S [ i ] [ j - 1 ] ) + A [ i - 1 ] [ j - 1 ] ; for ( int i = N ; i >= 1 ; i -- ) for ( int j = M ; j >= 1 ; j -- ) P1E [ i ] [ j ] = max ( P1E [ i + 1 ] [ j ] , P1E [ i ] [ j + 1 ] ) + A [ i - 1 ] [ j - 1 ] ; for ( int i = N ; i >= 1 ; i -- ) for ( int j = 1 ; j <= M ; j ++ ) P2S [ i ] [ j ] = max ( P2S [ i + 1 ] [ j ] , P2S [ i ] [ j - 1 ] ) + A [ i - 1 ] [ j - 1 ] ; for ( int i = 1 ; i <= N ; i ++ ) for ( int j = M ; j >= 1 ; j -- ) P2E [ i ] [ j ] = max ( P2E [ i - 1 ] [ j ] , P2E [ i ] [ j + 1 ] ) + A [ i - 1 ] [ j - 1 ] ; int ans = 0 ; for ( int i = 2 ; i < N ; i ++ ) { for ( int j = 2 ; j < M ; j ++ ) { int op1 = P1S [ i ] [ j - 1 ] + P1E [ i ] [ j + 1 ] + P2S [ i + 1 ] [ j ] + P2E [ i - 1 ] [ j ] ; int op2 = P1S [ i - 1 ] [ j ] + P1E [ i + 1 ] [ j ] + P2S [ i ] [ j - 1 ] + P2E [ i ] [ j + 1 ] ; ans = max ( ans , max ( op1 , op2 ) ) ; } } return ans ; } int main ( ) { int A [ ] [ M ] = { { 100 , 100 , 100 } , { 100 , 1 , 100 } , { 100 , 100 , 100 } } ; cout << " Max ▁ Points ▁ : ▁ " << findMaxPoints ( A ) ; return 0 ; }