text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Modulo Operations in Programming With Negative Results | C ++ 14 program to illustrate modulo operations using the above equation ; Function to calculate and return the remainder of a % n ; ( a / n ) implicitly gives the truncated result ; Driver Code ; Modulo of two positive numbers ; Modulo of a negative number by a positive number ; Modulo of a positive number by a negative number ; Modulo of two negative numbers
#include <bits/stdc++.h> NEW_LINE using namespace std ; int truncMod ( int a , int n ) { int q = a / n ; return a - n * q ; } int main ( ) { int a , b ; a = 9 ; b = 4 ; cout << a << " ▁ % ▁ " << b << " ▁ = ▁ " << truncMod ( a , b ) << endl ; a = -9 ; b = 4 ; cout << a << " ▁ % ▁ " << b << " ▁ = ▁ " << truncMod ( a , b ) << endl ; a = 9 ; b = -4 ; cout << a << " ▁ % ▁ " << b << " ▁ = ▁ " << truncMod ( a , b ) << endl ; a = -9 ; b = -4 ; cout << a << " ▁ % ▁ " << b << " ▁ = ▁ " << truncMod ( a , b ) << endl ; }
Program for average of an array without running into overflow | C ++ program for the above approach ; Function to calculate average of an array using standard method ; Stores the sum of array ; Find the sum of the array ; Return the average ; Function to calculate average of an array using efficient method ; Store the average of the array ; Traverse the array arr [ ] ; Update avg ; Return avg ; Driver Code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; double average ( int arr [ ] , int N ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) sum += arr [ i ] ; return ( double ) sum / N ; } double mean ( int arr [ ] , int N ) { double avg = 0 ; for ( int i = 0 ; i < N ; i ++ ) { avg += ( arr [ i ] - avg ) / ( i + 1 ) ; } return avg ; } int main ( ) { int arr [ ] = { INT_MAX , 1 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Average ▁ by ▁ Standard ▁ method : ▁ " << fixed << setprecision ( 10 ) << average ( arr , N ) << endl ; cout << " Average ▁ by ▁ Efficient ▁ method : ▁ " << fixed << setprecision ( 10 ) << mean ( arr , N ) << endl ; return 0 ; }
Count number of pairs ( i , j ) from an array such that arr [ i ] * j = arr [ j ] * i | C ++ program for the above approach ; Function to count pairs from an array satisfying given conditions ; Stores the total count of pairs ; Stores count of a [ i ] / i ; Traverse the array ; Updating count ; Update frequency in the Map ; Print count of pairs ; Driver Code ; Given array ; Size of the array ; Function call to count pairs satisfying given conditions
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countPairs ( int arr [ ] , int N ) { int count = 0 ; unordered_map < double , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { double val = 1.0 * arr [ i ] ; double idx = 1.0 * ( i + 1 ) ; count += mp [ val / idx ] ; mp [ val / idx ] ++ ; } cout << count ; } int main ( ) { int arr [ ] = { 1 , 3 , 5 , 6 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countPairs ( arr , N ) ; return 0 ; }
Count ancestors with smaller value for each node of a Binary Tree | C ++ program for the above approach ; Function to add an edge between nodes u and v ; Function to perform the DFS Traversal and store parent of each node ; Store the immediate parent ; Traverse the children of the current node ; Recursively call for function dfs for the child node ; Function to count the number of ancestors with values smaller than that of the current node ; Stores the parent of each node ; Perform the DFS Traversal ; Traverse all the nodes ; Store the number of ancestors smaller than node ; Loop until parent [ node ] != - 1 ; If the condition satisfies , increment cnt by 1 ; Print the required result for the current node ; Driver Code ; Tree Formation
#include <bits/stdc++.h> NEW_LINE using namespace std ; void add_edge ( vector < int > adj [ ] , int u , int v ) { adj [ u ] . push_back ( v ) ; adj [ v ] . push_back ( u ) ; } void dfs ( vector < int > & parent , vector < int > adj [ ] , int u , int par = -1 ) { parent [ u ] = par ; for ( auto child : adj [ u ] ) { if ( child != par ) dfs ( parent , adj , child , u ) ; } } void countSmallerAncestors ( vector < int > adj [ ] , int n ) { vector < int > parent ( int ( 1e5 ) , 0 ) ; dfs ( parent , adj , 1 ) ; for ( int i = 1 ; i <= n ; i ++ ) { int node = i ; int cnt = 0 ; while ( parent [ node ] != -1 ) { if ( parent [ node ] < i ) cnt += 1 ; node = parent [ node ] ; } cout << cnt << " ▁ " ; } } int main ( ) { int N = 6 ; vector < int > adj [ int ( 1e5 ) ] ; add_edge ( adj , 1 , 5 ) ; add_edge ( adj , 1 , 4 ) ; add_edge ( adj , 4 , 6 ) ; add_edge ( adj , 5 , 3 ) ; add_edge ( adj , 5 , 2 ) ; countSmallerAncestors ( adj , N ) ; return 0 ; }
Count subsequences having odd Bitwise XOR values from an array | C ++ program for the above approach ; Function to count the subsequences having odd bitwise XOR value ; Stores count of odd elements ; Stores count of even elements ; Traverse the array A [ ] ; If el is odd ; If count of odd elements is 0 ; Driver Code ; Given array A [ ] ; Function call to count subsequences having odd bitwise XOR value
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countSubsequences ( vector < int > A ) { int odd = 0 ; int even = 0 ; for ( int el : A ) { if ( el % 2 == 1 ) odd ++ ; else even ++ ; } if ( odd == 0 ) cout << ( 0 ) ; else cout << ( 1 << ( A . size ( ) - 1 ) ) ; } int main ( ) { vector < int > A = { 1 , 3 , 4 } ; countSubsequences ( A ) ; }
Maximum subarray product modulo M | C ++ program for above approach ; Function to find maximum subarray product modulo M and minimum length of the subarray ; Stores maximum subarray product modulo M and minimum length of the subarray ; Stores the minimum length of subarray having maximum product ; Traverse the array ; Stores the product of a subarray ; Calculate Subarray whose start index is i ; Multiply product by arr [ i ] ; If product greater than ans ; Update ans ; Update length ; Print maximum subarray product mod M ; Print minimum length of subarray having maximum product ; Drivers Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxModProdSubarr ( int arr [ ] , int n , int M ) { int ans = 0 ; int length = n ; for ( int i = 0 ; i < n ; i ++ ) { int product = 1 ; for ( int j = i ; j < n ; j ++ ) { product = ( product * arr [ i ] ) % M ; if ( product > ans ) { ans = product ; if ( length > j - i + 1 ) { length = j - i + 1 ; } } } } cout << " Maximum ▁ subarray ▁ product ▁ is ▁ " << ans << endl ; cout << " Minimum ▁ length ▁ of ▁ the ▁ maximum ▁ product ▁ " << " subarray ▁ is ▁ " << length << endl ; } int main ( ) { int arr [ ] = { 2 , 3 , 4 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int M = 5 ; maxModProdSubarr ( arr , N , M ) ; return 0 ; }
Number of co | C ++ program for the above approach ; Function to check whether given integers are co - prime or not ; Utility function to count number of co - prime pairs ; Traverse the array ; If co - prime ; Increment count ; Return count ; Function to count number of co - prime pairs ; Stores digits in string form ; Sort the list ; Keep two copies of list l ; Generate 2 digit numbers using d1 and d2 ; If current number does not exceed N ; Stores length of list ; Stores number of co - prime pairs ; Print number of co - prime pairs ; Driver Code ; Given value of N , d1 , d2 ; Function call to count number of co - prime pairs
#include <bits/stdc++.h> NEW_LINE using namespace std ; int coprime ( int a , int b ) { return ( __gcd ( a , b ) == 1 ) ; } int numOfPairs ( vector < string > arr , int N ) { int count = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { if ( coprime ( stoi ( arr [ i ] ) , stoi ( arr [ j ] ) ) ) { count = count + 1 ; } } } return count ; } int noOfCoPrimePairs ( int N , int d1 , int d2 ) { vector < string > l ; l . push_back ( to_string ( d1 ) ) ; l . push_back ( to_string ( d2 ) ) ; sort ( l . begin ( ) , l . end ( ) ) ; if ( N < stoi ( l [ 1 ] ) ) return 0 ; vector < string > total = l ; vector < string > temp2 = l ; int flag = 0 ; vector < string > temp3 ; while ( l [ 0 ] . length ( ) < 10 ) { for ( int i = 0 ; i < l . size ( ) ; i ++ ) { for ( int j = 0 ; j < 2 ; j ++ ) { if ( stoi ( l [ i ] + temp2 [ j ] ) > N ) { flag = 1 ; break ; } total . push_back ( l [ i ] + temp2 [ j ] ) ; temp3 . push_back ( l [ i ] + temp2 [ j ] ) ; } if ( flag == 1 ) break ; } if ( flag == 1 ) break ; l = temp3 ; vector < string > temp3 ; } int lenOfTotal = total . size ( ) ; int ans = numOfPairs ( total , lenOfTotal ) ; cout << ( ans ) ; } int main ( ) { int N = 30 , d1 = 2 , d2 = 3 ; noOfCoPrimePairs ( N , d1 , d2 ) ; }
Minimize cost of placing tiles of dimensions 2 * 1 over a Matrix | C ++ program for the above approach ; Function to find the minimum cost in placing N tiles in a grid M [ ] [ ] ; Stores the minimum profit after placing i tiles ; Traverse the grid [ ] [ ] ; Update the orig_cost ; Traverse over the range [ 2 , N ] ; Place tiles horizentally or vertically ; Print the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void tile_placing ( vector < vector < int > > grid , int N ) { int dp [ N + 5 ] = { 0 } ; int orig_cost = 0 ; for ( int i = 0 ; i < 2 ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { orig_cost += grid [ i ] [ j ] ; } } dp [ 0 ] = 0 ; dp [ 1 ] = abs ( grid [ 0 ] [ 0 ] - grid [ 1 ] [ 0 ] ) ; for ( int i = 2 ; i <= N ; i ++ ) { dp [ i ] = max ( dp [ i - 1 ] + abs ( grid [ 0 ] [ i - 1 ] - grid [ 1 ] [ i - 1 ] ) , dp [ i - 2 ] + abs ( grid [ 0 ] [ i - 2 ] - grid [ 0 ] [ i - 1 ] ) + abs ( grid [ 1 ] [ i - 2 ] - grid [ 1 ] [ i - 1 ] ) ) ; } cout << orig_cost - dp [ N ] ; } int32_t main ( ) { vector < vector < int > > M = { { 7 , 5 , 1 , 3 } , { 8 , 6 , 0 , 2 } } ; int N = M [ 0 ] . size ( ) ; tile_placing ( M , N ) ; return 0 ; }
Print indices of pair of array elements required to be removed to split array into 3 equal sum subarrays | C ++ program for the above approach ; Function to check if array can be split into three equal sum subarrays by removing two elements ; Stores sum of all three subarrays ; Sum of left subarray ; Sum of middle subarray ; Sum of right subarray ; Check if sum of subarrays are equal ; Print the possible pair ; If no pair exists , print - 1 ; Driver code ; Given array ; Size of the array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findSplit ( int arr [ ] , int N ) { for ( int l = 1 ; l <= N - 4 ; l ++ ) { for ( int r = l + 2 ; r <= N - 2 ; r ++ ) { int lsum = 0 , rsum = 0 , msum = 0 ; for ( int i = 0 ; i <= l - 1 ; i ++ ) { lsum += arr [ i ] ; } for ( int i = l + 1 ; i <= r - 1 ; i ++ ) { msum += arr [ i ] ; } for ( int i = r + 1 ; i < N ; i ++ ) { rsum += arr [ i ] ; } if ( lsum == rsum && rsum == msum ) { cout << l << " ▁ " << r << endl ; return ; } } } cout << -1 << endl ; } int main ( ) { int arr [ ] = { 2 , 5 , 12 , 7 , 19 , 4 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findSplit ( arr , N ) ; return 0 ; }
Count the number of times a Bulb switches its state | C ++ program for the above approach ; Function to find the number of times a bulb switches its state ; Count of 1 s ; Traverse the array ; Update count of 1 s ; Update the status of bulb ; Traverse the array Q [ ] ; Stores previous state of the bulb ; Toggle the switch and update count of 1 s ; If the bulb switches state ; Return count ; Driver Code ; Input ; Queries ; Function call to find number of times the bulb toggles
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( int A [ ] , int n , int Q [ ] , int q ) { int one = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( A [ i ] == 1 ) one ++ ; int glows = 0 , count = 0 ; if ( one >= ceil ( n / 2 ) ) glows = 1 ; for ( int i = 0 ; i < q ; i ++ ) { int prev = glows ; if ( A [ Q [ i ] - 1 ] == 1 ) one -- ; if ( A [ Q [ i ] - 1 ] == 0 ) one ++ ; A [ Q [ i ] - 1 ] ^= 1 ; if ( one >= ceil ( n / 2.0 ) ) { glows = 1 ; } else { glows = 0 ; } if ( prev != glows ) count ++ ; } return count ; } int main ( ) { int n = 3 ; int arr [ ] = { 1 , 1 , 0 } ; int q = 3 ; int Q [ ] = { 3 , 2 , 1 } ; cout << solve ( arr , n , Q , q ) ; return 0 ; }
Count array elements having sum of digits equal to K | C ++ program for the above approach ; Function to calculate the sum of digits of the number N ; Stores the sum of digits ; Return the sum ; Function to count array elements ; Store the count of array elements having sum of digits K ; Traverse the array ; If sum of digits is equal to K ; Increment the count ; Print the count ; Driver Code ; Given array ; Given value of K ; Size of the array ; Function call to count array elements having sum of digits equal to K
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfDigits ( int N ) { int sum = 0 ; while ( N != 0 ) { sum += N % 10 ; N /= 10 ; } return sum ; } int elementsHavingDigitSumK ( int arr [ ] , int N , int K ) { int count = 0 ; for ( int i = 0 ; i < N ; ++ i ) { if ( sumOfDigits ( arr [ i ] ) == K ) { count ++ ; } } cout << count ; } int main ( ) { int arr [ ] = { 23 , 54 , 87 , 29 , 92 , 62 } ; int K = 11 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; elementsHavingDigitSumK ( arr , N , K ) ; return 0 ; }
Postfix to Infix | CPP program to find infix for a given postfix . ; Get Infix for a given postfix expression ; Push operands ; We assume that input is a valid postfix and expect an operator . ; There must be a single element in stack now which is the required infix . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isOperand ( char x ) { return ( x >= ' a ' && x <= ' z ' ) || ( x >= ' A ' && x <= ' Z ' ) ; } string getInfix ( string exp ) { stack < string > s ; for ( int i = 0 ; exp [ i ] != ' \0' ; i ++ ) { if ( isOperand ( exp [ i ] ) ) { string op ( 1 , exp [ i ] ) ; s . push ( op ) ; } else { string op1 = s . top ( ) ; s . pop ( ) ; string op2 = s . top ( ) ; s . pop ( ) ; s . push ( " ( " + op2 + exp [ i ] + op1 + " ) " ) ; } } return s . top ( ) ; } int main ( ) { string exp = " ab * c + " ; cout << getInfix ( exp ) ; return 0 ; }
Change a Binary Tree so that every node stores sum of all nodes in left subtree | C ++ program to store sum of nodes in left subtree in every node ; A tree node ; Constructor that allocates a new node with the given data and NULL left and right pointers . ; Function to modify a Binary Tree so that every node stores sum of values in its left child including its own value ; Base cases ; Update left and right subtrees ; Add leftsum to current node ; Return sum of values under root ; Utility function to do inorder traversal ; Driver code ; Let us construct below tree 1 / \ 2 3 / \ \ 4 5 6
#include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int data ; node * left , * right ; node ( int data ) { this -> data = data ; this -> left = NULL ; this -> right = NULL ; } } ; int updatetree ( node * root ) { if ( ! root ) return 0 ; if ( root -> left == NULL && root -> right == NULL ) return root -> data ; int leftsum = updatetree ( root -> left ) ; int rightsum = updatetree ( root -> right ) ; root -> data += leftsum ; return root -> data + rightsum ; } void inorder ( node * node ) { if ( node == NULL ) return ; inorder ( node -> left ) ; cout << node -> data << " ▁ " ; inorder ( node -> right ) ; } int main ( ) { struct node * root = new node ( 1 ) ; root -> left = new node ( 2 ) ; root -> right = new node ( 3 ) ; root -> left -> left = new node ( 4 ) ; root -> left -> right = new node ( 5 ) ; root -> right -> right = new node ( 6 ) ; updatetree ( root ) ; cout << " Inorder ▁ traversal ▁ of ▁ the ▁ modified ▁ tree ▁ is : ▁ STRNEWLINE " ; inorder ( root ) ; return 0 ; }
The Stock Span Problem | C ++ program for brute force method to calculate stock span values ; Fills array S [ ] with span values ; Span value of first day is always 1 ; Calculate span value of remaining days by linearly checking previous days ; Initialize span value ; Traverse left while the next element on left is smaller than price [ i ] ; A utility function to print elements of array ; Driver code ; Fill the span values in array S [ ] ; print the calculated span values
#include <bits/stdc++.h> NEW_LINE using namespace std ; void calculateSpan ( int price [ ] , int n , int S [ ] ) { S [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { S [ i ] = 1 ; for ( int j = i - 1 ; ( j >= 0 ) && ( price [ i ] >= price [ j ] ) ; j -- ) S [ i ] ++ ; } } void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; } int main ( ) { int price [ ] = { 10 , 4 , 5 , 90 , 120 , 80 } ; int n = sizeof ( price ) / sizeof ( price [ 0 ] ) ; int S [ n ] ; calculateSpan ( price , n , S ) ; printArray ( S , n ) ; return 0 ; }
The Stock Span Problem | C ++ linear time solution for stock span problem ; A stack based efficient method to calculate stock span values ; Create a stack and push index of first element to it ; Span value of first element is always 1 ; Calculate span values for rest of the elements ; Pop elements from stack while stack is not empty and top of stack is smaller than price [ i ] ; If stack becomes empty , then price [ i ] is greater than all elements on left of it , i . e . , price [ 0 ] , price [ 1 ] , . . price [ i - 1 ] . Else price [ i ] is greater than elements after top of stack ; Push this element to stack ; A utility function to print elements of array ; Driver program to test above function ; Fill the span values in array S [ ] ; print the calculated span values
#include <iostream> NEW_LINE #include <stack> NEW_LINE using namespace std ; void calculateSpan ( int price [ ] , int n , int S [ ] ) { stack < int > st ; st . push ( 0 ) ; S [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { while ( ! st . empty ( ) && price [ st . top ( ) ] <= price [ i ] ) st . pop ( ) ; S [ i ] = ( st . empty ( ) ) ? ( i + 1 ) : ( i - st . top ( ) ) ; st . push ( i ) ; } } void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; } int main ( ) { int price [ ] = { 10 , 4 , 5 , 90 , 120 , 80 } ; int n = sizeof ( price ) / sizeof ( price [ 0 ] ) ; int S [ n ] ; calculateSpan ( price , n , S ) ; printArray ( S , n ) ; return 0 ; }
The Stock Span Problem | C ++ program for a linear time solution for stock span problem without using stack ; An efficient method to calculate stock span values implementing the same idea without using stack ; Span value of first element is always 1 ; Calculate span values for rest of the elements ; A utility function to print elements of array ; Driver program to test above function ; Fill the span values in array S [ ] ; print the calculated span values
#include <iostream> NEW_LINE #include <stack> NEW_LINE using namespace std ; void calculateSpan ( int A [ ] , int n , int ans [ ] ) { ans [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { int counter = 1 ; while ( ( i - counter ) >= 0 && A [ i ] >= A [ i - counter ] ) { counter += ans [ i - counter ] ; } ans [ i ] = counter ; } } void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; } int main ( ) { int price [ ] = { 10 , 4 , 5 , 90 , 120 , 80 } ; int n = sizeof ( price ) / sizeof ( price [ 0 ] ) ; int S [ n ] ; calculateSpan ( price , n , S ) ; printArray ( S , n ) ; return 0 ; }
Next Greater Element | Simple C ++ program to print next greater elements in a given array ; prints element and NGE pair for all elements of arr [ ] of size n ; Driver Code
#include <iostream> NEW_LINE using namespace std ; void printNGE ( int arr [ ] , int n ) { int next , i , j ; for ( i = 0 ; i < n ; i ++ ) { next = -1 ; for ( j = i + 1 ; j < n ; j ++ ) { if ( arr [ i ] < arr [ j ] ) { next = arr [ j ] ; break ; } } cout << arr [ i ] << " ▁ - - ▁ " << next << endl ; } } int main ( ) { int arr [ ] = { 11 , 13 , 21 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printNGE ( arr , n ) ; return 0 ; }
Convert a Binary Tree into its Mirror Tree | C ++ program to convert a binary tree to its mirror ; 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 . ; Change a tree so that the roles of the left and right pointers are swapped at every node . So the tree ... 4 / \ 2 5 / \ 1 3 is changed to ... 4 / \ 5 2 / \ 3 1 ; do the subtrees ; swap the pointers in this node ; Helper function to print Inorder traversal . ; Driver Code ; Print inorder traversal of the input tree ; Convert tree to its mirror ; Print inorder traversal of the mirror tree
#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 = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; return ( node ) ; } void mirror ( struct Node * node ) { if ( node == NULL ) return ; else { struct Node * temp ; mirror ( node -> left ) ; mirror ( node -> right ) ; temp = node -> left ; node -> left = node -> right ; node -> right = temp ; } } void inOrder ( struct Node * node ) { if ( node == NULL ) return ; inOrder ( node -> left ) ; cout << node -> data << " ▁ " ; inOrder ( node -> 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 << " Inorder ▁ traversal ▁ of ▁ the ▁ constructed " << " ▁ tree ▁ is " << endl ; inOrder ( root ) ; mirror ( root ) ; cout << " Inorder traversal of the mirror tree " << " ▁ is ▁ STRNEWLINE " ; inOrder ( root ) ; return 0 ; }
Number of NGEs to the right | ; array to store the next greater element index ; use of stl stack in c ++ ; push the 0 th index to the stack ; traverse in the loop from 1 - nth index ; iterate till loop is empty ; get the topmost index in the stack ; if the current element is greater then the top index - th element , then this will be the next greatest index of the top index - th element ; initialize the cur index position 's next greatest as index ; pop the cur index as its greater element has been found ; if not greater then break ; push the i index so that its next greatest can be found ; iterate for all other index left inside stack ; mark it as - 1 as no element in greater then it in right ; Function to count the number of next greater numbers to the right ; initializes the next array as 0 ; calls the function to pre - calculate the next greatest element indexes ; if the i - th element has no next greater element to right ; Count of next greater numbers to right . ; answers all queries in O ( 1 ) ; returns the number of next greater elements to the right . ; driver program to test the above function ; calls the function to count the number of greater elements to the right for every element . ; query 1 answered ; query 2 answered ; query 3 answered
#include <bits/stdc++.h> NEW_LINE using namespace std ; void fillNext ( int next [ ] , int a [ ] , int n ) { stack < int > s ; s . push ( 0 ) ; for ( int i = 1 ; i < n ; i ++ ) { while ( ! s . empty ( ) ) { int cur = s . top ( ) ; if ( a [ cur ] < a [ i ] ) { next [ cur ] = i ; s . pop ( ) ; } else break ; } s . push ( i ) ; } while ( ! s . empty ( ) ) { int cur = s . top ( ) ; next [ cur ] = -1 ; s . pop ( ) ; } } void count ( int a [ ] , int dp [ ] , int n ) { int next [ n ] ; memset ( next , 0 , sizeof ( next ) ) ; fillNext ( next , a , n ) ; for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( next [ i ] == -1 ) dp [ i ] = 0 ; else dp [ i ] = 1 + dp [ next [ i ] ] ; } } int answerQuery ( int dp [ ] , int index ) { return dp [ index ] ; } int main ( ) { int a [ ] = { 3 , 4 , 2 , 7 , 5 , 8 , 10 , 6 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int dp [ n ] ; count ( a , dp , n ) ; cout << answerQuery ( dp , 3 ) << endl ; cout << answerQuery ( dp , 6 ) << endl ; cout << answerQuery ( dp , 1 ) << endl ; return 0 ; }
Number of NGEs to the right | ; use of stl stack in c ++ ; push the ( n - 1 ) th index to the stack ; traverse in reverse order ; if no element is greater than arr [ i ] the number of NGEs to right is 0 ; number of NGEs to right of arr [ i ] is one greater than the number of NGEs to right of higher number to its right ; reverse again because values are in reverse order ; returns the vector of number of next greater elements to the right of each index . ; Driver code ; query 1 answered ; query 2 answered ; query 3 answered
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > no_NGN ( int arr [ ] , int n ) { vector < int > nxt ; stack < int > s ; nxt . push_back ( 0 ) ; s . push ( n - 1 ) ; for ( int i = n - 2 ; i >= 0 ; i -- ) { while ( ! s . empty ( ) && arr [ i ] >= arr [ s . top ( ) ] ) s . pop ( ) ; if ( s . empty ( ) ) nxt . push_back ( 0 ) ; else nxt . push_back ( nxt [ n - s . top ( ) - 1 ] + 1 ) ; s . push ( i ) ; } reverse ( nxt . begin ( ) , nxt . end ( ) ) ; return nxt ; } int main ( ) { int n = 8 ; int arr [ ] = { 3 , 4 , 2 , 7 , 5 , 8 , 10 , 6 } ; vector < int > nxt = no_NGN ( arr , n ) ; cout << nxt [ 3 ] << endl ; cout << nxt [ 6 ] << endl ; cout << nxt [ 1 ] << endl ; return 0 ; }
Maximum product of indexes of next greater on left and right | C ++ program to find the max LRproduct [ i ] among all i ; function to find just next greater element in left side ; checking if current element is greater than top ; on index of top store the current element index which is just greater than top element ; else push the current element in stack ; function to find just next greater element in right side ; checking if current element is greater than top ; on index of top store the current element index which is just greater than top element stored index should be start with 1 ; else push the current element in stack ; Function to find maximum LR product ; for each element storing the index of just greater element in left side ; for each element storing the index of just greater element in right side ; finding the max index product ; Drivers code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1000 NEW_LINE vector < int > nextGreaterInLeft ( int a [ ] , int n ) { vector < int > left_index ( MAX , 0 ) ; stack < int > s ; for ( int i = n - 1 ; i >= 0 ; i -- ) { while ( ! s . empty ( ) && a [ i ] > a [ s . top ( ) - 1 ] ) { int r = s . top ( ) ; s . pop ( ) ; left_index [ r - 1 ] = i + 1 ; } s . push ( i + 1 ) ; } return left_index ; } vector < int > nextGreaterInRight ( int a [ ] , int n ) { vector < int > right_index ( MAX , 0 ) ; stack < int > s ; for ( int i = 0 ; i < n ; ++ i ) { while ( ! s . empty ( ) && a [ i ] > a [ s . top ( ) - 1 ] ) { int r = s . top ( ) ; s . pop ( ) ; right_index [ r - 1 ] = i + 1 ; } s . push ( i + 1 ) ; } return right_index ; } int LRProduct ( int arr [ ] , int n ) { vector < int > left = nextGreaterInLeft ( arr , n ) ; vector < int > right = nextGreaterInRight ( arr , n ) ; int ans = -1 ; for ( int i = 1 ; i <= n ; i ++ ) { ans = max ( ans , left [ i ] * right [ i ] ) ; } return ans ; } int main ( ) { int arr [ ] = { 5 , 4 , 3 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 1 ] ) ; cout << LRProduct ( arr , n ) ; return 0 ; }
The Celebrity Problem | C ++ program to find celebrity ; Max # of persons in the party ; Person with 2 is celebrity ; Returns - 1 if celebrity is not present . If present , returns id ( value from 0 to n - 1 ) . ; the graph needs not be constructed as the edges can be found by using knows function degree array ; ; query for all edges ; set the degrees ; find a person with indegree n - 1 and out degree 0 ; Driver code
#include <bits/stdc++.h> NEW_LINE #include <list> NEW_LINE using namespace std ; #define N 8 NEW_LINE bool MATRIX [ N ] [ N ] = { { 0 , 0 , 1 , 0 } , { 0 , 0 , 1 , 0 } , { 0 , 0 , 0 , 0 } , { 0 , 0 , 1 , 0 } } ; bool knows ( int a , int b ) { return MATRIX [ a ] [ b ] ; } int findCelebrity ( int n ) { int indegree [ n ] = { 0 } , outdegree [ n ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { int x = knows ( i , j ) ; outdegree [ i ] += x ; indegree [ j ] += x ; } } for ( int i = 0 ; i < n ; i ++ ) if ( indegree [ i ] == n - 1 && outdegree [ i ] == 0 ) return i ; return -1 ; } int main ( ) { int n = 4 ; int id = findCelebrity ( n ) ; id == -1 ? cout << " No ▁ celebrity " : cout << " Celebrity ▁ ID ▁ " << id ; return 0 ; }
The Celebrity Problem | C ++ program to find celebrity ; Max # of persons in the party ; Person with 2 is celebrity ; Returns - 1 if a ' potential ▁ celebrity ' is not present . If present , returns id ( value from 0 to n - 1 ) . ; base case - when n reaches 0 , returns - 1 since n represents the number of people , 0 people implies no celebrity ( = - 1 ) ; find the celebrity with n - 1 persons ; if there are no celebrities ; if the id knows the nth person then the id cannot be a celebrity , but nth person could be one ; if the nth person knows the id , then the nth person cannot be a celebrity and the id could be one ; if there is no celebrity ; Returns - 1 if celebrity is not present . If present , returns id ( value from 0 to n - 1 ) . a wrapper over findCelebrity ; find the celebrity ; check if the celebrity found is really the celebrity ; check the id is really the celebrity ; if the person is known to everyone . ; Driver code
#include <bits/stdc++.h> NEW_LINE #include <list> NEW_LINE using namespace std ; #define N 8 NEW_LINE bool MATRIX [ N ] [ N ] = { { 0 , 0 , 1 , 0 } , { 0 , 0 , 1 , 0 } , { 0 , 0 , 0 , 0 } , { 0 , 0 , 1 , 0 } } ; bool knows ( int a , int b ) { return MATRIX [ a ] [ b ] ; } int findPotentialCelebrity ( int n ) { if ( n == 0 ) return -1 ; int id = findPotentialCelebrity ( n - 1 ) ; if ( id == -1 ) return n - 1 ; else if ( knows ( id , n - 1 ) ) { return n - 1 ; } else if ( knows ( n - 1 , id ) ) { return id ; } return -1 ; } int Celebrity ( int n ) { int id = findPotentialCelebrity ( n ) ; if ( id == -1 ) return id ; else { int c1 = 0 , c2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( i != id ) { c1 += knows ( id , i ) ; c2 += knows ( i , id ) ; } if ( c1 == 0 && c2 == n - 1 ) return id ; return -1 ; } } int main ( ) { int n = 4 ; int id = Celebrity ( n ) ; id == -1 ? cout << " No ▁ celebrity " : cout << " Celebrity ▁ ID ▁ " << id ; return 0 ; }
Expression Evaluation | CPP program to evaluate a given expression where tokens are separated by space . ; Function to find precedence of operators . ; Function to perform arithmetic operations . ; Function that returns value of expression after evaluation . ; stack to store integer values . ; stack to store operators . ; Current token is a whitespace , skip it . ; Current token is an opening brace , push it to ' ops ' ; Current token is a number , push it to stack for numbers . ; There may be more than one digits in number . ; right now the i points to the character next to the digit , since the for loop also increases the i , we would skip one token position ; we need to decrease the value of i by 1 to correct the offset . ; Closing brace encountered , solve entire brace . ; pop opening brace . ; Current token is an operator . ; While top of ' ops ' has same or greater precedence to current token , which is an operator . Apply operator on top of ' ops ' to top two elements in values stack . ; Push current token to ' ops ' . ; Entire expression has been parsed at this point , apply remaining ops to remaining values . ; Top of ' values ' contains result , return it . ; Driver method to test above methods
#include <bits/stdc++.h> NEW_LINE using namespace std ; int precedence ( char op ) { if ( op == ' + ' op == ' - ' ) return 1 ; if ( op == ' * ' op == ' / ' ) return 2 ; return 0 ; } int applyOp ( int a , int b , char op ) { switch ( op ) { case ' + ' : return a + b ; case ' - ' : return a - b ; case ' * ' : return a * b ; case ' / ' : return a / b ; } } int evaluate ( string tokens ) { int i ; stack < int > values ; stack < char > ops ; for ( i = 0 ; i < tokens . length ( ) ; i ++ ) { if ( tokens [ i ] == ' ▁ ' ) continue ; else if ( tokens [ i ] == ' ( ' ) { ops . push ( tokens [ i ] ) ; } else if ( isdigit ( tokens [ i ] ) ) { int val = 0 ; while ( i < tokens . length ( ) && isdigit ( tokens [ i ] ) ) { val = ( val * 10 ) + ( tokens [ i ] - '0' ) ; i ++ ; } values . push ( val ) ; i -- ; } else if ( tokens [ i ] == ' ) ' ) { while ( ! ops . empty ( ) && ops . top ( ) != ' ( ' ) { int val2 = values . top ( ) ; values . pop ( ) ; int val1 = values . top ( ) ; values . pop ( ) ; char op = ops . top ( ) ; ops . pop ( ) ; values . push ( applyOp ( val1 , val2 , op ) ) ; } if ( ! ops . empty ( ) ) ops . pop ( ) ; } else { while ( ! ops . empty ( ) && precedence ( ops . top ( ) ) >= precedence ( tokens [ i ] ) ) { int val2 = values . top ( ) ; values . pop ( ) ; int val1 = values . top ( ) ; values . pop ( ) ; char op = ops . top ( ) ; ops . pop ( ) ; values . push ( applyOp ( val1 , val2 , op ) ) ; } ops . push ( tokens [ i ] ) ; } } while ( ! ops . empty ( ) ) { int val2 = values . top ( ) ; values . pop ( ) ; int val1 = values . top ( ) ; values . pop ( ) ; char op = ops . top ( ) ; ops . pop ( ) ; values . push ( applyOp ( val1 , val2 , op ) ) ; } return values . top ( ) ; } int main ( ) { cout << evaluate ( "10 ▁ + ▁ 2 ▁ * ▁ 6" ) << " STRNEWLINE " ; cout << evaluate ( "100 ▁ * ▁ 2 ▁ + ▁ 12" ) << " STRNEWLINE " ; cout << evaluate ( "100 ▁ * ▁ ( ▁ 2 ▁ + ▁ 12 ▁ ) " ) << " STRNEWLINE " ; cout << evaluate ( "100 ▁ * ▁ ( ▁ 2 ▁ + ▁ 12 ▁ ) ▁ / ▁ 14" ) ; return 0 ; }
Convert a Binary Tree into its Mirror Tree | Iterative CPP program to convert a Binary Tree to its mirror ; 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 . ; Change a tree so that the roles of the left and right pointers are swapped at every node . So the tree ... 4 / \ 2 5 / \ 1 3 is changed to ... 4 / \ 5 2 / \ 3 1 ; Do BFS . While doing BFS , keep swapping left and right children ; pop top node from queue ; swap left child with right child ; push left and right children ; Helper function to print Inorder traversal . ; Driver program to test mirror ( ) ; Print inorder traversal of the input tree ; Convert tree to its mirror ; Print inorder traversal of the mirror tree
#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 ) ; } void mirror ( Node * root ) { if ( root == NULL ) return ; queue < Node * > q ; q . push ( root ) ; while ( ! q . empty ( ) ) { Node * curr = q . front ( ) ; q . pop ( ) ; swap ( curr -> left , curr -> right ) ; if ( curr -> left ) q . push ( curr -> left ) ; if ( curr -> right ) q . push ( curr -> right ) ; } } void inOrder ( struct Node * node ) { if ( node == NULL ) return ; inOrder ( node -> left ) ; cout << node -> data << " ▁ " ; inOrder ( node -> 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 << " Inorder traversal of the " STRNEWLINE TABSYMBOL TABSYMBOL TABSYMBOL " constructed tree is " ; inOrder ( root ) ; mirror ( root ) ; cout << " Inorder traversal of the " STRNEWLINE TABSYMBOL TABSYMBOL " mirror tree is " ; inOrder ( root ) ; return 0 ; }
Iterative Tower of Hanoi | C Program for Iterative Tower of Hanoi ; A structure to represent a stack ; function to create a stack of given capacity . ; Stack is full when top is equal to the last index ; Stack is empty when top is equal to - 1 ; Function to add an item to stack . It increases top by 1 ; Function to remove an item from stack . It decreases top by 1 ; Function to show the movement of disks ; Function to implement legal movement between two poles ; When pole 1 is empty ; When pole2 pole is empty ; When top disk of pole1 > top disk of pole2 ; When top disk of pole1 < top disk of pole2 ; Function to implement TOH puzzle ; If number of disks is even , then interchange destination pole and auxiliary pole ; Larger disks will be pushed first ; Driver Program ; Input : number of disks ; Create three stacks of size ' num _ of _ disks ' to hold the disks
#include <stdio.h> NEW_LINE #include <math.h> NEW_LINE #include <stdlib.h> NEW_LINE #include <limits.h> NEW_LINE struct Stack { unsigned capacity ; int top ; int * array ; } ; struct Stack * createStack ( unsigned capacity ) { struct Stack * stack = ( struct Stack * ) malloc ( sizeof ( struct Stack ) ) ; stack -> capacity = capacity ; stack -> top = -1 ; stack -> array = ( int * ) malloc ( stack -> capacity * sizeof ( int ) ) ; return stack ; } int isFull ( struct Stack * stack ) { return ( stack -> top == stack -> capacity - 1 ) ; } int isEmpty ( struct Stack * stack ) { return ( stack -> top == -1 ) ; } void push ( struct Stack * stack , int item ) { if ( isFull ( stack ) ) return ; stack -> array [ ++ stack -> top ] = item ; } int pop ( struct Stack * stack ) { if ( isEmpty ( stack ) ) return INT_MIN ; return stack -> array [ stack -> top -- ] ; } void moveDisk ( char fromPeg , char toPeg , int disk ) { printf ( " Move ▁ the ▁ disk ▁ % d ▁ from ▁ \' % c \' ▁ to ▁ \' % c \' STRNEWLINE " , disk , fromPeg , toPeg ) ; } void moveDisksBetweenTwoPoles ( struct Stack * src , struct Stack * dest , char s , char d ) { int pole1TopDisk = pop ( src ) ; int pole2TopDisk = pop ( dest ) ; if ( pole1TopDisk == INT_MIN ) { push ( src , pole2TopDisk ) ; moveDisk ( d , s , pole2TopDisk ) ; } else if ( pole2TopDisk == INT_MIN ) { push ( dest , pole1TopDisk ) ; moveDisk ( s , d , pole1TopDisk ) ; } else if ( pole1TopDisk > pole2TopDisk ) { push ( src , pole1TopDisk ) ; push ( src , pole2TopDisk ) ; moveDisk ( d , s , pole2TopDisk ) ; } else { push ( dest , pole2TopDisk ) ; push ( dest , pole1TopDisk ) ; moveDisk ( s , d , pole1TopDisk ) ; } } void tohIterative ( int num_of_disks , struct Stack * src , struct Stack * aux , struct Stack * dest ) { int i , total_num_of_moves ; char s = ' S ' , d = ' D ' , a = ' A ' ; if ( num_of_disks % 2 == 0 ) { char temp = d ; d = a ; a = temp ; } total_num_of_moves = pow ( 2 , num_of_disks ) - 1 ; for ( i = num_of_disks ; i >= 1 ; i -- ) push ( src , i ) ; for ( i = 1 ; i <= total_num_of_moves ; i ++ ) { if ( i % 3 == 1 ) moveDisksBetweenTwoPoles ( src , dest , s , d ) ; else if ( i % 3 == 2 ) moveDisksBetweenTwoPoles ( src , aux , s , a ) ; else if ( i % 3 == 0 ) moveDisksBetweenTwoPoles ( aux , dest , a , d ) ; } } int main ( ) { unsigned num_of_disks = 3 ; struct Stack * src , * dest , * aux ; src = createStack ( num_of_disks ) ; aux = createStack ( num_of_disks ) ; dest = createStack ( num_of_disks ) ; tohIterative ( num_of_disks , src , aux , dest ) ; return 0 ; }
Delete middle element of a stack | C ++ code to delete middle of a stack without using additional data structure . ; Deletes middle of stack of size n . Curr is current item number ; If stack is empty or all items are traversed ; Remove current item ; Remove other items ; Put all items back except middle ; Driver function to test above functions ; push elements into the stack ; Printing stack after deletion of middle .
#include <bits/stdc++.h> NEW_LINE using namespace std ; void deleteMid ( stack < char > & st , int n , int curr = 0 ) { if ( st . empty ( ) curr == n ) return ; char x = st . top ( ) ; st . pop ( ) ; deleteMid ( st , n , curr + 1 ) ; if ( curr != n / 2 ) st . push ( x ) ; } int main ( ) { stack < char > st ; st . push ( '1' ) ; st . push ( '2' ) ; st . push ( '3' ) ; st . push ( '4' ) ; st . push ( '5' ) ; st . push ( '6' ) ; st . push ( '7' ) ; deleteMid ( st , st . size ( ) ) ; while ( ! st . empty ( ) ) { char p = st . top ( ) ; st . pop ( ) ; cout << p << " ▁ " ; } return 0 ; }
Sorting array using Stacks | C ++ program to sort an array using stack ; This function return the sorted stack ; pop out the first element ; while temporary stack is not empty and top of stack is smaller than temp ; pop from temporary stack and push it to the input stack ; push temp in tempory of stack ; Push array elements to stack ; Sort the temporary stack ; Put stack elements in arrp [ ] ; main function
#include <bits/stdc++.h> NEW_LINE using namespace std ; stack < int > sortStack ( stack < int > input ) { stack < int > tmpStack ; while ( ! input . empty ( ) ) { int tmp = input . top ( ) ; input . pop ( ) ; while ( ! tmpStack . empty ( ) && tmpStack . top ( ) < tmp ) { input . push ( tmpStack . top ( ) ) ; tmpStack . pop ( ) ; } tmpStack . push ( tmp ) ; } return tmpStack ; } void sortArrayUsingStacks ( int arr [ ] , int n ) { stack < int > input ; for ( int i = 0 ; i < n ; i ++ ) input . push ( arr [ i ] ) ; stack < int > tmpStack = sortStack ( input ) ; for ( int i = 0 ; i < n ; i ++ ) { arr [ i ] = tmpStack . top ( ) ; tmpStack . pop ( ) ; } } int main ( ) { int arr [ ] = { 10 , 5 , 15 , 45 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortArrayUsingStacks ( arr , n ) ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; return 0 ; }
Convert a Binary Tree into Doubly Linked List in spiral fashion | c ++ program to convert Binary Tree into Doubly Linked List where the nodes are represented spirally . ; A Binary Tree Node ; Given a reference to the head of a list and a node , inserts the node on the front of the list . ; Make right of given node as head and left as NULL ; change left of head node to given node ; move the head to point to the given node ; Function to prints contents of DLL ; Function to print corner node at each level ; Base Case ; Create an empty deque for doing spiral level order traversal and enqueue root ; create a stack to store Binary Tree nodes to insert into DLL later ; nodeCount indicates number of Nodes at current level . ; Dequeue all Nodes of current level and Enqueue all Nodes of next level odd level ; dequeue node from front & push it to stack ; insert its left and right children in the back of the deque ; even level ; dequeue node from the back & push it to stack ; inserts its right and left children in the front of the deque ; head pointer for DLL ; pop all nodes from stack and push them in the beginning of the list ; Utility function to create a new tree Node ; Driver program to test above functions ; Let us create binary tree shown in above diagram ; root -> right -> left -> left = newNode ( 12 ) ; ; root -> right -> right -> right = newNode ( 15 ) ;
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; void push ( Node * * head_ref , Node * node ) { node -> right = ( * head_ref ) ; node -> left = NULL ; if ( ( * head_ref ) != NULL ) ( * head_ref ) -> left = node ; ( * head_ref ) = node ; } void printList ( Node * node ) { while ( node != NULL ) { cout << node -> data << " ▁ " ; node = node -> right ; } } void spiralLevelOrder ( Node * root ) { if ( root == NULL ) return ; deque < Node * > q ; q . push_front ( root ) ; stack < Node * > stk ; int level = 0 ; while ( ! q . empty ( ) ) { int nodeCount = q . size ( ) ; if ( level & 1 ) { while ( nodeCount > 0 ) { Node * node = q . front ( ) ; q . pop_front ( ) ; stk . push ( node ) ; if ( node -> left != NULL ) q . push_back ( node -> left ) ; if ( node -> right != NULL ) q . push_back ( node -> right ) ; nodeCount -- ; } } else { while ( nodeCount > 0 ) { Node * node = q . back ( ) ; q . pop_back ( ) ; stk . push ( node ) ; if ( node -> right != NULL ) q . push_front ( node -> right ) ; if ( node -> left != NULL ) q . push_front ( node -> left ) ; nodeCount -- ; } } level ++ ; } Node * head = NULL ; while ( ! stk . empty ( ) ) { push ( & head , stk . top ( ) ) ; stk . pop ( ) ; } cout << " Created ▁ DLL ▁ is : STRNEWLINE " ; printList ( head ) ; } Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> left = newNode ( 6 ) ; root -> right -> right = newNode ( 7 ) ; root -> left -> left -> left = newNode ( 8 ) ; root -> left -> left -> right = newNode ( 9 ) ; root -> left -> right -> left = newNode ( 10 ) ; root -> left -> right -> right = newNode ( 11 ) ; root -> right -> left -> right = newNode ( 13 ) ; root -> right -> right -> left = newNode ( 14 ) ; spiralLevelOrder ( root ) ; return 0 ; }
Reverse individual words | C ++ program to reverse individual words in a given string using STL list ; reverses individual words of a string ; Traverse given string and push all characters to stack until we see a space . ; When we see a space , we print contents of stack . ; Since there may not be space after last word . ; Driver program to test function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void reverseWords ( string str ) { stack < char > st ; for ( int i = 0 ; i < str . length ( ) ; ++ i ) { if ( str [ i ] != ' ▁ ' ) st . push ( str [ i ] ) ; else { while ( st . empty ( ) == false ) { cout << st . top ( ) ; st . pop ( ) ; } cout << " ▁ " ; } } while ( st . empty ( ) == false ) { cout << st . top ( ) ; st . pop ( ) ; } } int main ( ) { string str = " Geeks ▁ for ▁ Geeks " ; reverseWords ( str ) ; return 0 ; }
Count subarrays where second highest lie before highest | C ++ program to count number of distinct instance where second highest number lie before highest number in all subarrays . ; Finding the next greater element of the array . ; Finding the previous greater element of the array . ; Wrapper Function ; Finding previous largest element ; Finding next largest element ; Driven Program
#include <bits/stdc++.h> NEW_LINE #define MAXN 100005 NEW_LINE using namespace std ; void makeNext ( int arr [ ] , int n , int nextBig [ ] ) { stack < pair < int , int > > s ; for ( int i = n - 1 ; i >= 0 ; i -- ) { nextBig [ i ] = i ; while ( ! s . empty ( ) && s . top ( ) . first < arr [ i ] ) s . pop ( ) ; if ( ! s . empty ( ) ) nextBig [ i ] = s . top ( ) . second ; s . push ( pair < int , int > ( arr [ i ] , i ) ) ; } } void makePrev ( int arr [ ] , int n , int prevBig [ ] ) { stack < pair < int , int > > s ; for ( int i = 0 ; i < n ; i ++ ) { prevBig [ i ] = -1 ; while ( ! s . empty ( ) && s . top ( ) . first < arr [ i ] ) s . pop ( ) ; if ( ! s . empty ( ) ) prevBig [ i ] = s . top ( ) . second ; s . push ( pair < int , int > ( arr [ i ] , i ) ) ; } } int wrapper ( int arr [ ] , int n ) { int nextBig [ MAXN ] ; int prevBig [ MAXN ] ; int maxi [ MAXN ] ; int ans = 0 ; makePrev ( arr , n , prevBig ) ; makeNext ( arr , n , nextBig ) ; for ( int i = 0 ; i < n ; i ++ ) if ( nextBig [ i ] != i ) maxi [ nextBig [ i ] - i ] = max ( maxi [ nextBig [ i ] - i ] , i - prevBig [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) ans += maxi [ i ] ; return ans ; } int main ( ) { int arr [ ] = { 1 , 3 , 2 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << wrapper ( arr , n ) << endl ; return 0 ; }
Largest Rectangular Area in a Histogram | Set 2 | C ++ program to find maximum rectangular area in linear time ; The main function to find the maximum rectangular area under given histogram with n bars ; Create an empty stack . The stack holds indexes of hist [ ] array . The bars stored in stack are always in increasing order of their heights . ; Initialize max area ; To store top of stack ; To store area with top bar as the smallest bar ; Run through all bars of given histogram ; If this bar is higher than the bar on top stack , push it to stack ; If this bar is lower than top of stack , then calculate area of rectangle with stack top as the smallest ( or minimum height ) bar . ' i ' is ' right ▁ index ' for the top and element before top in stack is ' left ▁ index ' ; store the top index ; pop the top ; Calculate the area with hist [ tp ] stack as smallest bar ; update max area , if needed ; Now pop the remaining bars from stack and calculate area with every popped bar as the smallest bar ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMaxArea ( int hist [ ] , int n ) { stack < int > s ; int max_area = 0 ; int tp ; int area_with_top ; int i = 0 ; while ( i < n ) { if ( s . empty ( ) || hist [ s . top ( ) ] <= hist [ i ] ) s . push ( i ++ ) ; else { tp = s . top ( ) ; s . pop ( ) ; area_with_top = hist [ tp ] * ( s . empty ( ) ? i : i - s . top ( ) - 1 ) ; if ( max_area < area_with_top ) max_area = area_with_top ; } } while ( s . empty ( ) == false ) { tp = s . top ( ) ; s . pop ( ) ; area_with_top = hist [ tp ] * ( s . empty ( ) ? i : i - s . top ( ) - 1 ) ; if ( max_area < area_with_top ) max_area = area_with_top ; } return max_area ; } int main ( ) { int hist [ ] = { 6 , 2 , 5 , 4 , 5 , 1 , 6 } ; int n = sizeof ( hist ) / sizeof ( hist [ 0 ] ) ; cout << " Maximum ▁ area ▁ is ▁ " << getMaxArea ( hist , n ) ; return 0 ; }
Program for Tower of Hanoi | C ++ recursive function to solve tower of hanoi puzzle ; Driver code ; Number of disks ; A , B and C are names of rods
#include <bits/stdc++.h> NEW_LINE using namespace std ; void towerOfHanoi ( int n , char from_rod , char to_rod , char aux_rod ) { if ( n == 1 ) { cout << " Move ▁ disk ▁ 1 ▁ from ▁ rod ▁ " << from_rod << " ▁ to ▁ rod ▁ " << to_rod << endl ; return ; } towerOfHanoi ( n - 1 , from_rod , aux_rod , to_rod ) ; cout << " Move ▁ disk ▁ " << n << " ▁ from ▁ rod ▁ " << from_rod << " ▁ to ▁ rod ▁ " << to_rod << endl ; towerOfHanoi ( n - 1 , aux_rod , to_rod , from_rod ) ; } int main ( ) { int n = 4 ; towerOfHanoi ( n , ' A ' , ' C ' , ' B ' ) ; return 0 ; }
Find maximum of minimum for every window size in a given array | A naive method to find maximum of minimum of all windows of different sizes ; Consider all windows of different sizes starting from size 1 ; Initialize max of min for current window size k ; Traverse through all windows of current size k ; Find minimum of current window ; Update maxOfMin if required ; Print max of min for current window size ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printMaxOfMin ( int arr [ ] , int n ) { for ( int k = 1 ; k <= n ; k ++ ) { int maxOfMin = INT_MIN ; for ( int i = 0 ; i <= n - k ; i ++ ) { int min = arr [ i ] ; for ( int j = 1 ; j < k ; j ++ ) { if ( arr [ i + j ] < min ) min = arr [ i + j ] ; } if ( min > maxOfMin ) maxOfMin = min ; } cout << maxOfMin << " ▁ " ; } } int main ( ) { int arr [ ] = { 10 , 20 , 30 , 50 , 10 , 70 , 30 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printMaxOfMin ( arr , n ) ; return 0 ; }
Find maximum of minimum for every window size in a given array | An efficient C ++ program to find maximum of all minimums of windows of different sizes ; Used to find previous and next smaller ; Arrays to store previous and next smaller ; Initialize elements of left [ ] and right [ ] ; Fill elements of left [ ] using logic discussed on www . geeksforgeeks . org / next - greater - element / https : ; Empty the stack as stack is going to be used for right [ ] ; Fill elements of right [ ] using same logic ; Create and initialize answer array ; Fill answer array by comparing minimums of all lengths computed using left [ ] and right [ ] ; length of the interval ; arr [ i ] is a possible answer for this length ' len ' interval , check if arr [ i ] is more than max for ' len ' ; Some entries in ans [ ] may not be filled yet . Fill them by taking values from right side of ans [ ] ; Print the result ; Driver program
#include <iostream> NEW_LINE #include <stack> NEW_LINE using namespace std ; void printMaxOfMin ( int arr [ ] , int n ) { stack < int > s ; int left [ n + 1 ] ; int right [ n + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) { left [ i ] = -1 ; right [ i ] = n ; } for ( int i = 0 ; i < n ; i ++ ) { while ( ! s . empty ( ) && arr [ s . top ( ) ] >= arr [ i ] ) s . pop ( ) ; if ( ! s . empty ( ) ) left [ i ] = s . top ( ) ; s . push ( i ) ; } while ( ! s . empty ( ) ) s . pop ( ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { while ( ! s . empty ( ) && arr [ s . top ( ) ] >= arr [ i ] ) s . pop ( ) ; if ( ! s . empty ( ) ) right [ i ] = s . top ( ) ; s . push ( i ) ; } int ans [ n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) ans [ i ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int len = right [ i ] - left [ i ] - 1 ; ans [ len ] = max ( ans [ len ] , arr [ i ] ) ; } for ( int i = n - 1 ; i >= 1 ; i -- ) ans [ i ] = max ( ans [ i ] , ans [ i + 1 ] ) ; for ( int i = 1 ; i <= n ; i ++ ) cout << ans [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 10 , 20 , 30 , 50 , 10 , 70 , 30 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printMaxOfMin ( arr , n ) ; return 0 ; }
Length of the longest valid substring | C ++ program to find length of the longest valid substring ; method to get length of the longest valid ; Create a stack and push - 1 as initial index to it . ; Initialize result ; Traverse all characters of given string ; If opening bracket , push index of it ; If closing bracket , i . e . , str [ i ] = ' ) ' ; Pop the previous opening bracket 's index ; Check if this length formed with base of current valid substring is more than max so far ; If stack is empty . push current index as base for next valid substring ( if any ) ; Driver code ; Function call ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaxLen ( string str ) { int n = str . length ( ) ; stack < int > stk ; stk . push ( -1 ) ; int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == ' ( ' ) stk . push ( i ) ; else { if ( ! stk . empty ( ) ) { stk . pop ( ) ; } if ( ! stk . empty ( ) ) result = max ( result , i - stk . top ( ) ) ; else stk . push ( i ) ; } } return result ; } int main ( ) { string str = " ( ( ( ) ( ) " ; cout << findMaxLen ( str ) << endl ; str = " ( ) ( ( ) ) ) ) ) " ; cout << findMaxLen ( str ) << endl ; return 0 ; }
Convert a tree to forest of even nodes | C ++ program to find maximum number to be removed to convert a tree into forest containing trees of even number of nodes ; Return the number of nodes of subtree having node as a root . ; Mark node as visited . ; Traverse the adjacency list to find non - visited node . ; Finding number of nodes of the subtree of a subtree . ; If nodes are even , increment number of edges to removed . Else leave the node as child of subtree . ; Return the maximum number of edge to remove to make forest . ; Driven Program
#include <bits/stdc++.h> NEW_LINE #define N 12 NEW_LINE using namespace std ; int dfs ( vector < int > tree [ N ] , int visit [ N ] , int * ans , int node ) { int num = 0 , temp = 0 ; visit [ node ] = 1 ; for ( int i = 0 ; i < tree [ node ] . size ( ) ; i ++ ) { if ( visit [ tree [ node ] [ i ] ] == 0 ) { temp = dfs ( tree , visit , ans , tree [ node ] [ i ] ) ; ( temp % 2 ) ? ( num += temp ) : ( ( * ans ) ++ ) ; } } return num + 1 ; } int minEdge ( vector < int > tree [ N ] , int n ) { int visit [ n + 2 ] ; int ans = 0 ; memset ( visit , 0 , sizeof visit ) ; dfs ( tree , visit , & ans , 1 ) ; return ans ; } int main ( ) { int n = 10 ; vector < int > tree [ n + 2 ] ; tree [ 1 ] . push_back ( 3 ) ; tree [ 3 ] . push_back ( 1 ) ; tree [ 1 ] . push_back ( 6 ) ; tree [ 6 ] . push_back ( 1 ) ; tree [ 1 ] . push_back ( 2 ) ; tree [ 2 ] . push_back ( 1 ) ; tree [ 3 ] . push_back ( 4 ) ; tree [ 4 ] . push_back ( 3 ) ; tree [ 6 ] . push_back ( 8 ) ; tree [ 8 ] . push_back ( 6 ) ; tree [ 2 ] . push_back ( 7 ) ; tree [ 7 ] . push_back ( 2 ) ; tree [ 2 ] . push_back ( 5 ) ; tree [ 5 ] . push_back ( 2 ) ; tree [ 4 ] . push_back ( 9 ) ; tree [ 9 ] . push_back ( 4 ) ; tree [ 4 ] . push_back ( 10 ) ; tree [ 10 ] . push_back ( 4 ) ; cout << minEdge ( tree , n ) << endl ; return 0 ; }
Length of the longest valid substring | C ++ program to find length of the longest valid substring ; Initialize curMax to zero ; Iterate over the string starting from second index ; Driver code ; Function call ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaxLen ( string s ) { if ( s . length ( ) <= 1 ) return 0 ; int curMax = 0 ; vector < int > longest ( s . size ( ) , 0 ) ; for ( int i = 1 ; i < s . length ( ) ; i ++ ) { if ( s [ i ] == ' ) ' && i - longest [ i - 1 ] - 1 >= 0 && s [ i - longest [ i - 1 ] - 1 ] == ' ( ' ) { longest [ i ] = longest [ i - 1 ] + 2 + ( ( i - longest [ i - 1 ] - 2 >= 0 ) ? longest [ i - longest [ i - 1 ] - 2 ] : 0 ) ; curMax = max ( longest [ i ] , curMax ) ; } } return curMax ; } int main ( ) { string str = " ( ( ( ) ( ) " ; cout << findMaxLen ( str ) << endl ; str = " ( ) ( ( ) ) ) ) ) " ; cout << findMaxLen ( str ) << endl ; return 0 ; }
Length of the longest valid substring | C ++ program to implement the above approach ; Function to return the length of the longest valid substring ; Variables for left and right counter . maxlength to store the maximum length found so far ; Iterating the string from left to right ; If " ( " is encountered , then left counter is incremented else right counter is incremented ; Whenever left is equal to right , it signifies that the subsequence is valid and ; Reseting the counters when the subsequence becomes invalid ; Iterating the string from right to left ; If " ( " is encountered , then left counter is incremented else right counter is incremented ; Whenever left is equal to right , it signifies that the subsequence is valid and ; Reseting the counters when the subsequence becomes invalid ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( string s , int n ) { int left = 0 , right = 0 , maxlength = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ' ( ' ) left ++ ; else right ++ ; if ( left == right ) maxlength = max ( maxlength , 2 * right ) ; else if ( right > left ) left = right = 0 ; } left = right = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( s [ i ] == ' ( ' ) left ++ ; else right ++ ; if ( left == right ) maxlength = max ( maxlength , 2 * left ) ; else if ( left > right ) left = right = 0 ; } return maxlength ; } int main ( ) { cout << solve ( " ( ( ( ) ( ) ( ) ( ) ( ( ( ( ) ) " , 16 ) ; return 0 ; }
Expression contains redundant bracket or not | C ++ Program to check whether valid expression is redundant or not ; Function to check redundant brackets in a balanced expression ; create a stack of characters ; Iterate through the given expression ; if current character is close parenthesis ' ) ' ; If immediate pop have open parenthesis ' ( ' duplicate brackets found ; Check for operators in expression ; Fetch top element of stack ; If operators not found ; push open parenthesis ' ( ' , ; operators and operands to stack ; Function to check redundant brackets ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkRedundancy ( string & str ) { stack < char > st ; for ( auto & ch : str ) { if ( ch == ' ) ' ) { char top = st . top ( ) ; st . pop ( ) ; bool flag = true ; while ( ! st . empty ( ) and top != ' ( ' ) { if ( top == ' + ' top == ' - ' top == ' * ' top == ' / ' ) flag = false ; top = st . top ( ) ; st . pop ( ) ; } if ( flag == true ) return true ; } else st . push ( ch ) ; } return false ; } void findRedundant ( string & str ) { bool ans = checkRedundancy ( str ) ; if ( ans == true ) cout << " Yes STRNEWLINE " ; else cout << " No STRNEWLINE " ; } int main ( ) { string str = " ( ( a + b ) ) " ; findRedundant ( str ) ; str = " ( a + ( b ) / c ) " ; findRedundant ( str ) ; str = " ( a + b * ( c - d ) ) " ; findRedundant ( str ) ; return 0 ; }
Check if two expressions with brackets are same | CPP program to check if two expressions evaluate to same . ; Return local sign of the operand . For example , in the expr a - b - ( c ) , local signs of the operands are + a , - b , + c ; Evaluate expressions into the count vector of the 26 alphabets . If add is true , then add count to the count vector of the alphabets , else remove count from the count vector . ; stack stores the global sign for operands . ; + means true global sign is positive initially ; global sign for the bracket is pushed to the stack ; global sign is popped out which was pushed in for the last bracket ; global sign is positive ( we use different values in two calls of functions so that we finally check if all vector elements are 0. ; global sign is negative here ; Returns true if expr1 and expr2 represent same expressions ; Create a vector for all operands and initialize the vector as 0. ; Put signs of all operands in expr1 ; Subtract signs of operands in expr2 ; If expressions are same , vector must be 0. ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; bool adjSign ( string s , int i ) { if ( i == 0 ) return true ; if ( s [ i - 1 ] == ' - ' ) return false ; return true ; } ; void eval ( string s , vector < int > & v , bool add ) { stack < bool > stk ; stk . push ( true ) ; int i = 0 ; while ( s [ i ] != ' \0' ) { if ( s [ i ] == ' + ' s [ i ] == ' - ' ) { i ++ ; continue ; } if ( s [ i ] == ' ( ' ) { if ( adjSign ( s , i ) ) stk . push ( stk . top ( ) ) ; else stk . push ( ! stk . top ( ) ) ; } else if ( s [ i ] == ' ) ' ) stk . pop ( ) ; else { if ( stk . top ( ) ) v [ s [ i ] - ' a ' ] += ( adjSign ( s , i ) ? add ? 1 : -1 : add ? -1 : 1 ) ; else v [ s [ i ] - ' a ' ] += ( adjSign ( s , i ) ? add ? -1 : 1 : add ? 1 : -1 ) ; } i ++ ; } } ; bool areSame ( string expr1 , string expr2 ) { vector < int > v ( MAX_CHAR , 0 ) ; eval ( expr1 , v , true ) ; eval ( expr2 , v , false ) ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) if ( v [ i ] != 0 ) return false ; return true ; } int main ( ) { string expr1 = " - ( a + b + c ) " , expr2 = " - a - b - c " ; if ( areSame ( expr1 , expr2 ) ) cout << " Yes STRNEWLINE " ; else cout << " No STRNEWLINE " ; return 0 ; }
Find index of closing bracket for a given opening bracket in an expression | CPP program to find index of closing bracket for given opening bracket . ; Function to find index of closing bracket for given opening bracket . ; If index given is invalid and is not an opening bracket . ; Stack to store opening brackets . ; Traverse through string starting from given index . ; If current character is an opening bracket push it in stack . ; If current character is a closing bracket , pop from stack . If stack is empty , then this closing bracket is required bracket . ; If no matching closing bracket is found . ; Driver Code ; should be 8 ; should be 7 ; should be 12 ; No matching bracket
#include <bits/stdc++.h> NEW_LINE using namespace std ; void test ( string expression , int index ) { int i ; if ( expression [ index ] != ' [ ' ) { cout << expression << " , ▁ " << index << " : ▁ - 1 STRNEWLINE " ; return ; } stack < int > st ; for ( i = index ; i < expression . length ( ) ; i ++ ) { if ( expression [ i ] == ' [ ' ) st . push ( expression [ i ] ) ; else if ( expression [ i ] == ' ] ' ) { st . pop ( ) ; if ( st . empty ( ) ) { cout << expression << " , ▁ " << index << " : ▁ " << i << " STRNEWLINE " ; return ; } } } cout << expression << " , ▁ " << index << " : ▁ - 1 STRNEWLINE " ; } int main ( ) { test ( " [ ABC [ 23 ] ] [89 ] " , 0 ) ; test ( " [ ABC [ 23 ] ] [89 ] " , 4 ) ; test ( " [ ABC [ 23 ] ] [89 ] " , 9 ) ; test ( " [ ABC [ 23 ] ] [89 ] " , 1 ) ; return 0 ; }
Convert a given Binary tree to a tree that holds Logical AND property | C ++ code to convert a given binary tree to a tree that holds logical AND property . ; Structure of binary tree ; function to create a new node ; Convert the given tree to a tree where each node is logical AND of its children The main idea is to do Postorder traversal ; first recur on left child ; then recur on right child ; first recur on left child ; then print the data of node ; now recur on right child ; main function ; Create following Binary Tree 1 / \ 1 0 / \ / \ 0 1 1 1
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left ; struct Node * right ; } ; struct Node * newNode ( int key ) { struct Node * node = new Node ; node -> data = key ; node -> left = node -> right = NULL ; return node ; } void convertTree ( Node * root ) { if ( root == NULL ) return ; convertTree ( root -> left ) ; convertTree ( root -> right ) ; if ( root -> left != NULL && root -> right != NULL ) root -> data = ( root -> left -> data ) & ( root -> right -> data ) ; } void printInorder ( Node * root ) { if ( root == NULL ) return ; printInorder ( root -> left ) ; printf ( " % d ▁ " , root -> data ) ; printInorder ( root -> right ) ; } int main ( ) { Node * root = newNode ( 0 ) ; root -> left = newNode ( 1 ) ; root -> right = newNode ( 0 ) ; root -> left -> left = newNode ( 0 ) ; root -> left -> right = newNode ( 1 ) ; root -> right -> left = newNode ( 1 ) ; root -> right -> right = newNode ( 1 ) ; printf ( " Inorder traversal before conversion " printInorder ( root ) ; convertTree ( root ) ; printf ( " Inorder traversal after conversion " printInorder ( root ) ; return 0 ; }
Find if an expression has duplicate parenthesis or not | C ++ program to find duplicate parenthesis in a balanced expression ; Function to find duplicate parenthesis in a balanced expression ; create a stack of characters ; Iterate through the given expression ; if current character is close parenthesis ' ) ' ; pop character from the stack ; stores the number of characters between a closing and opening parenthesis if this count is less than or equal to 1 then the brackets are redundant else not ; push open parenthesis ' ( ' , operators and operands to stack ; No duplicates found ; Driver code ; input balanced expression
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool findDuplicateparenthesis ( string str ) { stack < char > Stack ; for ( char ch : str ) { if ( ch == ' ) ' ) { char top = Stack . top ( ) ; Stack . pop ( ) ; int elementsInside = 0 ; while ( top != ' ( ' ) { elementsInside ++ ; top = Stack . top ( ) ; Stack . pop ( ) ; } if ( elementsInside < 1 ) { return 1 ; } } else Stack . push ( ch ) ; } return false ; } int main ( ) { string str = " ( ( ( a + ( b ) ) + ( c + d ) ) ) " ; if ( findDuplicateparenthesis ( str ) ) cout << " Duplicate ▁ Found ▁ " ; else cout << " No ▁ Duplicates ▁ Found ▁ " ; return 0 ; }
Find next Smaller of next Greater in an array | C ++ Program to find Right smaller element of next greater element ; function find Next greater element ; create empty stack ; Traverse all array elements in reverse order order == ' G ' we compute next greater elements of every element order == ' S ' we compute right smaller element of every element ; Keep removing top element from S while the top element is smaller then or equal to arr [ i ] ( if Key is G ) element is greater then or equal to arr [ i ] ( if order is S ) ; store the next greater element of current element ; If all elements in S were smaller than arr [ i ] ; Push this element ; Function to find Right smaller element of next greater element ; stores indexes of next greater elements ; stores indexes of right smaller elements ; Find next greater element Here G indicate next greater element ; Find right smaller element using same function nextGreater ( ) Here S indicate right smaller elements ; If NG [ i ] = = - 1 then there is no smaller element on right side . We can find Right smaller of next greater by arr [ RS [ NG [ i ] ] ] ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void nextGreater ( int arr [ ] , int n , int next [ ] , char order ) { stack < int > S ; for ( int i = n - 1 ; i >= 0 ; i -- ) { while ( ! S . empty ( ) && ( ( order == ' G ' ) ? arr [ S . top ( ) ] <= arr [ i ] : arr [ S . top ( ) ] >= arr [ i ] ) ) S . pop ( ) ; if ( ! S . empty ( ) ) next [ i ] = S . top ( ) ; else next [ i ] = -1 ; S . push ( i ) ; } } void nextSmallerOfNextGreater ( int arr [ ] , int n ) { int NG [ n ] ; int RS [ n ] ; nextGreater ( arr , n , NG , ' G ' ) ; nextGreater ( arr , n , RS , ' S ' ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( NG [ i ] != -1 && RS [ NG [ i ] ] != -1 ) cout << arr [ RS [ NG [ i ] ] ] << " ▁ " ; else cout << " - 1" << " ▁ " ; } } int main ( ) { int arr [ ] = { 5 , 1 , 9 , 2 , 5 , 1 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; nextSmallerOfNextGreater ( arr , n ) ; return 0 ; }
Count natural numbers whose all permutation are greater than that number | C ++ program to count the number less than N , whose all permutation is greater than or equal to the number . ; Return the count of the number having all permutation greater than or equal to the number . ; Pushing 1 to 9 because all number from 1 to 9 have this property . ; take a number from stack and add a digit smaller than last digit of it . ; Driven Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countNumber ( int n ) { int result = 0 ; stack < int > s ; for ( int i = 1 ; i <= 9 ; i ++ ) { if ( i <= n ) { s . push ( i ) ; result ++ ; } while ( ! s . empty ( ) ) { int tp = s . top ( ) ; s . pop ( ) ; for ( int j = tp % 10 ; j <= 9 ; j ++ ) { int x = tp * 10 + j ; if ( x <= n ) { s . push ( x ) ; result ++ ; } } } } return result ; } int main ( ) { int n = 15 ; cout << countNumber ( n ) << endl ; return 0 ; }
Delete consecutive same words in a sequence | C ++ program to remove consecutive same words ; Function to find the size of manipulated sequence ; Start traversing the sequence ; Compare the current string with next one Erase both if equal ; Erase function delete the element and also shifts other element that 's why i is not updated ; Update i , as to check from previous element again ; Reduce sequence size ; Increment i , if not equal ; Return modified size ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int removeConsecutiveSame ( vector < string > v ) { int n = v . size ( ) ; for ( int i = 0 ; i < n - 1 ; ) { if ( v [ i ] . compare ( v [ i + 1 ] ) == 0 ) { v . erase ( v . begin ( ) + i ) ; v . erase ( v . begin ( ) + i ) ; if ( i > 0 ) i -- ; n = n - 2 ; } else i ++ ; } return v . size ( ) ; } int main ( ) { vector < string > v = { " tom " , " jerry " , " jerry " , " tom " } ; cout << removeConsecutiveSame ( v ) ; return 0 ; }
Delete consecutive same words in a sequence | C ++ implementation of above method ; Function to find the size of manipulated sequence ; Start traversing the sequence ; Push the current string if the stack is empty ; compare the current string with stack top if equal , pop the top ; Otherwise push the current string ; Return stack size ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int removeConsecutiveSame ( vector < string > v ) { stack < string > st ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { if ( st . empty ( ) ) st . push ( v [ i ] ) ; else { string str = st . top ( ) ; if ( str . compare ( v [ i ] ) == 0 ) st . pop ( ) ; else st . push ( v [ i ] ) ; } } return st . size ( ) ; } int main ( ) { vector < string > V = { " ab " , " aa " , " aa " , " bcd " , " ab " } ; cout << removeConsecutiveSame ( V ) ; return 0 ; }
Decode a string recursively encoded as count followed by substring | C ++ program to decode a string recursively encoded as count followed substring ; Returns decoded string for ' str ' ; Traversing the string ; If number , convert it into number and push it into integerstack . ; If closing bracket ' ] ' , pop elemment until ' [ ' opening bracket is not found in the character stack . ; Repeating the popped string ' temo ' count number of times . ; Push it in the character stack . ; If ' [ ' opening bracket , push it into character stack . ; Pop all the elmenet , make a string and return . ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; string decode ( string str ) { stack < int > integerstack ; stack < char > stringstack ; string temp = " " , result = " " ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { int count = 0 ; if ( str [ i ] >= '0' && str [ i ] <= '9' ) { while ( str [ i ] >= '0' && str [ i ] <= '9' ) { count = count * 10 + str [ i ] - '0' ; i ++ ; } i -- ; integerstack . push ( count ) ; } else if ( str [ i ] == ' ] ' ) { temp = " " ; count = 0 ; if ( ! integerstack . empty ( ) ) { count = integerstack . top ( ) ; integerstack . pop ( ) ; } while ( ! stringstack . empty ( ) && stringstack . top ( ) != ' [ ' ) { temp = stringstack . top ( ) + temp ; stringstack . pop ( ) ; } if ( ! stringstack . empty ( ) && stringstack . top ( ) == ' [ ' ) stringstack . pop ( ) ; for ( int j = 0 ; j < count ; j ++ ) result = result + temp ; for ( int j = 0 ; j < result . length ( ) ; j ++ ) stringstack . push ( result [ j ] ) ; result = " " ; } else if ( str [ i ] == ' [ ' ) { if ( str [ i - 1 ] >= '0' && str [ i - 1 ] <= '9' ) stringstack . push ( str [ i ] ) ; else { stringstack . push ( str [ i ] ) ; integerstack . push ( 1 ) ; } } else stringstack . push ( str [ i ] ) ; } while ( ! stringstack . empty ( ) ) { result = stringstack . top ( ) + result ; stringstack . pop ( ) ; } return result ; } int main ( ) { string str = "3 [ b2 [ ca ] ] " ; cout << decode ( str ) << endl ; return 0 ; }
Iterative method to find ancestors of a given binary tree | C ++ program to print all ancestors of a given key ; Structure for a tree node ; A utility function to create a new tree node ; Iterative Function to print all ancestors of a given key ; Create a stack to hold ancestors ; Traverse the complete tree in postorder way till we find the key ; Traverse the left side . While traversing , push the nodes into the stack so that their right subtrees can be traversed later ; push current node ; move to next node ; If the node whose ancestors are to be printed is found , then break the while loop . ; Check if right sub - tree exists for the node at top If not then pop that node because we don 't need this node any more. ; If the popped node is right child of top , then remove the top as well . Left child of the top must have processed before . ; if stack is not empty then simply set the root as right child of top and start traversing right sub - tree . ; If stack is not empty , print contents of stack Here assumption is that the key is there in tree ; Driver program to test above functions ; Let us construct a binary tree
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; struct Node * newNode ( int data ) { struct Node * node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; node -> data = data ; node -> left = node -> right = NULL ; return node ; } void printAncestors ( struct Node * root , int key ) { if ( root == NULL ) return ; stack < struct Node * > st ; while ( 1 ) { while ( root && root -> data != key ) { st . push ( root ) ; root = root -> left ; } if ( root && root -> data == key ) break ; if ( st . top ( ) -> right == NULL ) { root = st . top ( ) ; st . pop ( ) ; while ( ! st . empty ( ) && st . top ( ) -> right == root ) { root = st . top ( ) ; st . pop ( ) ; } } root = st . empty ( ) ? NULL : st . top ( ) -> right ; } while ( ! st . empty ( ) ) { cout << st . top ( ) -> data << " ▁ " ; st . pop ( ) ; } } int main ( ) { struct Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 7 ) ; root -> left -> left = newNode ( 3 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> left = newNode ( 8 ) ; root -> right -> right = newNode ( 9 ) ; root -> left -> left -> left = newNode ( 4 ) ; root -> left -> right -> right = newNode ( 6 ) ; root -> right -> right -> left = newNode ( 10 ) ; int key = 6 ; printAncestors ( root , key ) ; return 0 ; }
Tracking current Maximum Element in a Stack | C ++ program to keep track of maximum element in a stack ; main stack ; stack to keep track of max element ; If current element is greater than the top element of track stack , push the current element to track stack otherwise push the element at top of track stack again into it . ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; class StackWithMax { stack < int > mainStack ; stack < int > trackStack ; public : void push ( int x ) { mainStack . push ( x ) ; if ( mainStack . size ( ) == 1 ) { trackStack . push ( x ) ; return ; } if ( x > trackStack . top ( ) ) trackStack . push ( x ) ; else trackStack . push ( trackStack . top ( ) ) ; } int getMax ( ) { return trackStack . top ( ) ; } int pop ( ) { mainStack . pop ( ) ; trackStack . pop ( ) ; } } ; int main ( ) { StackWithMax s ; s . push ( 20 ) ; cout << s . getMax ( ) << endl ; s . push ( 10 ) ; cout << s . getMax ( ) << endl ; s . push ( 50 ) ; cout << s . getMax ( ) << endl ; return 0 ; }
Reverse a number using stack | CPP program to reverse the number using a stack ; Stack to maintain order of digits ; Function to push digits into stack ; Function to reverse the number ; Function call to push number 's digits to stack ; Popping the digits and forming the reversed number ; Return the reversed number formed ; Driver program to test above function ; Function call to reverse number
#include <bits/stdc++.h> NEW_LINE using namespace std ; stack < int > st ; void push_digits ( int number ) { while ( number != 0 ) { st . push ( number % 10 ) ; number = number / 10 ; } } int reverse_number ( int number ) { push_digits ( number ) ; int reverse = 0 ; int i = 1 ; while ( ! st . empty ( ) ) { reverse = reverse + ( st . top ( ) * i ) ; st . pop ( ) ; i = i * 10 ; } return reverse ; } int main ( ) { int number = 39997 ; cout << reverse_number ( number ) ; return 0 ; }
Flip Binary Tree | C / C ++ program to flip a binary tree ; A binary tree node structure ; Utility function to create a new Binary Tree Node ; method to flip the binary tree ; recursively call the same method ; rearranging main root Node after returning from recursive call ; Iterative method to do level order traversal line by line ; Base Case ; Create an empty queue for level order traversal ; Enqueue Root and initialize height ; nodeCount ( queue size ) indicates number of nodes at current lelvel . ; Dequeue all nodes of current level and Enqueue all nodes of next level ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; struct Node * newNode ( int data ) { struct Node * temp = new struct Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } Node * flipBinaryTree ( Node * root ) { if ( root == NULL ) return root ; if ( root -> left == NULL && root -> right == NULL ) return root ; Node * flippedRoot = flipBinaryTree ( root -> left ) ; root -> left -> left = root -> right ; root -> left -> right = root ; root -> left = root -> right = NULL ; return flippedRoot ; } void printLevelOrder ( Node * root ) { if ( root == NULL ) return ; queue < Node * > q ; q . push ( root ) ; while ( 1 ) { int nodeCount = q . size ( ) ; if ( nodeCount == 0 ) break ; while ( nodeCount > 0 ) { Node * node = q . front ( ) ; cout << node -> data << " ▁ " ; q . pop ( ) ; if ( node -> left != NULL ) q . push ( node -> left ) ; if ( node -> right != NULL ) q . push ( node -> right ) ; nodeCount -- ; } cout << endl ; } } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> right -> left = newNode ( 4 ) ; root -> right -> right = newNode ( 5 ) ; cout << " Level ▁ order ▁ traversal ▁ of ▁ given ▁ tree STRNEWLINE " ; printLevelOrder ( root ) ; root = flipBinaryTree ( root ) ; cout << " Level order traversal of the flipped " STRNEWLINE TABSYMBOL TABSYMBOL TABSYMBOL " tree " printLevelOrder ( root ) ; return 0 ; }
Check if stack elements are pairwise consecutive | C ++ program to check if successive pair of numbers in the stack are consecutive or not ; Function to check if elements are pairwise consecutive in stack ; Transfer elements of s to aux . ; Traverse aux and see if elements are pairwise consecutive or not . We also need to make sure that original content is retained . ; Fetch current top two elements of aux and check if they are consecutive . ; Push the elements to original stack . ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool pairWiseConsecutive ( stack < int > s ) { stack < int > aux ; while ( ! s . empty ( ) ) { aux . push ( s . top ( ) ) ; s . pop ( ) ; } bool result = true ; while ( aux . size ( ) > 1 ) { int x = aux . top ( ) ; aux . pop ( ) ; int y = aux . top ( ) ; aux . pop ( ) ; if ( abs ( x - y ) != 1 ) result = false ; s . push ( x ) ; s . push ( y ) ; } if ( aux . size ( ) == 1 ) s . push ( aux . top ( ) ) ; return result ; } int main ( ) { stack < int > s ; s . push ( 4 ) ; s . push ( 5 ) ; s . push ( -2 ) ; s . push ( -3 ) ; s . push ( 11 ) ; s . push ( 10 ) ; s . push ( 5 ) ; s . push ( 6 ) ; s . push ( 20 ) ; if ( pairWiseConsecutive ( s ) ) cout << " Yes " << endl ; else cout << " No " << endl ; cout << " Stack ▁ content ▁ ( from ▁ top ) " " ▁ after ▁ function ▁ call STRNEWLINE " ; while ( s . empty ( ) == false ) { cout << s . top ( ) << " ▁ " ; s . pop ( ) ; } return 0 ; }
Remove brackets from an algebraic string containing + and | C ++ program to simplify algebraic string ; Function to simplify the string ; resultant string of max length equal to length of input string ; create empty stack ; If top is 1 , flip the operator ; If top is 0 , append the same operator ; x is opposite to the top of stack ; push value equal to top of the stack ; If closing parentheses pop the stack once ; copy the character to the result ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; char * simplify ( string str ) { int len = str . length ( ) ; char * res = new char ( len ) ; int index = 0 , i = 0 ; stack < int > s ; s . push ( 0 ) ; while ( i < len ) { if ( str [ i ] == ' + ' ) { if ( s . top ( ) == 1 ) res [ index ++ ] = ' - ' ; if ( s . top ( ) == 0 ) res [ index ++ ] = ' + ' ; } else if ( str [ i ] == ' - ' ) { if ( s . top ( ) == 1 ) res [ index ++ ] = ' + ' ; else if ( s . top ( ) == 0 ) res [ index ++ ] = ' - ' ; } else if ( str [ i ] == ' ( ' && i > 0 ) { if ( str [ i - 1 ] == ' - ' ) { int x = ( s . top ( ) == 1 ) ? 0 : 1 ; s . push ( x ) ; } else if ( str [ i - 1 ] == ' + ' ) s . push ( s . top ( ) ) ; } else if ( str [ i ] == ' ) ' ) s . pop ( ) ; else res [ index ++ ] = str [ i ] ; i ++ ; } return res ; } int main ( ) { string s1 = " a - ( b + c ) " ; string s2 = " a - ( b - c - ( d + e ) ) - f " ; cout << simplify ( s1 ) << endl ; cout << simplify ( s2 ) << endl ; return 0 ; }
Growable array based stack | CPP Program to implement growable array based stack using tight strategy ; constant amount at which stack is increased ; top of the stack ; length of stack ; function to create new stack ; allocate memory for new stack ; copying the content of old stack ; re - sizing the length ; function to push new element ; if stack is full , create new one ; insert element at top of the stack ; function to pop an element ; function to display ; if top is - 1 , that means stack is empty ; Driver Code ; creating initial stack ; pushing element to top of stack ; pushing more element when stack is full ; pushing more element so that stack can grow
#include <iostream> NEW_LINE using namespace std ; #define BOUND 4 NEW_LINE int top = -1 ; int length = 0 ; int * create_new ( int * a ) { int * new_a = new int [ length + BOUND ] ; for ( int i = 0 ; i < length ; i ++ ) new_a [ i ] = a [ i ] ; length += BOUND ; return new_a ; } int * push ( int * a , int element ) { if ( top == length - 1 ) a = create_new ( a ) ; a [ ++ top ] = element ; return a ; } void pop ( int * a ) { top -- ; } void display ( int * a ) { if ( top == -1 ) cout << " Stack ▁ is ▁ Empty " << endl ; else { cout << " Stack : ▁ " ; for ( int i = 0 ; i <= top ; i ++ ) cout << a [ i ] << " ▁ " ; cout << endl ; } } int main ( ) { int * a = create_new ( a ) ; a = push ( a , 1 ) ; a = push ( a , 2 ) ; a = push ( a , 3 ) ; a = push ( a , 4 ) ; display ( a ) ; a = push ( a , 5 ) ; a = push ( a , 6 ) ; display ( a ) ; a = push ( a , 7 ) ; a = push ( a , 8 ) ; display ( a ) ; a = push ( a , 9 ) ; display ( a ) ; return 0 ; }
Range Queries for Longest Correct Bracket Subsequence Set | 2 | CPP code to answer the query in constant time ; function for precomputation ; Create a stack and push - 1 as initial index to it . ; Initialize result ; Traverse all characters of given string ; If opening bracket , push index of it ; If closing bracket , i . e . , str [ i ] = ' ) ' ; If closing bracket , i . e . , str [ i ] = ' ) ' && stack is not empty then mark both " open ▁ & ▁ close " bracket indexs as 1 . Pop the previous opening bracket 's index ; If stack is empty . ; Function return output of each query in O ( 1 ) ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void constructBlanceArray ( int BOP [ ] , int BCP [ ] , char * str , int n ) { stack < int > stk ; int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == ' ( ' ) stk . push ( i ) ; else { if ( ! stk . empty ( ) ) { BCP [ i ] = 1 ; BOP [ stk . top ( ) ] = 1 ; stk . pop ( ) ; } else BCP [ i ] = 0 ; } } for ( int i = 1 ; i < n ; i ++ ) { BCP [ i ] += BCP [ i - 1 ] ; BOP [ i ] += BOP [ i - 1 ] ; } } int query ( int BOP [ ] , int BCP [ ] , int s , int e ) { if ( BOP [ s - 1 ] == BOP [ s ] ) { return ( BCP [ e ] - BOP [ s ] ) * 2 ; } else { return ( BCP [ e ] - BOP [ s ] + 1 ) * 2 ; } } int main ( ) { char str [ ] = " ( ) ) ( ( ) ) ( ( ) ) ( " ; int n = strlen ( str ) ; int BCP [ n + 1 ] = { 0 } ; int BOP [ n + 1 ] = { 0 } ; constructBlanceArray ( BOP , BCP , str , n ) ; int startIndex = 5 , endIndex = 11 ; cout << " Maximum ▁ Length ▁ Correct ▁ Bracket " " ▁ Subsequence ▁ between ▁ " << startIndex << " ▁ and ▁ " << endIndex << " ▁ = ▁ " << query ( BOP , BCP , startIndex , endIndex ) << endl ; startIndex = 4 , endIndex = 5 ; cout << " Maximum ▁ Length ▁ Correct ▁ Bracket " " ▁ Subsequence ▁ between ▁ " << startIndex << " ▁ and ▁ " << endIndex << " ▁ = ▁ " << query ( BOP , BCP , startIndex , endIndex ) << endl ; startIndex = 1 , endIndex = 5 ; cout << " Maximum ▁ Length ▁ Correct ▁ Bracket " " ▁ Subsequence ▁ between ▁ " << startIndex << " ▁ and ▁ " << endIndex << " ▁ = ▁ " << query ( BOP , BCP , startIndex , endIndex ) << endl ; return 0 ; }
HeapSort | C ++ program for implementation of Heap Sort ; To heapify a subtree rooted with node i which is an index in arr [ ] . n is size of heap ; Initialize largest as root ; left = 2 * i + 1 ; right = 2 * i + 2 ; If left child is larger than root ; If right child is larger than largest so far ; If largest is not root ; Recursively heapify the affected sub - tree ; main function to do heap sort ; Build heap ( rearrange array ) ; One by one extract an element from heap ; Move current root to end ; call max heapify on the reduced heap ; A utility function to print array of size n ; Driver code
#include <iostream> NEW_LINE using namespace std ; void heapify ( int arr [ ] , int n , int i ) { int largest = i ; int l = 2 * i + 1 ; int r = 2 * i + 2 ; if ( l < n && arr [ l ] > arr [ largest ] ) largest = l ; if ( r < n && arr [ r ] > arr [ largest ] ) largest = r ; if ( largest != i ) { swap ( arr [ i ] , arr [ largest ] ) ; heapify ( arr , n , largest ) ; } } void heapSort ( int arr [ ] , int n ) { for ( int i = n / 2 - 1 ; i >= 0 ; i -- ) heapify ( arr , n , i ) ; for ( int i = n - 1 ; i > 0 ; i -- ) { swap ( arr [ 0 ] , arr [ i ] ) ; heapify ( arr , i , 0 ) ; } } void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; ++ i ) cout << arr [ i ] << " ▁ " ; cout << " STRNEWLINE " ; } int main ( ) { int arr [ ] = { 12 , 11 , 13 , 5 , 6 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; heapSort ( arr , n ) ; cout << " Sorted ▁ array ▁ is ▁ STRNEWLINE " ; printArray ( arr , n ) ; }
Iterative HeapSort | C ++ program for implementation of Iterative Heap Sort ; function build Max Heap where value of each child is always smaller than value of their parent ; if child is bigger than parent ; swap child and parent until parent is smaller ; swap value of first indexed with last indexed ; maintaining heap property after each swapping ; if left child is smaller than right child point index variable to right child ; if parent is smaller than child then swapping parent with child having higher value ; Driver Code to test above ; print array after sorting
#include <bits/stdc++.h> NEW_LINE using namespace std ; void buildMaxHeap ( int arr [ ] , int n ) { for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] > arr [ ( i - 1 ) / 2 ] ) { int j = i ; while ( arr [ j ] > arr [ ( j - 1 ) / 2 ] ) { swap ( arr [ j ] , arr [ ( j - 1 ) / 2 ] ) ; j = ( j - 1 ) / 2 ; } } } } void heapSort ( int arr [ ] , int n ) { buildMaxHeap ( arr , n ) ; for ( int i = n - 1 ; i > 0 ; i -- ) { swap ( arr [ 0 ] , arr [ i ] ) ; int j = 0 , index ; do { index = ( 2 * j + 1 ) ; if ( arr [ index ] < arr [ index + 1 ] && index < ( i - 1 ) ) index ++ ; if ( arr [ j ] < arr [ index ] && index < i ) swap ( arr [ j ] , arr [ index ] ) ; j = index ; } while ( index < i ) ; } } int main ( ) { int arr [ ] = { 10 , 20 , 15 , 17 , 9 , 21 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Given ▁ array : ▁ " ) ; for ( int i = 0 ; i < n ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; printf ( " STRNEWLINE STRNEWLINE " ) ; heapSort ( arr , n ) ; printf ( " Sorted ▁ array : ▁ " ) ; for ( int i = 0 ; i < n ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; return 0 ; }
Flip Binary Tree | C / C ++ program to flip a binary tree ; A binary tree node structure ; Utility function to create a new Binary Tree Node ; method to flip the binary tree ; Initialization of pointers ; Iterate through all left nodes ; Swapping nodes now , need temp to keep the previous right child Making prev ' s ▁ right ▁ as ▁ curr ' s left child ; Storing curr 's right child ; Making prev as curr 's right child ; Iterative method to do level order traversal line by line ; Base Case ; Create an empty queue for level order traversal ; Enqueue Root and initialize height ; nodeCount ( queue size ) indicates number of nodes at current lelvel . ; Dequeue all nodes of current level and Enqueue all nodes of next level ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; struct Node * newNode ( int data ) { struct Node * temp = new struct Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } Node * flipBinaryTree ( Node * root ) { Node * curr = root ; Node * next = NULL ; Node * temp = NULL ; Node * prev = NULL ; while ( curr ) { next = curr -> left ; curr -> left = temp ; temp = curr -> right ; curr -> right = prev ; prev = curr ; curr = next ; } return prev ; } void printLevelOrder ( Node * root ) { if ( root == NULL ) return ; queue < Node * > q ; q . push ( root ) ; while ( 1 ) { int nodeCount = q . size ( ) ; if ( nodeCount == 0 ) break ; while ( nodeCount > 0 ) { Node * node = q . front ( ) ; cout << node -> data << " ▁ " ; q . pop ( ) ; if ( node -> left != NULL ) q . push ( node -> left ) ; if ( node -> right != NULL ) q . push ( node -> right ) ; nodeCount -- ; } cout << endl ; } } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> right -> left = newNode ( 4 ) ; root -> right -> right = newNode ( 5 ) ; cout << " Level ▁ order ▁ traversal ▁ of ▁ given ▁ tree STRNEWLINE " ; printLevelOrder ( root ) ; root = flipBinaryTree ( root ) ; cout << " Level order traversal of the flipped " STRNEWLINE TABSYMBOL TABSYMBOL TABSYMBOL " tree " printLevelOrder ( root ) ; return 0 ; }
Foldable Binary Trees | ; A binary tree node has data , pointer to left child and a pointer to right child ; A utility function that checks if trees with roots as n1 and n2 are mirror of each other ; Returns true if the given tree can be folded ; A utility function that checks if trees with roots as n1 and n2 are mirror of each other ; If both left and right subtrees are NULL , then return true ; If one of the trees is NULL and other is not , then return false ; Otherwise check if left and right subtrees are mirrors of their counterparts ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver code ; The constructed binary tree is 1 / \ 2 3 \ / 4 5
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define bool int NEW_LINE #define true 1 NEW_LINE #define false 0 NEW_LINE class node { public : int data ; node * left ; node * right ; } ; bool IsFoldableUtil ( node * n1 , node * n2 ) ; bool IsFoldable ( node * root ) { if ( root == NULL ) { return true ; } return IsFoldableUtil ( root -> left , root -> right ) ; } bool IsFoldableUtil ( node * n1 , node * n2 ) { if ( n1 == NULL && n2 == NULL ) { return true ; } if ( n1 == NULL n2 == NULL ) { return false ; } return IsFoldableUtil ( n1 -> left , n2 -> right ) && IsFoldableUtil ( n1 -> right , n2 -> left ) ; } node * newNode ( int data ) { node * Node = new node ( ) ; Node -> data = data ; Node -> left = NULL ; Node -> right = NULL ; return ( Node ) ; } int main ( void ) { node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> right = newNode ( 4 ) ; root -> right -> left = newNode ( 5 ) ; if ( IsFoldable ( root ) == true ) { cout << " Tree ▁ is ▁ foldable " ; } else { cout << " Tree ▁ is ▁ not ▁ foldable " ; } return 0 ; }
Check for Children Sum Property in a Binary Tree | Program to check children sum property ; A binary tree node has data , left child and right child ; returns 1 if children sum property holds for the given node and both of its children ; left_data is left child data and right_data is for right child data ; If node is NULL or it 's a leaf node then return true ; If left child is not present then 0 is used as data of left child ; If right child is not present then 0 is used as data of right child ; if the node and both of its children satisfy the property return 1 else 0 ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int data ; struct node * left ; struct node * right ; } ; int isSumProperty ( struct node * node ) { int left_data = 0 , right_data = 0 ; if ( node == NULL || ( node -> left == NULL && node -> right == NULL ) ) return 1 ; else { if ( node -> left != NULL ) left_data = node -> left -> data ; if ( node -> right != NULL ) right_data = node -> right -> data ; if ( ( node -> data == left_data + right_data ) && isSumProperty ( node -> left ) && isSumProperty ( node -> right ) ) return 1 ; else return 0 ; } } 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 ( 10 ) ; root -> left = newNode ( 8 ) ; root -> right = newNode ( 2 ) ; root -> left -> left = newNode ( 3 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> right = newNode ( 2 ) ; if ( isSumProperty ( root ) ) cout << " The ▁ given ▁ tree ▁ satisfies ▁ " << " the ▁ children ▁ sum ▁ property ▁ " ; else cout << " The ▁ given ▁ tree ▁ does ▁ not ▁ satisfy ▁ " << " the ▁ children ▁ sum ▁ property ▁ " ; getchar ( ) ; return 0 ; }
How to check if a given array represents a Binary Heap ? | C program to check whether a given array represents a max - heap or not ; Returns true if arr [ i . . n - 1 ] represents a max - heap ; If a leaf node ; If an internal node and is greater than its children , and same is recursively true for the children ; Driver program
#include <limits.h> NEW_LINE #include <stdio.h> NEW_LINE bool isHeap ( int arr [ ] , int i , int n ) { if ( i >= ( n - 2 ) / 2 ) return true ; if ( arr [ i ] >= arr [ 2 * i + 1 ] && arr [ i ] >= arr [ 2 * i + 2 ] && isHeap ( arr , 2 * i + 1 , n ) && isHeap ( arr , 2 * i + 2 , n ) ) return true ; return false ; } int main ( ) { int arr [ ] = { 90 , 15 , 10 , 7 , 12 , 2 , 7 , 3 } ; int n = sizeof ( arr ) / sizeof ( int ) - 1 ; isHeap ( arr , 0 , n ) ? printf ( " Yes " ) : printf ( " No " ) ; return 0 ; }
How to check if a given array represents a Binary Heap ? | C program to check whether a given array represents a max - heap or not ; Returns true if arr [ i . . n - 1 ] represents a max - heap ; Start from root and go till the last internal node ; If left child is greater , return false ; If right child is greater , return false ; Driver program
#include <stdio.h> NEW_LINE #include <limits.h> NEW_LINE bool isHeap ( int arr [ ] , int n ) { for ( int i = 0 ; i <= ( n - 2 ) / 2 ; i ++ ) { if ( arr [ 2 * i + 1 ] > arr [ i ] ) return false ; if ( 2 * i + 2 < n && arr [ 2 * i + 2 ] > arr [ i ] ) return false ; } return true ; } int main ( ) { int arr [ ] = { 90 , 15 , 10 , 7 , 12 , 2 , 7 , 3 } ; int n = sizeof ( arr ) / sizeof ( int ) ; isHeap ( arr , n ) ? printf ( " Yes " ) : printf ( " No " ) ; return 0 ; }
Connect n ropes with minimum cost | ; Create a priority queue ; Initialize result ; While size of priority queue is more than 1 ; Extract shortest two ropes from pq ; Connect the ropes : update result and insert the new rope to pq ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minCost ( int arr [ ] , int n ) { priority_queue < int , vector < int > , greater < int > > pq ( arr , arr + n ) ; int res = 0 ; while ( pq . size ( ) > 1 ) { int first = pq . top ( ) ; pq . pop ( ) ; int second = pq . top ( ) ; pq . pop ( ) ; res += first + second ; pq . push ( first + second ) ; } return res ; } int main ( ) { int len [ ] = { 4 , 3 , 2 , 6 } ; int size = sizeof ( len ) / sizeof ( len [ 0 ] ) ; cout << " Total ▁ cost ▁ for ▁ connecting ▁ ropes ▁ is ▁ " << minCost ( len , size ) ; return 0 ; }
Merge k sorted arrays | Set 1 | C ++ program to merge k sorted arrays of size n each . ; This function takes an array of arrays as an argument and All arrays are assumed to be sorted . It merges them together and prints the final sorted output . ; traverse the matrix ; sort the array ; A utility function to print array elements ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define n 4 NEW_LINE void mergeKArrays ( int arr [ ] [ n ] , int a , int output [ ] ) { int c = 0 ; for ( int i = 0 ; i < a ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) output [ c ++ ] = arr [ i ] [ j ] ; } sort ( output , output + n * a ) ; } void printArray ( int arr [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) cout << arr [ i ] << " ▁ " ; } int main ( ) { int arr [ ] [ n ] = { { 2 , 6 , 12 , 34 } , { 1 , 9 , 20 , 1000 } , { 23 , 34 , 90 , 2000 } } ; int k = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int output [ n * k ] ; mergeKArrays ( arr , 3 , output ) ; cout << " Merged ▁ array ▁ is ▁ " << endl ; printArray ( output , n * k ) ; return 0 ; }
Merge k sorted arrays | Set 1 | C ++ program to merge k sorted arrays of size n each . ; Merge arr1 [ 0. . n1 - 1 ] and arr2 [ 0. . n2 - 1 ] into arr3 [ 0. . n1 + n2 - 1 ] ; Traverse both array ; Check if current element of first array is smaller than current element of second array . If yes , store first array element and increment first array index . Otherwise do same with second array ; Store remaining elements of first array ; Store remaining elements of second array ; A utility function to print array elements ; This function takes an array of arrays as an argument and All arrays are assumed to be sorted . It merges them together and prints the final sorted output . ; if one array is in range ; if only two arrays are left them merge them ; output arrays ; divide the array into halves ; merge the output array ; Driver program to test above functions ; Change n at the top to change number of elements in an array
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define n 4 NEW_LINE void mergeArrays ( int arr1 [ ] , int arr2 [ ] , int n1 , int n2 , int arr3 [ ] ) { int i = 0 , j = 0 , k = 0 ; while ( i < n1 && j < n2 ) { if ( arr1 [ i ] < arr2 [ j ] ) arr3 [ k ++ ] = arr1 [ i ++ ] ; else arr3 [ k ++ ] = arr2 [ j ++ ] ; } while ( i < n1 ) arr3 [ k ++ ] = arr1 [ i ++ ] ; while ( j < n2 ) arr3 [ k ++ ] = arr2 [ j ++ ] ; } void printArray ( int arr [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) cout << arr [ i ] << " ▁ " ; } void mergeKArrays ( int arr [ ] [ n ] , int i , int j , int output [ ] ) { if ( i == j ) { for ( int p = 0 ; p < n ; p ++ ) output [ p ] = arr [ i ] [ p ] ; return ; } if ( j - i == 1 ) { mergeArrays ( arr [ i ] , arr [ j ] , n , n , output ) ; return ; } int out1 [ n * ( ( ( i + j ) / 2 ) - i + 1 ) ] , out2 [ n * ( j - ( ( i + j ) / 2 ) ) ] ; mergeKArrays ( arr , i , ( i + j ) / 2 , out1 ) ; mergeKArrays ( arr , ( i + j ) / 2 + 1 , j , out2 ) ; mergeArrays ( out1 , out2 , n * ( ( ( i + j ) / 2 ) - i + 1 ) , n * ( j - ( ( i + j ) / 2 ) ) , output ) ; } int main ( ) { int arr [ ] [ n ] = { { 2 , 6 , 12 , 34 } , { 1 , 9 , 20 , 1000 } , { 23 , 34 , 90 , 2000 } } ; int k = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int output [ n * k ] ; mergeKArrays ( arr , 0 , 2 , output ) ; cout << " Merged ▁ array ▁ is ▁ " << endl ; printArray ( output , n * k ) ; return 0 ; }
Smallest Derangement of Sequence | C ++ program to generate smallest derangement using priority queue . ; Generate Sequence and insert into a priority queue . ; Generate Least Derangement ; Print Derangement ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void generate_derangement ( int N ) { int S [ N + 1 ] ; priority_queue < int , vector < int > , greater < int > > PQ ; for ( int i = 1 ; i <= N ; i ++ ) { S [ i ] = i ; PQ . push ( S [ i ] ) ; } int D [ N + 1 ] ; for ( int i = 1 ; i <= N ; i ++ ) { int d = PQ . top ( ) ; PQ . pop ( ) ; if ( d != S [ i ] i == N ) { D [ i ] = d ; } else { D [ i ] = PQ . top ( ) ; PQ . pop ( ) ; PQ . push ( d ) ; } } if ( D [ N ] == S [ N ] ) swap ( D [ N - 1 ] , D [ N ] ) ; for ( int i = 1 ; i <= N ; i ++ ) printf ( " % d ▁ " , D [ i ] ) ; printf ( " STRNEWLINE " ) ; } int main ( ) { generate_derangement ( 10 ) ; return 0 ; }
Smallest Derangement of Sequence | Efficient C ++ program to find smallest derangement . ; Generate Sequence S ; Generate Derangement ; Only if i is odd Swap D [ N - 1 ] and D [ N ] ; Print Derangement ; Driver Program
#include <bits/stdc++.h> NEW_LINE void generate_derangement ( int N ) { int S [ N + 1 ] ; for ( int i = 1 ; i <= N ; i ++ ) S [ i ] = i ; int D [ N + 1 ] ; for ( int i = 1 ; i <= N ; i += 2 ) { if ( i == N && i % N != 0 ) { int temp = D [ N ] ; D [ N ] = D [ N - 1 ] ; D [ N - 1 ] = temp ; } else { D [ i ] = i + 1 ; D [ i + 1 ] = i ; } } for ( int i = 1 ; i <= N ; i ++ ) printf ( " % d ▁ " , D [ i ] ) ; printf ( " STRNEWLINE " ) ; } int main ( ) { generate_derangement ( 10 ) ; return 0 ; }
Largest Derangement of a Sequence | C ++ program to find the largest derangement ; Stores result ; Insert all elements into a priority queue ; Fill Up res [ ] from left to right ; New Element poped equals the element in original sequence . Get the next largest element ; If given sequence is in descending order then we need to swap last two elements again ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printLargest ( int seq [ ] , int N ) { int res [ N ] ; std :: priority_queue < int > pq ; for ( int i = 0 ; i < N ; i ++ ) pq . push ( seq [ i ] ) ; for ( int i = 0 ; i < N ; i ++ ) { int d = pq . top ( ) ; pq . pop ( ) ; if ( d != seq [ i ] i == N - 1 ) { res [ i ] = d ; } else { res [ i ] = pq . top ( ) ; pq . pop ( ) ; pq . push ( d ) ; } } if ( res [ N - 1 ] == seq [ N - 1 ] ) { res [ N - 1 ] = res [ N - 2 ] ; res [ N - 2 ] = seq [ N - 1 ] ; } printf ( " Largest Derangement " for ( int i = 0 ; i < N ; i ++ ) printf ( " % d ▁ " , res [ i ] ) ; } int main ( ) { int seq [ ] = { 92 , 3 , 52 , 13 , 2 , 31 , 1 } ; int n = sizeof ( seq ) / sizeof ( seq [ 0 ] ) ; printLargest ( seq , n ) ; return 0 ; }
Program to calculate Profit Or Loss | C ++ code to demonstrate Profit and Loss ; Function to calculate Profit . ; Function to calculate Loss . ; Driver Code .
#include <iostream> NEW_LINE using namespace std ; int Profit ( int costPrice , int sellingPrice ) { int profit = ( sellingPrice - costPrice ) ; return profit ; } int Loss ( int costPrice , int sellingPrice ) { int Loss = ( costPrice - sellingPrice ) ; return Loss ; } int main ( ) { int costPrice = 1500 , sellingPrice = 2000 ; if ( sellingPrice == costPrice ) cout << " No ▁ profit ▁ nor ▁ Loss " ; else if ( sellingPrice > costPrice ) cout << Profit ( costPrice , sellingPrice ) << " ▁ Profit ▁ " ; else cout << Loss ( costPrice , sellingPrice ) << " ▁ Loss ▁ " ; return 0 ; }
Find the Next perfect square greater than a given number | C ++ implementation of above approach ; Function to find the next perfect square ; Driver Code
#include <iostream> NEW_LINE #include <cmath> NEW_LINE using namespace std ; int nextPerfectSquare ( int N ) { int nextN = floor ( sqrt ( N ) ) + 1 ; return nextN * nextN ; } int main ( ) { int n = 35 ; cout << nextPerfectSquare ( n ) ; return 0 ; }
Print all substring of a number without any conversion | C ++ implementation of above approach ; Function to print the substrings of a number ; Calculate the total number of digits ; 0.5 has been added because of it will return double value like 99.556 ; Print all the numbers from starting position ; Update the no . ; Update the no . of digits ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printSubstrings ( int n ) { int s = log10 ( n ) ; int d = ( int ) ( pow ( 10 , s ) + 0.5 ) ; int k = d ; while ( n ) { while ( d ) { cout << n / d << endl ; d = d / 10 ; } n = n % k ; k = k / 10 ; d = k ; } } int main ( ) { int n = 123 ; printSubstrings ( n ) ; return 0 ; }
Modulo power for large numbers represented as strings | CPP program to find ( a ^ b ) % MOD where a and b may be very large and represented as strings . ; Returns modulo exponentiation for two numbers represented as long long int . It is used by powerStrings ( ) . Its complexity is log ( n ) ; Returns modulo exponentiation for two numbers represented as strings . It is used by powerStrings ( ) ; We convert strings to number ; calculating a % MOD ; calculating b % ( MOD - 1 ) ; Now a and b are long long int . We calculate a ^ b using modulo exponentiation ; Driver code ; As numbers are very large that is it may contains upto 10 ^ 6 digits . So , we use string .
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE const ll MOD = 1e9 + 7 ; ll powerLL ( ll x , ll n ) { ll result = 1 ; while ( n ) { if ( n & 1 ) result = result * x % MOD ; n = n / 2 ; x = x * x % MOD ; } return result ; } ll powerStrings ( string sa , string sb ) { ll a = 0 , b = 0 ; for ( int i = 0 ; i < sa . length ( ) ; i ++ ) a = ( a * 10 + ( sa [ i ] - '0' ) ) % MOD ; for ( int i = 0 ; i < sb . length ( ) ; i ++ ) b = ( b * 10 + ( sb [ i ] - '0' ) ) % ( MOD - 1 ) ; return powerLL ( a , b ) ; } int main ( ) { string sa = "2" , sb = "3" ; cout << powerStrings ( sa , sb ) << endl ; return 0 ; }
Check if a number can be expressed as 2 ^ x + 2 ^ y | CPP code to check if a number can be expressed as 2 ^ x + 2 ^ y ; Utility function to check if a number is power of 2 or not ; Utility function to determine the value of previous power of 2 ; function to check if n can be expressed as 2 ^ x + 2 ^ y or not ; if value of n is 0 or 1 it can not be expressed as 2 ^ x + 2 ^ y ; if a number is power of 2 then it can be expressed as 2 ^ x + 2 ^ y ; if the remainder after subtracting previous power of 2 is also a power of 2 then it can be expressed as 2 ^ x + 2 ^ y ; driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPowerOfTwo ( int n ) { return ( n && ! ( n & ( n - 1 ) ) ) ; } int previousPowerOfTwo ( int n ) { while ( n & n - 1 ) { n = n & n - 1 ; } return n ; } bool checkSum ( int n ) { if ( n == 0 n == 1 ) return false ; else if ( isPowerOfTwo ( n ) ) { cout << " ▁ " << n / 2 << " ▁ " << n / 2 ; return true ; } else { int x = previousPowerOfTwo ( n ) ; int y = n - x ; if ( isPowerOfTwo ( y ) ) { cout << " ▁ " << x << " ▁ " << y ; return true ; } } return false ; } int main ( ) { int n1 = 20 ; if ( checkSum ( n1 ) == false ) cout << " No " ; cout << endl ; int n2 = 11 ; if ( checkSum ( n2 ) == false ) cout << " No " ; return 0 ; }
10 's Complement of a decimal number | C ++ program to find 10 's complement ; Function to find 10 's complement ; Calculating total digits in num ; restore num ; calculate 10 's complement ; Driver code
#include <iostream> NEW_LINE #include <cmath> NEW_LINE using namespace std ; int complement ( int num ) { int i , len = 0 , temp , comp ; temp = num ; while ( 1 ) { len ++ ; num = num / 10 ; if ( abs ( num ) == 0 ) break ; } num = temp ; comp = pow ( 10 , len ) - num ; return comp ; } int main ( ) { cout << complement ( 25 ) << endl ; cout << complement ( 456 ) ; return 0 ; }
Program to find HCF ( Highest Common Factor ) of 2 Numbers | C ++ program to find GCD of two numbers ; Recursive function to return gcd of a and b ; Everything divides 0 ; base case ; a is greater ; Driver program to test above function
#include <iostream> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( a == 0 && b == 0 ) return 0 ; if ( a == 0 ) return b ; if ( b == 0 ) return a ; if ( a == b ) return a ; if ( a > b ) return gcd ( a - b , b ) ; return gcd ( a , b - a ) ; } int main ( ) { int a = 0 , b = 56 ; cout << " GCD ▁ of ▁ " << a << " ▁ and ▁ " << b << " ▁ is ▁ " << gcd ( a , b ) ; return 0 ; }
Number of sub arrays with odd sum | C ++ program to find number of subarrays with odd sum ; Function to find number of subarrays with odd sum ; ' odd ' stores number of odd numbers upto ith index ' c _ odd ' stores number of odd sum subarrays starting at ith index ' Result ' stores the number of odd sum subarrays ; First find number of odd sum subarrays starting at 0 th index ; Find number of odd sum subarrays starting at ith index add to result ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countOddSum ( int a [ ] , int n ) { int odd = 0 , c_odd = 0 , result = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] & 1 ) { odd = ! odd ; } if ( odd ) { c_odd ++ ; } } for ( int i = 0 ; i < n ; i ++ ) { result += c_odd ; if ( a [ i ] & 1 ) { c_odd = ( n - i - c_odd ) ; } } return result ; } int main ( ) { int ar [ ] = { 5 , 4 , 4 , 5 , 1 , 3 } ; int n = sizeof ( ar ) / sizeof ( ar [ 0 ] ) ; cout << " The ▁ Number ▁ of ▁ Subarrays ▁ with ▁ odd ▁ sum ▁ is ▁ " << countOddSum ( ar , n ) ; return ( 0 ) ; }
Calculating n | C ++ Program to find n - th real root of x ; Initialize boundary values ; Used for taking approximations of the answer ; Do binary search ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findNthRoot ( double x , int n ) { double low , high ; if ( x >= 0 and x <= 1 ) { low = x ; high = 1 ; } else { low = 1 ; high = x ; } double epsilon = 0.00000001 ; double guess = ( low + high ) / 2 ; while ( abs ( ( pow ( guess , n ) ) - x ) >= epsilon ) { if ( pow ( guess , n ) > x ) { high = guess ; } else { low = guess ; } guess = ( low + high ) / 2 ; } cout << fixed << setprecision ( 16 ) << guess ; } int main ( ) { double x = 5 ; int n = 2 ; findNthRoot ( x , n ) ; }
Sum of all elements up to Nth row in a Pascal triangle | C ++ program to find sum of all elements upto nth row in Pascal triangle . ; Function to find sum of all elements upto nth row . ; Initialize sum with 0 ; Loop to calculate power of 2 upto n and add them ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long int calculateSum ( int n ) { long long int sum = 0 ; for ( int row = 0 ; row < n ; row ++ ) { sum = sum + ( 1 << row ) ; } return sum ; } int main ( ) { int n = 10 ; cout << " ▁ Sum ▁ of ▁ all ▁ elements : " << calculateSum ( n ) ; return 0 ; }
Number of sequences which has HEAD at alternate positions to the right of the first HEAD | C ++ program to find number of sequences ; function to calculate total sequences possible ; Value of N is even ; Value of N is odd ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findAllSequence ( int N ) { if ( N % 2 == 0 ) { return pow ( 2 , N / 2 + 1 ) + pow ( 2 , N / 2 ) - 2 ; } else { return pow ( 2 , ( N + 1 ) / 2 ) + pow ( 2 , ( N + 1 ) / 2 ) - 2 ; } } int main ( ) { int N = 2 ; cout << findAllSequence ( N ) << endl ; return 0 ; }
Compute power of power k times % m | C ++ program to compute x ^ x ^ x ^ x . . % m ; Create an array to store phi or totient values ; Function to calculate Euler Totient values ; indicates not evaluated yet and initializes for product formula . ; Compute other Phi values ; If phi [ p ] is not computed already , then number p is prime ; Phi of a prime number p is always equal to p - 1. ; Update phi values of all multiples of p ; Add contribution of p to its multiple i by multiplying with ( 1 - 1 / p ) ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; x = x % p ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 ; y = y / 2 ; Function to calculate ( x ^ x ^ x ^ x ... k times ) % m ; to store different mod values ; run loop in reverse to calculate result ; Driver Code ; compute euler totient function values ; Calling function to compute answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 1000000 ; long long phi [ N + 5 ] ; void computeTotient ( ) { for ( int i = 1 ; i <= N ; i ++ ) phi [ i ] = i ; for ( int p = 2 ; p <= N ; p ++ ) { if ( phi [ p ] == p ) { phi [ p ] = p - 1 ; for ( int i = 2 * p ; i <= N ; i += p ) { phi [ i ] = ( phi [ i ] / p ) * ( p - 1 ) ; } } } } long long power ( long long x , long long y , long long p ) { while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return res ; } long long calculate ( long long x , long long k , long long mod ) { long long arr [ N ] ; long long count = 0 ; while ( mod > 1 ) { arr [ count ++ ] = mod ; mod = phi [ mod ] ; } long long result = 1 ; long long loop = count + 1 ; arr [ count ] = 1 ; for ( int i = min ( k , loop ) - 1 ; i >= 0 ; i -- ) result = power ( x , result , arr [ i ] ) ; return result ; } int main ( ) { computeTotient ( ) ; long long x = 3 , k = 2 , m = 3 ; cout << calculate ( x , k , m ) << endl ; return 0 ; }
Number of ones in the smallest repunit | CPP program to print the number of 1 s in smallest repunit multiple of the number . ; Function to find number of 1 s in smallest repunit multiple of the number ; to store number of 1 s in smallest repunit multiple of the number . ; initialize rem with 1 ; run loop until rem becomes zero ; rem * 10 + 1 here represents the repunit modulo n ; when remainder becomes 0 return count ; Driver Code ; Calling function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countOnes ( int n ) { int count = 1 ; int rem = 1 ; while ( rem != 0 ) { rem = ( rem * 10 + 1 ) % n ; count ++ ; } return count ; } int main ( ) { int n = 13 ; cout << countOnes ( n ) ; }
Largest of two distinct numbers without using any conditional statements or operators | C ++ program for above implementation ; Function to find the largest number ; Drivers code
#include <iostream> NEW_LINE using namespace std ; int largestNum ( int a , int b ) { return a * ( bool ) ( a / b ) + b * ( bool ) ( b / a ) ; } int main ( ) { int a = 22 , b = 1231 ; cout << largestNum ( a , b ) ; return 0 ; }
Number of Distinct Meeting Points on a Circular Road | CPP Program to find number of distinct point of meet on a circular road ; Returns the GCD of two number . ; Returns the number of distinct meeting points . ; Find the relative speed . ; convert the negative value to positive . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int a , int b ) { int c = a % b ; while ( c != 0 ) { a = b ; b = c ; c = a % b ; } return b ; } int numberOfmeet ( int a , int b ) { int ans ; if ( a > b ) ans = a - b ; else ans = b - a ; if ( a < 0 ) a = a * ( -1 ) ; if ( b < 0 ) b = b * ( -1 ) ; return ans / gcd ( a , b ) ; } int main ( ) { int a = 1 , b = -1 ; cout << numberOfmeet ( a , b ) << endl ; return 0 ; }
Minimum number of Square Free Divisors | CPP Program to find the minimum number of square free divisors ; Initializing MAX with SQRT ( 10 ^ 6 ) ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Print all prime numbers ; This function returns the minimum number of Square Free divisors ; Precomputing Prime Factors ; holds max of max power of all prime factors ; holds the max power of current prime factor ; If number itself is prime , it will be included as answer and thus minimum required answer is 1 ; Driver Code to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1005 NEW_LINE void SieveOfEratosthenes ( vector < int > & primes ) { bool prime [ MAX ] ; memset ( prime , true , sizeof ( prime ) ) ; for ( int p = 2 ; p * p < MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i < MAX ; i += p ) prime [ i ] = false ; } } for ( int p = 2 ; p < MAX ; p ++ ) if ( prime [ p ] ) primes . push_back ( p ) ; } int minimumSquareFreeDivisors ( int N ) { vector < int > primes ; SieveOfEratosthenes ( primes ) ; int max_count = 0 ; for ( int i = 0 ; i < primes . size ( ) && primes [ i ] * primes [ i ] <= N ; i ++ ) { if ( N % primes [ i ] == 0 ) { int tmp = 0 ; while ( N % primes [ i ] == 0 ) { tmp ++ ; N /= primes [ i ] ; } max_count = max ( max_count , tmp ) ; } } if ( max_count == 0 ) max_count = 1 ; return max_count ; } int main ( ) { int N = 24 ; cout << " Minimum ▁ Number ▁ of ▁ Square ▁ Free ▁ Divisors ▁ is ▁ " << minimumSquareFreeDivisors ( N ) << endl ; N = 6 ; cout << " Minimum ▁ Number ▁ of ▁ Square ▁ Free ▁ Divisors ▁ is ▁ " << minimumSquareFreeDivisors ( N ) << endl ; return 0 ; }
Subsequence of size k with maximum possible GCD | CPP program to find subsequence of size k with maximum possible GCD . ; function to find GCD of sub sequence of size k with max GCD in the array ; Computing highest element ; Array to store the count of divisors i . e . Potential GCDs ; Iterating over every element ; Calculating all the divisors ; Divisor found ; Incrementing count for divisor ; Element / divisor is also a divisor Checking if both divisors are not same ; Checking the highest potential GCD ; If this divisor can divide at least k numbers , it is a GCD of at least one sub sequence of size k ; Driver code ; Array in which sub sequence with size k with max GCD is to be found
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaxGCD ( int arr [ ] , int n , int k ) { int high = * max_element ( arr , arr + n ) ; int divisors [ high + 1 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 1 ; j <= sqrt ( arr [ i ] ) ; j ++ ) { if ( arr [ i ] % j == 0 ) { divisors [ j ] ++ ; if ( j != arr [ i ] / j ) divisors [ arr [ i ] / j ] ++ ; } } } for ( int i = high ; i >= 1 ; i -- ) if ( divisors [ i ] >= k ) return i ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 8 , 8 , 12 } ; int k = 3 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findMaxGCD ( arr , n , k ) ; return 0 ; }
System of Linear Equations in three variables using Cramer 's Rule | CPP program to calculate solutions of linear equations using cramer 's rule ; This functions finds the determinant of Matrix ; This function finds the solution of system of linear equations using cramer 's rule ; Matrix d using coeff as given in cramer 's rule ; Matrix d1 using coeff as given in cramer 's rule ; Matrix d2 using coeff as given in cramer 's rule ; Matrix d3 using coeff as given in cramer 's rule ; Calculating Determinant of Matrices d , d1 , d2 , d3 ; Case 1 ; Coeff have a unique solution . Apply Cramer 's Rule ; double z = D3 / D ; calculating z using cramer 's rule ; Case 2 ; Driver Code ; storing coefficients of linear equations in coeff matrix
#include <bits/stdc++.h> NEW_LINE using namespace std ; double determinantOfMatrix ( double mat [ 3 ] [ 3 ] ) { double ans ; ans = mat [ 0 ] [ 0 ] * ( mat [ 1 ] [ 1 ] * mat [ 2 ] [ 2 ] - mat [ 2 ] [ 1 ] * mat [ 1 ] [ 2 ] ) - mat [ 0 ] [ 1 ] * ( mat [ 1 ] [ 0 ] * mat [ 2 ] [ 2 ] - mat [ 1 ] [ 2 ] * mat [ 2 ] [ 0 ] ) + mat [ 0 ] [ 2 ] * ( mat [ 1 ] [ 0 ] * mat [ 2 ] [ 1 ] - mat [ 1 ] [ 1 ] * mat [ 2 ] [ 0 ] ) ; return ans ; } void findSolution ( double coeff [ 3 ] [ 4 ] ) { double d [ 3 ] [ 3 ] = { { coeff [ 0 ] [ 0 ] , coeff [ 0 ] [ 1 ] , coeff [ 0 ] [ 2 ] } , { coeff [ 1 ] [ 0 ] , coeff [ 1 ] [ 1 ] , coeff [ 1 ] [ 2 ] } , { coeff [ 2 ] [ 0 ] , coeff [ 2 ] [ 1 ] , coeff [ 2 ] [ 2 ] } , } ; double d1 [ 3 ] [ 3 ] = { { coeff [ 0 ] [ 3 ] , coeff [ 0 ] [ 1 ] , coeff [ 0 ] [ 2 ] } , { coeff [ 1 ] [ 3 ] , coeff [ 1 ] [ 1 ] , coeff [ 1 ] [ 2 ] } , { coeff [ 2 ] [ 3 ] , coeff [ 2 ] [ 1 ] , coeff [ 2 ] [ 2 ] } , } ; double d2 [ 3 ] [ 3 ] = { { coeff [ 0 ] [ 0 ] , coeff [ 0 ] [ 3 ] , coeff [ 0 ] [ 2 ] } , { coeff [ 1 ] [ 0 ] , coeff [ 1 ] [ 3 ] , coeff [ 1 ] [ 2 ] } , { coeff [ 2 ] [ 0 ] , coeff [ 2 ] [ 3 ] , coeff [ 2 ] [ 2 ] } , } ; double d3 [ 3 ] [ 3 ] = { { coeff [ 0 ] [ 0 ] , coeff [ 0 ] [ 1 ] , coeff [ 0 ] [ 3 ] } , { coeff [ 1 ] [ 0 ] , coeff [ 1 ] [ 1 ] , coeff [ 1 ] [ 3 ] } , { coeff [ 2 ] [ 0 ] , coeff [ 2 ] [ 1 ] , coeff [ 2 ] [ 3 ] } , } ; double D = determinantOfMatrix ( d ) ; double D1 = determinantOfMatrix ( d1 ) ; double D2 = determinantOfMatrix ( d2 ) ; double D3 = determinantOfMatrix ( d3 ) ; printf ( " D ▁ is ▁ : ▁ % lf ▁ STRNEWLINE " , D ) ; printf ( " D1 ▁ is ▁ : ▁ % lf ▁ STRNEWLINE " , D1 ) ; printf ( " D2 ▁ is ▁ : ▁ % lf ▁ STRNEWLINE " , D2 ) ; printf ( " D3 ▁ is ▁ : ▁ % lf ▁ STRNEWLINE " , D3 ) ; if ( D != 0 ) { double x = D1 / D ; double y = D2 / D ; printf ( " Value ▁ of ▁ x ▁ is ▁ : ▁ % lf STRNEWLINE " , x ) ; printf ( " Value ▁ of ▁ y ▁ is ▁ : ▁ % lf STRNEWLINE " , y ) ; printf ( " Value ▁ of ▁ z ▁ is ▁ : ▁ % lf STRNEWLINE " , z ) ; } else { if ( D1 == 0 && D2 == 0 && D3 == 0 ) printf ( " Infinite ▁ solutions STRNEWLINE " ) ; else if ( D1 != 0 D2 != 0 D3 != 0 ) printf ( " No ▁ solutions STRNEWLINE " ) ; } } int main ( ) { double coeff [ 3 ] [ 4 ] = { { 2 , -1 , 3 , 9 } , { 1 , 1 , 1 , 6 } , { 1 , -1 , 1 , 2 } , } ; findSolution ( coeff ) ; return 0 ; }
Find larger of x ^ y and y ^ x | C ++ program to print greater of x ^ y and y ^ x ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printGreater ( double x , double y ) { long double X = y * log ( x ) ; long double Y = x * log ( y ) ; if ( abs ( X - Y ) < 1e-9 ) { cout << " Equal " ; } else if ( X > Y ) { cout << x << " ^ " << y ; } else { cout << y << " ^ " << x ; } } int main ( ) { double x = 5 , y = 8 ; printGreater ( x , y ) ; return 0 ; }
n | CPP program to find the n - th term in series ; Function to find nth term ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfSeries ( int n ) { return n * ( n + 1 ) * ( 6 * n * n * n + 9 * n * n + n - 1 ) / 30 ; } int main ( ) { int n = 4 ; cout << sumOfSeries ( n ) ; return 0 ; }
Product of first N factorials | CPP Program to find the product of first N factorials ; To compute ( a * b ) % MOD ; long long int res = 0 ; Initialize result ; If b is odd , add ' a ' to result ; Multiply ' a ' with 2 ; Divide b by 2 ; Return result ; This function computes factorials and product by using above function i . e . modular multiplication ; Initialize product and fact with 1 ; ith factorial ; product of first i factorials ; If at any iteration , product becomes divisible by MOD , simply return 0 ; ; Driver Code to Test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long int mulmod ( long long int a , long long int b , long long int mod ) { a = a % mod ; while ( b > 0 ) { if ( b % 2 == 1 ) res = ( res + a ) % mod ; a = ( a * 2 ) % mod ; b /= 2 ; } return res % mod ; } long long int findProduct ( long long int N ) { long long int product = 1 , fact = 1 ; long long int MOD = 1e9 + 7 ; for ( int i = 1 ; i <= N ; i ++ ) { fact = mulmod ( fact , i , MOD ) ; product = mulmod ( product , fact , MOD ) ; if ( product == 0 ) return 0 ; } return product ; } int main ( ) { long long int N = 3 ; cout << findProduct ( N ) << endl ; N = 5 ; cout << findProduct ( N ) << endl ; return 0 ; }
Check if sum of divisors of two numbers are same | C ++ program to find if two numbers are equivalent or not ; Function to calculate sum of all proper divisors num -- > given natural number ; To store sum of divisors ; Find all divisors and add them ; Function to check if both numbers are equivalent or not ; Drivers code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int divSum ( int n ) { long long int sum = 1 ; for ( long long int i = 2 ; i * i <= n ; i ++ ) if ( n % i == 0 ) sum = sum + i + n / i ; return sum ; } bool areEquivalent ( int num1 , int num2 ) { return divSum ( num1 ) == divSum ( num2 ) ; } int main ( ) { int num1 = 559 , num2 = 703 ; areEquivalent ( num1 , num2 ) ? cout << " Equivalent " : cout << " Not ▁ Equivalent " ; return 0 ; }
Dodecahedral number | C ++ program to find nth dodecahedral number ; Function to find dodecahedral number ; Formula to calculate nth dodecahedral number and return it into main function . ; Driver Code ; print result
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dodecahedral_num ( int n ) { return n * ( 3 * n - 1 ) * ( 3 * n - 2 ) / 2 ; } int main ( ) { int n = 5 ; cout << n << " th ▁ Dodecahedral ▁ number : ▁ " ; cout << dodecahedral_num ( n ) ; return 0 ; }
Count of divisors having more set bits than quotient on dividing N | C ++ Program to find number of Divisors which on integer division produce quotient having less set bit than divisor ; Return the count of set bit . ; check if q and d have same number of set bit . ; Binary Search to find the point at which number of set in q is less than or equal to d . ; while left index is less than right index ; finding the middle . ; check if q and d have same number of set it or not . ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int bit ( int x ) { int ans = 0 ; while ( x ) { x /= 2 ; ans ++ ; } return ans ; } bool check ( int d , int x ) { if ( bit ( x / d ) <= bit ( d ) ) return true ; return false ; } int bs ( int n ) { int l = 1 , r = sqrt ( n ) ; while ( l < r ) { int m = ( l + r ) / 2 ; if ( check ( m , n ) ) r = m ; else l = m + 1 ; } if ( ! check ( l , n ) ) return l + 1 ; else return l ; } int countDivisor ( int n ) { return n - bs ( n ) + 1 ; } int main ( ) { int n = 5 ; cout << countDivisor ( n ) << endl ; return 0 ; }
Check if two people starting from different points ever meet | C ++ program to find if two people starting from different positions ever meet or not . ; If speed of a person at a position before other person is smaller , then return false . ; Making sure that x1 is greater ; Until one person crosses other ; first person taking one jump in each iteration ; second person taking one jump in each iteration ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool everMeet ( int x1 , int x2 , int v1 , int v2 ) { if ( x1 < x2 && v1 <= v2 ) return false ; if ( x1 > x2 && v1 >= v2 ) return false ; if ( x1 < x2 ) { swap ( x1 , x2 ) ; swap ( v1 , v2 ) ; } while ( x1 >= x2 ) { if ( x1 == x2 ) return true ; x1 = x1 + v1 ; x2 = x2 + v2 ; } return false ; } int main ( ) { int x1 = 5 , v1 = 8 , x2 = 4 , v2 = 7 ; if ( everMeet ( x1 , x2 , v1 , v2 ) ) printf ( " Yes " ) ; else printf ( " No " ) ; return 0 ; }
Divisibility by 3 where each digit is the sum of all prefix digits modulo 10 | CPP code to check divisibility by 3 ; Function to check the divisibility ; Cycle ; no of residual terms ; sum of residual terms ; if no of residue term = 0 ; if no of residue term = 1 ; if no of residue term = 2 ; if no of residue term = 3 ; sum of all digits ; divisibility check ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string check ( long int k , int d0 , int d1 ) { long int s = ( 2 * ( d0 + d1 ) ) % 10 + ( 4 * ( d0 + d1 ) ) % 10 + ( 8 * ( d0 + d1 ) ) % 10 + ( 6 * ( d0 + d1 ) ) % 10 ; int a = ( k - 3 ) % 4 ; int x ; switch ( a ) { case 0 : x = 0 ; break ; case 1 : x = ( 2 * ( d0 + d1 ) ) % 10 ; break ; case 2 : x = ( 2 * ( d0 + d1 ) ) % 10 + ( 4 * ( d0 + d1 ) ) % 10 ; break ; case 3 : x = ( 2 * ( d0 + d1 ) ) % 10 + ( 4 * ( d0 + d1 ) ) % 10 + ( 8 * ( d0 + d1 ) ) % 10 ; break ; } long int sum = d0 + d1 + ( ( k - 3 ) / 4 ) * s + x ; if ( sum % 3 == 0 ) return " YES " ; return " NO " ; } int main ( ) { long int k , d0 , d1 ; k = 13 ; d0 = 8 ; d1 = 1 ; cout << check ( k , d0 , d1 ) << endl ; k = 5 ; d0 = 3 ; d1 = 4 ; cout << check ( k , d0 , d1 ) << endl ; return 0 ; }
Find ceil of a / b without using ceil ( ) function | C ++ program to find ceil ( a / b ) without using ceil ( ) function ; Driver function ; taking input 1 ; example of perfect division taking input 2
#include <cmath> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int main ( ) { int a = 4 ; int b = 3 ; int val = ( a / b ) + ( ( a % b ) != 0 ) ; cout << " The ▁ ceiling ▁ value ▁ of ▁ 4/3 ▁ is ▁ " << val << endl ; a = 6 ; b = 3 ; val = ( a / b ) + ( ( a % b ) != 0 ) ; cout << " The ▁ ceiling ▁ value ▁ of ▁ 6/3 ▁ is ▁ " << val << endl ; return 0 ; }
Program to print Collatz Sequence | CPP program to print Collatz sequence ; We simply follow steps while we do not reach 1 ; If n is odd ; If even ; Print 1 at the end ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printCollatz ( int n ) { while ( n != 1 ) { cout << n << " ▁ " ; if ( n & 1 ) n = 3 * n + 1 ; else n = n / 2 ; } cout << n ; } int main ( ) { printCollatz ( 6 ) ; return 0 ; }
Powers of 2 to required sum | CPP program to find the blocks for given number . ; Converting the decimal number into its binary equivalent . ; Displaying the output when the bit is '1' in binary equivalent of number . ; Driver Function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void block ( long int x ) { vector < long int > v ; cout << " Blocks ▁ for ▁ " << x << " ▁ : ▁ " ; while ( x > 0 ) { v . push_back ( x % 2 ) ; x = x / 2 ; } for ( int i = 0 ; i < v . size ( ) ; i ++ ) { if ( v [ i ] == 1 ) { cout << i ; if ( i != v . size ( ) - 1 ) cout << " , ▁ " ; } } cout << endl ; } int main ( ) { block ( 71307 ) ; block ( 1213 ) ; block ( 29 ) ; block ( 100 ) ; return 0 ; }
Given a number N in decimal base , find number of its digits in any base ( base b ) | C ++ program to Find Number of digits in base b . ; function to print number of digits ; Calculating log using base changing property and then taking it floor and then adding 1. ; printing output ; Driver method ; taking inputs ; calling the method
#include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; void findNumberOfDigits ( long n , int base ) { int dig = ( int ) ( floor ( log ( n ) / log ( base ) ) + 1 ) ; cout << " The ▁ Number ▁ of ▁ digits ▁ of ▁ " << " Number ▁ " << n << " ▁ in ▁ base ▁ " << base << " ▁ is ▁ " << dig ; } int main ( ) { long n = 1446 ; int base = 7 ; findNumberOfDigits ( n , base ) ; return 0 ; }