text stringlengths 17 4.49k | code stringlengths 49 5.46k |
|---|---|
Count the number of possible triangles | C ++ code to count the number of possible triangles using brute force approach ; Function to count all possible triangles with arr [ ] elements ; Count of triangles ; The three loops select three different values from array ; The innermost loop checks for the triangle property ;... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findNumberOfTriangles ( int arr [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { for ( int k = j + 1 ; k < n ; k ++ ) if ( arr [ i ] + arr [ j ] > arr [ k ] && arr [ i ] + arr [ k ] > arr [ j ] && arr [ ... |
Count the number of possible triangles | C ++ program to count number of triangles that can be formed from given array ; Following function is needed for library function qsort ( ) . Refer www . cplusplus . com / reference / clibrary / cstdlib / qsort / ; Function to count all possible triangles with arr [ ] elements ;... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int comp ( const void * a , const void * b ) { return * ( int * ) a > * ( int * ) b ; } int findNumberOfTriangles ( int arr [ ] , int n ) { qsort ( arr , n , sizeof ( arr [ 0 ] ) , comp ) ; int count = 0 ; for ( int i = 0 ; i < n - 2 ; ++ i ) { int k = i + 2 ; for... |
Count the number of possible triangles | C ++ implementation of the above approach ; CountTriangles function ; If it is possible with a [ l ] , a [ r ] and a [ i ] then it is also possible with a [ l + 1 ] . . a [ r - 1 ] , a [ r ] and a [ i ] ; checking for more possible solutions ; if not possible check for higher va... | #include <bits/stdc++.h> NEW_LINE using namespace std ; void CountTriangles ( vector < int > A ) { int n = A . size ( ) ; sort ( A . begin ( ) , A . end ( ) ) ; int count = 0 ; for ( int i = n - 1 ; i >= 1 ; i -- ) { int l = 0 , r = i - 1 ; while ( l < r ) { if ( A [ l ] + A [ r ] > A [ i ] ) { count += r - l ; r -- ; ... |
Maximum sum of nodes in Binary tree such that no two are adjacent | C ++ program to find maximum sum from a subset of nodes of binary tree ; A binary tree node structure ; Utility function to create a new Binary Tree node ; Declaration of methods ; method returns maximum sum possible from subtrees rooted at grandChildr... | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int data ; struct node * left , * right ; } ; struct node * newNode ( int data ) { struct node * temp = new struct node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } int sumOfGrandChildren ( node * node ) ; int getMaxS... |
Flip minimum signs of array elements to get minimum sum of positive elements possible | C ++ implementation of the approach ; Function to return the minimum number of elements whose sign must be flipped to get the positive sum of array elements as close to 0 as possible ; boolean variable used for toggling between maps... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( int A [ ] , int n ) { unordered_map < int , int > dp [ 2 ] ; bool flag = 1 ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += A [ i ] ; for ( int i = - sum ; i <= sum ; i ++ ) dp [ 0 ] [ i ] = INT_MAX ; dp [ 0 ] [ 0 ] = 0 ; for ( int i = 1 ; i <= ... |
Find number of pairs ( x , y ) in an array such that x ^ y > y ^ x | | #include <bits/stdc++.h> NEW_LINE long long countPairsBruteForce ( long long X [ ] , long long Y [ ] , long long m , long long n ) { long long ans = 0 ; for ( int i = 0 ; i < m ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) if ( pow ( X [ i ] , Y [ j ] ) > pow ( Y [ j ] , X [ i ] ) ) ans ++ ; return ans ; } |
Iterative approach to print all permutations of an Array | C ++ implementation of the approach ; The input array for permutation ; Length of the input array ; Index array to store indexes of input array ; The index of the first " increase " in the Index array which is the smallest i such that Indexes [ i ] < Indexes [ ... | #include <iostream> NEW_LINE using namespace std ; template < typename T > class AllPermutation { private : const T * Arr ; const int Length ; int * Indexes ; int Increase ; public : AllPermutation ( T * arr , int length ) : Arr ( arr ) , Length ( length ) { this -> Indexes = nullptr ; this -> Increase = -1 ; } ~ AllPe... |
Maximum items that can be filled in K Knapsacks of given Capacity | ; 2 - d array to store states of DP ; 2 - d array to store if a state has been solved ; Vector to store power of variable ' C ' . ; function to compute the states ; Base case ; Checking if a state has been solved ; Setting a state as solved ; Recurren... | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < vector < int > > dp ; vector < vector < bool > > v ; vector < int > exp_c ; int FindMax ( int i , int r , int w [ ] , int n , int c , int k ) { if ( i >= n ) return 0 ; if ( v [ i ] [ r ] ) return dp [ i ] [ r ] ; v [ i ] [ r ] = 1 ; dp [ i ] [ r ] = Find... |
Find number of pairs ( x , y ) in an array such that x ^ y > y ^ x | C ++ program to finds the number of pairs ( x , y ) in an array such that x ^ y > y ^ x ; Function to return count of pairs with x as one element of the pair . It mainly looks for all values in Y [ ] where x ^ Y [ i ] > Y [ i ] ^ x ; If x is 0 , then ... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int count ( int x , int Y [ ] , int n , int NoOfY [ ] ) { if ( x == 0 ) return 0 ; if ( x == 1 ) return NoOfY [ 0 ] ; int * idx = upper_bound ( Y , Y + n , x ) ; int ans = ( Y + n ) - idx ; ans += ( NoOfY [ 0 ] + NoOfY [ 1 ] ) ; if ( x == 2 ) ans -= ( NoOfY [ 3 ] ... |
Count all distinct pairs with difference equal to k | A simple program to count pairs with difference k ; Pick all elements one by one ; See if there is a pair of this picked element ; Driver program to test above function | #include <iostream> NEW_LINE using namespace std ; int countPairsWithDiffK ( int arr [ ] , int n , int k ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) if ( arr [ i ] - arr [ j ] == k arr [ j ] - arr [ i ] == k ) count ++ ; } return count ; } int main ( ) { int arr [ ] = { 1... |
Count all distinct pairs with difference equal to k | A sorting based program to count pairs with difference k ; Standard binary search function ; Returns count of pairs with difference k in arr [ ] of size n . ; Sort array elements ; Pick a first element point ; Driver program | #include <iostream> NEW_LINE #include <algorithm> NEW_LINE using namespace std ; int binarySearch ( int arr [ ] , int low , int high , int x ) { if ( high >= low ) { int mid = low + ( high - low ) / 2 ; if ( x == arr [ mid ] ) return mid ; if ( x > arr [ mid ] ) return binarySearch ( arr , ( mid + 1 ) , high , x ) ; el... |
Count all distinct pairs with difference equal to k | An efficient program to count pairs with difference k when the range numbers is small ; Initialize count ; Initialize empty hashmap . ; Insert array elements to hashmap | #define MAX 100000 NEW_LINE int countPairsWithDiffK ( int arr [ ] , int n , int k ) { int count = 0 ; bool hashmap [ MAX ] = { false } ; for ( int i = 0 ; i < n ; i ++ ) hashmap [ arr [ i ] ] = true ; for ( int i = 0 ; i < n ; i ++ ) { int x = arr [ i ] ; if ( x - k >= 0 && hashmap [ x - k ] ) count ++ ; if ( x + k < ... |
Count all distinct pairs with difference equal to k | A sorting based program to count pairs with difference k ; Returns count of pairs with difference k in arr [ ] of size n . ; Sort array elements ; arr [ r ] - arr [ l ] < sum ; Driver program to test above function | #include <iostream> NEW_LINE #include <algorithm> NEW_LINE using namespace std ; int countPairsWithDiffK ( int arr [ ] , int n , int k ) { int count = 0 ; sort ( arr , arr + n ) ; int l = 0 ; int r = 0 ; while ( r < n ) { if ( arr [ r ] - arr [ l ] == k ) { count ++ ; l ++ ; r ++ ; } else if ( arr [ r ] - arr [ l ] > k... |
Sum of Bitwise | C ++ program to find sum of Bitwise - OR of all submatrices ; Function to find prefix - count for each row from right to left ; Function to create a boolean matrix set_bit which stores a 1 aTM at an index ( R , C ) if ith bit of arr [ R ] [ C ] is set . ; array to store prefix count of zeros from right... | #include <iostream> NEW_LINE #include <stack> NEW_LINE using namespace std ; #define n 3 NEW_LINE void findPrefixCount ( int p_arr [ ] [ n ] , bool set_bit [ ] [ n ] ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = n - 1 ; j >= 0 ; j -- ) { if ( set_bit [ i ] [ j ] ) continue ; if ( j != n - 1 ) p_arr [ i ] [ j ] ... |
Count of sub | C ++ implementation of the approach ; Function to return the total number of required sub - sets ; Variable to store total elements which on dividing by 3 give remainder 0 , 1 and 2 respectively ; Create a dp table ; Process for n states and store the sum ( mod 3 ) for 0 , 1 and 2 ; Use of MOD for large ... | #include <bits/stdc++.h> NEW_LINE #define MOD 1000000007 NEW_LINE #define ll long long int NEW_LINE using namespace std ; int totalSubSets ( ll n , ll l , ll r ) { ll zero = floor ( ( double ) r / 3 ) - ceil ( ( double ) l / 3 ) + 1 ; ll one = floor ( ( double ) ( r - 1 ) / 3 ) - ceil ( ( double ) ( l - 1 ) / 3 ) + 1... |
Maximum sum of nodes in Binary tree such that no two are adjacent | C ++ program to find maximum sum in Binary Tree such that no two nodes are adjacent . ; A binary tree node structure ; maxSumHelper function ; This node is included ( Left and right children are not included ) ; This node is excluded ( Either left or r... | #include <iostream> NEW_LINE using namespace std ; class Node { public : int data ; Node * left , * right ; Node ( int data ) { this -> data = data ; left = NULL ; right = NULL ; } } ; pair < int , int > maxSumHelper ( Node * root ) { if ( root == NULL ) { pair < int , int > sum ( 0 , 0 ) ; return sum ; } pair < int , ... |
Check if a word exists in a grid or not | C ++ program to check if the word exists in the grid or not ; Function to check if a word exists in a grid starting from the first match in the grid level : index till which pattern is matched x , y : current position in 2D array ; Pattern matched ; Out of Boundary ; If grid ma... | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define r 4 NEW_LINE #define c 5 NEW_LINE bool findmatch ( char mat [ r ] , string pat , int x , int y , int nrow , int ncol , int level ) { int l = pat . length ( ) ; if ( level == l ) return true ; if ( x < 0 y < 0 x > = nrow y > = ncol ) return false ; if ( m... |
Construct an array from its pair | ; Fills element in arr [ ] from its pair sum array pair [ ] . n is size of arr [ ] ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void constructArr ( int arr [ ] , int pair [ ] , int n ) { arr [ 0 ] = ( pair [ 0 ] + pair [ 1 ] - pair [ n - 1 ] ) / 2 ; for ( int i = 1 ; i < n ; i ++ ) arr [ i ] = pair [ i - 1 ] - arr [ 0 ] ; } int main ( ) { int pair [ ] = { 15 , 13 , 11 , 10 , 12 , 10 , 9 , ... |
Merge two sorted arrays with O ( 1 ) extra space | C ++ program to merge two sorted arrays with O ( 1 ) extra space . ; Merge ar1 [ ] and ar2 [ ] with O ( 1 ) extra space ; Iterate through all elements of ar2 [ ] starting from the last element ; Find the smallest element greater than ar2 [ i ] . Move all elements one p... | #include <bits/stdc++.h> NEW_LINE using namespace std ; void merge ( int ar1 [ ] , int ar2 [ ] , int m , int n ) { for ( int i = n - 1 ; i >= 0 ; i -- ) { int j , last = ar1 [ m - 1 ] ; for ( j = m - 2 ; j >= 0 && ar1 [ j ] > ar2 [ i ] ; j -- ) ar1 [ j + 1 ] = ar1 [ j ] ; if ( j != m - 2 last > ar2 [ i ] ) { ar1 [ j + ... |
Merge two sorted arrays with O ( 1 ) extra space | CPP program for the above approach ; Function to merge two arrays ; Untill i less than equal to k or j is less tha m ; Sort first array ; Sort second array ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void merge ( int arr1 [ ] , int arr2 [ ] , int n , int m ) { int i = 0 , j = 0 , k = n - 1 ; while ( i <= k and j < m ) { if ( arr1 [ i ] < arr2 [ j ] ) i ++ ; else { swap ( arr2 [ j ++ ] , arr1 [ k -- ] ) ; } } sort ( arr1 , arr1 + n ) ; sort ( arr2 , arr2 + m ) ... |
Gould 's Sequence | CPP program to generate Gould 's Sequence ; Function to generate gould 's Sequence ; loop to generate each row of pascal 's Triangle up to nth row ; Loop to generate each element of ith row ; if c is odd increment count ; print count of odd elements ; Driver code ; Get n ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void gouldSequence ( int n ) { for ( int row_num = 1 ; row_num <= n ; row_num ++ ) { int count = 1 ; int c = 1 ; for ( int i = 1 ; i <= row_num ; i ++ ) { c = c * ( row_num - i ) / i ; if ( c % 2 == 1 ) count ++ ; } cout << count << " β " ; } } int main ( ) { int ... |
Product of maximum in first array and minimum in second | C ++ program to calculate the product of max element of first array and min element of second array ; Function to calculate the product ; Sort the arrays to find the maximum and minimum elements in given arrays ; Return product of maximum and minimum . ; Driven ... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minMaxProduct ( int arr1 [ ] , int arr2 [ ] , int n1 , int n2 ) { sort ( arr1 , arr1 + n1 ) ; sort ( arr2 , arr2 + n2 ) ; return arr1 [ n1 - 1 ] * arr2 [ 0 ] ; } int main ( ) { int arr1 [ ] = { 10 , 2 , 3 , 6 , 4 , 1 } ; int arr2 [ ] = { 5 , 1 , 4 , 2 , 6 , 9 ... |
Minimum odd cost path in a matrix | C ++ program to find Minimum odd cost path in a matrix ; Function to find the minimum cost ; leftmost element ; rightmost element ; Any element except leftmost and rightmost element of a row is reachable from direct upper or left upper or right upper row 's block ; Counting the minim... | #include <bits/stdc++.h> NEW_LINE #define M 100 NEW_LINE #define N 100 NEW_LINE using namespace std ; int find_min_odd_cost ( int given [ M ] [ N ] , int m , int n ) { int floor [ M ] [ N ] = { { 0 } , { 0 } } ; int min_odd_cost = 0 ; int i , j , temp ; for ( j = 0 ; j < n ; j ++ ) floor [ 0 ] [ j ] = given [ 0 ] [... |
Product of maximum in first array and minimum in second | C ++ program to find the to calculate the product of max element of first array and min element of second array ; Function to calculate the product ; Initialize max of first array ; initialize min of second array ; To find the maximum element in first array ; To... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minMaxProduct ( int arr1 [ ] , int arr2 [ ] , int n1 , int n2 ) { int max = arr1 [ 0 ] ; int min = arr2 [ 0 ] ; int i ; for ( i = 1 ; i < n1 && i < n2 ; ++ i ) { if ( arr1 [ i ] > max ) max = arr1 [ i ] ; if ( arr2 [ i ] < min ) min = arr2 [ i ] ; } while ( i ... |
Burst Balloon to maximize coins | C ++ program burst balloon problem ; Add Bordering Balloons ; Declare DP Array ; For a sub - array from indices left , right This innermost loop finds the last balloon burst ; Driver code ; Size of the array ; Calling function | #include <bits/stdc++.h> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int getMax ( int A [ ] , int N ) { int B [ N + 2 ] ; B [ 0 ] = 1 ; B [ N + 1 ] = 1 ; for ( int i = 1 ; i <= N ; i ++ ) B [ i ] = A [ i - 1 ] ; int dp [ N + 2 ] [ N + 2 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; for ( int length = 1 ; leng... |
Search , insert and delete in an unsorted array | C ++ program to implement linear search in unsorted array ; Function to implement search operation ; Driver Code ; Using a last element as search element | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findElement ( int arr [ ] , int n , int key ) { int i ; for ( i = 0 ; i < n ; i ++ ) if ( arr [ i ] == key ) return i ; return -1 ; } int main ( ) { int arr [ ] = { 12 , 34 , 10 , 6 , 40 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int key = 40 ; int po... |
Search , insert and delete in an unsorted array | C ++ program to implement insert operation in an unsorted array . ; Inserts a key in arr [ ] of given capacity . n is current size of arr [ ] . This function returns n + 1 if insertion is successful , else n . ; Cannot insert more elements if n is already more than or e... | #include <iostream> NEW_LINE using namespace std ; int insertSorted ( int arr [ ] , int n , int key , int capacity ) { if ( n >= capacity ) return n ; arr [ n ] = key ; return ( n + 1 ) ; } int main ( ) { int arr [ 20 ] = { 12 , 16 , 20 , 40 , 50 , 70 } ; int capacity = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int n = 6... |
Search , insert and delete in an unsorted array | C ++ program to implement delete operation in a unsorted array ; Function to implement search operation ; Function to delete an element ; Find position of element to be deleted ; Deleting element ; Driver code | #include <iostream> NEW_LINE using namespace std ; int findElement ( int arr [ ] , int n , int key ) { int i ; for ( i = 0 ; i < n ; i ++ ) if ( arr [ i ] == key ) return i ; return - 1 ; } int deleteElement ( int arr [ ] , int n , int key ) { int pos = findElement ( arr , n , key ) ; if ( pos == - 1 ) { cout << " Elem... |
Search , insert and delete in a sorted array | C ++ program to implement binary search in sorted array ; function to implement binary search ; low + ( high - low ) / 2 ; ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int binarySearch ( int arr [ ] , int low , int high , int key ) { if ( high < low ) return -1 ; int mid = ( low + high ) / 2 ; if ( key == arr [ mid ] ) return mid ; if ( key > arr [ mid ] ) return binarySearch ( arr , ( mid + 1 ) , high , key ) ; return binarySea... |
Search , insert and delete in a sorted array | C ++ program to implement insert operation in an sorted array . ; Inserts a key in arr [ ] of given capacity . n is current size of arr [ ] . This function returns n + 1 if insertion is successful , else n . ; Cannot insert more elements if n is already more than or equal ... | #include <iostream> NEW_LINE using namespace std ; int insertSorted ( int arr [ ] , int n , int key , int capacity ) { if ( n >= capacity ) return n ; int i ; for ( i = n - 1 ; ( i >= 0 && arr [ i ] > key ) ; i -- ) arr [ i + 1 ] = arr [ i ] ; arr [ i + 1 ] = key ; return ( n + 1 ) ; } int main ( ) { int arr [ 20 ] = {... |
Search , insert and delete in a sorted array | C ++ program to implement delete operation in a sorted array ; To search a ley to be deleted ; Function to delete an element ; Find position of element to be deleted ; Deleting element ; Driver code | #include <iostream> NEW_LINE using namespace std ; int binarySearch ( int arr [ ] , int low , int high , int key ) ; int binarySearch ( int arr [ ] , int low , int high , int key ) { if ( high < low ) return -1 ; int mid = ( low + high ) / 2 ; if ( key == arr [ mid ] ) return mid ; if ( key > arr [ mid ] ) return binar... |
Queries on number of Binary sub | CPP Program to answer queries on number of submatrix of given size ; Return the minimum of three numbers ; Solve each query on matrix ; For each of the cell . ; finding submatrix size of oth row and column . ; intermediate cells . ; Find frequency of each distinct size for 0 s and 1 s ... | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100 NEW_LINE #define N 5 NEW_LINE #define M 4 NEW_LINE int min ( int a , int b , int c ) { return min ( a , min ( b , c ) ) ; } void solveQuery ( int n , int m , int mat [ N ] [ M ] , int q , int a [ ] , int binary [ ] ) { int dp [ n ] [ m ] , max =... |
Dynamic Programming | Wildcard Pattern Matching | Linear Time and Constant Space | C ++ program to implement wildcard pattern matching algorithm ; Function that matches input text with given wildcard pattern ; empty pattern can only match with empty string . Base Case : ; step - 1 : initialize markers : ; For step - ( ... | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool strmatch ( char txt [ ] , char pat [ ] , int n , int m ) { if ( m == 0 ) return ( n == 0 ) ; int i = 0 , j = 0 , index_txt = -1 , index_pat = -1 ; while ( i < n ) { if ( j < m && txt [ i ] == pat [ j ] ) { i ++ ; j ++ ; } else if ( j < m && pat [ j ] == ' ? '... |
Find n | Program to find the nth element of Stern 's Diatomic Series ; function to find nth stern ' diatomic series ; Initializing the DP array ; SET the Base case ; Traversing the array from 2 nd Element to nth Element ; Case 1 : for even n ; Case 2 : for odd n ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findSDSFunc ( int n ) { int DP [ n + 1 ] ; DP [ 0 ] = 0 ; DP [ 1 ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { if ( i % 2 == 0 ) DP [ i ] = DP [ i / 2 ] ; else DP [ i ] = DP [ ( i - 1 ) / 2 ] + DP [ ( i + 1 ) / 2 ] ; } return DP [ n ] ; } int main ( ) { int n = ... |
Find common elements in three sorted arrays | C ++ program to print common elements in three arrays ; This function prints common elements in ar1 ; Initialize starting indexes for ar1 [ ] , ar2 [ ] and ar3 [ ] ; Iterate through three arrays while all arrays have elements ; If x = y and y = z , print any of them and mov... | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findCommon ( int ar1 [ ] , int ar2 [ ] , int ar3 [ ] , int n1 , int n2 , int n3 ) { int i = 0 , j = 0 , k = 0 ; while ( i < n1 && j < n2 && k < n3 ) { if ( ar1 [ i ] == ar2 [ j ] && ar2 [ j ] == ar3 [ k ] ) { cout << ar1 [ i ] << " β " ; i ++ ; j ++ ; k ++ ; ... |
Dynamic Programming on Trees | Set | C ++ code to find the maximum path sum ; function for dfs traversal and to store the maximum value in dp [ ] for every node till the leaves ; initially dp [ u ] is always a [ u ] ; stores the maximum value from nodes ; traverse the tree ; if child is parent , then we continue withou... | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > dp ; void dfs ( int a [ ] , vector < int > v [ ] , int u , int parent ) { dp [ u ] = a [ u - 1 ] ; int maximum = 0 ; for ( int child : v [ u ] ) { if ( child == parent ) continue ; dfs ( a , v , child , u ) ; maximum = max ( maximum , dp [ child ] )... |
Find common elements in three sorted arrays | C ++ program to print common elements in three arrays ; This function prints common elements in ar1 ; Initialize starting indexes for ar1 [ ] , ar2 [ ] and ar3 [ ] ; Declare three variables prev1 , prev2 , prev3 to track previous element ; Initialize prev1 , prev2 , prev3 w... | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findCommon ( int ar1 [ ] , int ar2 [ ] , int ar3 [ ] , int n1 , int n2 , int n3 ) { int i = 0 , j = 0 , k = 0 ; int prev1 , prev2 , prev3 ; prev1 = prev2 = prev3 = INT_MIN ; while ( i < n1 && j < n2 && k < n3 ) { while ( ar1 [ i ] == prev1 && i < n1 ) i ++ ; ... |
Jacobsthal and Jacobsthal | A DP based solution to find Jacobsthal and Jacobsthal - Lucas numbers ; Return nth Jacobsthal number . ; base case ; Return nth Jacobsthal - Lucas number . ; base case ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Jacobsthal ( int n ) { int dp [ n + 1 ] ; dp [ 0 ] = 0 ; dp [ 1 ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) dp [ i ] = dp [ i - 1 ] + 2 * dp [ i - 2 ] ; return dp [ n ] ; } int Jacobsthal_Lucas ( int n ) { int dp [ n + 1 ] ; dp [ 0 ] = 2 ; dp [ 1 ] = 1 ; for ( i... |
Find position of an element in a sorted array of infinite numbers | C ++ program to demonstrate working of an algorithm that finds an element in an array of infinite size ; Simple binary search algorithm ; function takes an infinite size array and a key to be searched and returns its position if found else - 1. We don ... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int binarySearch ( int arr [ ] , int l , int r , int x ) { if ( r >= l ) { int mid = l + ( r - l ) / 2 ; if ( arr [ mid ] == x ) return mid ; if ( arr [ mid ] > x ) return binarySearch ( arr , l , mid - 1 , x ) ; return binarySearch ( arr , mid + 1 , r , x ) ; } r... |
Count of possible hexagonal walks | C ++ implementation of counting number of possible hexagonal walks ; We initialize our origin with 1 ; For each N = 1 to 14 , we traverse in all possible direction . Using this 3D array we calculate the number of ways at each step and the total ways for a given step shall be found at... | #include <iostream> NEW_LINE using namespace std ; int depth = 16 ; int ways [ 16 ] [ 16 ] [ 16 ] ; int stepNum ; void preprocess ( int list [ ] ) { ways [ 0 ] [ 8 ] [ 8 ] = 1 ; for ( int N = 1 ; N <= 14 ; N ++ ) { for ( int i = 1 ; i <= depth ; i ++ ) { for ( int j = 1 ; j <= depth ; j ++ ) { ways [ N ] [ i ] [ j ] = ... |
Check if possible to cross the matrix with given power | CPP program to find if it is possible to cross the matrix with given power ; Initializing array dp with false value . ; For each value of dp [ i ] [ j ] [ k ] ; For first cell and for each value of k ; For first cell of each row ; For first cell of each column ; ... | #include <bits/stdc++.h> NEW_LINE #define N 105 NEW_LINE #define R 3 NEW_LINE #define C 4 NEW_LINE using namespace std ; int maximumValue ( int n , int m , int p , int grid [ R ] [ C ] ) { bool dp [ N ] [ N ] [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { for ( int k = 0 ; k < N ; k ++... |
Number of n digit stepping numbers | CPP program to calculate the number of n digit stepping numbers . ; function that calculates the answer ; dp [ i ] [ j ] stores count of i digit stepping numbers ending with digit j . ; if n is 1 then answer will be 10. ; Initialize values for count of digits equal to 1. ; Compute v... | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long answer ( int n ) { int dp [ n + 1 ] [ 10 ] ; if ( n == 1 ) return 10 ; for ( int j = 0 ; j <= 9 ; j ++ ) dp [ 1 ] [ j ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { for ( int j = 0 ; j <= 9 ; j ++ ) { if ( j == 0 ) dp [ i ] [ j ] = dp [ i - 1 ] [ j + 1 ] ; ... |
Print Longest Palindromic Subsequence | CPP program to print longest palindromic subsequence ; Returns LCS X and Y ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains length of LCS of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] ; Following code is used to print LCS ; Create a... | #include <bits/stdc++.h> NEW_LINE using namespace std ; string lcs ( string & X , string & Y ) { int m = X . length ( ) ; int n = Y . length ( ) ; int L [ m + 1 ] [ n + 1 ] ; for ( int i = 0 ; i <= m ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) L [ i ] [ j ] = 0 ; else if ( X [ i - 1 ] == Y [ j -... |
Count all subsequences having product less than K | CPP program to find number of subarrays having product less than k . ; Function to count numbers of such subsequences having product less than k . ; number of subsequence using j - 1 terms ; if arr [ j - 1 ] > i it will surely make product greater thus it won 't contr... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int productSubSeqCount ( vector < int > & arr , int k ) { int n = arr . size ( ) ; int dp [ k + 1 ] [ n + 1 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; for ( int i = 1 ; i <= k ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { dp [ i ] [ j ] = dp [ i ] [ j - 1 ] ; if ( a... |
Find the element that appears once in an array where every other element appears twice | C ++ program to find the array element that appears only once ; Return the maximum Sum of difference between consecutive elements . ; Do XOR of all elements and return ; Driver code | #include <iostream> NEW_LINE using namespace std ; int findSingle ( int ar [ ] , int ar_size ) { int res = ar [ 0 ] ; for ( int i = 1 ; i < ar_size ; i ++ ) res = res ^ ar [ i ] ; return res ; } int main ( ) { int ar [ ] = { 2 , 3 , 5 , 4 , 5 , 3 , 4 } ; int n = sizeof ( ar ) / sizeof ( ar [ 0 ] ) ; cout << " Element β... |
Count all triplets whose sum is equal to a perfect cube | C ++ program to calculate all triplets whose sum is perfect cube . ; Function to calculate all occurrence of a number in a given range ; if i == 0 assign 1 to present state ; else add + 1 to current state with previous state ; Function to calculate triplets whos... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 1001 ] [ 15001 ] ; void computeDpArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; ++ i ) { for ( int j = 1 ; j <= 15000 ; ++ j ) { if ( i == 0 ) dp [ i ] [ j ] = ( j == arr [ i ] ) ; else dp [ i ] [ j ] = dp [ i - 1 ] [ j ] + ( arr [ i ] == j ) ;... |
Find the element that appears once in an array where every other element appears twice | C ++ program to find element that appears once ; function which find number ; applying the formula . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int singleNumber ( int nums [ ] , int n ) { map < int , int > m ; long sum1 = 0 , sum2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( m [ nums [ i ] ] == 0 ) { sum1 += nums [ i ] ; m [ nums [ i ] ] ++ ; } sum2 += nums [ i ] ; } return 2 * ( sum1 ) - sum2 ; } int ma... |
Maximum Subarray Sum Excluding Certain Elements | C ++ Program to find max subarray sum excluding some elements ; Function to check the element present in array B ; Utility function for findMaxSubarraySum ( ) with the following parameters A = > Array A , B = > Array B , n = > Number of elements in Array A , m = > Numbe... | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPresent ( int B [ ] , int m , int x ) { for ( int i = 0 ; i < m ; i ++ ) if ( B [ i ] == x ) return true ; return false ; } int findMaxSubarraySumUtil ( int A [ ] , int B [ ] , int n , int m ) { int max_so_far = INT_MIN , curr_max = 0 ; for ( int i = 0 ; i ... |
Maximum Subarray Sum Excluding Certain Elements | C ++ Program to find max subarray sum excluding some elements ; Utility function for findMaxSubarraySum ( ) with the following parameters A = > Array A , B = > Array B , n = > Number of elements in Array A , m = > Number of elements in Array B ; set max_so_far to INT_MI... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaxSubarraySumUtil ( int A [ ] , int B [ ] , int n , int m ) { int max_so_far = INT_MIN , curr_max = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( binary_search ( B , B + m , A [ i ] ) ) { curr_max = 0 ; continue ; } curr_max = max ( A [ i ] , curr_max + A [... |
Number of n | C ++ program for counting n digit numbers with non decreasing digits ; Returns count of non - decreasing numbers with n digits . ; a [ i ] [ j ] = count of all possible number with i digits having leading digit as j ; Initialization of all 0 - digit number ; Initialization of all i - digit non - decreasin... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int nonDecNums ( int n ) { int a [ n + 1 ] [ 10 ] ; for ( int i = 0 ; i <= 9 ; i ++ ) a [ 0 ] [ i ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) a [ i ] [ 9 ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) for ( int j = 8 ; j >= 0 ; j -- ) a [ i ] [ j ] = a [ i - 1 ] [ j ] + ... |
Count Balanced Binary Trees of Height h | C ++ program to count number of balanced binary trees of height h . ; base cases ; Driver program | #include <bits/stdc++.h> NEW_LINE #define mod 1000000007 NEW_LINE using namespace std ; long long int countBT ( int h ) { long long int dp [ h + 1 ] ; dp [ 0 ] = dp [ 1 ] = 1 ; for ( int i = 2 ; i <= h ; i ++ ) { dp [ i ] = ( dp [ i - 1 ] * ( ( 2 * dp [ i - 2 ] ) % mod + dp [ i - 1 ] ) % mod ) % mod ; } return dp [ h ... |
Maximum Subarray Sum Excluding Certain Elements | C ++ Program implementation of the above idea ; Function to calculate the max sum of contigous subarray of B whose elements are not present in A ; mark all the elements present in B ; initialize max_so_far with INT_MIN ; traverse the array A ; if current max is greater ... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaxSubarraySum ( vector < int > A , vector < int > B ) { unordered_map < int , int > m ; for ( int i = 0 ; i < B . size ( ) ; i ++ ) { m [ B [ i ] ] = 1 ; } int max_so_far = INT_MIN ; int currmax = 0 ; for ( int i = 0 ; i < A . size ( ) ; i ++ ) { if ( cur... |
Print all k | C ++ program to print all paths with sum k . ; utility function to print contents of a vector from index i to it 's end ; binary tree node ; This function prints all paths that have sum k ; empty node ; add current node to the path ; check if there 's any k sum path in the left sub-tree. ; check if there... | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printVector ( const vector < int > & v , int i ) { for ( int j = i ; j < v . size ( ) ; j ++ ) cout << v [ j ] << " β " ; cout << endl ; } struct Node { int data ; Node * left , * right ; Node ( int x ) { data = x ; left = right = NULL ; } } ; void printKPath... |
Number of substrings divisible by 8 but not by 3 | CPP Program to count substrings which are divisible by 8 but not by 3 ; Returns count of substrings divisible by 8 but not by 3. ; Iterating the string . ; Prefix sum of number of substrings whose sum of digits mudolo 3 is 0 , 1 , 2. ; Iterating the string . ; Since si... | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1000 NEW_LINE int count ( char s [ ] , int len ) { int cur = 0 , dig = 0 ; int sum [ MAX ] , dp [ MAX ] [ 3 ] ; memset ( sum , 0 , sizeof ( sum ) ) ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ 0 ] [ 0 ] = 1 ; for ( int i = 1 ; i <= len ; i ++ ) { dig = ... |
Print all distinct characters of a string in order ( 3 Methods ) | C ++ program to find all distinct characters in a string ; Function to print distinct characters in given string str [ ] ; count [ x ] is going to store count of character ' x ' in str . If x is not present , then it is going to store 0. ; index [ x ] i... | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 256 ; void printDistinct ( string str ) { int n = str . length ( ) ; int count [ MAX_CHAR ] ; int index [ MAX_CHAR ] ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) { count [ i ] = 0 ; } for ( int i = 0 ; i < n ; i ++ ) { char x = str [ i ] ; ++ cou... |
Smallest length string with repeated replacement of two distinct adjacent | C ++ program to find smallest possible length of a string of only three characters ; Program to find length of reduced string in a string made of three characters . ; To store results of subproblems ; A memoized function find result recursively... | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX_LEN 110 NEW_LINE int DP [ MAX_LEN ] [ MAX_LEN ] [ MAX_LEN ] ; int length ( int a , int b , int c ) { if ( DP [ a ] [ b ] != -1 ) return DP [ a ] [ b ] ; if ( a == 0 && b == 0 ) return ( DP [ a ] [ b ] = c ) ; if ( a == 0 && c == 0 ) return ( DP [ a ] ... |
Equilibrium index of an array | C ++ program to find equilibrium index of an array ; function to find the equilibrium index ; Check for indexes one by one until an equilibrium index is found ; get left sum ; get right sum ; if leftsum and rightsum are same , then we are done ; return - 1 if no equilibrium index is foun... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int equilibrium ( int arr [ ] , int n ) { int i , j ; int leftsum , rightsum ; for ( i = 0 ; i < n ; ++ i ) { leftsum = 0 ; rightsum = 0 ; for ( j = 0 ; j < i ; j ++ ) leftsum += arr [ j ] ; for ( j = i + 1 ; j < n ; j ++ ) rightsum += arr [ j ] ; if ( leftsum == ... |
Find number of endless points | C ++ program to find count of endless points ; Returns count of endless points ; Fills column matrix . For every column , start from every last row and fill every entry as blockage after a 0 is found . ; flag which will be zero once we get a '0' and it will be 1 otherwise ; encountered a... | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100 ; int countEndless ( bool input [ ] [ MAX ] , int n ) { bool row [ n ] [ n ] , col [ n ] [ n ] ; for ( int j = 0 ; j < n ; j ++ ) { bool isEndless = 1 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( input [ i ] [ j ] == 0 ) isEndless = 0 ; col [... |
Equilibrium index of an array | C ++ program to find equilibrium index of an array ; function to find the equilibrium index ; initialize sum of whole array ; initialize leftsum ; Find sum of the whole array ; sum is now right sum for index i ; If no equilibrium index found , then return 0 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int equilibrium ( int arr [ ] , int n ) { int sum = 0 ; int leftsum = 0 ; for ( int i = 0 ; i < n ; ++ i ) sum += arr [ i ] ; for ( int i = 0 ; i < n ; ++ i ) { sum -= arr [ i ] ; if ( leftsum == sum ) return i ; leftsum += arr [ i ] ; } return -1 ; } int main ( )... |
Sum of all substrings of a string representing a number | Set 1 | C ++ program to print sum of all substring of a number represented as a string ; Utility method to convert character digit to integer digit ; Returns sum of all substring of num ; allocate memory equal to length of string ; initialize first value with fi... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int toDigit ( char ch ) { return ( ch - '0' ) ; } int sumOfSubstrings ( string num ) { int n = num . length ( ) ; int sumofdigit [ n ] ; sumofdigit [ 0 ] = toDigit ( num [ 0 ] ) ; int res = sumofdigit [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { int numi = toDigit (... |
Sum of all substrings of a string representing a number | Set 1 | C ++ program to print sum of all substring of a number represented as a string ; Utility method to convert character digit to integer digit ; Returns sum of all substring of num ; storing prev value ; substrings sum upto current index loop over all digit... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int toDigit ( char ch ) { return ( ch - '0' ) ; } int sumOfSubstrings ( string num ) { int n = num . length ( ) ; int prev = toDigit ( num [ 0 ] ) ; int res = prev ; int current = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int numi = toDigit ( num [ i ] ) ; current = ... |
Equilibrium index of an array | C ++ program to find equilibrium index of an array ; Taking the prefixsum from front end array ; Taking the prefixsum from back end of array ; Checking if forward prefix sum is equal to rev prefix sum ; If You want all the points of equilibrium create vector and push all equilibrium poin... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int equilibrium ( int a [ ] , int n ) { if ( n == 1 ) return ( 0 ) ; int forward [ n ] = { 0 } ; int rev [ n ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { if ( i ) { forward [ i ] = forward [ i - 1 ] + a [ i ] ; } else { forward [ i ] = a [ i ] ; } } for ( int i ... |
Leaders in an array | C ++ Function to print leaders in an array ; the loop didn 't break ; Driver program to test above function | #include <iostream> NEW_LINE using namespace std ; void printLeaders ( int arr [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) { int j ; for ( j = i + 1 ; j < size ; j ++ ) { if ( arr [ i ] <= arr [ j ] ) break ; } if ( j == size ) cout << arr [ i ] << " β " ; } } int main ( ) { int arr [ ] = { 16 , 17 , 4 , 3 ,... |
Minimize cost to reach end of an N | C ++ program for the above approach ; For priority_queue ; Function to calculate the minimum cost required to reach the end of Line ; Checks if possible to reach end or not ; Stores the stations and respective rate of fuel ; Stores the station index and cost of fuel and litres of pe... | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Compare { bool operator() ( array < int , 3 > a , array < int , 3 > b ) { return a [ 1 ] > b [ 1 ] ; } } ; void minCost ( int N , int K , int M , int a [ ] , int b [ ] ) { bool flag = true ; unordered_map < int , int > map ; for ( int i = 0 ; i < M ; i ++ )... |
Leaders in an array | ; C ++ Function to print leaders in an array ; Rightmost element is always leader ; Driver program to test above function | #include <iostream> NEW_LINE using namespace std ; void printLeaders ( int arr [ ] , int size ) { int max_from_right = arr [ size - 1 ] ; cout << max_from_right << " β " ; for ( int i = size - 2 ; i >= 0 ; i -- ) { if ( max_from_right < arr [ i ] ) { max_from_right = arr [ i ] ; cout << max_from_right << " β " ; } } } ... |
Unbounded Knapsack ( Repetition of items allowed ) | C ++ program to find maximum achievable value with a knapsack of weight W and multiple instances allowed . ; Returns the maximum value with knapsack of W capacity ; dp [ i ] is going to store maximum value with knapsack capacity i . ; Fill dp [ ] using above recursiv... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int unboundedKnapsack ( int W , int n , int val [ ] , int wt [ ] ) { int dp [ W + 1 ] ; memset ( dp , 0 , sizeof dp ) ; for ( int i = 0 ; i <= W ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) if ( wt [ j ] <= i ) dp [ i ] = max ( dp [ i ] , dp [ i - wt [ j ] ] + val [ ... |
Ceiling in a sorted array | C ++ implementation of above approach ; Function to get index of ceiling of x in arr [ low . . high ] ; If x is smaller than or equal to first element , then return the first element ; Otherwise , linearly search for ceil value ; if x lies between arr [ i ] and arr [ i + 1 ] including arr [ ... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int ceilSearch ( int arr [ ] , int low , int high , int x ) { int i ; if ( x <= arr [ low ] ) return low ; for ( i = low ; i < high ; i ++ ) { if ( arr [ i ] == x ) return i ; if ( arr [ i ] < x && arr [ i + 1 ] >= x ) return i + 1 ; } return -1 ; } int main ( ) {... |
Ceiling in a sorted array | ; Function to get index of ceiling of x in arr [ low . . high ] ; If x is smaller than or equal to the first element , then return the first element ; If x is greater than the last element , then return - 1 ; get the index of middle element of arr [ low . . high ] ; If x is same as middle e... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int ceilSearch ( int arr [ ] , int low , int high , int x ) { int mid ; if ( x <= arr [ low ] ) return low ; if ( x > arr [ high ] ) return -1 ; mid = ( low + high ) / 2 ; if ( arr [ mid ] == x ) return mid ; else if ( arr [ mid ] < x ) { if ( mid + 1 <= high && x... |
Sum of heights of all individual nodes in a binary tree | C ++ program to find sum of heights of all nodes in a binary tree ; A binary tree Node has data , pointer to left child and a pointer to right child ; Compute the " maxHeight " of a particular Node ; compute the height of each subtree ; use the larger one ; Help... | #include <bits/stdc++.h> NEW_LINE struct Node { int data ; struct Node * left ; struct Node * right ; } ; int getHeight ( struct Node * Node ) { if ( Node == NULL ) return 0 ; else { int lHeight = getHeight ( Node -> left ) ; int rHeight = getHeight ( Node -> right ) ; if ( lHeight > rHeight ) return ( lHeight + 1 ) ; ... |
Path with maximum average value | C / C ++ program to find maximum average cost path ; Maximum number of rows and / or columns ; method returns maximum average of all path of cost matrix ; Initialize first column of total cost ( dp ) array ; Initialize first row of dp array ; Construct rest of the dp array ; divide max... | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int M = 100 ; double maxAverageOfPath ( int cost [ M ] [ M ] , int N ) { int dp [ N + 1 ] [ N + 1 ] ; dp [ 0 ] [ 0 ] = cost [ 0 ] [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) dp [ i ] [ 0 ] = dp [ i - 1 ] [ 0 ] + cost [ i ] [ 0 ] ; for ( int j = 1 ; j < N ; j ++... |
Maximum weight path ending at any element of last row in a matrix | C ++ program to find the path having the maximum weight in matrix ; Function which return the maximum weight path sum ; creat 2D matrix to store the sum of the path ; Initialize first column of total weight array ( dp [ i to N ] [ 0 ] ) ; Calculate res... | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 1000 ; int maxCost ( int mat [ ] [ MAX ] , int N ) { int dp [ N ] [ N ] ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ 0 ] [ 0 ] = mat [ 0 ] [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) dp [ i ] [ 0 ] = mat [ i ] [ 0 ] + dp [ i - 1 ] [ 0 ] ; for ( int i = ... |
Number of permutation with K inversions | C ++ program to find number of permutation with K inversion using Memoization ; Limit on N and K ; 2D array memo for stopping solving same problem again ; method recursively calculates permutation with K inversion ; base cases ; if already solved then return result directly ; c... | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int M = 100 ; int memo [ M ] [ M ] ; int numberOfPermWithKInversion ( int N , int K ) { if ( N == 0 ) return 0 ; if ( K == 0 ) return 1 ; if ( memo [ N ] [ K ] != 0 ) return memo [ N ] [ K ] ; int sum = 0 ; for ( int i = 0 ; i <= K ; i ++ ) { if ( i <= N - 1... |
A Space Optimized DP solution for 0 | C ++ program of a space optimized DP solution for 0 - 1 knapsack problem . ; val [ ] is for storing maximum profit for each weight wt [ ] is for storing weights n number of item W maximum capacity of bag mat [ 2 ] [ W + 1 ] to store final result ; matrix to store final result ; ite... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int KnapSack ( int val [ ] , int wt [ ] , int n , int W ) { int mat [ 2 ] [ W + 1 ] ; memset ( mat , 0 , sizeof ( mat ) ) ; int i = 0 ; while ( i < n ) { int j = 0 ; if ( i % 2 != 0 ) { while ( ++ j <= W ) { if ( wt [ i ] <= j ) mat [ 1 ] [ j ] = max ( val [ i ] +... |
Maximum profit by buying and selling a share at most k times | C ++ program to find out maximum profit by buying and / selling a share atmost k times given stock price of n days ; Function to find out maximum profit by buying & selling / a share atmost k times given stock price of n days ; table to store results of sub... | #include <climits> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int maxProfit ( int price [ ] , int n , int k ) { int profit [ k + 1 ] [ n + 1 ] ; for ( int i = 0 ; i <= k ; i ++ ) profit [ i ] [ 0 ] = 0 ; for ( int j = 0 ; j <= n ; j ++ ) profit [ 0 ] [ j ] = 0 ; for ( int i = 1 ; i <= k ; i ++ ) { int ... |
Check if an array has a majority element | Hashing based C ++ program to find if there is a majority element in input array . ; Returns true if there is a majority element in a [ ] ; Insert all elements in a hash table ; Check if frequency of any element is n / 2 or more . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isMajority ( int a [ ] , int n ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) mp [ a [ i ] ] ++ ; for ( auto x : mp ) if ( x . second >= n / 2 ) return true ; return false ; } int main ( ) { int a [ ] = { 2 , 3 , 9 , 2 , 2 } ; int n = s... |
Count even length binary sequences with same sum of first and second half bits | A Naive Recursive C ++ program to count even length binary sequences such that the sum of first and second half bits is same ; diff is difference between sums first n bits and last n bits respectively ; We can 't cover difference of more ... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSeq ( int n , int diff ) { if ( abs ( diff ) > n ) return 0 ; if ( n == 1 && diff == 0 ) return 2 ; if ( n == 1 && abs ( diff ) == 1 ) return 1 ; int res = countSeq ( n - 1 , diff + 1 ) + 2 * countSeq ( n - 1 , diff ) + countSeq ( n - 1 , diff - 1 ) ; ret... |
Count even length binary sequences with same sum of first and second half bits | A memoization based C ++ program to count even length binary sequences such that the sum of first and second half bits is same ; A lookup table to store the results of subproblems ; dif is difference between sums of first n bits and last n... | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1000 NEW_LINE int lookup [ MAX ] [ MAX ] ; int countSeqUtil ( int n , int dif ) { if ( abs ( dif ) > n ) return 0 ; if ( n == 1 && dif == 0 ) return 2 ; if ( n == 1 && abs ( dif ) == 1 ) return 1 ; if ( lookup [ n ] [ n + dif ] != -1 ) return lookup [... |
Two Pointers Technique | Naive solution to find if there is a pair in A [ 0. . N - 1 ] with given sum . ; as equal i and j means same element ; pair exists ; as the array is sorted ; No pair found with given sum . ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPairSum ( int A [ ] , int N , int X ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( i == j ) continue ; if ( A [ i ] + A [ j ] == X ) return true ; if ( A [ i ] + A [ j ] > X ) break ; } } return false ; } int main ( ) { int a... |
Remove minimum elements from either side such that 2 * min becomes more than max | C ++ implementation of above approach ; A utility function to find minimum of two numbers ; A utility function to find minimum in arr [ l . . h ] ; A utility function to find maximum in arr [ l . . h ] ; Returns the minimum number of rem... | #include <iostream> NEW_LINE using namespace std ; int min ( int a , int b ) { return ( a < b ) ? a : b ; } int min ( int arr [ ] , int l , int h ) { int mn = arr [ l ] ; for ( int i = l + 1 ; i <= h ; i ++ ) if ( mn > arr [ i ] ) mn = arr [ i ] ; return mn ; } int max ( int arr [ ] , int l , int h ) { int mx = arr [ l... |
Two Pointers Technique | ; Two pointer technique based solution to find if there is a pair in A [ 0. . N - 1 ] with a given sum . ; represents first pointer ; represents second pointer ; If we find a pair ; If sum of elements at current pointers is less , we move towards higher values by doing i ++ ; If sum of element... | #include <iostream> NEW_LINE using namespace std ; int isPairSum ( int A [ ] , int N , int X ) { int i = 0 ; int j = N - 1 ; while ( i < j ) { if ( A [ i ] + A [ j ] == X ) return 1 ; else if ( A [ i ] + A [ j ] < X ) i ++ ; else j -- ; } return 0 ; } int main ( ) { int arr [ ] = { 3 , 5 , 9 , 2 , 8 , 10 , 11 } ; int v... |
Sum of heights of all individual nodes in a binary tree | C ++ program to find sum of heights of all nodes in a binary tree ; A binary tree Node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new Node with the given data and NULL left and right pointers . ; Function to ... | #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... |
Inorder Tree Traversal without Recursion | C ++ program to print inorder traversal using stack . ; A binary tree Node has data , pointer to left child and a pointer to right child ; Iterative function for inorder tree traversal ; traverse the tree ; Reach the left most Node of the curr Node ; place pointer to a tree no... | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left ; struct Node * right ; Node ( int data ) { this -> data = data ; left = right = NULL ; } } ; void inOrder ( struct Node * root ) { stack < Node * > s ; Node * curr = root ; while ( curr != NULL || s . empty ( ) == false... |
Count all possible paths from top left to bottom right of a mXn matrix | A C ++ program to count all possible paths from top left to bottom right ; Returns count of possible paths to reach cell at row number m and column number n from the topmost leftmost cell ( cell at 1 , 1 ) ; Create a 2D table to store results of s... | #include <iostream> NEW_LINE using namespace std ; int numberOfPaths ( int m , int n ) { int count [ m ] [ n ] ; for ( int i = 0 ; i < m ; i ++ ) count [ i ] [ 0 ] = 1 ; for ( int j = 0 ; j < n ; j ++ ) count [ 0 ] [ j ] = 1 ; for ( int i = 1 ; i < m ; i ++ ) { for ( int j = 1 ; j < n ; j ++ ) } return count [ m - 1 ] ... |
Split array into two equal length subsets such that all repetitions of a number lies in a single subset | C ++ program for the above approach ; Function to create the frequency array of the given array arr [ ] ; Hashmap to store the frequencies ; Store freq for each element ; Get the total frequencies ; Store frequenci... | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > findSubsets ( vector < int > arr , int N ) { map < int , int > M ; for ( int i = 0 ; i < N ; i ++ ) { M [ arr [ i ] ] ++ ; } vector < int > subsets ; int I = 0 ; for ( auto playerEntry = M . begin ( ) ; playerEntry != M . end ( ) ; playerEntry ++ ) ... |
Maximum Product Cutting | DP | A Naive Recursive method to find maximum product ; Utility function to get the maximum of two and three integers ; The main function that returns maximum product obtainable from a rope of length n ; Base cases ; Make a cut at different places and take the maximum of all ; Return the maxim... | #include <iostream> NEW_LINE using namespace std ; int max ( int a , int b ) { return ( a > b ) ? a : b ; } int max ( int a , int b , int c ) { return max ( a , max ( b , c ) ) ; } int maxProd ( int n ) { if ( n == 0 n == 1 ) return 0 ; int max_val = 0 ; for ( int i = 1 ; i < n ; i ++ ) max_val = max ( max_val , i * ( ... |
Assembly Line Scheduling | DP | A C ++ program to find minimum possible time by the car chassis to complete ; Utility function to find a minimum of two numbers ; time taken to leave first station in line 1 ; time taken to leave first station in line 2 ; Fill tables T1 [ ] and T2 [ ] using the above given recursive rela... | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define NUM_LINE 2 NEW_LINE #define NUM_STATION 4 NEW_LINE int min ( int a , int b ) { return a < b ? a : b ; } int carAssembly ( int a [ ] [ NUM_STATION ] , int t [ ] [ NUM_STATION ] , int * e , int * x ) { int T1 [ NUM_STATION ] , T2 [ NUM_STATION ] , i ; T1 [... |
Longest Common Substring | DP | Dynamic Programming solution to find length of the longest common substring ; Returns length of longest common substring of X [ 0. . m - 1 ] and Y [ 0. . n - 1 ] ; Create a table to store lengths of longest common suffixes of substrings . Note that LCSuff [ i ] [ j ] contains length of l... | #include <iostream> NEW_LINE #include <string.h> NEW_LINE using namespace std ; int LCSubStr ( char * X , char * Y , int m , int n ) { int LCSuff [ m + 1 ] [ n + 1 ] ; int result = 0 ; for ( int i = 0 ; i <= m ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) LCSuff [ i ] [ j ] = 0 ; else if ( X [ i -... |
Minimum insertions to form a palindrome | DP | A Dynamic Programming based program to find minimum number insertions needed to make a string palindrome ; A DP function to find minimum number of insertions ; Create a table of size n * n . table [ i ] [ j ] will store minimum number of insertions needed to convert str [ ... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinInsertionsDP ( char str [ ] , int n ) { int table [ n ] [ n ] , l , h , gap ; memset ( table , 0 , sizeof ( table ) ) ; for ( gap = 1 ; gap < n ; ++ gap ) for ( l = 0 , h = gap ; h < n ; ++ l , ++ h ) table [ l ] [ h ] = ( str [ l ] == str [ h ] ) ? tab... |
Maximum Subarray Sum using Divide and Conquer algorithm | A Divide and Conquer based program for maximum subarray sum problem ; A utility function to find maximum of two integers ; A utility function to find maximum of three integers ; Find the maximum possible sum in arr [ ] auch that arr [ m ] is part of it ; Include... | #include <limits.h> NEW_LINE #include <stdio.h> NEW_LINE int max ( int a , int b ) { return ( a > b ) ? a : b ; } int max ( int a , int b , int c ) { return max ( max ( a , b ) , c ) ; } int maxCrossingSum ( int arr [ ] , int l , int m , int h ) { int sum = 0 ; int left_sum = INT_MIN ; for ( int i = m ; i >= l ; i -- )... |
Largest Independent Set Problem | DP | A naive recursive implementation of Largest Independent Set problem ; A utility function to find max of two integers ; A binary tree node has data , pointer to left child and a pointer to right child ; The function returns size of the largest independent set in a given binary tree... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int max ( int x , int y ) { return ( x > y ) ? x : y ; } class node { public : int data ; node * left , * right ; } ; int LISS ( node * root ) { if ( root == NULL ) return 0 ; int size_excl = LISS ( root -> left ) + LISS ( root -> right ) ; int size_incl = 1 ; if ... |
Program to find amount of water in a given glass | Program to find the amount of water in j - th glass of i - th row ; Returns the amount of water in jth glass of ith row ; A row number i has maximum i columns . So input column number must be less than i ; There will be i * ( i + 1 ) / 2 glasses till ith row ( includin... | #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #include <string.h> NEW_LINE float findWater ( int i , int j , float X ) { if ( j > i ) { printf ( " Incorrect β Inputn " ) ; exit ( 0 ) ; } float glass [ i * ( i + 1 ) / 2 ] ; memset ( glass , 0 , sizeof ( glass ) ) ; int index = 0 ; glass [ index ] = X ; for ( ... |
Maximum Length Chain of Pairs | DP | CPP program for above approach ; This function assumes that arr [ ] is sorted in increasing order according the first ( or smaller ) values in Pairs . ; Initialize MCL ( max chain length ) values for all indexes ; Compute optimized chain length values in bottom up manner ; Pick maxi... | #include <bits/stdc++.h> NEW_LINE using namespace std ; class Pair { public : int a ; int b ; } ; int maxChainLength ( Pair arr [ ] , int n ) { int i , j , max = 0 ; int * mcl = new int [ sizeof ( int ) * n ] ; for ( i = 0 ; i < n ; i ++ ) mcl [ i ] = 1 ; for ( i = 1 ; i < n ; i ++ ) for ( j = 0 ; j < i ; j ++ ) if ( a... |
Palindrome Partitioning | DP | Dynamic Programming Solution for Palindrome Partitioning Problem ; Returns the minimum number of cuts needed to partition a string such that every part is a palindrome ; Get the length of the string ; Create two arrays to build the solution in bottom up manner C [ i ] [ j ] = Minimum numb... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minPalPartion ( string str ) { int n = str . length ( ) ; int C [ n ] [ n ] ; bool P [ n ] [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { P [ i ] [ i ] = true ; C [ i ] [ i ] = 0 ; } for ( int L = 2 ; L <= n ; L ++ ) { for ( int i = 0 ; i < n - L + 1 ; i ++ ) { in... |
Count subtrees that sum up to a given value x only using single recursive function | C ++ implementation to count subtress that sum up to a given value x ; structure of a node of binary tree ; function to get a new node ; allocate space ; put in the data ; function to count subtress that sum up to a given value x ; if ... | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * getNode ( int data ) { Node * newNode = ( Node * ) malloc ( sizeof ( Node ) ) ; newNode -> data = data ; newNode -> left = newNode -> right = NULL ; return newNode ; } int countSubtreesWithSumX ( Node * r... |
Minimum replacements required to make given Matrix palindromic | C ++ program for the above approach ; Function to count minimum changes to make the matrix palindromic ; Rows in the matrix ; Columns in the matrix ; Traverse the given matrix ; Store the frequency of the four cells ; Iterate over the map ; Min changes to... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minchanges ( vector < vector < int > > mat ) { int N = mat . size ( ) ; int M = mat [ 0 ] . size ( ) ; int i , j , ans = 0 , x ; map < int , int > mp ; for ( i = 0 ; i < N / 2 ; i ++ ) { for ( j = 0 ; j < M / 2 ; j ++ ) { mp [ mat [ i ] [ M - 1 - j ] ] ++ ; mp... |
Check if a number starts with another number or not | C ++ program for the above approach ; Function to check if B is a prefix of A or not ; Convert numbers into strings ; Check if s2 is a prefix of s1 or not using starts_with ( ) function ; If result is true , print " Yes " ; Driver Code ; Given numbers ; Function Cal... | #include <bits/stdc++.h> NEW_LINE #include <boost/algorithm/string.hpp> NEW_LINE using namespace std ; void checkprefix ( int A , int B ) { string s1 = to_string ( A ) ; string s2 = to_string ( B ) ; bool result ; result = boost :: algorithm :: starts_with ( s1 , s2 ) ; if ( result ) { cout << " Yes " ; } else { cout <... |
Check three or more consecutive identical characters or numbers | C ++ program to check three or more consecutive identical characters or numbers using Regular Expression ; Function to check three or more consecutive identical characters or numbers . ; Regex to check valid three or more consecutive identical characters... | #include <iostream> NEW_LINE #include <regex> NEW_LINE using namespace std ; bool isIdentical ( string str ) { const regex pattern ( " \\ b ( [ a - zA - Z0-9 ] ) \\ 1 \\ 1 + \\ b " ) ; if ( str . empty ( ) ) { return false ; } if ( regex_match ( str , pattern ) ) { return true ; } else { return false ; } } int main ( )... |
How to validate MAC address using Regular Expression | C ++ program to validate the MAC address using Regular Expression ; Function to validate the MAC address ; Regex to check valid MAC address ; If the MAC address is empty return false ; Return true if the MAC address matched the ReGex ; Driver Code ; Test Case 1 : ;... | #include <iostream> NEW_LINE #include <regex> NEW_LINE using namespace std ; bool isValidMACAddress ( string str ) { const regex pattern ( " ^ ( [0-9A - Fa - f ] { 2 } [ : - ] ) { 5 } " " ( [0-9A - Fa - f ] { 2 } ) | ( [0-9a - " " fA - F ] { 4 } \\ . [0-9a - fA - F ] " " { 4 } \\ . [0-9a - fA - F ] { 4 } ) $ " ) ; if (... |
How to validate GUID ( Globally Unique Identifier ) using Regular Expression | C ++ program to validate the GUID ( Globally Unique Identifier ) using Regular Expression ; Function to validate the GUID ( Globally Unique Identifier ) . ; Regex to check valid GUID ( Globally Unique Identifier ) . ; If the GUID ( Globally ... | #include <iostream> NEW_LINE #include <regex> NEW_LINE using namespace std ; bool isValidGUID ( string str ) { const regex pattern ( " ^ [ { ] ? [ 0-9a - fA - F ] { 8 } - ( [ 0-9a - fA - F ] { 4 } - ) { 3 } [ 0-9a - fA - F ] { 12 } [ } ] ? $ " ) ; if ( str . empty ( ) ) { return false ; } if ( regex_match ( str , patte... |
How to validate Indian driving license number using Regular Expression | C ++ program to validate the Indian driving license number using Regular Expression ; Function to validate the Indian driving license number ; Regex to check valid Indian driving license number ; If the Indian driving license number is empty retur... | #include <iostream> NEW_LINE #include <regex> NEW_LINE using namespace std ; bool isValidLicenseNo ( string str ) { const regex pattern ( " ^ ( ( [ A - Z ] { 2 } [ 0-9 ] { 2 } ) ( β " " ) | ( [ A - Z ] { 2 } - [0-9 ] { 2 } ) ) " " ( (19 β 20 ) [ 0 - " "9 ] [ 0-9 ] ) [0-9 ] { 7 } $ " ) ; if ( str . empty ( ) ) { return ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.