text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Maximum mirrors which can transfer light from bottom to right | C ++ program to find how many mirror can transfer light from bottom to right ; method returns number of mirror which can transfer light from bottom to right ; To store first obstacles horizontaly ( from right ) and vertically ( from bottom ) ; initialize both array as - 1 , signifying no obstacle ; looping matrix to mark column for obstacles ; mark rightmost column with obstacle ; looping matrix to mark rows for obstacles ; mark leftmost row with obstacle ; Initialize result ; if there is not obstacle on right or below , then mirror can be placed to transfer light ; if i > vertical [ j ] then light can from bottom if j > horizontal [ i ] then light can go to right ; uncomment this code to print actual mirror position also cout << i << " β " << j << endl ; ; Driver code to test above method ; B - Blank O - Obstacle | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumMirrorInMatrix ( string mat [ ] , int N ) { int horizontal [ N ] , vertical [ N ] ; memset ( horizontal , -1 , sizeof ( horizontal ) ) ; memset ( vertical , -1 , sizeof ( vertical ) ) ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = N - 1 ; j >= 0 ; j -- ) { if ( mat [ i ] [ j ] == ' B ' ) continue ; horizontal [ i ] = j ; break ; } } for ( int j = 0 ; j < N ; j ++ ) { for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( mat [ i ] [ j ] == ' B ' ) continue ; vertical [ j ] = i ; break ; } } int res = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( i > vertical [ j ] && j > horizontal [ i ] ) { res ++ ; } } } return res ; } int main ( ) { int N = 5 ; string mat [ N ] = { " BBOBB " , " BBBBO " , " BBBBB " , " BOOBO " , " BBBOB " } ; cout << maximumMirrorInMatrix ( mat , N ) << endl ; return 0 ; } |
Direction at last square block | C ++ program to tell the Current direction in R x C grid ; Function which tells the Current direction ; Driver program to test the Cases | #include <iostream> NEW_LINE using namespace std ; typedef long long int ll ; void direction ( ll R , ll C ) { if ( R != C && R % 2 == 0 && C % 2 != 0 && R < C ) { cout << " Left " << endl ; return ; } if ( R != C && R % 2 != 0 && C % 2 == 0 && R > C ) { cout << " Up " << endl ; return ; } if ( R == C && R % 2 != 0 && C % 2 != 0 ) { cout << " Right " << endl ; return ; } if ( R == C && R % 2 == 0 && C % 2 == 0 ) { cout << " Left " << endl ; return ; } if ( R != C && R % 2 != 0 && C % 2 != 0 && R < C ) { cout << " Right " << endl ; return ; } if ( R != C && R % 2 != 0 && C % 2 != 0 && R > C ) { cout << " Down " << endl ; return ; } if ( R != C && R % 2 == 0 && C % 2 == 0 && R < C ) { cout << " Left " << endl ; return ; } if ( R != C && R % 2 == 0 && C % 2 == 0 && R > C ) { cout << " Up " << endl ; return ; } if ( R != C && R % 2 == 0 && C % 2 != 0 && R > C ) { cout << " Down " << endl ; return ; } if ( R != C && R % 2 != 0 && C % 2 == 0 && R < C ) { cout << " Right " << endl ; return ; } } int main ( ) { ll R = 3 , C = 1 ; direction ( R , C ) ; return 0 ; } |
Print K 'th element in spiral form of matrix | ; k - starting row index m - ending row index l - starting column index n - ending column index i - iterator ; check the first row from the remaining rows ; check the last column from the remaining columns ; check the last row from the remaining rows ; check the first column from the remaining columns ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define R 3 NEW_LINE #define C 6 NEW_LINE void spiralPrint ( int m , int n , int a [ R ] [ C ] , int c ) { int i , k = 0 , l = 0 ; int count = 0 ; while ( k < m && l < n ) { for ( i = l ; i < n ; ++ i ) { count ++ ; if ( count == c ) cout << a [ k ] [ i ] << " β " ; } k ++ ; for ( i = k ; i < m ; ++ i ) { count ++ ; if ( count == c ) cout << a [ i ] [ n - 1 ] << " β " ; } n -- ; if ( k < m ) { for ( i = n - 1 ; i >= l ; -- i ) { count ++ ; if ( count == c ) cout << a [ m - 1 ] [ i ] << " β " ; } m -- ; } if ( l < n ) { for ( i = m - 1 ; i >= k ; -- i ) { count ++ ; if ( count == c ) cout << a [ i ] [ l ] << " β " ; } l ++ ; } } } int main ( ) { int a [ R ] [ C ] = { { 1 , 2 , 3 , 4 , 5 , 6 } , { 7 , 8 , 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 16 , 17 , 18 } } , k = 17 ; spiralPrint ( R , C , a , k ) ; return 0 ; } |
Print K 'th element in spiral form of matrix | C ++ program for Kth element in spiral form of matrix ; function for Kth element ; Element is in first row ; Element is in last column ; Element is in last row ; Element is in first column ; Recursion for sub - matrix . & A [ 1 ] [ 1 ] is address to next inside sub matrix . ; Driver code | #include <bits/stdc++.h> NEW_LINE #define MAX 100 NEW_LINE using namespace std ; int findK ( int A [ MAX ] [ MAX ] , int n , int m , int k ) { if ( n < 1 m < 1 ) return -1 ; if ( k <= m ) return A [ 0 ] [ k - 1 ] ; if ( k <= ( m + n - 1 ) ) return A [ ( k - m ) ] [ m - 1 ] ; if ( k <= ( m + n - 1 + m - 1 ) ) return A [ n - 1 ] [ m - 1 - ( k - ( m + n - 1 ) ) ] ; if ( k <= ( m + n - 1 + m - 1 + n - 2 ) ) return A [ n - 1 - ( k - ( m + n - 1 + m - 1 ) ) ] [ 0 ] ; return findK ( ( int ( * ) [ MAX ] ) ( & ( A [ 1 ] [ 1 ] ) ) , n - 2 , m - 2 , k - ( 2 * n + 2 * m - 4 ) ) ; } int main ( ) { int a [ MAX ] [ MAX ] = { { 1 , 2 , 3 , 4 , 5 , 6 } , { 7 , 8 , 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 16 , 17 , 18 } } ; int k = 17 ; cout << findK ( a , 3 , 6 , k ) << endl ; return 0 ; } |
Find if given matrix is Toeplitz or not | C ++ program to check whether given matrix is a Toeplitz matrix or not ; Function to check if all elements present in descending diagonal starting from position ( i , j ) in the matrix are all same or not ; mismatch found ; we only reach here when all elements in given diagonal are same ; Function to check whether given matrix is a Toeplitz matrix or not ; do for each element in first row ; check descending diagonal starting from position ( 0 , j ) in the matrix ; do for each element in first column ; check descending diagonal starting from position ( i , 0 ) in the matrix ; we only reach here when each descending diagonal from left to right is same ; Driver code ; Function call | #include <iostream> NEW_LINE using namespace std ; #define N 5 NEW_LINE #define M 4 NEW_LINE bool checkDiagonal ( int mat [ N ] [ M ] , int i , int j ) { int res = mat [ i ] [ j ] ; while ( ++ i < N && ++ j < M ) { if ( mat [ i ] [ j ] != res ) return false ; } return true ; } bool isToepliz ( int mat [ N ] [ M ] ) { for ( int i = 0 ; i < M ; i ++ ) { if ( ! checkDiagonal ( mat , 0 , i ) ) return false ; } for ( int i = 1 ; i < N ; i ++ ) { if ( ! checkDiagonal ( mat , i , 0 ) ) return false ; } return true ; } int main ( ) { int mat [ N ] [ M ] = { { 6 , 7 , 8 , 9 } , { 4 , 6 , 7 , 8 } , { 1 , 4 , 6 , 7 } , { 0 , 1 , 4 , 6 } , { 2 , 0 , 1 , 4 } } ; if ( isToepliz ( mat ) ) cout << " Matrix β is β a β Toepliz β " ; else cout << " Matrix β is β not β a β Toepliz β " ; return 0 ; } |
Find if given matrix is Toeplitz or not | C ++ program to check whether given matrix is a Toeplitz matrix or not ; row = number of rows col = number of columns ; HashMap to store key , value pairs ; If key value exists in the hashmap , ; We check whether the current value stored in this key matches to element at current index or not . If not , return false ; Else we put key , value pair in hashmap ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isToeplitz ( vector < vector < int > > matrix ) { int row = matrix . size ( ) ; int col = matrix [ 0 ] . size ( ) ; map < int , int > Map ; for ( int i = 0 ; i < row ; i ++ ) { for ( int j = 0 ; j < col ; j ++ ) { int key = i - j ; if ( Map [ key ] ) { if ( Map [ key ] != matrix [ i ] [ j ] ) return false ; } else { Map [ i - j ] = matrix [ i ] [ j ] ; } } } return true ; } int main ( ) { vector < vector < int > > matrix = { { 12 , 23 , -32 } , { -20 , 12 , 23 } , { 56 , -20 , 12 } , { 38 , 56 , -20 } } ; string result = ( isToeplitz ( matrix ) ) ? " Yes " : " No " ; cout << result ; return 0 ; } |
Count zeros in a row wise and column wise sorted matrix | C ++ program to count number of 0 s in the given row - wise and column - wise sorted binary matrix . ; Function to count number of 0 s in the given row - wise and column - wise sorted binary matrix . ; start from bottom - left corner of the matrix ; stores number of zeroes in the matrix ; move up until you find a 0 ; if zero is not found in current column , we are done ; add 0 s present in current column to result ; move right to next column ; Driver Program to test above functions | #include <iostream> NEW_LINE using namespace std ; #define N 5 NEW_LINE int countZeroes ( int mat [ N ] [ N ] ) { int row = N - 1 , col = 0 ; int count = 0 ; while ( col < N ) { while ( mat [ row ] [ col ] ) if ( -- row < 0 ) return count ; count += ( row + 1 ) ; col ++ ; } return count ; } int main ( ) { int mat [ N ] [ N ] = { { 0 , 0 , 0 , 0 , 1 } , { 0 , 0 , 0 , 1 , 1 } , { 0 , 1 , 1 , 1 , 1 } , { 1 , 1 , 1 , 1 , 1 } , { 1 , 1 , 1 , 1 , 1 } } ; cout << countZeroes ( mat ) ; return 0 ; } |
Linked complete binary tree & its creation | Program for linked implementation of complete binary tree ; For Queue Size ; A tree node ; A queue node ; A utility function to create a new tree node ; A utility function to create a new Queue ; Standard Queue Functions ; A utility function to check if a tree node has both left and right children ; Function to insert a new node in complete binary tree ; Create a new node for given data ; If the tree is empty , initialize the root with new node . ; get the front node of the queue . ; If the left child of this front node doesn t exist , set the left child as the new node ; If the right child of this front node doesn t exist , set the right child as the new node ; If the front node has both the left child and right child , Dequeue ( ) it . ; Enqueue ( ) the new node for later insertions ; Standard level order traversal to test above function ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define SIZE 50 NEW_LINE class node { public : int data ; node * right , * left ; } ; class Queue { public : int front , rear ; int size ; node * * array ; } ; node * newNode ( int data ) { node * temp = new node ( ) ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } Queue * createQueue ( int size ) { Queue * queue = new Queue ( ) ; queue -> front = queue -> rear = -1 ; queue -> size = size ; queue -> array = new node * [ queue -> size * sizeof ( node * ) ] ; int i ; for ( i = 0 ; i < size ; ++ i ) queue -> array [ i ] = NULL ; return queue ; } int isEmpty ( Queue * queue ) { return queue -> front == -1 ; } int isFull ( Queue * queue ) { return queue -> rear == queue -> size - 1 ; } int hasOnlyOneItem ( Queue * queue ) { return queue -> front == queue -> rear ; } void Enqueue ( node * root , Queue * queue ) { if ( isFull ( queue ) ) return ; queue -> array [ ++ queue -> rear ] = root ; if ( isEmpty ( queue ) ) ++ queue -> front ; } node * Dequeue ( Queue * queue ) { if ( isEmpty ( queue ) ) return NULL ; node * temp = queue -> array [ queue -> front ] ; if ( hasOnlyOneItem ( queue ) ) queue -> front = queue -> rear = -1 ; else ++ queue -> front ; return temp ; } node * getFront ( Queue * queue ) { return queue -> array [ queue -> front ] ; } int hasBothChild ( node * temp ) { return temp && temp -> left && temp -> right ; } void insert ( node * * root , int data , Queue * queue ) { node * temp = newNode ( data ) ; if ( ! * root ) * root = temp ; else { node * front = getFront ( queue ) ; if ( ! front -> left ) front -> left = temp ; else if ( ! front -> right ) front -> right = temp ; if ( hasBothChild ( front ) ) Dequeue ( queue ) ; } Enqueue ( temp , queue ) ; } void levelOrder ( node * root ) { Queue * queue = createQueue ( SIZE ) ; Enqueue ( root , queue ) ; while ( ! isEmpty ( queue ) ) { node * temp = Dequeue ( queue ) ; cout << temp -> data << " β " ; if ( temp -> left ) Enqueue ( temp -> left , queue ) ; if ( temp -> right ) Enqueue ( temp -> right , queue ) ; } } int main ( ) { node * root = NULL ; Queue * queue = createQueue ( SIZE ) ; int i ; for ( i = 1 ; i <= 12 ; ++ i ) insert ( & root , i , queue ) ; levelOrder ( root ) ; return 0 ; } |
Find size of the largest ' + ' formed by all ones in a binary matrix | C ++ program to find the size of the largest ' + ' formed by all 1 's in given binary matrix ; size of binary square matrix ; Function to find the size of the largest ' + ' formed by all 1 's in given binary matrix ; left [ j ] [ j ] , right [ i ] [ j ] , top [ i ] [ j ] and bottom [ i ] [ j ] store maximum number of consecutive 1 's present to the left, right, top and bottom of mat[i][j] including cell(i, j) respectively ; initialize above four matrix ; initialize first row of top ; initialize last row of bottom ; initialize first column of left ; initialize last column of right ; fill all cells of above four matrix ; calculate left matrix ( filled left to right ) ; calculate top matrix ; calculate new value of j to calculate value of bottom ( i , j ) and right ( i , j ) ; calculate bottom matrix ; calculate right matrix ; revert back to old j ; n stores length of longest + found so far ; compute longest + ; find minimum of left ( i , j ) , right ( i , j ) , top ( i , j ) , bottom ( i , j ) ; largest + would be formed by a cell that has maximum value ; 4 directions of length n - 1 and 1 for middle cell ; matrix contains all 0 's ; Driver function to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 10 NEW_LINE int findLargestPlus ( int mat [ N ] [ N ] ) { int left [ N ] [ N ] , right [ N ] [ N ] , top [ N ] [ N ] , bottom [ N ] [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { top [ 0 ] [ i ] = mat [ 0 ] [ i ] ; bottom [ N - 1 ] [ i ] = mat [ N - 1 ] [ i ] ; left [ i ] [ 0 ] = mat [ i ] [ 0 ] ; right [ i ] [ N - 1 ] = mat [ i ] [ N - 1 ] ; } for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 1 ; j < N ; j ++ ) { if ( mat [ i ] [ j ] == 1 ) left [ i ] [ j ] = left [ i ] [ j - 1 ] + 1 ; else left [ i ] [ j ] = 0 ; if ( mat [ j ] [ i ] == 1 ) top [ j ] [ i ] = top [ j - 1 ] [ i ] + 1 ; else top [ j ] [ i ] = 0 ; j = N - 1 - j ; if ( mat [ j ] [ i ] == 1 ) bottom [ j ] [ i ] = bottom [ j + 1 ] [ i ] + 1 ; else bottom [ j ] [ i ] = 0 ; if ( mat [ i ] [ j ] == 1 ) right [ i ] [ j ] = right [ i ] [ j + 1 ] + 1 ; else right [ i ] [ j ] = 0 ; j = N - 1 - j ; } } int n = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { int len = min ( min ( top [ i ] [ j ] , bottom [ i ] [ j ] ) , min ( left [ i ] [ j ] , right [ i ] [ j ] ) ) ; if ( len > n ) n = len ; } } if ( n ) return 4 * ( n - 1 ) + 1 ; return 0 ; } int main ( ) { int mat [ N ] [ N ] = { { 1 , 0 , 1 , 1 , 1 , 1 , 0 , 1 , 1 , 1 } , { 1 , 0 , 1 , 0 , 1 , 1 , 1 , 0 , 1 , 1 } , { 1 , 1 , 1 , 0 , 1 , 1 , 0 , 1 , 0 , 1 } , { 0 , 0 , 0 , 0 , 1 , 0 , 0 , 1 , 0 , 0 } , { 1 , 1 , 1 , 0 , 1 , 1 , 1 , 1 , 1 , 1 } , { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 0 } , { 1 , 0 , 0 , 0 , 1 , 0 , 0 , 1 , 0 , 1 } , { 1 , 0 , 1 , 1 , 1 , 1 , 0 , 0 , 1 , 1 } , { 1 , 1 , 0 , 0 , 1 , 0 , 1 , 0 , 0 , 1 } , { 1 , 0 , 1 , 1 , 1 , 1 , 0 , 1 , 0 , 0 } } ; cout << findLargestPlus ( mat ) ; return 0 ; } |
Return previous element in an expanding matrix | C ++ Program to return previous element in an expanding matrix . ; Returns left of str in an expanding matrix of a , b , c , and d . ; Start from rightmost position ; If the current character is b or d , change to a or c respectively and break the loop ; If the current character is a or c , change it to b or d respectively ; driver program to test above method | #include <bits/stdc++.h> NEW_LINE using namespace std ; string findLeft ( string str ) { int n = str . length ( ) ; while ( n -- ) { if ( str [ n ] == ' d ' ) { str [ n ] = ' c ' ; break ; } if ( str [ n ] == ' b ' ) { str [ n ] = ' a ' ; break ; } if ( str [ n ] == ' a ' ) str [ n ] = ' b ' ; else if ( str [ n ] == ' c ' ) str [ n ] = ' d ' ; } return str ; } int main ( ) { string str = " aacbddc " ; cout << " Left β of β " << str << " β is β " << findLeft ( str ) ; return 0 ; } |
Print n x n spiral matrix using O ( 1 ) extra space | C ++ program to print a n x n spiral matrix in clockwise direction using O ( 1 ) space ; Prints spiral matrix of size n x n containing numbers from 1 to n x n ; x stores the layer in which ( i , j ) th element lies ; Finds minimum of four inputs ; For upper right half ; for lower left half ; Driver code ; print a n x n spiral matrix in O ( 1 ) space | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printSpiral ( int n ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { int x ; x = min ( min ( i , j ) , min ( n - 1 - i , n - 1 - j ) ) ; if ( i <= j ) printf ( " % d TABSYMBOL β " , ( n - 2 * x ) * ( n - 2 * x ) - ( i - x ) - ( j - x ) ) ; else printf ( " % d TABSYMBOL β " , ( n - 2 * x - 2 ) * ( n - 2 * x - 2 ) + ( i - x ) + ( j - x ) ) ; } printf ( " STRNEWLINE " ) ; } } int main ( ) { int n = 5 ; printSpiral ( n ) ; return 0 ; } |
Shortest path in a Binary Maze | C ++ program to find the shortest path between a given source cell to a destination cell . ; To store matrix cell cordinates ; A Data Structure for queue used in BFS ; The cordinates of a cell ; cell 's distance of from the source ; check whether given cell ( row , col ) is a valid cell or not . ; return true if row number and column number is in range ; These arrays are used to get row and column numbers of 4 neighbours of a given cell ; function to find the shortest path between a given source cell to a destination cell . ; check source and destination cell of the matrix have value 1 ; Mark the source cell as visited ; Create a queue for BFS ; Distance of source cell is 0 ; Enqueue source cell ; Do a BFS starting from source cell ; If we have reached the destination cell , we are done ; Otherwise dequeue the front cell in the queue and enqueue its adjacent cells ; if adjacent cell is valid , has path and not visited yet , enqueue it . ; mark cell as visited and enqueue it ; Return - 1 if destination cannot be reached ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ROW 9 NEW_LINE #define COL 10 NEW_LINE struct Point { int x ; int y ; } ; struct queueNode { Point pt ; int dist ; } ; bool isValid ( int row , int col ) { return ( row >= 0 ) && ( row < ROW ) && ( col >= 0 ) && ( col < COL ) ; } int rowNum [ ] = { -1 , 0 , 0 , 1 } ; int colNum [ ] = { 0 , -1 , 1 , 0 } ; int BFS ( int mat [ ] [ COL ] , Point src , Point dest ) { if ( ! mat [ src . x ] [ src . y ] ! mat [ dest . x ] [ dest . y ] ) return -1 ; bool visited [ ROW ] [ COL ] ; memset ( visited , false , sizeof visited ) ; visited [ src . x ] [ src . y ] = true ; queue < queueNode > q ; queueNode s = { src , 0 } ; q . push ( s ) ; while ( ! q . empty ( ) ) { queueNode curr = q . front ( ) ; Point pt = curr . pt ; if ( pt . x == dest . x && pt . y == dest . y ) return curr . dist ; q . pop ( ) ; for ( int i = 0 ; i < 4 ; i ++ ) { int row = pt . x + rowNum [ i ] ; int col = pt . y + colNum [ i ] ; if ( isValid ( row , col ) && mat [ row ] [ col ] && ! visited [ row ] [ col ] ) { visited [ row ] [ col ] = true ; queueNode Adjcell = { { row , col } , curr . dist + 1 } ; q . push ( Adjcell ) ; } } } return -1 ; } int main ( ) { int mat [ ROW ] [ COL ] = { { 1 , 0 , 1 , 1 , 1 , 1 , 0 , 1 , 1 , 1 } , { 1 , 0 , 1 , 0 , 1 , 1 , 1 , 0 , 1 , 1 } , { 1 , 1 , 1 , 0 , 1 , 1 , 0 , 1 , 0 , 1 } , { 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 1 } , { 1 , 1 , 1 , 0 , 1 , 1 , 1 , 0 , 1 , 0 } , { 1 , 0 , 1 , 1 , 1 , 1 , 0 , 1 , 0 , 0 } , { 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 } , { 1 , 0 , 1 , 1 , 1 , 1 , 0 , 1 , 1 , 1 } , { 1 , 1 , 0 , 0 , 0 , 0 , 1 , 0 , 0 , 1 } } ; Point source = { 0 , 0 } ; Point dest = { 3 , 4 } ; int dist = BFS ( mat , source , dest ) ; if ( dist != -1 ) cout << " Shortest β Path β is β " << dist ; else cout << " Shortest β Path β doesn ' t β exist " ; return 0 ; } |
Convert a given Binary Tree to Doubly Linked List | Set 1 | A C ++ program for in - place conversion of Binary Tree to DLL ; A binary tree node has data , and left and right pointers ; This is the core function to convert Tree to list . This function follows steps 1 and 2 of the above algorithm ; Base case ; Convert the left subtree and link to root ; Convert the left subtree ; Find inorder predecessor . After this loop , left will point to the inorder predecessor ; Make root as next of the predecessor ; Make predecssor as previous of root ; Convert the right subtree and link to root ; Convert the right subtree ; Find inorder successor . After this loop , right will point to the inorder successor ; Make root as previous of successor ; Make successor as next of root ; The main function that first calls bintree2listUtil ( ) , then follows step 3 of the above algorithm ; Base case ; Convert to DLL using bintree2listUtil ( ) ; bintree2listUtil ( ) returns root node of the converted DLL . We need pointer to the leftmost node which is head of the constructed DLL , so move to the leftmost node ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Function to print nodes in a given doubly linked list ; Driver code ; Let us create the tree shown in above diagram ; Convert to DLL ; Print the converted list | #include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int data ; node * left ; node * right ; } ; node * bintree2listUtil ( node * root ) { if ( root == NULL ) return root ; if ( root -> left != NULL ) { node * left = bintree2listUtil ( root -> left ) ; for ( ; left -> right != NULL ; left = left -> right ) ; left -> right = root ; root -> left = left ; } if ( root -> right != NULL ) { node * right = bintree2listUtil ( root -> right ) ; for ( ; right -> left != NULL ; right = right -> left ) ; right -> left = root ; root -> right = right ; } return root ; } node * bintree2list ( node * root ) { if ( root == NULL ) return root ; root = bintree2listUtil ( root ) ; while ( root -> left != NULL ) root = root -> left ; return ( root ) ; } node * newNode ( int data ) { node * new_node = new node ( ) ; new_node -> data = data ; new_node -> left = new_node -> right = NULL ; return ( new_node ) ; } void printList ( node * node ) { while ( node != NULL ) { cout << node -> data << " β " ; node = node -> right ; } } int main ( ) { node * root = newNode ( 10 ) ; root -> left = newNode ( 12 ) ; root -> right = newNode ( 15 ) ; root -> left -> left = newNode ( 25 ) ; root -> left -> right = newNode ( 30 ) ; root -> right -> left = newNode ( 36 ) ; node * head = bintree2list ( root ) ; printList ( head ) ; return 0 ; } |
A Boolean Matrix Question | C ++ Code For A Boolean Matrix Question ; Initialize all values of row [ ] as 0 ; Initialize all values of col [ ] as 0 ; Store the rows and columns to be marked as 1 in row [ ] and col [ ] arrays respectively ; Modify the input matrix mat [ ] using the above constructed row [ ] and col [ ] arrays ; A utility function to print a 2D matrix ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define R 3 NEW_LINE #define C 4 NEW_LINE void modifyMatrix ( bool mat [ R ] [ C ] ) { bool row [ R ] ; bool col [ C ] ; int i , j ; for ( i = 0 ; i < R ; i ++ ) { row [ i ] = 0 ; } for ( i = 0 ; i < C ; i ++ ) { col [ i ] = 0 ; } for ( i = 0 ; i < R ; i ++ ) { for ( j = 0 ; j < C ; j ++ ) { if ( mat [ i ] [ j ] == 1 ) { row [ i ] = 1 ; col [ j ] = 1 ; } } } for ( i = 0 ; i < R ; i ++ ) { for ( j = 0 ; j < C ; j ++ ) { if ( row [ i ] == 1 col [ j ] == 1 ) { mat [ i ] [ j ] = 1 ; } } } } void printMatrix ( bool mat [ R ] [ C ] ) { int i , j ; for ( i = 0 ; i < R ; i ++ ) { for ( j = 0 ; j < C ; j ++ ) { cout << mat [ i ] [ j ] ; } cout << endl ; } } int main ( ) { bool mat [ R ] [ C ] = { { 1 , 0 , 0 , 1 } , { 0 , 0 , 1 , 0 } , { 0 , 0 , 0 , 0 } } ; cout << " Input β Matrix β STRNEWLINE " ; printMatrix ( mat ) ; modifyMatrix ( mat ) ; printf ( " Matrix β after β modification β STRNEWLINE " ) ; printMatrix ( mat ) ; return 0 ; } |
A Boolean Matrix Question | ; variables to check if there are any 1 in first row and column ; updating the first row and col if 1 is encountered ; Modify the input matrix mat [ ] using the first row and first column of Matrix mat ; modify first row if there was any 1 ; modify first col if there was any 1 ; A utility function to print a 2D matrix ; Driver function to test the above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define R 3 NEW_LINE #define C 4 NEW_LINE void modifyMatrix ( int mat [ R ] [ C ] ) { bool row_flag = false ; bool col_flag = false ; for ( int i = 0 ; i < R ; i ++ ) { for ( int j = 0 ; j < C ; j ++ ) { if ( i == 0 && mat [ i ] [ j ] == 1 ) row_flag = true ; if ( j == 0 && mat [ i ] [ j ] == 1 ) col_flag = true ; if ( mat [ i ] [ j ] == 1 ) { mat [ 0 ] [ j ] = 1 ; mat [ i ] [ 0 ] = 1 ; } } } for ( int i = 1 ; i < R ; i ++ ) { for ( int j = 1 ; j < C ; j ++ ) { if ( mat [ 0 ] [ j ] == 1 mat [ i ] [ 0 ] == 1 ) { mat [ i ] [ j ] = 1 ; } } } if ( row_flag == true ) { for ( int i = 0 ; i < C ; i ++ ) { mat [ 0 ] [ i ] = 1 ; } } if ( col_flag == true ) { for ( int i = 0 ; i < R ; i ++ ) { mat [ i ] [ 0 ] = 1 ; } } } void printMatrix ( int mat [ R ] [ C ] ) { for ( int i = 0 ; i < R ; i ++ ) { for ( int j = 0 ; j < C ; j ++ ) { cout << mat [ i ] [ j ] ; } cout << " STRNEWLINE " ; } } int main ( ) { int mat [ R ] [ C ] = { { 1 , 0 , 0 , 1 } , { 0 , 0 , 1 , 0 } , { 0 , 0 , 0 , 0 } } ; cout << " Input β Matrix β : STRNEWLINE " ; printMatrix ( mat ) ; modifyMatrix ( mat ) ; cout << " Matrix β After β Modification β : STRNEWLINE " ; printMatrix ( mat ) ; return 0 ; } |
Given a Boolean Matrix , find k such that all elements in k ' th β row β are β 0 β and β k ' th column are 1. | C ++ program to find i such that all entries in i ' th β row β are β 0 β and β all β entries β in β i ' t column are 1 ; Start from top - most rightmost corner ( We could start from other corners also ) ; Initialize result ; Find the index ( This loop runs at most 2 n times , we either increment row number or decrement column number ) ; If current element is 0 , then this row may be a solution ; Check for all elements in this row ; If all values are 0 , then store this row as result ; We reach here if we found a 1 in current row , so this row cannot be a solution , increment row number ; If current element is 1 ; Check for all elements in this column ; If all elements are 1 ; We reach here if we found a 0 in current column , so this column cannot be a solution , increment column number ; If we could not find result in above loop , then result doesn 't exist ; Check if above computed res is valid ; Driver program to test above functions | #include <iostream> NEW_LINE using namespace std ; #define n 5 NEW_LINE int find ( bool arr [ n ] [ n ] ) { int i = 0 , j = n - 1 ; int res = -1 ; while ( i < n && j >= 0 ) { if ( arr [ i ] [ j ] == 0 ) { while ( j >= 0 && ( arr [ i ] [ j ] == 0 i == j ) ) j -- ; if ( j == -1 ) { res = i ; break ; } else i ++ ; } else { while ( i < n && ( arr [ i ] [ j ] == 1 i == j ) ) i ++ ; if ( i == n ) { res = j ; break ; } else j -- ; } } if ( res == -1 ) return res ; for ( int i = 0 ; i < n ; i ++ ) if ( res != i && arr [ i ] [ res ] != 1 ) return -1 ; for ( int j = 0 ; j < n ; j ++ ) if ( res != j && arr [ res ] [ j ] != 0 ) return -1 ; return res ; } int main ( ) { bool mat [ n ] [ n ] = { { 0 , 0 , 1 , 1 , 0 } , { 0 , 0 , 0 , 1 , 0 } , { 1 , 1 , 1 , 1 , 0 } , { 0 , 0 , 0 , 0 , 0 } , { 1 , 1 , 1 , 1 , 1 } } ; cout << find ( mat ) ; return 0 ; } |
Print unique rows in a given boolean matrix | Given a binary matrix of M X N of integers , you need to return only unique rows of binary array ; The main function that prints all unique rows in a given matrix . ; Traverse through the matrix ; check if there is similar column is already printed , i . e if i and jth column match . ; if no row is similar ; print the row ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ROW 4 NEW_LINE #define COL 5 NEW_LINE void findUniqueRows ( int M [ ROW ] [ COL ] ) { for ( int i = 0 ; i < ROW ; i ++ ) { int flag = 0 ; for ( int j = 0 ; j < i ; j ++ ) { flag = 1 ; for ( int k = 0 ; k <= COL ; k ++ ) if ( M [ i ] [ k ] != M [ j ] [ k ] ) flag = 0 ; if ( flag == 1 ) break ; } if ( flag == 0 ) { for ( int j = 0 ; j < COL ; j ++ ) cout << M [ i ] [ j ] << " β " ; cout << endl ; } } } int main ( ) { int M [ ROW ] [ COL ] = { { 0 , 1 , 0 , 0 , 1 } , { 1 , 0 , 1 , 1 , 0 } , { 0 , 1 , 0 , 0 , 1 } , { 1 , 0 , 1 , 0 , 0 } } ; findUniqueRows ( M ) ; return 0 ; } |
Print unique rows in a given boolean matrix | Given a binary matrix of M X N of integers , you need to return only unique rows of binary array ; A Trie node ; Only two children needed for 0 and 1 ; A utility function to allocate memory for a new Trie node ; Inserts a new matrix row to Trie . If row is already present , then returns 0 , otherwise insets the row and return 1 ; base case ; Recur if there are more entries in this row ; If all entries of this row are processed ; unique row found , return 1 ; duplicate row found , return 0 ; A utility function to print a row ; The main function that prints all unique rows in a given matrix . ; create an empty Trie ; Iterate through all rows ; insert row to TRIE ; unique row found , print it ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ROW 4 NEW_LINE #define COL 5 NEW_LINE class Node { public : bool isEndOfCol ; Node * child [ 2 ] ; } ; Node * newNode ( ) { Node * temp = new Node ( ) ; temp -> isEndOfCol = 0 ; temp -> child [ 0 ] = temp -> child [ 1 ] = NULL ; return temp ; } bool insert ( Node * * root , int ( * M ) [ COL ] , int row , int col ) { if ( * root == NULL ) * root = newNode ( ) ; if ( col < COL ) return insert ( & ( ( * root ) -> child [ M [ row ] [ col ] ] ) , M , row , col + 1 ) ; else { if ( ! ( ( * root ) -> isEndOfCol ) ) return ( * root ) -> isEndOfCol = 1 ; return 0 ; } } void printRow ( int ( * M ) [ COL ] , int row ) { int i ; for ( i = 0 ; i < COL ; ++ i ) cout << M [ row ] [ i ] << " β " ; cout << endl ; } void findUniqueRows ( int ( * M ) [ COL ] ) { Node * root = NULL ; int i ; for ( i = 0 ; i < ROW ; ++ i ) if ( insert ( & root , M , i , 0 ) ) printRow ( M , i ) ; } int main ( ) { int M [ ROW ] [ COL ] = { { 0 , 1 , 0 , 0 , 1 } , { 1 , 0 , 1 , 1 , 0 } , { 0 , 1 , 0 , 0 , 1 } , { 1 , 0 , 1 , 0 , 0 } } ; findUniqueRows ( M ) ; return 0 ; } |
Print unique rows in a given boolean matrix | C ++ code to print unique row in a given binary matrix ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printArray ( int arr [ ] [ 5 ] , int row , int col ) { unordered_set < string > uset ; for ( int i = 0 ; i < row ; i ++ ) { string s = " " ; for ( int j = 0 ; j < col ; j ++ ) s += to_string ( arr [ i ] [ j ] ) ; if ( uset . count ( s ) == 0 ) { uset . insert ( s ) ; cout << s << endl ; } } } int main ( ) { int arr [ ] [ 5 ] = { { 0 , 1 , 0 , 0 , 1 } , { 1 , 0 , 1 , 1 , 0 } , { 0 , 1 , 0 , 0 , 1 } , { 1 , 1 , 1 , 0 , 0 } } ; printArray ( arr , 4 , 5 ) ; } |
Find the largest rectangle of 1 's with swapping of columns allowed | C ++ program to find the largest rectangle of 1 's with swapping of columns allowed. ; Returns area of the largest rectangle of 1 's ; An auxiliary array to store count of consecutive 1 's in every column. ; Step 1 : Fill the auxiliary array hist [ ] [ ] ; First row in hist [ ] [ ] is copy of first row in mat [ ] [ ] ; Fill remaining rows of hist [ ] [ ] ; Step 2 : Sort columns of hist [ ] [ ] in non - increasing order ; counting occurrence ; Traverse the count array from right side ; Step 3 : Traverse the sorted hist [ ] [ ] to find maximum area ; Since values are in decreasing order , The area ending with cell ( i , j ) can be obtained by multiplying column number with value of hist [ i ] [ j ] ; Driver program | #include <bits/stdc++.h> NEW_LINE #define R 3 NEW_LINE #define C 5 NEW_LINE using namespace std ; int maxArea ( bool mat [ R ] [ C ] ) { int hist [ R + 1 ] [ C + 1 ] ; for ( int i = 0 ; i < C ; i ++ ) { hist [ 0 ] [ i ] = mat [ 0 ] [ i ] ; for ( int j = 1 ; j < R ; j ++ ) hist [ j ] [ i ] = ( mat [ j ] [ i ] == 0 ) ? 0 : hist [ j - 1 ] [ i ] + 1 ; } for ( int i = 0 ; i < R ; i ++ ) { int count [ R + 1 ] = { 0 } ; for ( int j = 0 ; j < C ; j ++ ) count [ hist [ i ] [ j ] ] ++ ; int col_no = 0 ; for ( int j = R ; j >= 0 ; j -- ) { if ( count [ j ] > 0 ) { for ( int k = 0 ; k < count [ j ] ; k ++ ) { hist [ i ] [ col_no ] = j ; col_no ++ ; } } } } int curr_area , max_area = 0 ; for ( int i = 0 ; i < R ; i ++ ) { for ( int j = 0 ; j < C ; j ++ ) { curr_area = ( j + 1 ) * hist [ i ] [ j ] ; if ( curr_area > max_area ) max_area = curr_area ; } } return max_area ; } int main ( ) { bool mat [ R ] [ C ] = { { 0 , 1 , 0 , 1 , 0 } , { 0 , 1 , 0 , 1 , 1 } , { 1 , 1 , 0 , 1 , 0 } } ; cout << " Area β of β the β largest β rectangle β is β " << maxArea ( mat ) ; return 0 ; } |
Submatrix Sum Queries | C ++ program to compute submatrix query sum in O ( 1 ) time ; Function to preprcess input mat [ M ] [ N ] . This function mainly fills aux [ M ] [ N ] such that aux [ i ] [ j ] stores sum of elements from ( 0 , 0 ) to ( i , j ) ; Copy first row of mat [ ] [ ] to aux [ ] [ ] ; Do column wise sum ; Do row wise sum ; A O ( 1 ) time function to compute sum of submatrix between ( tli , tlj ) and ( rbi , rbj ) using aux [ ] [ ] which is built by the preprocess function ; result is now sum of elements between ( 0 , 0 ) and ( rbi , rbj ) ; Remove elements between ( 0 , 0 ) and ( tli - 1 , rbj ) ; Remove elements between ( 0 , 0 ) and ( rbi , tlj - 1 ) ; Add aux [ tli - 1 ] [ tlj - 1 ] as elements between ( 0 , 0 ) and ( tli - 1 , tlj - 1 ) are subtracted twice ; Driver program | #include <iostream> NEW_LINE using namespace std ; #define M 4 NEW_LINE #define N 5 NEW_LINE int preProcess ( int mat [ M ] [ N ] , int aux [ M ] [ N ] ) { for ( int i = 0 ; i < N ; i ++ ) aux [ 0 ] [ i ] = mat [ 0 ] [ i ] ; for ( int i = 1 ; i < M ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) aux [ i ] [ j ] = mat [ i ] [ j ] + aux [ i - 1 ] [ j ] ; for ( int i = 0 ; i < M ; i ++ ) for ( int j = 1 ; j < N ; j ++ ) aux [ i ] [ j ] += aux [ i ] [ j - 1 ] ; } int sumQuery ( int aux [ M ] [ N ] , int tli , int tlj , int rbi , int rbj ) { int res = aux [ rbi ] [ rbj ] ; if ( tli > 0 ) res = res - aux [ tli - 1 ] [ rbj ] ; if ( tlj > 0 ) res = res - aux [ rbi ] [ tlj - 1 ] ; if ( tli > 0 && tlj > 0 ) res = res + aux [ tli - 1 ] [ tlj - 1 ] ; return res ; } int main ( ) { int mat [ M ] [ N ] = { { 1 , 2 , 3 , 4 , 6 } , { 5 , 3 , 8 , 1 , 2 } , { 4 , 6 , 7 , 5 , 5 } , { 2 , 4 , 8 , 9 , 4 } } ; int aux [ M ] [ N ] ; preProcess ( mat , aux ) ; int tli = 2 , tlj = 2 , rbi = 3 , rbj = 4 ; cout << " Query1 : " tli = 0 , tlj = 0 , rbi = 1 , rbj = 1 ; cout << " Query2 : " tli = 1 , tlj = 2 , rbi = 3 , rbj = 3 ; cout << " Query3 : " return 0 ; } |
Program for Rank of Matrix | C ++ program to find rank of a matrix ; function for exchanging two rows of a matrix ; Function to display a matrix ; function for finding rank of matrix ; Before we visit current row ' row ' , we make sure that mat [ row ] [ 0 ] , ... . mat [ row ] [ row - 1 ] are 0. Diagonal element is not zero ; This makes all entries of current column as 0 except entry ' mat [ row ] [ row ] ' ; Diagonal element is already zero . Two cases arise : 1 ) If there is a row below it with non - zero entry , then swap this row with that row and process that row 2 ) If all elements in current column below mat [ r ] [ row ] are 0 , then remvoe this column by swapping it with last column and reducing number of columns by 1. ; Find the non - zero element in current column ; Swap the row with non - zero element with this row . ; If we did not find any row with non - zero element in current columnm , then all values in this column are 0. ; Reduce number of columns ; Copy the last column here ; Process this row again ; Uncomment these lines to see intermediate results display ( mat , R , C ) ; printf ( " \n " ) ; ; function for displaying the matrix ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define R 3 NEW_LINE #define C 3 NEW_LINE void swap ( int mat [ R ] [ C ] , int row1 , int row2 , int col ) { for ( int i = 0 ; i < col ; i ++ ) { int temp = mat [ row1 ] [ i ] ; mat [ row1 ] [ i ] = mat [ row2 ] [ i ] ; mat [ row2 ] [ i ] = temp ; } } void display ( int mat [ R ] [ C ] , int row , int col ) ; int rankOfMatrix ( int mat [ R ] [ C ] ) { int rank = C ; for ( int row = 0 ; row < rank ; row ++ ) { if ( mat [ row ] [ row ] ) { for ( int col = 0 ; col < R ; col ++ ) { if ( col != row ) { double mult = ( double ) mat [ col ] [ row ] / mat [ row ] [ row ] ; for ( int i = 0 ; i < rank ; i ++ ) mat [ col ] [ i ] -= mult * mat [ row ] [ i ] ; } } } else { bool reduce = true ; for ( int i = row + 1 ; i < R ; i ++ ) { if ( mat [ i ] [ row ] ) { swap ( mat , row , i , rank ) ; reduce = false ; break ; } } if ( reduce ) { rank -- ; for ( int i = 0 ; i < R ; i ++ ) mat [ i ] [ row ] = mat [ i ] [ rank ] ; } row -- ; } } return rank ; } void display ( int mat [ R ] [ C ] , int row , int col ) { for ( int i = 0 ; i < row ; i ++ ) { for ( int j = 0 ; j < col ; j ++ ) printf ( " β % d " , mat [ i ] [ j ] ) ; printf ( " STRNEWLINE " ) ; } } int main ( ) { int mat [ ] [ 3 ] = { { 10 , 20 , 10 } , { -20 , -30 , 10 } , { 30 , 50 , 0 } } ; printf ( " Rank β of β the β matrix β is β : β % d " , rankOfMatrix ( mat ) ) ; return 0 ; } |
Maximum size rectangle binary sub | C ++ program to find largest rectangle with all 1 s in a binary matrix ; Finds the maximum area under the histogram represented by histogram . See below article for details . ; Create an empty stack . The stack holds indexes of hist [ ] array / The bars stored in stack are always in increasing order of their heights . ; Top of stack ; Initialize max area in current ; row ( or histogram ) Initialize area with current top ; Run through all bars of given histogram ( or row ) ; 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 ' ; Now pop the remaining bars from stack and calculate area with every popped bar as the smallest bar ; Returns area of the largest rectangle with all 1 s in A [ ] [ ] ; Calculate area for first row and initialize it as result ; iterate over row to find maximum rectangular area considering each row as histogram ; if A [ i ] [ j ] is 1 then add A [ i - 1 ] [ j ] ; Update result if area with current row ( as last row ) of rectangle ) is more ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define R 4 NEW_LINE #define C 4 NEW_LINE int maxHist ( int row [ ] ) { stack < int > result ; int top_val ; int max_area = 0 ; int area = 0 ; int i = 0 ; while ( i < C ) { if ( result . empty ( ) || row [ result . top ( ) ] <= row [ i ] ) result . push ( i ++ ) ; else { top_val = row [ result . top ( ) ] ; result . pop ( ) ; area = top_val * i ; if ( ! result . empty ( ) ) area = top_val * ( i - result . top ( ) - 1 ) ; max_area = max ( area , max_area ) ; } } while ( ! result . empty ( ) ) { top_val = row [ result . top ( ) ] ; result . pop ( ) ; area = top_val * i ; if ( ! result . empty ( ) ) area = top_val * ( i - result . top ( ) - 1 ) ; max_area = max ( area , max_area ) ; } return max_area ; } int maxRectangle ( int A [ ] [ C ] ) { int result = maxHist ( A [ 0 ] ) ; for ( int i = 1 ; i < R ; i ++ ) { for ( int j = 0 ; j < C ; j ++ ) if ( A [ i ] [ j ] ) A [ i ] [ j ] += A [ i - 1 ] [ j ] ; result = max ( result , maxHist ( A [ i ] ) ) ; } return result ; } int main ( ) { int A [ ] [ C ] = { { 0 , 1 , 1 , 0 } , { 1 , 1 , 1 , 1 } , { 1 , 1 , 1 , 1 } , { 1 , 1 , 0 , 0 } , } ; cout << " Area β of β maximum β rectangle β is β " << maxRectangle ( A ) ; return 0 ; } |
Find sum of all elements in a matrix except the elements in row and / or column of given cell ? | ; A structure to represent a cell index ; r is row , varies from 0 to R - 1 ; c is column , varies from 0 to C - 1 ; A simple solution to find sums for a given array of cell indexes ; Iterate through all cell indexes ; Compute sum for current cell index ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE #define R 3 NEW_LINE #define C 3 NEW_LINE using namespace std ; struct Cell { int r ; int c ; } ; void printSums ( int mat [ ] [ C ] , struct Cell arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { int sum = 0 , r = arr [ i ] . r , c = arr [ i ] . c ; for ( int j = 0 ; j < R ; j ++ ) for ( int k = 0 ; k < C ; k ++ ) if ( j != r && k != c ) sum += mat [ j ] [ k ] ; cout << sum << endl ; } } int main ( ) { int mat [ ] [ C ] = { { 1 , 1 , 2 } , { 3 , 4 , 6 } , { 5 , 3 , 2 } } ; struct Cell arr [ ] = { { 0 , 0 } , { 1 , 1 } , { 0 , 1 } } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printSums ( mat , arr , n ) ; return 0 ; } |
Find sum of all elements in a matrix except the elements in row and / or column of given cell ? | An efficient C ++ program to compute sum for given array of cell indexes ; A structure to represent a cell index ; r is row , varies from 0 to R - 1 ; c is column , varies from 0 to C - 1 ; Compute sum of all elements , sum of every row and sum every column ; Compute the desired sum for all given cell indexes ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE #define R 3 NEW_LINE #define C 3 NEW_LINE using namespace std ; struct Cell { int r ; int c ; } ; void printSums ( int mat [ ] [ C ] , struct Cell arr [ ] , int n ) { int sum = 0 ; int row [ R ] = { } ; int col [ C ] = { } ; for ( int i = 0 ; i < R ; i ++ ) { for ( int j = 0 ; j < C ; j ++ ) { sum += mat [ i ] [ j ] ; col [ j ] += mat [ i ] [ j ] ; row [ i ] += mat [ i ] [ j ] ; } } for ( int i = 0 ; i < n ; i ++ ) { int ro = arr [ i ] . r , co = arr [ i ] . c ; cout << sum - row [ ro ] - col [ co ] + mat [ ro ] [ co ] << endl ; } } int main ( ) { int mat [ ] [ C ] = { { 1 , 1 , 2 } , { 3 , 4 , 6 } , { 5 , 3 , 2 } } ; struct Cell arr [ ] = { { 0 , 0 } , { 1 , 1 } , { 0 , 1 } } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printSums ( mat , arr , n ) ; return 0 ; } |
Count number of islands where every island is row | A C ++ program to count the number of rectangular islands where every island is separated by a line ; This function takes a matrix of ' X ' and ' O ' and returns the number of rectangular islands of ' X ' where no two islands are row - wise or column - wise adjacent , the islands may be diagonaly adjacent ; Initialize result ; Traverse the input matrix ; If current cell is ' X ' , then check whether this is top - leftmost of a rectangle . If yes , then increment count ; Driver program to test above function | #include <iostream> NEW_LINE using namespace std ; #define M 6 NEW_LINE #define N 3 NEW_LINE int countIslands ( int mat [ ] [ N ] ) { int count = 0 ; for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( mat [ i ] [ j ] == ' X ' ) { if ( ( i == 0 mat [ i - 1 ] [ j ] == ' O ' ) && ( j == 0 mat [ i ] [ j - 1 ] == ' O ' ) ) count ++ ; } } } return count ; } int main ( ) { int mat [ M ] [ N ] = { { ' O ' , ' O ' , ' O ' } , { ' X ' , ' X ' , ' O ' } , { ' X ' , ' X ' , ' O ' } , { ' O ' , ' O ' , ' X ' } , { ' O ' , ' O ' , ' X ' } , { ' X ' , ' X ' , ' O ' } } ; cout << " Number β of β rectangular β islands β is β " << countIslands ( mat ) ; return 0 ; } |
Find a common element in all rows of a given row | A C ++ program to find a common element in all rows of a row wise sorted array ; Specify number of rows and columns ; Returns common element in all rows of mat [ M ] [ N ] . If there is no common element , then - 1 is returned ; An array to store indexes of current last column ; To store index of row whose current last element is minimum ; Initialize current last element of all rows ; Initialize min_row as first row ; Keep finding min_row in current last column , till either all elements of last column become same or we hit first column . ; Find minimum in current last column ; eq_count is count of elements equal to minimum in current last column . ; Traverse current last column elements again to update it ; Decrease last column index of a row whose value is more than minimum . ; Reduce last column index by 1 ; If equal count becomes M , return the value ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define M 4 NEW_LINE #define N 5 NEW_LINE int findCommon ( int mat [ M ] [ N ] ) { int column [ M ] ; int min_row ; int i ; for ( i = 0 ; i < M ; i ++ ) column [ i ] = N - 1 ; min_row = 0 ; while ( column [ min_row ] >= 0 ) { for ( i = 0 ; i < M ; i ++ ) { if ( mat [ i ] [ column [ i ] ] < mat [ min_row ] [ column [ min_row ] ] ) min_row = i ; } int eq_count = 0 ; for ( i = 0 ; i < M ; i ++ ) { if ( mat [ i ] [ column [ i ] ] > mat [ min_row ] [ column [ min_row ] ] ) { if ( column [ i ] == 0 ) return -1 ; column [ i ] -= 1 ; } else eq_count ++ ; } if ( eq_count == M ) return mat [ min_row ] [ column [ min_row ] ] ; } return -1 ; } int main ( ) { int mat [ M ] [ N ] = { { 1 , 2 , 3 , 4 , 5 } , { 2 , 4 , 5 , 8 , 10 } , { 3 , 5 , 7 , 9 , 11 } , { 1 , 3 , 5 , 7 , 9 } , } ; int result = findCommon ( mat ) ; if ( result == -1 ) cout << " No β common β element " ; else cout << " Common β element β is β " << result ; return 0 ; } |
Find a common element in all rows of a given row | C ++ implementation of the approach ; Specify number of rows and columns ; Returns common element in all rows of mat [ M ] [ N ] . If there is no common element , then - 1 is returned ; A hash map to store count of elements ; Increment the count of first element of the row ; Starting from the second element of the current row ; If current element is different from the previous element i . e . it is appearing for the first time in the current row ; Find element having count equal to number of rows ; No such element found ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define M 4 NEW_LINE #define N 5 NEW_LINE int findCommon ( int mat [ M ] [ N ] ) { unordered_map < int , int > cnt ; int i , j ; for ( i = 0 ; i < M ; i ++ ) { cnt [ mat [ i ] [ 0 ] ] ++ ; for ( j = 1 ; j < N ; j ++ ) { if ( mat [ i ] [ j ] != mat [ i ] [ j - 1 ] ) cnt [ mat [ i ] [ j ] ] ++ ; } } for ( auto ele : cnt ) { if ( ele . second == M ) return ele . first ; } return -1 ; } int main ( ) { int mat [ M ] [ N ] = { { 1 , 2 , 3 , 4 , 5 } , { 2 , 4 , 5 , 8 , 10 } , { 3 , 5 , 7 , 9 , 11 } , { 1 , 3 , 5 , 7 , 9 } , } ; int result = findCommon ( mat ) ; if ( result == -1 ) cout << " No β common β element " ; else cout << " Common β element β is β " << result ; return 0 ; } |
Given a matrix of β O β and β X β , replace ' O ' with ' X ' if surrounded by ' X ' | A C ++ program to replace all ' O ' s with ' X ' ' s β if β surrounded β by β ' X ' ; Size of given matrix is M X N ; A recursive function to replace previous value ' prevV ' at ' ( x , β y ) ' and all surrounding values of ( x , y ) with new value ' newV ' . ; Base cases ; Replace the color at ( x , y ) ; Recur for north , east , south and west ; Returns size of maximum size subsquare matrix surrounded by ' X ' ; Step 1 : Replace all ' O ' with ' - ' ; Call floodFill for all ' - ' lying on edges Left side ; Right side ; Top side ; Bottom side ; Step 3 : Replace all ' - ' with ' X ' ; Driver program to test above function | #include <iostream> NEW_LINE using namespace std ; #define M 6 NEW_LINE #define N 6 NEW_LINE void floodFillUtil ( char mat [ ] [ N ] , int x , int y , char prevV , char newV ) { if ( x < 0 x > = M y < 0 y > = N ) return ; if ( mat [ x ] [ y ] != prevV ) return ; mat [ x ] [ y ] = newV ; floodFillUtil ( mat , x + 1 , y , prevV , newV ) ; floodFillUtil ( mat , x - 1 , y , prevV , newV ) ; floodFillUtil ( mat , x , y + 1 , prevV , newV ) ; floodFillUtil ( mat , x , y - 1 , prevV , newV ) ; } int replaceSurrounded ( char mat [ ] [ N ] ) { for ( int i = 0 ; i < M ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) if ( mat [ i ] [ j ] == ' O ' ) mat [ i ] [ j ] = ' - ' ; for ( int i = 0 ; i < M ; i ++ ) if ( mat [ i ] [ 0 ] == ' - ' ) floodFillUtil ( mat , i , 0 , ' - ' , ' O ' ) ; for ( int i = 0 ; i < M ; i ++ ) if ( mat [ i ] [ N - 1 ] == ' - ' ) floodFillUtil ( mat , i , N - 1 , ' - ' , ' O ' ) ; for ( int i = 0 ; i < N ; i ++ ) if ( mat [ 0 ] [ i ] == ' - ' ) floodFillUtil ( mat , 0 , i , ' - ' , ' O ' ) ; for ( int i = 0 ; i < N ; i ++ ) if ( mat [ M - 1 ] [ i ] == ' - ' ) floodFillUtil ( mat , M - 1 , i , ' - ' , ' O ' ) ; for ( int i = 0 ; i < M ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) if ( mat [ i ] [ j ] == ' - ' ) mat [ i ] [ j ] = ' X ' ; } int main ( ) { char mat [ ] [ N ] = { { ' X ' , ' O ' , ' X ' , ' O ' , ' X ' , ' X ' } , { ' X ' , ' O ' , ' X ' , ' X ' , ' O ' , ' X ' } , { ' X ' , ' X ' , ' X ' , ' O ' , ' X ' , ' X ' } , { ' O ' , ' X ' , ' X ' , ' X ' , ' X ' , ' X ' } , { ' X ' , ' X ' , ' X ' , ' O ' , ' X ' , ' O ' } , { ' O ' , ' O ' , ' X ' , ' O ' , ' O ' , ' O ' } , } ; replaceSurrounded ( mat ) ; for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) cout << mat [ i ] [ j ] << " β " ; cout << endl ; } return 0 ; } |
Convert a given Binary Tree to Doubly Linked List | Set 2 | A simple inorder traversal based program to convert a Binary Tree to DLL ; A tree node ; A utility function to create a new tree node ; Standard Inorder traversal of tree ; Changes left pointers to work as previous pointers in converted DLL The function simply does inorder traversal of Binary Tree and updates left pointer using previously visited node ; Changes right pointers to work as next pointers in converted DLL ; Find the right most node in BT or last node in DLL ; Start from the rightmost node , traverse back using left pointers . While traversing , change right pointer of nodes . ; The leftmost node is head of linked list , return it ; The main function that converts BST to DLL and returns head of DLL ; Set the previous pointer ; Set the next pointer and return head of DLL ; Traverses the DLL from left tor right ; Driver code ; Let us create the tree shown in above diagram | #include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int data ; node * left , * right ; } ; node * newNode ( int data ) { node * Node = new node ( ) ; Node -> data = data ; Node -> left = Node -> right = NULL ; return ( Node ) ; } void inorder ( node * root ) { if ( root != NULL ) { inorder ( root -> left ) ; cout << " TABSYMBOL " << root -> data ; inorder ( root -> right ) ; } } void fixPrevPtr ( node * root ) { static node * pre = NULL ; if ( root != NULL ) { fixPrevPtr ( root -> left ) ; root -> left = pre ; pre = root ; fixPrevPtr ( root -> right ) ; } } node * fixNextPtr ( node * root ) { node * prev = NULL ; while ( root && root -> right != NULL ) root = root -> right ; while ( root && root -> left != NULL ) { prev = root ; root = root -> left ; root -> right = prev ; } return ( root ) ; } node * BTToDLL ( node * root ) { fixPrevPtr ( root ) ; return fixNextPtr ( root ) ; } void printList ( node * root ) { while ( root != NULL ) { cout << " TABSYMBOL " << root -> data ; root = root -> right ; } } int main ( void ) { node * root = newNode ( 10 ) ; root -> left = newNode ( 12 ) ; root -> right = newNode ( 15 ) ; root -> left -> left = newNode ( 25 ) ; root -> left -> right = newNode ( 30 ) ; root -> right -> left = newNode ( 36 ) ; cout << " Inorder Tree Traversal " ; inorder ( root ) ; node * head = BTToDLL ( root ) ; cout << " DLL Traversal " printList ( head ) ; return 0 ; } |
Given a matrix of ' O ' and ' X ' , find the largest subsquare surrounded by ' X ' | A C ++ program to find the largest subsquare surrounded by ' X ' in a given matrix of ' O ' and ' X ' ; Size of given matrix is N X N ; Initialize maxside with 0 ; Fill the dp matrix horizontally . for contiguous ' X ' increment the value of x , otherwise make it 0 ; Fill the dp matrix vertically . For contiguous ' X ' increment the value of y , otherwise make it 0 ; Now check , for every value of ( i , j ) if sub - square is possible , traverse back horizontally by value val , and check if vertical contiguous ' X ' enfing at ( i , j - val + 1 ) is greater than equal to val . Similarly , check if traversing back vertically , the horizontal contiguous ' X ' ending at ( i - val + 1 , j ) is greater than equal to val . ; store the final answer in maxval ; return the final answe . ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 6 NEW_LINE int maximumSubSquare ( int arr [ ] [ N ] ) { pair < int , int > dp [ 51 ] [ 51 ] ; int maxside [ 51 ] [ 51 ] ; memset ( maxside , 0 , sizeof ( maxside ) ) ; int x = 0 , y = 0 ; for ( int i = 0 ; i < N ; i ++ ) { x = 0 ; for ( int j = 0 ; j < N ; j ++ ) { if ( arr [ i ] [ j ] == ' X ' ) x += 1 ; else x = 0 ; dp [ i ] [ j ] . first = x ; } } for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( arr [ j ] [ i ] == ' X ' ) y += 1 ; else y = 0 ; dp [ j ] [ i ] . second = y ; } } int maxval = 0 , val = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { val = min ( dp [ i ] [ j ] . first , dp [ i ] [ j ] . second ) ; if ( dp [ i ] [ j - val + 1 ] . second >= val && dp [ i - val + 1 ] [ j ] . first >= val ) maxside [ i ] [ j ] = val ; else maxside [ i ] [ j ] = 0 ; maxval = max ( maxval , maxside [ i ] [ j ] ) ; } } return maxval ; } int main ( ) { int mat [ ] [ N ] = { { ' X ' , ' O ' , ' X ' , ' X ' , ' X ' , ' X ' } , { ' X ' , ' O ' , ' X ' , ' X ' , ' O ' , ' X ' } , { ' X ' , ' X ' , ' X ' , ' O ' , ' O ' , ' X ' } , { ' O ' , ' X ' , ' X ' , ' X ' , ' X ' , ' X ' } , { ' X ' , ' X ' , ' X ' , ' O ' , ' X ' , ' O ' } , { ' O ' , ' O ' , ' X ' , ' O ' , ' O ' , ' O ' } , } ; cout << maximumSubSquare ( mat ) ; return 0 ; } |
Flood fill Algorithm | A C ++ program to implement flood fill algorithm ; Dimentions of paint screen ; A recursive function to replace previous color ' prevC ' at ' ( x , β y ) ' and all surrounding pixels of ( x , y ) with new color ' newC ' and ; Base cases ; Replace the color at ( x , y ) ; Recur for north , east , south and west ; It mainly finds the previous color on ( x , y ) and calls floodFillUtil ( ) ; Driver code | #include <iostream> NEW_LINE using namespace std ; #define M 8 NEW_LINE #define N 8 NEW_LINE void floodFillUtil ( int screen [ ] [ N ] , int x , int y , int prevC , int newC ) { if ( x < 0 x > = M y < 0 y > = N ) return ; if ( screen [ x ] [ y ] != prevC ) return ; if ( screen [ x ] [ y ] == newC ) return ; screen [ x ] [ y ] = newC ; floodFillUtil ( screen , x + 1 , y , prevC , newC ) ; floodFillUtil ( screen , x - 1 , y , prevC , newC ) ; floodFillUtil ( screen , x , y + 1 , prevC , newC ) ; floodFillUtil ( screen , x , y - 1 , prevC , newC ) ; } void floodFill ( int screen [ ] [ N ] , int x , int y , int newC ) { int prevC = screen [ x ] [ y ] ; floodFillUtil ( screen , x , y , prevC , newC ) ; } int main ( ) { int screen [ M ] [ N ] = { { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 } , { 1 , 1 , 1 , 1 , 1 , 1 , 0 , 0 } , { 1 , 0 , 0 , 1 , 1 , 0 , 1 , 1 } , { 1 , 2 , 2 , 2 , 2 , 0 , 1 , 0 } , { 1 , 1 , 1 , 2 , 2 , 0 , 1 , 0 } , { 1 , 1 , 1 , 2 , 2 , 2 , 2 , 0 } , { 1 , 1 , 1 , 1 , 1 , 2 , 1 , 1 } , { 1 , 1 , 1 , 1 , 1 , 2 , 2 , 1 } , } ; int x = 4 , y = 4 , newC = 3 ; floodFill ( screen , x , y , newC ) ; cout << " Updated β screen β after β call β to β floodFill : β STRNEWLINE " ; for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) cout << screen [ i ] [ j ] << " β " ; cout << endl ; } } |
Flood fill Algorithm | CPP program for above approach ; Function to check valid coordinate ; Function to run bfs ; Visiing array ; Initialing all as zero ; Creating queue for bfs ; Pushing pair of { x , y } ; Marking { x , y } as visited ; Untill queue is emppty ; Extrating front pair ; Poping front pair of queue ; For Upside Pixel or Cell ; For Downside Pixel or Cell ; For Right side Pixel or Cell ; For Left side Pixel or Cell ; Printing The Changed Matrix Of Pixels ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int validCoord ( int x , int y , int n , int m ) { if ( x < 0 y < 0 ) { return 0 ; } if ( x >= n y >= m ) { return 0 ; } return 1 ; } void bfs ( int n , int m , int data [ ] [ 8 ] , int x , int y , int color ) { int vis [ 101 ] [ 101 ] ; memset ( vis , 0 , sizeof ( vis ) ) ; queue < pair < int , int > > obj ; obj . push ( { x , y } ) ; vis [ x ] [ y ] = 1 ; while ( obj . empty ( ) != 1 ) { pair < int , int > coord = obj . front ( ) ; int x = coord . first ; int y = coord . second ; int preColor = data [ x ] [ y ] ; data [ x ] [ y ] = color ; obj . pop ( ) ; if ( validCoord ( x + 1 , y , n , m ) && vis [ x + 1 ] [ y ] == 0 && data [ x + 1 ] [ y ] == preColor ) { obj . push ( { x + 1 , y } ) ; vis [ x + 1 ] [ y ] = 1 ; } if ( validCoord ( x - 1 , y , n , m ) && vis [ x - 1 ] [ y ] == 0 && data [ x - 1 ] [ y ] == preColor ) { obj . push ( { x - 1 , y } ) ; vis [ x - 1 ] [ y ] = 1 ; } if ( validCoord ( x , y + 1 , n , m ) && vis [ x ] [ y + 1 ] == 0 && data [ x ] [ y + 1 ] == preColor ) { obj . push ( { x , y + 1 } ) ; vis [ x ] [ y + 1 ] = 1 ; } if ( validCoord ( x , y - 1 , n , m ) && vis [ x ] [ y - 1 ] == 0 && data [ x ] [ y - 1 ] == preColor ) { obj . push ( { x , y - 1 } ) ; vis [ x ] [ y - 1 ] = 1 ; } } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { cout << data [ i ] [ j ] << " β " ; } cout << endl ; } cout << endl ; } int main ( ) { int n , m , x , y , color ; n = 8 ; m = 8 ; int data [ 8 ] [ 8 ] = { { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 } , { 1 , 1 , 1 , 1 , 1 , 1 , 0 , 0 } , { 1 , 0 , 0 , 1 , 1 , 0 , 1 , 1 } , { 1 , 2 , 2 , 2 , 2 , 0 , 1 , 0 } , { 1 , 1 , 1 , 2 , 2 , 0 , 1 , 0 } , { 1 , 1 , 1 , 2 , 2 , 2 , 2 , 0 } , { 1 , 1 , 1 , 1 , 1 , 2 , 1 , 1 } , { 1 , 1 , 1 , 1 , 1 , 2 , 2 , 1 } , } ; x = 4 , y = 4 , color = 3 ; bfs ( n , m , data , x , y , color ) ; return 0 ; } |
Convert a given Binary Tree to Doubly Linked List | Set 3 | A C ++ program for in - place conversion of Binary Tree to DLL ; A binary tree node has data , and left and right pointers ; A simple recursive function to convert a given Binary tree to Doubly Linked List root -- > Root of Binary Tree head -- > Pointer to head node of created doubly linked list ; Base case ; Initialize previously visited node as NULL . This is static so that the same value is accessible in all recursive calls ; Recursively convert left subtree ; Now convert this node ; Finally convert right subtree ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Function to print nodes in a given doubly linked list ; Driver program to test above functions ; Let us create the tree shown in above diagram ; Convert to DLL ; Print the converted list | #include <iostream> NEW_LINE using namespace std ; struct node { int data ; node * left ; node * right ; } ; void BinaryTree2DoubleLinkedList ( node * root , node * * head ) { if ( root == NULL ) return ; static node * prev = NULL ; BinaryTree2DoubleLinkedList ( root -> left , head ) ; if ( prev == NULL ) * head = root ; else { root -> left = prev ; prev -> right = root ; } prev = root ; BinaryTree2DoubleLinkedList ( root -> right , head ) ; } node * newNode ( int data ) { node * new_node = new node ; new_node -> data = data ; new_node -> left = new_node -> right = NULL ; return ( new_node ) ; } void printList ( node * node ) { while ( node != NULL ) { cout << node -> data << " β " ; node = node -> right ; } } int main ( ) { node * root = newNode ( 10 ) ; root -> left = newNode ( 12 ) ; root -> right = newNode ( 15 ) ; root -> left -> left = newNode ( 25 ) ; root -> left -> right = newNode ( 30 ) ; root -> right -> left = newNode ( 36 ) ; node * head = NULL ; BinaryTree2DoubleLinkedList ( root , & head ) ; printList ( head ) ; return 0 ; } |
Collect maximum points in a grid using two traversals | A Memoization based program to find maximum collection using two traversals of a grid ; checks whether a given input is valid or not ; Driver function to collect max value ; if P1 or P2 is at an invalid cell ; if both traversals reach their destinations ; If both traversals are at last row but not at their destination ; If subproblem is already solved ; Initialize answer for this subproblem ; this variable is used to store gain of current cell ( s ) ; Recur for all possible cases , then store and return the one with max value ; This is mainly a wrapper over recursive function getMaxUtil ( ) . This function creates a table for memoization and calls getMaxUtil ( ) ; Create a memoization table and initialize all entries as - 1 ; Calculation maximum value using memoization based function getMaxUtil ( ) ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define R 5 NEW_LINE #define C 4 NEW_LINE bool isValid ( int x , int y1 , int y2 ) { return ( x >= 0 && x < R && y1 >= 0 && y1 < C && y2 >= 0 && y2 < C ) ; } int getMaxUtil ( int arr [ R ] [ C ] , int mem [ R ] [ C ] [ C ] , int x , int y1 , int y2 ) { if ( ! isValid ( x , y1 , y2 ) ) return INT_MIN ; if ( x == R - 1 && y1 == 0 && y2 == C - 1 ) return ( y1 == y2 ) ? arr [ x ] [ y1 ] : arr [ x ] [ y1 ] + arr [ x ] [ y2 ] ; if ( x == R - 1 ) return INT_MIN ; if ( mem [ x ] [ y1 ] [ y2 ] != -1 ) return mem [ x ] [ y1 ] [ y2 ] ; int ans = INT_MIN ; int temp = ( y1 == y2 ) ? arr [ x ] [ y1 ] : arr [ x ] [ y1 ] + arr [ x ] [ y2 ] ; ans = max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 , y2 - 1 ) ) ; ans = max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 , y2 + 1 ) ) ; ans = max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 , y2 ) ) ; ans = max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 - 1 , y2 ) ) ; ans = max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 - 1 , y2 - 1 ) ) ; ans = max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 - 1 , y2 + 1 ) ) ; ans = max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 + 1 , y2 ) ) ; ans = max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 + 1 , y2 - 1 ) ) ; ans = max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 + 1 , y2 + 1 ) ) ; return ( mem [ x ] [ y1 ] [ y2 ] = ans ) ; } int geMaxCollection ( int arr [ R ] [ C ] ) { int mem [ R ] [ C ] [ C ] ; memset ( mem , -1 , sizeof ( mem ) ) ; return getMaxUtil ( arr , mem , 0 , 0 , C - 1 ) ; } int main ( ) { int arr [ R ] [ C ] = { { 3 , 6 , 8 , 2 } , { 5 , 2 , 4 , 3 } , { 1 , 1 , 20 , 10 } , { 1 , 1 , 20 , 10 } , { 1 , 1 , 20 , 10 } , } ; cout << " Maximum β collection β is β " << geMaxCollection ( arr ) ; return 0 ; } |
Collect maximum coins before hitting a dead end | A Naive Recursive C ++ program to find maximum number of coins that can be collected before hitting a dead end ; to check whether current cell is out of the grid or not ; dir = 0 for left , dir = 1 for facing right . This function returns number of maximum coins that can be collected starting from ( i , j ) . ; If this is a invalid cell or if cell is a blocking cell ; Check if this cell contains the coin ' C ' or if its empty ' E ' . ; Get the maximum of two cases when you are facing right in this cell Direction is right ; Down ; Ahead in right ; Direction is left Get the maximum of two cases when you are facing left in this cell Down ; Ahead in left ; Driver program to test above function ; As per the question initial cell is ( 0 , 0 ) and direction is right | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define R 5 NEW_LINE #define C 5 NEW_LINE bool isValid ( int i , int j ) { return ( i >= 0 && i < R && j >= 0 && j < C ) ; } int maxCoinsRec ( char arr [ R ] [ C ] , int i , int j , int dir ) { if ( isValid ( i , j ) == false arr [ i ] [ j ] == ' # ' ) return 0 ; int result = ( arr [ i ] [ j ] == ' C ' ) ? 1 : 0 ; if ( dir == 1 ) return result + max ( maxCoinsRec ( arr , i + 1 , j , 0 ) , maxCoinsRec ( arr , i , j + 1 , 1 ) ) ; return result + max ( maxCoinsRec ( arr , i + 1 , j , 1 ) , maxCoinsRec ( arr , i , j - 1 , 0 ) ) ; } int main ( ) { char arr [ R ] [ C ] = { { ' E ' , ' C ' , ' C ' , ' C ' , ' C ' } , { ' C ' , ' # ' , ' C ' , ' # ' , ' E ' } , { ' # ' , ' C ' , ' C ' , ' # ' , ' C ' } , { ' C ' , ' E ' , ' E ' , ' C ' , ' E ' } , { ' C ' , ' E ' , ' # ' , ' C ' , ' E ' } } ; cout << " Maximum β number β of β collected β coins β is β " << maxCoinsRec ( arr , 0 , 0 , 1 ) ; return 0 ; } |
Find length of the longest consecutive path from a given starting character | C ++ program to find the longest consecutive path ; tool matrices to recur for adjacent cells . ; dp [ i ] [ j ] Stores length of longest consecutive path starting at arr [ i ] [ j ] . ; check whether mat [ i ] [ j ] is a valid cell or not . ; Check whether current character is adjacent to previous character ( character processed in parent call ) or not . ; i , j are the indices of the current cell and prev is the character processed in the parent call . . also mat [ i ] [ j ] is our current character . ; If this cell is not valid or current character is not adjacent to previous one ( e . g . d is not adjacent to b ) or if this cell is already included in the path than return 0. ; If this subproblem is already solved , return the answer ; Initialize answer ; recur for paths with different adjacent cells and store the length of longest path . ; save the answer and return ; Returns length of the longest path with all characters consecutive to each other . This function first initializes dp array that is used to store results of subproblems , then it calls recursive DFS based function getLenUtil ( ) to find max length path ; check for each possible starting point ; recur for all eight adjacent cells ; Driver program | #include <bits/stdc++.h> NEW_LINE #define R 3 NEW_LINE #define C 3 NEW_LINE using namespace std ; int x [ ] = { 0 , 1 , 1 , -1 , 1 , 0 , -1 , -1 } ; int y [ ] = { 1 , 0 , 1 , 1 , -1 , -1 , 0 , -1 } ; int dp [ R ] [ C ] ; bool isvalid ( int i , int j ) { if ( i < 0 j < 0 i > = R j > = C ) return false ; return true ; } bool isadjacent ( char prev , char curr ) { return ( ( curr - prev ) == 1 ) ; } int getLenUtil ( char mat [ R ] [ C ] , int i , int j , char prev ) { if ( ! isvalid ( i , j ) || ! isadjacent ( prev , mat [ i ] [ j ] ) ) return 0 ; if ( dp [ i ] [ j ] != -1 ) return dp [ i ] [ j ] ; int ans = 0 ; for ( int k = 0 ; k < 8 ; k ++ ) ans = max ( ans , 1 + getLenUtil ( mat , i + x [ k ] , j + y [ k ] , mat [ i ] [ j ] ) ) ; return dp [ i ] [ j ] = ans ; } int getLen ( char mat [ R ] [ C ] , char s ) { memset ( dp , -1 , sizeof dp ) ; int ans = 0 ; for ( int i = 0 ; i < R ; i ++ ) { for ( int j = 0 ; j < C ; j ++ ) { if ( mat [ i ] [ j ] == s ) { for ( int k = 0 ; k < 8 ; k ++ ) ans = max ( ans , 1 + getLenUtil ( mat , i + x [ k ] , j + y [ k ] , s ) ) ; } } } return ans ; } int main ( ) { char mat [ R ] [ C ] = { { ' a ' , ' c ' , ' d ' } , { ' h ' , ' b ' , ' a ' } , { ' i ' , ' g ' , ' f ' } } ; cout << getLen ( mat , ' a ' ) << endl ; cout << getLen ( mat , ' e ' ) << endl ; cout << getLen ( mat , ' b ' ) << endl ; cout << getLen ( mat , ' f ' ) << endl ; return 0 ; } |
Minimum Initial Points to Reach Destination | C ++ program to find minimum initial points to reach destination ; dp [ i ] [ j ] represents the minimum initial points player should have so that when starts with cell ( i , j ) successfully reaches the destination cell ( m - 1 , n - 1 ) ; Base case ; Fill last row and last column as base to fill entire table ; fill the table in bottom - up fashion ; Driver Program | #include <bits/stdc++.h> NEW_LINE #define R 3 NEW_LINE #define C 3 NEW_LINE using namespace std ; int minInitialPoints ( int points [ ] [ C ] ) { int dp [ R ] [ C ] ; int m = R , n = C ; dp [ m - 1 ] [ n - 1 ] = points [ m - 1 ] [ n - 1 ] > 0 ? 1 : abs ( points [ m - 1 ] [ n - 1 ] ) + 1 ; for ( int i = m - 2 ; i >= 0 ; i -- ) dp [ i ] [ n - 1 ] = max ( dp [ i + 1 ] [ n - 1 ] - points [ i ] [ n - 1 ] , 1 ) ; for ( int j = n - 2 ; j >= 0 ; j -- ) dp [ m - 1 ] [ j ] = max ( dp [ m - 1 ] [ j + 1 ] - points [ m - 1 ] [ j ] , 1 ) ; for ( int i = m - 2 ; i >= 0 ; i -- ) { for ( int j = n - 2 ; j >= 0 ; j -- ) { int min_points_on_exit = min ( dp [ i + 1 ] [ j ] , dp [ i ] [ j + 1 ] ) ; dp [ i ] [ j ] = max ( min_points_on_exit - points [ i ] [ j ] , 1 ) ; } } return dp [ 0 ] [ 0 ] ; } int main ( ) { int points [ R ] [ C ] = { { -2 , -3 , 3 } , { -5 , -10 , 1 } , { 10 , 30 , -5 } } ; cout << " Minimum β Initial β Points β Required : β " << minInitialPoints ( points ) ; return 0 ; } |
Convert an arbitrary Binary Tree to a tree that holds Children Sum Property | C ++ Program to convert an aribitary binary tree to a tree that hold children sum property ; Constructor that allocates a new node with the given data and NULL left and right pointers . ; This function is used to increment left subtree ; This function changes a tree to hold children sum property ; If tree is empty or it 's a leaf node then return true ; convert left and right subtrees ; 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 ; get the diff of node 's data and children sum ; If node ' s β children β sum β is β β β greater β than β the β node ' s data ; THIS IS TRICKY -- > If node 's data is greater than children sum, then increment subtree by diff ; - diff is used to make diff positive ; This function is used to increment subtree by diff ; IF left child is not NULL then increment it ; Recursively call to fix the descendants of node -> left ; Else increment right child ; Recursively call to fix the descendants of node -> right ; Given a binary tree , printInorder ( ) prints out its inorder traversal ; first recur on left child ; then print the data of node ; now recur on right child ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int data ; node * left ; node * right ; node ( int data ) { this -> data = data ; this -> left = NULL ; this -> right = NULL ; } } ; void increment ( node * node , int diff ) ; void convertTree ( node * node ) { int left_data = 0 , right_data = 0 , diff ; if ( node == NULL || ( node -> left == NULL && node -> right == NULL ) ) return ; else { convertTree ( node -> left ) ; convertTree ( node -> right ) ; if ( node -> left != NULL ) left_data = node -> left -> data ; if ( node -> right != NULL ) right_data = node -> right -> data ; diff = left_data + right_data - node -> data ; if ( diff > 0 ) node -> data = node -> data + diff ; if ( diff < 0 ) increment ( node , - diff ) ; } } void increment ( node * node , int diff ) { if ( node -> left != NULL ) { node -> left -> data = node -> left -> data + diff ; increment ( node -> left , diff ) ; } else if ( node -> right != NULL ) { node -> right -> data = node -> right -> data + diff ; increment ( node -> right , diff ) ; } } void printInorder ( node * node ) { if ( node == NULL ) return ; printInorder ( node -> left ) ; cout << node -> data << " β " ; printInorder ( node -> right ) ; } int main ( ) { node * root = new node ( 50 ) ; root -> left = new node ( 7 ) ; root -> right = new node ( 2 ) ; root -> left -> left = new node ( 3 ) ; root -> left -> right = new node ( 5 ) ; root -> right -> left = new node ( 1 ) ; root -> right -> right = new node ( 30 ) ; cout << " Inorder traversal before conversion : " printInorder ( root ) ; convertTree ( root ) ; cout << " Inorder traversal after conversion : " printInorder ( root ) ; return 0 ; } |
Queue using Stacks | CPP program to implement Queue using two stacks with costly enQueue ( ) ; Move all elements from s1 to s2 ; Push item into s1 ; Push everything back to s1 ; Dequeue an item from the queue ; if first stack is empty ; Return top of s1 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Queue { stack < int > s1 , s2 ; void enQueue ( int x ) { while ( ! s1 . empty ( ) ) { s2 . push ( s1 . top ( ) ) ; s1 . pop ( ) ; } s1 . push ( x ) ; while ( ! s2 . empty ( ) ) { s1 . push ( s2 . top ( ) ) ; s2 . pop ( ) ; } } int deQueue ( ) { if ( s1 . empty ( ) ) { cout << " Q β is β Empty " ; exit ( 0 ) ; } int x = s1 . top ( ) ; s1 . pop ( ) ; return x ; } } ; int main ( ) { Queue q ; q . enQueue ( 1 ) ; q . enQueue ( 2 ) ; q . enQueue ( 3 ) ; cout << q . deQueue ( ) << ' ' ; cout << q . deQueue ( ) << ' ' ; cout << q . deQueue ( ) << ' ' ; return 0 ; } |
Convert left | C ++ program to convert left - right to down - right representation of binary tree ; A Binary Tree Node ; An Iterative level order traversal based function to convert left - right to down - right representation . ; Base Case ; Recursively convert left an right subtrees ; If left child is NULL , make right child as left as it is the first child . ; If left child is NOT NULL , then make right child as right of left child ; Set root 's right as NULL ; A utility function to traverse a tree stored in down - right form . ; Utility function to create a new tree node ; Driver program to test above functions ; 1 / \ 2 3 / \ 4 5 / / \ 6 7 8 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int key ; struct node * left , * right ; } ; void convert ( node * root ) { if ( root == NULL ) return ; convert ( root -> left ) ; convert ( root -> right ) ; if ( root -> left == NULL ) root -> left = root -> right ; else root -> left -> right = root -> right ; root -> right = NULL ; } void downRightTraversal ( node * root ) { if ( root != NULL ) { cout << root -> key << " β " ; downRightTraversal ( root -> right ) ; downRightTraversal ( root -> left ) ; } } node * newNode ( int key ) { node * temp = new node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return temp ; } int main ( ) { node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> right -> left = newNode ( 4 ) ; root -> right -> right = newNode ( 5 ) ; root -> right -> left -> left = newNode ( 6 ) ; root -> right -> right -> left = newNode ( 7 ) ; root -> right -> right -> right = newNode ( 8 ) ; convert ( root ) ; cout << " Traversal β of β the β tree β converted β to β down - right β form STRNEWLINE " ; downRightTraversal ( root ) ; return 0 ; } |
Design and Implement Special Stack Data Structure | Added Space Optimized Version | SpecialStack 's member method to insert an element to it. This method makes sure that the min stack is also updated with appropriate minimum values ; push only when the incoming element of main stack is smaller than or equal to top of auxiliary stack ; SpecialStack 's member method to remove an element from it. This method removes top element from min stack also. ; Push the popped element y back only if it is not equal to x | void SpecialStack :: push ( int x ) { if ( isEmpty ( ) == true ) { Stack :: push ( x ) ; min . push ( x ) ; } else { Stack :: push ( x ) ; int y = min . pop ( ) ; min . push ( y ) ; if ( x <= y ) min . push ( x ) ; } } int SpecialStack :: pop ( ) { int x = Stack :: pop ( ) ; int y = min . pop ( ) ; if ( y != x ) min . push ( y ) ; return x ; } |
Convert a given tree to its Sum Tree | C ++ program to convert a tree into its sum tree ; A tree node structure ; Convert a given tree to a tree where every node contains sum of values of nodes in left and right subtrees in the original tree ; Base case ; Store the old value ; Recursively call for left and right subtrees and store the sum as new value of this node ; Return the sum of values of nodes in left and right subtrees and old_value of this node ; A utility function to print inorder traversal of a Binary Tree ; Utility function to create a new Binary Tree node ; Driver code ; Constructing tree given in the above figure ; Print inorder traversal of the converted tree to test result of toSumTree ( ) | #include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int data ; node * left ; node * right ; } ; int toSumTree ( node * Node ) { if ( Node == NULL ) return 0 ; int old_val = Node -> data ; Node -> data = toSumTree ( Node -> left ) + toSumTree ( Node -> right ) ; return Node -> data + old_val ; } void printInorder ( node * Node ) { if ( Node == NULL ) return ; printInorder ( Node -> left ) ; cout << " β " << Node -> data ; printInorder ( Node -> right ) ; } node * newNode ( int data ) { node * temp = new node ; temp -> data = data ; temp -> left = NULL ; temp -> right = NULL ; return temp ; } int main ( ) { node * root = NULL ; int x ; root = newNode ( 10 ) ; root -> left = newNode ( -2 ) ; root -> right = newNode ( 6 ) ; root -> left -> left = newNode ( 8 ) ; root -> left -> right = newNode ( -4 ) ; root -> right -> left = newNode ( 7 ) ; root -> right -> right = newNode ( 5 ) ; toSumTree ( root ) ; cout << " Inorder β Traversal β of β the β resultant β tree β is : β STRNEWLINE " ; printInorder ( root ) ; return 0 ; } |
Find a peak element | A C ++ program to find a peak element ; Find the peak element in the array ; first or last element is peak element ; check for every other element ; check if the neighbors are smaller ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findPeak ( int arr [ ] , int n ) { if ( n == 1 ) return 0 ; if ( arr [ 0 ] >= arr [ 1 ] ) return 0 ; if ( arr [ n - 1 ] >= arr [ n - 2 ] ) return n - 1 ; for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( arr [ i ] >= arr [ i - 1 ] && arr [ i ] >= arr [ i + 1 ] ) return i ; } } int main ( ) { int arr [ ] = { 1 , 3 , 20 , 4 , 1 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Index β of β a β peak β point β is β " << findPeak ( arr , n ) ; return 0 ; } |
Find a peak element | A C ++ program to find a peak element using divide and conquer ; A binary search based function that returns index of a peak element ; Find index of middle element ( low + high ) / 2 ; Compare middle element with its neighbours ( if neighbours exist ) ; If middle element is not peak and its left neighbour is greater than it , then left half must have a peak element ; If middle element is not peak and its right neighbour is greater than it , then right half must have a peak element ; A wrapper over recursive function findPeakUtil ( ) ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findPeakUtil ( int arr [ ] , int low , int high , int n ) { int mid = low + ( high - low ) / 2 ; if ( ( mid == 0 arr [ mid - 1 ] <= arr [ mid ] ) && ( mid == n - 1 arr [ mid + 1 ] <= arr [ mid ] ) ) return mid ; else if ( mid > 0 && arr [ mid - 1 ] > arr [ mid ] ) return findPeakUtil ( arr , low , ( mid - 1 ) , n ) ; else return findPeakUtil ( arr , ( mid + 1 ) , high , n ) ; } int findPeak ( int arr [ ] , int n ) { return findPeakUtil ( arr , 0 , n - 1 , n ) ; } int main ( ) { int arr [ ] = { 1 , 3 , 20 , 4 , 1 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Index β of β a β peak β point β is β " << findPeak ( arr , n ) ; return 0 ; } |
Find the two repeating elements in a given array | C ++ program to Find the two repeating elements in a given array ; Print Repeating function ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printRepeating ( int arr [ ] , int size ) { int i , j ; printf ( " β Repeating β elements β are β " ) ; for ( i = 0 ; i < size ; i ++ ) for ( j = i + 1 ; j < size ; j ++ ) if ( arr [ i ] == arr [ j ] ) cout << arr [ i ] << " β " ; } int main ( ) { int arr [ ] = { 4 , 2 , 4 , 5 , 2 , 3 , 1 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printRepeating ( arr , arr_size ) ; } |
Find the two repeating elements in a given array | C ++ implementation of above approach ; Function ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printRepeating ( int arr [ ] , int size ) { int * count = new int [ sizeof ( int ) * ( size - 2 ) ] ; int i ; cout << " β Repeating β elements β are β " ; for ( i = 0 ; i < size ; i ++ ) { if ( count [ arr [ i ] ] == 1 ) cout << arr [ i ] << " β " ; else count [ arr [ i ] ] ++ ; } } int main ( ) { int arr [ ] = { 4 , 2 , 4 , 5 , 2 , 3 , 1 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printRepeating ( arr , arr_size ) ; return 0 ; } |
Find the two repeating elements in a given array | ; printRepeating function ; S is for sum of elements in arr [ ] ; P is for product of elements in arr [ ] ; x and y are two repeating elements ; D is for difference of x and y , i . e . , x - y ; Calculate Sum and Product of all elements in arr [ ] ; S is x + y now ; P is x * y now ; D is x - y now ; factorial of n ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int fact ( int n ) ; void printRepeating ( int arr [ ] , int size ) { int S = 0 ; int P = 1 ; int x , y ; int D ; int n = size - 2 , i ; for ( i = 0 ; i < size ; i ++ ) { S = S + arr [ i ] ; P = P * arr [ i ] ; } S = S - n * ( n + 1 ) / 2 ; P = P / fact ( n ) ; D = sqrt ( S * S - 4 * P ) ; x = ( D + S ) / 2 ; y = ( S - D ) / 2 ; cout << " The β two β Repeating β elements β are β " << x << " β & β " << y ; } int fact ( int n ) { return ( n == 0 ) ? 1 : n * fact ( n - 1 ) ; } int main ( ) { int arr [ ] = { 4 , 2 , 4 , 5 , 2 , 3 , 1 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printRepeating ( arr , arr_size ) ; return 0 ; } |
Find the two repeating elements in a given array | C ++ code to Find the two repeating elements in a given array ; Will hold Xor of all elements ; Will have only single set bit of Xor ; Get the Xor of all elements in arr [ ] and { 1 , 2 . . n } ; Get the rightmost set bit in set_bit_no ; Now divide elements in two sets by comparing rightmost set bit of Xor with bit at same position in each element . ; Xor of first set in arr [ ] ; Xor of second set in arr [ ] ; Xor of first set in arr [ ] and { 1 , 2 , ... n } ; Xor of second set in arr [ ] and { 1 , 2 , ... n } ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printRepeating ( int arr [ ] , int size ) { int Xor = arr [ 0 ] ; int set_bit_no ; int i ; int n = size - 2 ; int x = 0 , y = 0 ; for ( i = 1 ; i < size ; i ++ ) Xor ^= arr [ i ] ; for ( i = 1 ; i <= n ; i ++ ) Xor ^= i ; set_bit_no = Xor & ~ ( Xor - 1 ) ; for ( i = 0 ; i < size ; i ++ ) { if ( arr [ i ] & set_bit_no ) x = x ^ arr [ i ] ; else y = y ^ arr [ i ] ; } for ( i = 1 ; i <= n ; i ++ ) { if ( i & set_bit_no ) x = x ^ i ; else y = y ^ i ; } cout << " The β two β repeating β elements β are β " << y << " β " << x ; } int main ( ) { int arr [ ] = { 4 , 2 , 4 , 5 , 2 , 3 , 1 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printRepeating ( arr , arr_size ) ; return 0 ; } |
Find the two repeating elements in a given array | ; Function to print repeating ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printRepeating ( int arr [ ] , int size ) { int i ; cout << " The β repeating β elements β are " ; for ( i = 0 ; i < size ; i ++ ) { if ( arr [ abs ( arr [ i ] ) ] > 0 ) arr [ abs ( arr [ i ] ) ] = - arr [ abs ( arr [ i ] ) ] ; else cout << " β " << abs ( arr [ i ] ) << " β " ; } } int main ( ) { int arr [ ] = { 4 , 2 , 4 , 5 , 2 , 3 , 1 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printRepeating ( arr , arr_size ) ; return 0 ; } |
Find subarray with given sum | Set 1 ( Nonnegative Numbers ) | A simple program to print subarray with sum as given sum ; Returns true if the there is a subarray of arr [ ] with sum equal to ' sum ' otherwise returns false . Also , prints the result ; Pick a starting point ; try all subarrays starting with ' i ' ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int subArraySum ( int arr [ ] , int n , int sum ) { int curr_sum , i , j ; for ( i = 0 ; i < n ; i ++ ) { curr_sum = arr [ i ] ; for ( j = i + 1 ; j <= n ; j ++ ) { if ( curr_sum == sum ) { cout << " Sum β found β between β indexes β " << i << " β and β " << j - 1 ; return 1 ; } if ( curr_sum > sum j == n ) break ; curr_sum = curr_sum + arr [ j ] ; } } cout << " No β subarray β found " ; return 0 ; } int main ( ) { int arr [ ] = { 15 , 2 , 4 , 8 , 9 , 5 , 10 , 23 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int sum = 23 ; subArraySum ( arr , n , sum ) ; return 0 ; } |
Find subarray with given sum | Set 1 ( Nonnegative Numbers ) | An efficient program to print subarray with sum as given sum ; Returns true if the there is a subarray of arr [ ] with a sum equal to ' sum ' otherwise returns false . Also , prints the result ; Initialize curr_sum as value of first element and starting point as 0 ; Add elements one by one to curr_sum and if the curr_sum exceeds the sum , then remove starting element ; If curr_sum exceeds the sum , then remove the starting elements ; If curr_sum becomes equal to sum , then return true ; Add this element to curr_sum ; If we reach here , then no subarray ; Driver Code | #include <iostream> NEW_LINE using namespace std ; int subArraySum ( int arr [ ] , int n , int sum ) { int curr_sum = arr [ 0 ] , start = 0 , i ; for ( i = 1 ; i <= n ; i ++ ) { while ( curr_sum > sum && start < i - 1 ) { curr_sum = curr_sum - arr [ start ] ; start ++ ; } if ( curr_sum == sum ) { cout << " Sum β found β between β indexes β " << start << " β and β " << i - 1 ; return 1 ; } if ( i < n ) curr_sum = curr_sum + arr [ i ] ; } cout << " No β subarray β found " ; return 0 ; } int main ( ) { int arr [ ] = { 15 , 2 , 4 , 8 , 9 , 5 , 10 , 23 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int sum = 23 ; subArraySum ( arr , n , sum ) ; return 0 ; } |
Smallest Difference Triplet from Three arrays | C ++ implementation of smallest difference triplet ; function to find maximum number ; function to find minimum number ; Finds and prints the smallest Difference Triplet ; sorting all the three arrays ; To store resultant three numbers ; pointers to arr1 , arr2 , arr3 respectively ; Loop until one array reaches to its end Find the smallest difference . ; maximum number ; Find minimum and increment its index . ; comparing new difference with the previous one and updating accordingly ; Print result ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximum ( int a , int b , int c ) { return max ( max ( a , b ) , c ) ; } int minimum ( int a , int b , int c ) { return min ( min ( a , b ) , c ) ; } void smallestDifferenceTriplet ( int arr1 [ ] , int arr2 [ ] , int arr3 [ ] , int n ) { sort ( arr1 , arr1 + n ) ; sort ( arr2 , arr2 + n ) ; sort ( arr3 , arr3 + n ) ; int res_min , res_max , res_mid ; int i = 0 , j = 0 , k = 0 ; int diff = INT_MAX ; while ( i < n && j < n && k < n ) { int sum = arr1 [ i ] + arr2 [ j ] + arr3 [ k ] ; int max = maximum ( arr1 [ i ] , arr2 [ j ] , arr3 [ k ] ) ; int min = minimum ( arr1 [ i ] , arr2 [ j ] , arr3 [ k ] ) ; if ( min == arr1 [ i ] ) i ++ ; else if ( min == arr2 [ j ] ) j ++ ; else k ++ ; if ( diff > ( max - min ) ) { diff = max - min ; res_max = max ; res_mid = sum - ( max + min ) ; res_min = min ; } } cout << res_max << " , β " << res_mid << " , β " << res_min ; } int main ( ) { int arr1 [ ] = { 5 , 2 , 8 } ; int arr2 [ ] = { 10 , 7 , 12 } ; int arr3 [ ] = { 9 , 14 , 6 } ; int n = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; smallestDifferenceTriplet ( arr1 , arr2 , arr3 , n ) ; return 0 ; } |
Find a triplet that sum to a given value | ; returns true if there is triplet with sum equal to ' sum ' present in A [ ] . Also , prints the triplet ; Fix the first element as A [ i ] ; Fix the second element as A [ j ] ; Now look for the third number ; If we reach here , then no triplet was found ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool find3Numbers ( int A [ ] , int arr_size , int sum ) { int l , r ; for ( int i = 0 ; i < arr_size - 2 ; i ++ ) { for ( int j = i + 1 ; j < arr_size - 1 ; j ++ ) { for ( int k = j + 1 ; k < arr_size ; k ++ ) { if ( A [ i ] + A [ j ] + A [ k ] == sum ) { cout << " Triplet β is β " << A [ i ] << " , β " << A [ j ] << " , β " << A [ k ] ; return true ; } } } } return false ; } int main ( ) { int A [ ] = { 1 , 4 , 45 , 6 , 10 , 8 } ; int sum = 22 ; int arr_size = sizeof ( A ) / sizeof ( A [ 0 ] ) ; find3Numbers ( A , arr_size , sum ) ; return 0 ; } |
Find a triplet that sum to a given value | C ++ program to find a triplet ; returns true if there is triplet with sum equal to ' sum ' present in A [ ] . Also , prints the triplet ; Sort the elements ; Now fix the first element one by one and find the other two elements ; To find the other two elements , start two index variables from two corners of the array and move them toward each other index of the first element in the ; remaining elements index of the last element ; A [ i ] + A [ l ] + A [ r ] > sum ; If we reach here , then no triplet was found ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool find3Numbers ( int A [ ] , int arr_size , int sum ) { int l , r ; sort ( A , A + arr_size ) ; for ( int i = 0 ; i < arr_size - 2 ; i ++ ) { l = i + 1 ; r = arr_size - 1 ; while ( l < r ) { if ( A [ i ] + A [ l ] + A [ r ] == sum ) { printf ( " Triplet β is β % d , β % d , β % d " , A [ i ] , A [ l ] , A [ r ] ) ; return true ; } else if ( A [ i ] + A [ l ] + A [ r ] < sum ) l ++ ; else r -- ; } } return false ; } int main ( ) { int A [ ] = { 1 , 4 , 45 , 6 , 10 , 8 } ; int sum = 22 ; int arr_size = sizeof ( A ) / sizeof ( A [ 0 ] ) ; find3Numbers ( A , arr_size , sum ) ; return 0 ; } |
Find a triplet that sum to a given value | C ++ program to find a triplet using Hashing ; returns true if there is triplet with sum equal to ' sum ' present in A [ ] . Also , prints the triplet ; Fix the first element as A [ i ] ; Find pair in subarray A [ i + 1. . n - 1 ] with sum equal to sum - A [ i ] ; If we reach here , then no triplet was found ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool find3Numbers ( int A [ ] , int arr_size , int sum ) { for ( int i = 0 ; i < arr_size - 2 ; i ++ ) { unordered_set < int > s ; int curr_sum = sum - A [ i ] ; for ( int j = i + 1 ; j < arr_size ; j ++ ) { if ( s . find ( curr_sum - A [ j ] ) != s . end ( ) ) { printf ( " Triplet β is β % d , β % d , β % d " , A [ i ] , A [ j ] , curr_sum - A [ j ] ) ; return true ; } s . insert ( A [ j ] ) ; } } return false ; } int main ( ) { int A [ ] = { 1 , 4 , 45 , 6 , 10 , 8 } ; int sum = 22 ; int arr_size = sizeof ( A ) / sizeof ( A [ 0 ] ) ; find3Numbers ( A , arr_size , sum ) ; return 0 ; } |
Subarray / Substring vs Subsequence and Programs to Generate them | C ++ code to generate all possible subarrays / subArrays Complexity - O ( n ^ 3 ) ; Prints all subarrays in arr [ 0. . n - 1 ] ; Pick starting point ; Pick ending point ; Print subarray between current starting and ending points ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void subArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { for ( int k = i ; k <= j ; k ++ ) cout << arr [ k ] << " β " ; cout << endl ; } } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " All β Non - empty β Subarrays STRNEWLINE " ; subArray ( arr , n ) ; return 0 ; } |
Subarray / Substring vs Subsequence and Programs to Generate them | C ++ code to generate all possible subsequences . Time Complexity O ( n * 2 ^ n ) ; Number of subsequences is ( 2 * * n - 1 ) ; Run from counter 000. . 1 to 111. . 1 ; Check if jth bit in the counter is set If set then print jth element from arr [ ] ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printSubsequences ( int arr [ ] , int n ) { unsigned int opsize = pow ( 2 , n ) ; for ( int counter = 1 ; counter < opsize ; counter ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( counter & ( 1 << j ) ) cout << arr [ j ] << " β " ; } cout << endl ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " All β Non - empty β Subsequences STRNEWLINE " ; printSubsequences ( arr , n ) ; return 0 ; } |
A Product Array Puzzle | C ++ implementation of above approach ; Function to print product array for a given array arr [ ] of size n ; Base case ; Allocate memory for the product array ; Initialize the product array as 1 ; In this loop , temp variable contains product of elements on left side excluding arr [ i ] ; Initialize temp to 1 for product on right side ; In this loop , temp variable contains product of elements on right side excluding arr [ i ] ; print the constructed prod array ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void productArray ( int arr [ ] , int n ) { if ( n == 1 ) { cout << 0 ; return ; } int i , temp = 1 ; int * prod = new int [ ( sizeof ( int ) * n ) ] ; memset ( prod , 1 , n ) ; for ( i = 0 ; i < n ; i ++ ) { prod [ i ] = temp ; temp *= arr [ i ] ; } temp = 1 ; for ( i = n - 1 ; i >= 0 ; i -- ) { prod [ i ] *= temp ; temp *= arr [ i ] ; } for ( i = 0 ; i < n ; i ++ ) cout << prod [ i ] << " β " ; return ; } int main ( ) { int arr [ ] = { 10 , 3 , 5 , 6 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " The β product β array β is : β STRNEWLINE " ; productArray ( arr , n ) ; } |
A Product Array Puzzle | C ++ program for the above approach ; product of all elements ; counting number of elements which have value 0 ; creating a new array of size n ; if number of elements in array with value 0 is more than 1 than each value in new array will be equal to 0 ; if no element having value 0 than we will insert product / a [ i ] in new array ; if 1 element of array having value 0 than all the elements except that index value , will be equal to 0 ; if ( flag == 1 && a [ i ] == 0 ) ; Driver Code | #include <iostream> NEW_LINE using namespace std ; long * productExceptSelf ( int a [ ] , int n ) { long prod = 1 ; long flag = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == 0 ) flag ++ ; else prod *= a [ i ] ; } long * arr = new long [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( flag > 1 ) { arr [ i ] = 0 ; } else if ( flag == 0 ) arr [ i ] = ( prod / a [ i ] ) ; else if ( flag == 1 && a [ i ] != 0 ) { arr [ i ] = 0 ; } else arr [ i ] = prod ; } return arr ; } int main ( ) { int n = 5 ; int array [ ] = { 10 , 3 , 5 , 6 , 2 } ; long * ans ; ans = productExceptSelf ( array , n ) ; for ( int i = 0 ; i < n ; i ++ ) { cout << ans [ i ] << " β " ; } return 0 ; } |
Check if array elements are consecutive | Added Method 3 | ; Helper functions to get minimum and maximum in an array ; The function checks if the array elements are consecutive If elements are consecutive , then returns true , else returns false ; 1 ) Get the minimum element in array ; 2 ) Get the maximum element in array ; 3 ) max - min + 1 is equal to n , then only check all elements ; Create a temp array to hold visited flag of all elements . Note that , calloc is used here so that all values are initialized as false ; If we see an element again , then return false ; If visited first time , then mark the element as visited ; If all elements occur once , then return true ; if ( max - min + 1 != n ) ; UTILITY FUNCTIONS ; Driver program to test above functions | #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int getMin ( int arr [ ] , int n ) ; int getMax ( int arr [ ] , int n ) ; bool areConsecutive ( int arr [ ] , int n ) { if ( n < 1 ) return false ; int min = getMin ( arr , n ) ; int max = getMax ( arr , n ) ; if ( max - min + 1 == n ) { bool * visited = ( bool * ) calloc ( n , sizeof ( bool ) ) ; int i ; for ( i = 0 ; i < n ; i ++ ) { if ( visited [ arr [ i ] - min ] != false ) return false ; visited [ arr [ i ] - min ] = true ; } return true ; } return false ; } int getMin ( int arr [ ] , int n ) { int min = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] < min ) min = arr [ i ] ; return min ; } int getMax ( int arr [ ] , int n ) { int max = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] > max ) max = arr [ i ] ; return max ; } int main ( ) { int arr [ ] = { 5 , 4 , 2 , 3 , 1 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( areConsecutive ( arr , n ) == true ) printf ( " β Array β elements β are β consecutive β " ) ; else printf ( " β Array β elements β are β not β consecutive β " ) ; getchar ( ) ; return 0 ; } |
Check if array elements are consecutive | Added Method 3 | ; Helper functions to get minimum and maximum in an array ; The function checks if the array elements are consecutive If elements are consecutive , then returns true , else returns false ; 1 ) Get the minimum element in array ; 2 ) Get the maximum element in array ; 3 ) max - min + 1 is equal to n then only check all elements ; if the value at index j is negative then there is repetition ; If we do not see a negative value then all elements are distinct ; if ( max - min + 1 != n ) ; UTILITY FUNCTIONS ; Driver program to test above functions | #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int getMin ( int arr [ ] , int n ) ; int getMax ( int arr [ ] , int n ) ; bool areConsecutive ( int arr [ ] , int n ) { if ( n < 1 ) return false ; int min = getMin ( arr , n ) ; int max = getMax ( arr , n ) ; if ( max - min + 1 == n ) { int i ; for ( i = 0 ; i < n ; i ++ ) { int j ; if ( arr [ i ] < 0 ) j = - arr [ i ] - min ; else j = arr [ i ] - min ; if ( arr [ j ] > 0 ) arr [ j ] = - arr [ j ] ; else return false ; } return true ; } return false ; } int getMin ( int arr [ ] , int n ) { int min = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] < min ) min = arr [ i ] ; return min ; } int getMax ( int arr [ ] , int n ) { int max = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] > max ) max = arr [ i ] ; return max ; } int main ( ) { int arr [ ] = { 1 , 4 , 5 , 3 , 2 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( areConsecutive ( arr , n ) == true ) printf ( " β Array β elements β are β consecutive β " ) ; else printf ( " β Array β elements β are β not β consecutive β " ) ; getchar ( ) ; return 0 ; } |
Find relative complement of two sorted arrays | CPP program to find all those elements of arr1 [ ] that are not present in arr2 [ ] ; If current element in arr2 [ ] is greater , then arr1 [ i ] can 't be present in arr2[j..m-1] ; Skipping smaller elements of arr2 [ ] ; Equal elements found ( skipping in both arrays ) ; Printing remaining elements of arr1 [ ] ; Driver code | #include <iostream> NEW_LINE using namespace std ; void relativeComplement ( int arr1 [ ] , int arr2 [ ] , int n , int m ) { int i = 0 , j = 0 ; while ( i < n && j < m ) { if ( arr1 [ i ] < arr2 [ j ] ) { cout << arr1 [ i ] << " β " ; i ++ ; } else if ( arr1 [ i ] > arr2 [ j ] ) { j ++ ; } else if ( arr1 [ i ] == arr2 [ j ] ) { i ++ ; j ++ ; } } while ( i < n ) cout << arr1 [ i ] << " β " ; } int main ( ) { int arr1 [ ] = { 3 , 6 , 10 , 12 , 15 } ; int arr2 [ ] = { 1 , 3 , 5 , 10 , 16 } ; int n = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int m = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; relativeComplement ( arr1 , arr2 , n , m ) ; return 0 ; } |
Minimum increment by k operations to make all elements equal | Program to make all array equal ; function for calculating min operations ; max elements of array ; iterate for all elements ; check if element can make equal to max or not if not then return - 1 ; else update res for required operations ; return result ; driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minOps ( int arr [ ] , int n , int k ) { int max = * max_element ( arr , arr + n ) ; int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( max - arr [ i ] ) % k != 0 ) return -1 ; else res += ( max - arr [ i ] ) / k ; } return res ; } int main ( ) { int arr [ ] = { 21 , 33 , 9 , 45 , 63 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 6 ; cout << minOps ( arr , n , k ) ; return 0 ; } |
Minimize ( max ( A [ i ] , B [ j ] , C [ k ] ) | C ++ code for above approach ; calculating min difference from last index of lists ; checking condition ; calculating max term from list ; Moving to smaller value in the array with maximum out of three . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( int A [ ] , int B [ ] , int C [ ] , int i , int j , int k ) { int min_diff , current_diff , max_term ; min_diff = Integer . MAX_VALUE ; while ( i != -1 && j != -1 && k != -1 ) { current_diff = abs ( max ( A [ i ] , max ( B [ j ] , C [ k ] ) ) - min ( A [ i ] , min ( B [ j ] , C [ k ] ) ) ) ; if ( current_diff < min_diff ) min_diff = current_diff ; max_term = max ( A [ i ] , max ( B [ j ] , C [ k ] ) ) ; if ( A [ i ] == max_term ) i -= 1 ; else if ( B [ j ] == max_term ) j -= 1 ; else k -= 1 ; } return min_diff ; } int main ( ) { int D [ ] = { 5 , 8 , 10 , 15 } ; int E [ ] = { 6 , 9 , 15 , 78 , 89 } ; int F [ ] = { 2 , 3 , 6 , 6 , 8 , 8 , 10 } ; int nD = sizeof ( D ) / sizeof ( D [ 0 ] ) ; int nE = sizeof ( E ) / sizeof ( E [ 0 ] ) ; int nF = sizeof ( F ) / sizeof ( F [ 0 ] ) ; cout << solve ( D , E , F , nD - 1 , nE - 1 , nF - 1 ) ; return 0 ; } |
Analysis of Algorithms | Set 2 ( Worst , Average and Best Cases ) | C ++ implementation of the approach ; Linearly search x in arr [ ] . If x is present then return the index , otherwise return - 1 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int search ( int arr [ ] , int n , int x ) { int i ; for ( i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == x ) return i ; } return -1 ; } int main ( ) { int arr [ ] = { 1 , 10 , 30 , 15 } ; int x = 30 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << x << " β is β present β at β index β " << search ( arr , n , x ) ; getchar ( ) ; return 0 ; } |
Binary Search | C ++ program to implement recursive Binary Search ; A recursive binary search function . It returns location of x in given array arr [ l . . r ] is present , otherwise - 1 ; If the element is present at the middle itself ; If element is smaller than mid , then it can only be present in left subarray ; Else the element can only be present in right subarray ; We reach here when element is not present in array ; Driver method to test above | #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 ) ; } return -1 ; } int main ( void ) { int arr [ ] = { 2 , 3 , 4 , 10 , 40 } ; int x = 10 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int result = binarySearch ( arr , 0 , n - 1 , x ) ; ( result == -1 ) ? cout << " Element β is β not β present β in β array " : cout << " Element β is β present β at β index β " << result ; return 0 ; } |
Binary Search | C ++ program to implement recursive Binary Search ; A iterative binary search function . It returns location of x in given array arr [ l . . r ] if present , otherwise - 1 ; Check if x is present at mid ; If x greater , ignore left half ; If x is smaller , ignore right half ; if we reach here , then element was not present ; Driver method to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; int binarySearch ( int arr [ ] , int l , int r , int x ) { while ( l <= r ) { int m = l + ( r - l ) / 2 ; if ( arr [ m ] == x ) return m ; if ( arr [ m ] < x ) l = m + 1 ; else r = m - 1 ; } return -1 ; } int main ( void ) { int arr [ ] = { 2 , 3 , 4 , 10 , 40 } ; int x = 10 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int result = binarySearch ( arr , 0 , n - 1 , x ) ; ( result == -1 ) ? cout << " Element β is β not β present β in β array " : cout << " Element β is β present β at β index β " << result ; return 0 ; } |
Jump Search | C ++ program to implement Jump Search ; Finding block size to be jumped ; Finding the block where element is present ( if it is present ) ; Doing a linear search for x in block beginning with prev . ; If we reached next block or end of array , element is not present . ; If element is found ; Driver program to test function ; Find the index of ' x ' using Jump Search ; Print the index where ' x ' is located | #include <bits/stdc++.h> NEW_LINE using namespace std ; int jumpSearch ( int arr [ ] , int x , int n ) { int step = sqrt ( n ) ; int prev = 0 ; while ( arr [ min ( step , n ) - 1 ] < x ) { prev = step ; step += sqrt ( n ) ; if ( prev >= n ) return -1 ; } while ( arr [ prev ] < x ) { prev ++ ; if ( prev == min ( step , n ) ) return -1 ; } if ( arr [ prev ] == x ) return prev ; return -1 ; } int main ( ) { int arr [ ] = { 0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89 , 144 , 233 , 377 , 610 } ; int x = 55 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int index = jumpSearch ( arr , x , n ) ; cout << " Number " β < < β x β < < β " is at index " return 0 ; } |
Interpolation Search | C ++ program to implement interpolation search with recursion ; If x is present in arr [ 0. . n - 1 ] , then returns index of it , else returns - 1. ; Since array is sorted , an element present in array must be in range defined by corner ; Probing the position with keeping uniform distribution in mind . ; Condition of target found ; If x is larger , x is in right sub array ; If x is smaller , x is in left sub array ; Driver Code ; Array of items on which search will be conducted . ; Element to be searched ; If element was found | #include <bits/stdc++.h> NEW_LINE using namespace std ; int interpolationSearch ( int arr [ ] , int lo , int hi , int x ) { int pos ; if ( lo <= hi && x >= arr [ lo ] && x <= arr [ hi ] ) { pos = lo + ( ( ( double ) ( hi - lo ) / ( arr [ hi ] - arr [ lo ] ) ) * ( x - arr [ lo ] ) ) ; if ( arr [ pos ] == x ) return pos ; if ( arr [ pos ] < x ) return interpolationSearch ( arr , pos + 1 , hi , x ) ; if ( arr [ pos ] > x ) return interpolationSearch ( arr , lo , pos - 1 , x ) ; } return -1 ; } int main ( ) { int arr [ ] = { 10 , 12 , 13 , 16 , 18 , 19 , 20 , 21 , 22 , 23 , 24 , 33 , 35 , 42 , 47 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 18 ; int index = interpolationSearch ( arr , 0 , n - 1 , x ) ; if ( index != -1 ) cout << " Element β found β at β index β " << index ; else cout << " Element β not β found . " ; return 0 ; } |
Exponential Search | C ++ program to find an element x in a sorted array using Exponential search . ; Returns position of first occurrence of x in array ; If x is present at firt location itself ; Find range for binary search by repeated doubling ; Call binary search for the found range . ; A recursive binary search function . It returns location of x in given array arr [ l . . r ] is present , otherwise - 1 ; If the element is present at the middle itself ; If element is smaller than mid , then it can only be present n left subarray ; Else the element can only be present in right subarray ; We reach here when element is not present in array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int binarySearch ( int arr [ ] , int , int , int ) ; int exponentialSearch ( int arr [ ] , int n , int x ) { if ( arr [ 0 ] == x ) return 0 ; int i = 1 ; while ( i < n && arr [ i ] <= x ) i = i * 2 ; return binarySearch ( arr , i / 2 , min ( i , n - 1 ) , x ) ; } 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 ) ; } return -1 ; } int main ( void ) { int arr [ ] = { 2 , 3 , 4 , 10 , 40 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 10 ; int result = exponentialSearch ( arr , n , x ) ; ( result == -1 ) ? printf ( " Element β is β not β present β in β array " ) : printf ( " Element β is β present β at β index β % d " , result ) ; return 0 ; } |
Merge Sort | C ++ program for Merge Sort ; Merges two subarrays of arr [ ] . First subarray is arr [ l . . m ] Second subarray is arr [ m + 1. . r ] ; Find sizes of two subarrays to be merged ; Create temp arrays ; Copy data to temp arrays L [ ] and R [ ] ; Merge the temp arrays Initial indexes of first and second subarrays ; Initial index of merged subarray ; Copy the remaining elements of L [ ] , if there are any ; Copy the remaining elements of R [ ] , if there are any ; l is for left index and r is right index of the sub - array of arr to be sorted ; Find the middle point ; Sort first and second halves ; Merge the sorted halves ; Function to print an array ; Driver code | #include <iostream> NEW_LINE using namespace std ; void merge ( int arr [ ] , int l , int m , int r ) { int n1 = m - l + 1 ; int n2 = r - m ; int L [ n1 ] , R [ n2 ] ; for ( int i = 0 ; i < n1 ; i ++ ) L [ i ] = arr [ l + i ] ; for ( int j = 0 ; j < n2 ; j ++ ) R [ j ] = arr [ m + 1 + j ] ; int i = 0 ; int j = 0 ; int k = l ; while ( i < n1 && j < n2 ) { if ( L [ i ] <= R [ j ] ) { arr [ k ] = L [ i ] ; i ++ ; } else { arr [ k ] = R [ j ] ; j ++ ; } k ++ ; } while ( i < n1 ) { arr [ k ] = L [ i ] ; i ++ ; k ++ ; } while ( j < n2 ) { arr [ k ] = R [ j ] ; j ++ ; k ++ ; } } void mergeSort ( int arr [ ] , int l , int r ) { if ( l >= r ) { return ; } int m = l + ( r - l ) / 2 ; mergeSort ( arr , l , m ) ; mergeSort ( arr , m + 1 , r ) ; merge ( arr , l , m , r ) ; } void printArray ( int A [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) cout << A [ i ] << " β " ; } int main ( ) { int arr [ ] = { 12 , 11 , 13 , 5 , 6 , 7 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Given β array β is β STRNEWLINE " ; printArray ( arr , arr_size ) ; mergeSort ( arr , 0 , arr_size - 1 ) ; cout << " Sorted array is " ; printArray ( arr , arr_size ) ; return 0 ; } |
QuickSort | C ++ implementation of QuickSort ; A utility function to swap two elements ; This function takes last element as pivot , places the pivot element at its correct position in sorted array , and places all smaller ( smaller than pivot ) to left of pivot and all greater elements to right of pivot ; pivot ; Index of smaller element and indicates the right position of pivot found so far ; If current element is smaller than the pivot ; increment index of smaller element ; The main function that implements QuickSort arr [ ] -- > Array to be sorted , low -- > Starting index , high -- > Ending index ; pi is partitioning index , arr [ p ] is now at right place ; Separately sort elements before partition and after partition ; Function to print an array ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void swap ( int * a , int * b ) { int t = * a ; * a = * b ; * b = t ; } int partition ( int arr [ ] , int low , int high ) { int pivot = arr [ high ] ; int i = ( low - 1 ) ; for ( int j = low ; j <= high - 1 ; j ++ ) { if ( arr [ j ] < pivot ) { i ++ ; swap ( & arr [ i ] , & arr [ j ] ) ; } } swap ( & arr [ i + 1 ] , & arr [ high ] ) ; return ( i + 1 ) ; } void quickSort ( int arr [ ] , int low , int high ) { if ( low < high ) { int pi = partition ( arr , low , high ) ; quickSort ( arr , low , pi - 1 ) ; quickSort ( arr , pi + 1 , high ) ; } } void printArray ( int arr [ ] , int size ) { int i ; for ( i = 0 ; i < size ; i ++ ) cout << arr [ i ] << " β " ; cout << endl ; } int main ( ) { int arr [ ] = { 10 , 7 , 8 , 9 , 1 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; quickSort ( arr , 0 , n - 1 ) ; cout << " Sorted β array : β STRNEWLINE " ; printArray ( arr , n ) ; return 0 ; } |
Radix Sort | C ++ implementation of Radix Sort ; A utility function to get maximum value in arr [ ] ; A function to do counting sort of arr [ ] according to the digit represented by exp . ; output array ; Store count of occurrences in count [ ] ; Change count [ i ] so that count [ i ] now contains actual position of this digit in output [ ] ; Build the output array ; Copy the output array to arr [ ] , so that arr [ ] now contains sorted numbers according to current digit ; The main function to that sorts arr [ ] of size n using Radix Sort ; Find the maximum number to know number of digits ; Do counting sort for every digit . Note that instead of passing digit number , exp is passed . exp is 10 ^ i where i is current digit number ; A utility function to print an array ; Driver Code ; Function Call | #include <iostream> NEW_LINE using namespace std ; int getMax ( int arr [ ] , int n ) { int mx = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] > mx ) mx = arr [ i ] ; return mx ; } void countSort ( int arr [ ] , int n , int exp ) { int output [ n ] ; int i , count [ 10 ] = { 0 } ; for ( i = 0 ; i < n ; i ++ ) count [ ( arr [ i ] / exp ) % 10 ] ++ ; for ( i = 1 ; i < 10 ; i ++ ) count [ i ] += count [ i - 1 ] ; for ( i = n - 1 ; i >= 0 ; i -- ) { output [ count [ ( arr [ i ] / exp ) % 10 ] - 1 ] = arr [ i ] ; count [ ( arr [ i ] / exp ) % 10 ] -- ; } for ( i = 0 ; i < n ; i ++ ) arr [ i ] = output [ i ] ; } void radixsort ( int arr [ ] , int n ) { int m = getMax ( arr , n ) ; for ( int exp = 1 ; m / exp > 0 ; exp *= 10 ) countSort ( arr , n , exp ) ; } void print ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; } int main ( ) { int arr [ ] = { 170 , 45 , 75 , 90 , 802 , 24 , 2 , 66 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; radixsort ( arr , n ) ; print ( arr , n ) ; return 0 ; } |
Bucket Sort | C ++ program to sort an array using bucket sort ; Function to sort arr [ ] of size n using bucket sort ; 1 ) Create n empty buckets ; 2 ) Put array elements in different buckets ; 3 ) Sort individual buckets ; 4 ) Concatenate all buckets into arr [ ] ; Driver program to test above function | #include <algorithm> NEW_LINE #include <iostream> NEW_LINE #include <vector> NEW_LINE using namespace std ; void bucketSort ( float arr [ ] , int n ) { vector < float > b [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { int bi = n * arr [ i ] ; b [ bi ] . push_back ( arr [ i ] ) ; } for ( int i = 0 ; i < n ; i ++ ) sort ( b [ i ] . begin ( ) , b [ i ] . end ( ) ) ; int index = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < b [ i ] . size ( ) ; j ++ ) arr [ index ++ ] = b [ i ] [ j ] ; } int main ( ) { float arr [ ] = { 0.897 , 0.565 , 0.656 , 0.1234 , 0.665 , 0.3434 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; bucketSort ( arr , n ) ; cout << " Sorted β array β is β STRNEWLINE " ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; return 0 ; } |
ShellSort | C ++ implementation of Shell Sort ; An utility function to print array of size n ; function to sort arr using shellSort ; Start with a big gap , then reduce the gap ; Do a gapped insertion sort for this gap size . The first gap elements a [ 0. . gap - 1 ] are already in gapped order keep adding one more element until the entire array is gap sorted ; add a [ i ] to the elements that have been gap sorted save a [ i ] in temp and make a hole at position i ; shift earlier gap - sorted elements up until the correct location for a [ i ] is found ; put temp ( the original a [ i ] ) in its correct location ; Driver method | #include <iostream> NEW_LINE using namespace std ; void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; } int shellSort ( int arr [ ] , int n ) { for ( int gap = n / 2 ; gap > 0 ; gap /= 2 ) { for ( int i = gap ; i < n ; i += 1 ) { int temp = arr [ i ] ; int j ; for ( j = i ; j >= gap && arr [ j - gap ] > temp ; j -= gap ) arr [ j ] = arr [ j - gap ] ; arr [ j ] = temp ; } } return 0 ; } int main ( ) { int arr [ ] = { 12 , 34 , 54 , 2 , 3 } , i ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Array β before β sorting : β STRNEWLINE " ; printArray ( arr , n ) ; shellSort ( arr , n ) ; cout << " Array after sorting : " ; printArray ( arr , n ) ; return 0 ; } |
Comb Sort | C ++ implementation of Comb Sort ; To find gap between elements ; Shrink gap by Shrink factor ; Function to sort a [ 0. . n - 1 ] using Comb Sort ; Initialize gap ; Initialize swapped as true to make sure that loop runs ; Keep running while gap is more than 1 and last iteration caused a swap ; Find next gap ; Initialize swapped as false so that we can check if swap happened or not ; Compare all elements with current gap ; Swap arr [ i ] and arr [ i + gap ] ; Set swapped ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getNextGap ( int gap ) { gap = ( gap * 10 ) / 13 ; if ( gap < 1 ) return 1 ; return gap ; } void combSort ( int a [ ] , int n ) { int gap = n ; bool swapped = true ; while ( gap != 1 swapped == true ) { gap = getNextGap ( gap ) ; swapped = false ; for ( int i = 0 ; i < n - gap ; i ++ ) { if ( a [ i ] > a [ i + gap ] ) { swap ( a [ i ] , a [ i + gap ] ) ; swapped = true ; } } } } int main ( ) { int a [ ] = { 8 , 4 , 1 , 56 , 3 , -44 , 23 , -6 , 28 , 0 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; combSort ( a , n ) ; printf ( " Sorted β array : β STRNEWLINE " ) ; for ( int i = 0 ; i < n ; i ++ ) printf ( " % d β " , a [ i ] ) ; return 0 ; } |
Cycle Sort | C ++ program to implement cycle sort ; Function sort the array using Cycle sort ; count number of memory writes ; traverse array elements and put it to on the right place ; initialize item as starting point ; Find position where we put the item . We basically count all smaller elements on right side of item . ; If item is already in correct position ; ignore all duplicate elements ; put the item to it 's right position ; Rotate rest of the cycle ; Find position where we put the element ; ignore all duplicate elements ; put the item to it 's right position ; Driver program to test above function | #include <iostream> NEW_LINE using namespace std ; void cycleSort ( int arr [ ] , int n ) { int writes = 0 ; for ( int cycle_start = 0 ; cycle_start <= n - 2 ; cycle_start ++ ) { int item = arr [ cycle_start ] ; int pos = cycle_start ; for ( int i = cycle_start + 1 ; i < n ; i ++ ) if ( arr [ i ] < item ) pos ++ ; if ( pos == cycle_start ) continue ; while ( item == arr [ pos ] ) pos += 1 ; if ( pos != cycle_start ) { swap ( item , arr [ pos ] ) ; writes ++ ; } while ( pos != cycle_start ) { pos = cycle_start ; for ( int i = cycle_start + 1 ; i < n ; i ++ ) if ( arr [ i ] < item ) pos += 1 ; while ( item == arr [ pos ] ) pos += 1 ; if ( item != arr [ pos ] ) { swap ( item , arr [ pos ] ) ; writes ++ ; } } } } int main ( ) { int arr [ ] = { 1 , 8 , 3 , 9 , 10 , 10 , 2 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cycleSort ( arr , n ) ; cout << " After β sort β : β " << endl ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; return 0 ; } |
Iterative Quick Sort | CPP code for recursive function of Quicksort ; Function to swap numbers ; This function takes last element as pivot , places the pivot element at its correct position in sorted array , and places all smaller ( smaller than pivot ) to left of pivot and all greater elements to right of pivot ; A [ ] -- > Array to be sorted , l -- > Starting index , h -- > Ending index ; Partitioning index ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void swap ( int * a , int * b ) { int temp = * a ; * a = * b ; * b = temp ; } int partition ( int arr [ ] , int l , int h ) { int x = arr [ h ] ; int i = ( l - 1 ) ; for ( int j = l ; j <= h - 1 ; j ++ ) { if ( arr [ j ] <= x ) { i ++ ; swap ( & arr [ i ] , & arr [ j ] ) ; } } swap ( & arr [ i + 1 ] , & arr [ h ] ) ; return ( i + 1 ) ; } void quickSort ( int A [ ] , int l , int h ) { if ( l < h ) { int p = partition ( A , l , h ) ; quickSort ( A , l , p - 1 ) ; quickSort ( A , p + 1 , h ) ; } } int main ( ) { int n = 5 ; int arr [ n ] = { 4 , 2 , 6 , 9 , 2 } ; quickSort ( arr , 0 , n - 1 ) ; for ( int i = 0 ; i < n ; i ++ ) { cout << arr [ i ] << " β " ; } return 0 ; } |
Iterative Quick Sort | An iterative implementation of quick sort ; A utility function to swap two elements ; This function is same in both iterative and recursive ; A [ ] -- > Array to be sorted , l -- > Starting index , h -- > Ending index ; Create an auxiliary stack ; initialize top of stack ; push initial values of l and h to stack ; Keep popping from stack while is not empty ; Pop h and l ; Set pivot element at its correct position in sorted array ; If there are elements on left side of pivot , then push left side to stack ; If there are elements on right side of pivot , then push right side to stack ; A utility function to print contents of arr ; Driver code ; Function calling | #include <bits/stdc++.h> NEW_LINE using namespace std ; void swap ( int * a , int * b ) { int t = * a ; * a = * b ; * b = t ; } int partition ( int arr [ ] , int l , int h ) { int x = arr [ h ] ; int i = ( l - 1 ) ; for ( int j = l ; j <= h - 1 ; j ++ ) { if ( arr [ j ] <= x ) { i ++ ; swap ( & arr [ i ] , & arr [ j ] ) ; } } swap ( & arr [ i + 1 ] , & arr [ h ] ) ; return ( i + 1 ) ; } void quickSortIterative ( int arr [ ] , int l , int h ) { int stack [ h - l + 1 ] ; int top = -1 ; stack [ ++ top ] = l ; stack [ ++ top ] = h ; while ( top >= 0 ) { h = stack [ top -- ] ; l = stack [ top -- ] ; int p = partition ( arr , l , h ) ; if ( p - 1 > l ) { stack [ ++ top ] = l ; stack [ ++ top ] = p - 1 ; } if ( p + 1 < h ) { stack [ ++ top ] = p + 1 ; stack [ ++ top ] = h ; } } } void printArr ( int arr [ ] , int n ) { int i ; for ( i = 0 ; i < n ; ++ i ) cout << arr [ i ] << " β " ; } int main ( ) { int arr [ ] = { 4 , 3 , 5 , 2 , 1 , 3 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( * arr ) ; quickSortIterative ( arr , 0 , n - 1 ) ; printArr ( arr , n ) ; return 0 ; } |
Sort n numbers in range from 0 to n ^ 2 | ; A function to do counting sort of arr [ ] according to the digit represented by exp . ; output array ; Store count of occurrences in count [ ] ; Change count [ i ] so that count [ i ] now contains actual position of this digit in output [ ] ; Build the output array ; Copy the output array to arr [ ] , so that arr [ ] now contains sorted numbers according to current digit ; The main function to that sorts arr [ ] of size n using Radix Sort ; Do counting sort for first digit in base n . Note that instead of passing digit number , exp ( n ^ 0 = 1 ) is passed . ; Do counting sort for second digit in base n . Note that instead of passing digit number , exp ( n ^ 1 = n ) is passed . ; A utility function to print an array ; Driver program to test above functions ; Since array size is 7 , elements should be from 0 to 48 | #include <iostream> NEW_LINE using namespace std ; int countSort ( int arr [ ] , int n , int exp ) { int output [ n ] ; int i , count [ n ] ; for ( int i = 0 ; i < n ; i ++ ) count [ i ] = 0 ; for ( i = 0 ; i < n ; i ++ ) count [ ( arr [ i ] / exp ) % n ] ++ ; for ( i = 1 ; i < n ; i ++ ) count [ i ] += count [ i - 1 ] ; for ( i = n - 1 ; i >= 0 ; i -- ) { output [ count [ ( arr [ i ] / exp ) % n ] - 1 ] = arr [ i ] ; count [ ( arr [ i ] / exp ) % n ] -- ; } for ( i = 0 ; i < n ; i ++ ) arr [ i ] = output [ i ] ; } void sort ( int arr [ ] , int n ) { countSort ( arr , n , 1 ) ; countSort ( arr , n , n ) ; } void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; } int main ( ) { int arr [ ] = { 40 , 12 , 45 , 32 , 33 , 1 , 22 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Given β array β is β n " ; printArr ( arr , n ) ; sort ( arr , n ) ; cout << " nSorted β array β is β n " ; printArr ( arr , n ) ; return 0 ; } |
Search in an almost sorted array | C ++ program to find an element in an almost sorted array ; A recursive binary search based function . It returns index of x in given array arr [ l . . r ] is present , otherwise - 1 ; If the element is present at one of the middle 3 positions ; If element is smaller than mid , then it can only be present in left subarray ; Else the element can only be present in right subarray ; We reach here when element is not present in array ; Driver Code | #include <stdio.h> NEW_LINE 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 ( mid > l && arr [ mid - 1 ] == x ) return ( mid - 1 ) ; if ( mid < r && arr [ mid + 1 ] == x ) return ( mid + 1 ) ; if ( arr [ mid ] > x ) return binarySearch ( arr , l , mid - 2 , x ) ; return binarySearch ( arr , mid + 2 , r , x ) ; } return -1 ; } int main ( void ) { int arr [ ] = { 3 , 2 , 10 , 4 , 40 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 4 ; int result = binarySearch ( arr , 0 , n - 1 , x ) ; ( result == -1 ) ? printf ( " Element β is β not β present β in β array " ) : printf ( " Element β is β present β at β index β % d " , result ) ; return 0 ; } |
Find the closest pair from two sorted arrays | C ++ program to find the pair from two sorted arays such that the sum of pair is closest to a given number x ; ar1 [ 0. . m - 1 ] and ar2 [ 0. . n - 1 ] are two given sorted arrays and x is given number . This function prints the pair from both arrays such that the sum of the pair is closest to x . ; Initialize the diff between pair sum and x . ; res_l and res_r are result indexes from ar1 [ ] and ar2 [ ] respectively ; Start from left side of ar1 [ ] and right side of ar2 [ ] ; If this pair is closer to x than the previously found closest , then update res_l , res_r and diff ; If sum of this pair is more than x , move to smaller side ; move to the greater side ; Print the result ; Driver program to test above functions | #include <iostream> NEW_LINE #include <climits> NEW_LINE #include <cstdlib> NEW_LINE using namespace std ; void printClosest ( int ar1 [ ] , int ar2 [ ] , int m , int n , int x ) { int diff = INT_MAX ; int res_l , res_r ; int l = 0 , r = n - 1 ; while ( l < m && r >= 0 ) { if ( abs ( ar1 [ l ] + ar2 [ r ] - x ) < diff ) { res_l = l ; res_r = r ; diff = abs ( ar1 [ l ] + ar2 [ r ] - x ) ; } if ( ar1 [ l ] + ar2 [ r ] > x ) r -- ; else l ++ ; } cout << " The β closest β pair β is β [ " << ar1 [ res_l ] << " , β " << ar2 [ res_r ] << " ] β STRNEWLINE " ; } int main ( ) { int ar1 [ ] = { 1 , 4 , 5 , 7 } ; int ar2 [ ] = { 10 , 20 , 30 , 40 } ; int m = sizeof ( ar1 ) / sizeof ( ar1 [ 0 ] ) ; int n = sizeof ( ar2 ) / sizeof ( ar2 [ 0 ] ) ; int x = 38 ; printClosest ( ar1 , ar2 , m , n , x ) ; return 0 ; } |
Given a sorted array and a number x , find the pair in array whose sum is closest to x | Simple C ++ program to find the pair with sum closest to a given no . ; Prints the pair with sum closest to x ; To store indexes of result pair ; Initialize left and right indexes and difference between pair sum and x ; While there are elements between l and r ; Check if this pair is closer than the closest pair so far ; If this pair has more sum , move to smaller values . ; Move to larger values ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printClosest ( int arr [ ] , int n , int x ) { int res_l , res_r ; int l = 0 , r = n - 1 , diff = INT_MAX ; while ( r > l ) { if ( abs ( arr [ l ] + arr [ r ] - x ) < diff ) { res_l = l ; res_r = r ; diff = abs ( arr [ l ] + arr [ r ] - x ) ; } if ( arr [ l ] + arr [ r ] > x ) r -- ; else l ++ ; } cout << " β The β closest β pair β is β " << arr [ res_l ] << " β and β " << arr [ res_r ] ; } int main ( ) { int arr [ ] = { 10 , 22 , 28 , 29 , 30 , 40 } , x = 54 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printClosest ( arr , n , x ) ; return 0 ; } |
Count 1 's in a sorted binary array | C ++ program to count one 's in a boolean array ; Returns counts of 1 's in arr[low..high]. The array is assumed to be sorted in non-increasing order ; get the middle index ; check if the element at middle index is last 1 ; If element is not last 1 , recur for right side ; else recur for left side ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countOnes ( bool arr [ ] , int low , int high ) { if ( high >= low ) { int mid = low + ( high - low ) / 2 ; if ( ( mid == high arr [ mid + 1 ] == 0 ) && ( arr [ mid ] == 1 ) ) return mid + 1 ; if ( arr [ mid ] == 1 ) return countOnes ( arr , ( mid + 1 ) , high ) ; return countOnes ( arr , low , ( mid - 1 ) ) ; } return 0 ; } int main ( ) { bool arr [ ] = { 1 , 1 , 1 , 1 , 0 , 0 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Count β of β 1 ' s β in β given β array β is β " << countOnes ( arr , 0 , n - 1 ) ; return 0 ; } |
Minimum adjacent swaps to move maximum and minimum to corners | CPP program to count Minimum number of adjacent / swaps so that the largest element is at beginning and the smallest element is at last ; Function that returns the minimum swaps ; Index of leftmost largest element ; Index of rightmost smallest element ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( int a [ ] , int n ) { int maxx = -1 , minn = a [ 0 ] , l = 0 , r = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] > maxx ) { maxx = a [ i ] ; l = i ; } if ( a [ i ] <= minn ) { minn = a [ i ] ; r = i ; } } if ( r < l ) cout << l + ( n - r - 2 ) ; else cout << l + ( n - r - 1 ) ; } int main ( ) { int a [ ] = { 5 , 6 , 1 , 3 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; solve ( a , n ) ; return 0 ; } |
Activity Selection Problem | Greedy Algo | C ++ program for activity selection problem . The following implementation assumes that the activities are already sorted according to their finish time ; Prints a maximum set of activities that can be done by a single person , one at a time . n -- > Total number of activities s [ ] -- > An array that contains start time of all activities f [ ] -- > An array that contains finish time of all activities ; The first activity always gets selected ; Consider rest of the activities ; If this activity has start time greater than or equal to the finish time of previously selected activity , then select it ; driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printMaxActivities ( int s [ ] , int f [ ] , int n ) { int i , j ; cout << " Following β activities β are β selected β " << endl ; i = 0 ; cout << " β " << i ; for ( j = 1 ; j < n ; j ++ ) { if ( s [ j ] >= f [ i ] ) { cout << " β " << j ; i = j ; } } } int main ( ) { int s [ ] = { 1 , 3 , 0 , 5 , 8 , 5 } ; int f [ ] = { 2 , 4 , 6 , 7 , 9 , 9 } ; int n = sizeof ( s ) / sizeof ( s [ 0 ] ) ; printMaxActivities ( s , f , n ) ; return 0 ; } |
Activity Selection Problem | Greedy Algo | C ++ program for activity selection problem when input activities may not be sorted . ; A job has a start time , finish time and profit . ; A utility function that is used for sorting activities according to finish time ; Returns count of the maximum set of activities that can be done by a single person , one at a time . ; Sort jobs according to finish time ; The first activity always gets selected ; Consider rest of the activities ; If this activity has start time greater than or equal to the finish time of previously selected activity , then select it ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Activitiy { int start , finish ; } ; bool activityCompare ( Activitiy s1 , Activitiy s2 ) { return ( s1 . finish < s2 . finish ) ; } void printMaxActivities ( Activitiy arr [ ] , int n ) { sort ( arr , arr + n , activityCompare ) ; cout << " Following β activities β are β selected β n " ; int i = 0 ; cout << " ( " << arr [ i ] . start << " , β " << arr [ i ] . finish << " ) , β " ; for ( int j = 1 ; j < n ; j ++ ) { if ( arr [ j ] . start >= arr [ i ] . finish ) { cout << " ( " << arr [ j ] . start << " , β " << arr [ j ] . finish << " ) , β " ; i = j ; } } } int main ( ) { Activitiy arr [ ] = { { 5 , 9 } , { 1 , 2 } , { 3 , 4 } , { 0 , 6 } , { 5 , 7 } , { 8 , 9 } } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printMaxActivities ( arr , n ) ; return 0 ; } |
Activity Selection Problem | Greedy Algo | C ++ program for activity selection problem when input activities may not be sorted . ; Vector to store results . ; Minimum Priority Queue to sort activities in ascending order of finishing time ( f [ i ] ) . ; Pushing elements in priority queue where the key is f [ i ] ; Driver program ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void SelectActivities ( vector < int > s , vector < int > f ) { vector < pair < int , int > > ans ; priority_queue < pair < int , int > , vector < pair < int , int > > , greater < pair < int , int > > > p ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { p . push ( make_pair ( f [ i ] , s [ i ] ) ) ; } auto it = p . top ( ) ; int start = it . second ; int end = it . first ; p . pop ( ) ; ans . push_back ( make_pair ( start , end ) ) ; while ( ! p . empty ( ) ) { auto itr = p . top ( ) ; p . pop ( ) ; if ( itr . second >= end ) { start = itr . second ; end = itr . first ; ans . push_back ( make_pair ( start , end ) ) ; } } cout << " Following β Activities β should β be β selected . β " << endl << endl ; for ( auto itr = ans . begin ( ) ; itr != ans . end ( ) ; itr ++ ) { cout << " Activity β started β at : β " << ( * itr ) . first << " β and β ends β at β " << ( * itr ) . second << endl ; } } int main ( ) { vector < int > s = { 1 , 3 , 0 , 5 , 8 , 5 } ; vector < int > f = { 2 , 4 , 6 , 7 , 9 , 9 } ; SelectActivities ( s , f ) ; return 0 ; } |
Efficient Huffman Coding for Sorted Input | Greedy Algo | C ++ Program for Efficient Huffman Coding for Sorted input ; This constant can be avoided by explicitly calculating height of Huffman Tree ; A node of huffman tree ; Structure for Queue : collection of Huffman Tree nodes ( or QueueNodes ) ; A utility function to create a new Queuenode ; A utility function to create a Queue of given capacity ; A utility function to check if size of given queue is 1 ; A utility function to check if given queue is empty ; A utility function to check if given queue is full ; A utility function to add an item to queue ; A utility function to remove an item from queue ; If there is only one item in queue ; A utility function to get from of queue ; A function to get minimum item from two queues ; Step 3. a : If first queue is empty , dequeue from second queue ; Step 3. b : If second queue is empty , dequeue from first queue ; Step 3. c : Else , compare the front of two queues and dequeue minimum ; Utility function to check if this node is leaf ; A utility function to print an array of size n ; The main function that builds Huffman tree ; Step 1 : Create two empty queues ; Step 2 : Create a leaf node for each unique character and Enqueue it to the first queue in non - decreasing order of frequency . Initially second queue is empty ; Run while Queues contain more than one node . Finally , first queue will be empty and second queue will contain only one node ; Step 3 : Dequeue two nodes with the minimum frequency by examining the front of both queues ; Step 4 : Create a new internal node with frequency equal to the sum of the two nodes frequencies . Enqueue this node to second queue . ; Prints huffman codes from the root of Huffman Tree . It uses arr [ ] to store codes ; Assign 0 to left edge and recur ; Assign 1 to right edge and recur ; If this is a leaf node , then it contains one of the input characters , print the character and its code from arr [ ] ; The main function that builds a Huffman Tree and print codes by traversing the built Huffman Tree ; Construct Huffman Tree ; Print Huffman codes using the Huffman tree built above ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX_TREE_HT 100 NEW_LINE class QueueNode { public : char data ; unsigned freq ; QueueNode * left , * right ; } ; class Queue { public : int front , rear ; int capacity ; QueueNode * * array ; } ; QueueNode * newNode ( char data , unsigned freq ) { QueueNode * temp = new QueueNode [ ( sizeof ( QueueNode ) ) ] ; temp -> left = temp -> right = NULL ; temp -> data = data ; temp -> freq = freq ; return temp ; } Queue * createQueue ( int capacity ) { Queue * queue = new Queue [ ( sizeof ( Queue ) ) ] ; queue -> front = queue -> rear = -1 ; queue -> capacity = capacity ; queue -> array = new QueueNode * [ ( queue -> capacity * sizeof ( QueueNode * ) ) ] ; return queue ; } int isSizeOne ( Queue * queue ) { return queue -> front == queue -> rear && queue -> front != -1 ; } int isEmpty ( Queue * queue ) { return queue -> front == -1 ; } int isFull ( Queue * queue ) { return queue -> rear == queue -> capacity - 1 ; } void enQueue ( Queue * queue , QueueNode * item ) { if ( isFull ( queue ) ) return ; queue -> array [ ++ queue -> rear ] = item ; if ( queue -> front == -1 ) ++ queue -> front ; } QueueNode * deQueue ( Queue * queue ) { if ( isEmpty ( queue ) ) return NULL ; QueueNode * temp = queue -> array [ queue -> front ] ; if ( queue -> front == queue -> rear ) queue -> front = queue -> rear = -1 ; else ++ queue -> front ; return temp ; } QueueNode * getFront ( Queue * queue ) { if ( isEmpty ( queue ) ) return NULL ; return queue -> array [ queue -> front ] ; } QueueNode * findMin ( Queue * firstQueue , Queue * secondQueue ) { if ( isEmpty ( firstQueue ) ) return deQueue ( secondQueue ) ; if ( isEmpty ( secondQueue ) ) return deQueue ( firstQueue ) ; if ( getFront ( firstQueue ) -> freq < getFront ( secondQueue ) -> freq ) return deQueue ( firstQueue ) ; return deQueue ( secondQueue ) ; } int isLeaf ( QueueNode * root ) { return ! ( root -> left ) && ! ( root -> right ) ; } void printArr ( int arr [ ] , int n ) { int i ; for ( i = 0 ; i < n ; ++ i ) cout << arr [ i ] ; cout << endl ; } QueueNode * buildHuffmanTree ( char data [ ] , int freq [ ] , int size ) { QueueNode * left , * right , * top ; Queue * firstQueue = createQueue ( size ) ; Queue * secondQueue = createQueue ( size ) ; for ( int i = 0 ; i < size ; ++ i ) enQueue ( firstQueue , newNode ( data [ i ] , freq [ i ] ) ) ; while ( ! ( isEmpty ( firstQueue ) && isSizeOne ( secondQueue ) ) ) { left = findMin ( firstQueue , secondQueue ) ; right = findMin ( firstQueue , secondQueue ) ; top = newNode ( ' $ ' , left -> freq + right -> freq ) ; top -> left = left ; top -> right = right ; enQueue ( secondQueue , top ) ; } return deQueue ( secondQueue ) ; } void printCodes ( QueueNode * root , int arr [ ] , int top ) { if ( root -> left ) { arr [ top ] = 0 ; printCodes ( root -> left , arr , top + 1 ) ; } if ( root -> right ) { arr [ top ] = 1 ; printCodes ( root -> right , arr , top + 1 ) ; } if ( isLeaf ( root ) ) { cout << root -> data << " : β " ; printArr ( arr , top ) ; } } void HuffmanCodes ( char data [ ] , int freq [ ] , int size ) { QueueNode * root = buildHuffmanTree ( data , freq , size ) ; int arr [ MAX_TREE_HT ] , top = 0 ; printCodes ( root , arr , top ) ; } int main ( ) { char arr [ ] = { ' a ' , ' b ' , ' c ' , ' d ' , ' e ' , ' f ' } ; int freq [ ] = { 5 , 9 , 12 , 13 , 16 , 45 } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; HuffmanCodes ( arr , freq , size ) ; return 0 ; } |
Longest Increasing Subsequence | DP | A Naive C / C ++ recursive implementation of LIS problem ; To make use of recursive calls , thisfunction must return two things : 1 ) Length of LIS ending with element arr [ n - 1 ] . We use max_ending_here for this purpose2 ) Overall maximum as the LIS may end with an element before arr [ n - 1 ] max_ref is used this purpose . The value of LIS of full array of size n is stored in * max_ref which is our final result ; Base case ; ' max _ ending _ here ' is length of LIS ending with arr [ n - 1 ] ; Recursively get all LIS ending with arr [ 0 ] , arr [ 1 ] ... arr [ n - 2 ] . If arr [ i - 1 ] is smaller than arr [ n - 1 ] , and max ending with arr [ n - 1 ] needs to be updated , then update it ; Compare max_ending_here with the overall max . And update the overall max if needed ; Return length of LIS ending with arr [ n - 1 ] ; The wrapper function for _lis ( ) ; The max variable holds the result ; The function _lis ( ) stores its result in max ; returns max ; Driver program to test above function | #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int _lis ( int arr [ ] , int n , int * max_ref ) { if ( n == 1 ) return 1 ; int res , max_ending_here = 1 ; for ( int i = 1 ; i < n ; i ++ ) { res = _lis ( arr , i , max_ref ) ; if ( arr [ i - 1 ] < arr [ n - 1 ] && res + 1 > max_ending_here ) max_ending_here = res + 1 ; } if ( * max_ref < max_ending_here ) * max_ref = max_ending_here ; return max_ending_here ; } int lis ( int arr [ ] , int n ) { int max = 1 ; _lis ( arr , n , & max ) ; return max ; } int main ( ) { int arr [ ] = { 10 , 22 , 9 , 33 , 21 , 50 , 41 , 60 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Length β of β lis β is β % d " , lis ( arr , n ) ) ; return 0 ; } |
Longest Increasing Subsequence | DP | Dynamic Programming C ++ implementation of LIS problem ; lis ( ) returns the length of the longest increasing subsequence in arr [ ] of size n ; Compute optimized LIS values in bottom up manner ; Return maximum value in lis [ ] ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int lis ( int arr [ ] , int n ) { int lis [ n ] ; lis [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { lis [ i ] = 1 ; for ( int j = 0 ; j < i ; j ++ ) if ( arr [ i ] > arr [ j ] && lis [ i ] < lis [ j ] + 1 ) lis [ i ] = lis [ j ] + 1 ; } return * max_element ( lis , lis + n ) ; } int main ( ) { int arr [ ] = { 10 , 22 , 9 , 33 , 21 , 50 , 41 , 60 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Length β of β lis β is β % d STRNEWLINE " , lis ( arr , n ) ) ; return 0 ; } |
Longest Common Subsequence | DP | A Naive recursive implementation of LCS problem ; Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Utility function to get max of 2 integers ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int max ( int a , int b ) ; int lcs ( char * X , char * Y , int m , int n ) { if ( m == 0 n == 0 ) return 0 ; if ( X [ m - 1 ] == Y [ n - 1 ] ) return 1 + lcs ( X , Y , m - 1 , n - 1 ) ; else return max ( lcs ( X , Y , m , n - 1 ) , lcs ( X , Y , m - 1 , n ) ) ; } int max ( int a , int b ) { return ( a > b ) ? a : b ; } int main ( ) { char X [ ] = " AGGTAB " ; char Y [ ] = " GXTXAYB " ; int m = strlen ( X ) ; int n = strlen ( Y ) ; cout << " Length β of β LCS β is β " << lcs ( X , Y , m , n ) ; return 0 ; } |
Longest Common Subsequence | DP | Dynamic Programming C ++ implementation of LCS problem ; Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; 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 ] ; L [ m ] [ n ] contains length of LCS for X [ 0. . n - 1 ] and Y [ 0. . m - 1 ] ; Utility function to get max of 2 integers ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int max ( int a , int b ) ; int lcs ( char * X , char * Y , int m , int n ) { int L [ m + 1 ] [ n + 1 ] ; int i , j ; for ( i = 0 ; i <= m ; i ++ ) { for ( j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) L [ i ] [ j ] = 0 ; else if ( X [ i - 1 ] == Y [ j - 1 ] ) L [ i ] [ j ] = L [ i - 1 ] [ j - 1 ] + 1 ; else L [ i ] [ j ] = max ( L [ i - 1 ] [ j ] , L [ i ] [ j - 1 ] ) ; } } return L [ m ] [ n ] ; } int max ( int a , int b ) { return ( a > b ) ? a : b ; } int main ( ) { char X [ ] = " AGGTAB " ; char Y [ ] = " GXTXAYB " ; int m = strlen ( X ) ; int n = strlen ( Y ) ; cout << " Length β of β LCS β is β " << lcs ( X , Y , m , n ) ; return 0 ; } |
Edit Distance | DP | A Space efficient Dynamic Programming based C ++ program to find minimum number operations to convert str1 to str2 ; Create a DP array to memoize result of previous computations ; To fill the DP array with 0 ; Base condition when second string is empty then we remove all characters ; Start filling the DP This loop run for every character in second string ; This loop compares the char from second string with first string characters ; if first string is empty then we have to perform add character operation to get second string ; if character from both string is same then we do not perform any operation . here i % 2 is for bound the row number . ; if character from both string is not same then we take the minimum from three specified operation ; after complete fill the DP array if the len2 is even then we end up in the 0 th row else we end up in the 1 th row so we take len2 % 2 to get row ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void EditDistDP ( string str1 , string str2 ) { int len1 = str1 . length ( ) ; int len2 = str2 . length ( ) ; int DP [ 2 ] [ len1 + 1 ] ; memset ( DP , 0 , sizeof DP ) ; for ( int i = 0 ; i <= len1 ; i ++ ) DP [ 0 ] [ i ] = i ; for ( int i = 1 ; i <= len2 ; i ++ ) { for ( int j = 0 ; j <= len1 ; j ++ ) { if ( j == 0 ) DP [ i % 2 ] [ j ] = i ; else if ( str1 [ j - 1 ] == str2 [ i - 1 ] ) { DP [ i % 2 ] [ j ] = DP [ ( i - 1 ) % 2 ] [ j - 1 ] ; } else { DP [ i % 2 ] [ j ] = 1 + min ( DP [ ( i - 1 ) % 2 ] [ j ] , min ( DP [ i % 2 ] [ j - 1 ] , DP [ ( i - 1 ) % 2 ] [ j - 1 ] ) ) ; } } } cout << DP [ len2 % 2 ] [ len1 ] << endl ; } int main ( ) { string str1 = " food " ; string str2 = " money " ; EditDistDP ( str1 , str2 ) ; return 0 ; } |
Edit Distance | DP | ; If any string is empty , return the remaining characters of other string ; To check if the recursive tree for given n & m has already been executed ; If characters are equal , execute recursive function for n - 1 , m - 1 ; If characters are nt equal , we need to find the minimum cost out of all 3 operations . ; temp variables ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minDis ( string s1 , string s2 , int n , int m , vector < vector < int > > & dp ) { if ( n == 0 ) return m ; if ( m == 0 ) return n ; if ( dp [ n ] [ m ] != -1 ) return dp [ n ] [ m ] ; if ( s1 [ n - 1 ] == s2 [ m - 1 ] ) { if ( dp [ n - 1 ] [ m - 1 ] == -1 ) { return dp [ n ] [ m ] = minDis ( s1 , s2 , n - 1 , m - 1 , dp ) ; } else return dp [ n ] [ m ] = dp [ n - 1 ] [ m - 1 ] ; } else { int m1 , m2 , m3 ; if ( dp [ n - 1 ] [ m ] != -1 ) { m1 = dp [ n - 1 ] [ m ] ; } else { m1 = minDis ( s1 , s2 , n - 1 , m , dp ) ; } if ( dp [ n ] [ m - 1 ] != -1 ) { m2 = dp [ n ] [ m - 1 ] ; } else { m2 = minDis ( s1 , s2 , n , m - 1 , dp ) ; } if ( dp [ n - 1 ] [ m - 1 ] != -1 ) { m3 = dp [ n - 1 ] [ m - 1 ] ; } else { m3 = minDis ( s1 , s2 , n - 1 , m - 1 , dp ) ; } return dp [ n ] [ m ] = 1 + min ( m1 , min ( m2 , m3 ) ) ; } } int main ( ) { string str1 = " voldemort " ; string str2 = " dumbledore " ; int n = str1 . length ( ) , m = str2 . length ( ) ; vector < vector < int > > dp ( n + 1 , vector < int > ( m + 1 , -1 ) ) ; cout << minDis ( str1 , str2 , n , m , dp ) ; return 0 ; } |
Min Cost Path | DP | A Naive recursive implementation of MCP ( Minimum Cost Path ) problem ; A utility function that returns minimum of 3 integers ; Returns cost of minimum cost path from ( 0 , 0 ) to ( m , n ) in mat [ R ] [ C ] ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define R 3 NEW_LINE #define C 3 NEW_LINE int min ( int x , int y , int z ) ; int min ( int x , int y , int z ) { if ( x < y ) return ( x < z ) ? x : z ; else return ( y < z ) ? y : z ; } int minCost ( int cost [ R ] [ C ] , int m , int n ) { if ( n < 0 m < 0 ) return INT_MAX ; else if ( m == 0 && n == 0 ) return cost [ m ] [ n ] ; else return cost [ m ] [ n ] + min ( minCost ( cost , m - 1 , n - 1 ) , minCost ( cost , m - 1 , n ) , minCost ( cost , m , n - 1 ) ) ; } int main ( ) { int cost [ R ] [ C ] = { { 1 , 2 , 3 } , { 4 , 8 , 2 } , { 1 , 5 , 3 } } ; cout << minCost ( cost , 2 , 2 ) << endl ; return 0 ; } |
Min Cost Path | DP | Dynamic Programming implementation of MCP problem ; Instead of following line , we can use int tc [ m + 1 ] [ n + 1 ] or dynamically allocate memory to save space . The following line is used to keep the program simple and make it working on all compilers . ; Initialize first column of total cost ( tc ) array ; Initialize first row of tc array ; Construct rest of the tc array ; A utility function that returns minimum of 3 integers ; Driver code | #include <bits/stdc++.h> NEW_LINE #include <limits.h> NEW_LINE #define R 3 NEW_LINE #define C 3 NEW_LINE using namespace std ; int min ( int x , int y , int z ) ; int minCost ( int cost [ R ] [ C ] , int m , int n ) { int i , j ; int tc [ R ] [ C ] ; tc [ 0 ] [ 0 ] = cost [ 0 ] [ 0 ] ; for ( i = 1 ; i <= m ; i ++ ) tc [ i ] [ 0 ] = tc [ i - 1 ] [ 0 ] + cost [ i ] [ 0 ] ; for ( j = 1 ; j <= n ; j ++ ) tc [ 0 ] [ j ] = tc [ 0 ] [ j - 1 ] + cost [ 0 ] [ j ] ; for ( i = 1 ; i <= m ; i ++ ) for ( j = 1 ; j <= n ; j ++ ) tc [ i ] [ j ] = min ( tc [ i - 1 ] [ j - 1 ] , tc [ i - 1 ] [ j ] , tc [ i ] [ j - 1 ] ) + cost [ i ] [ j ] ; return tc [ m ] [ n ] ; } int min ( int x , int y , int z ) { if ( x < y ) return ( x < z ) ? x : z ; else return ( y < z ) ? y : z ; } int main ( ) { int cost [ R ] [ C ] = { { 1 , 2 , 3 } , { 4 , 8 , 2 } , { 1 , 5 , 3 } } ; cout << " β " << minCost ( cost , 2 , 2 ) ; return 0 ; } |
Min Cost Path | DP | ; for 1 st column ; for 1 st row ; for rest of the 2d matrix ; returning the value in last cell ; Driver code | #include <bits/stdc++.h> NEW_LINE #define endl " NEW_LINE " using namespace std ; const int row = 3 ; const int col = 3 ; int minCost ( int cost [ row ] [ col ] ) { for ( int i = 1 ; i < row ; i ++ ) { cost [ i ] [ 0 ] += cost [ i - 1 ] [ 0 ] ; } for ( int j = 1 ; j < col ; j ++ ) { cost [ 0 ] [ j ] += cost [ 0 ] [ j - 1 ] ; } for ( int i = 1 ; i < row ; i ++ ) { for ( int j = 1 ; j < col ; j ++ ) { cost [ i ] [ j ] += min ( cost [ i - 1 ] [ j - 1 ] , min ( cost [ i - 1 ] [ j ] , cost [ i ] [ j - 1 ] ) ) ; } } return cost [ row - 1 ] [ col - 1 ] ; } int main ( int argc , char const * argv [ ] ) { int cost [ row ] [ col ] = { { 1 , 2 , 3 } , { 4 , 8 , 2 } , { 1 , 5 , 3 } } ; cout << minCost ( cost ) << endl ; return 0 ; } |
0 | A Naive recursive implementation of 0 - 1 Knapsack problem ; A utility function that returns maximum of two integers ; Returns the maximum value that can be put in a knapsack of capacity W ; Base Case ; If weight of the nth item is more than Knapsack capacity W , then this item cannot be included in the optimal solution ; Return the maximum of two cases : ( 1 ) nth item included ( 2 ) not included ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int max ( int a , int b ) { return ( a > b ) ? a : b ; } int knapSack ( int W , int wt [ ] , int val [ ] , int n ) { if ( n == 0 W == 0 ) return 0 ; if ( wt [ n - 1 ] > W ) return knapSack ( W , wt , val , n - 1 ) ; else return max ( val [ n - 1 ] + knapSack ( W - wt [ n - 1 ] , wt , val , n - 1 ) , knapSack ( W , wt , val , n - 1 ) ) ; } int main ( ) { int val [ ] = { 60 , 100 , 120 } ; int wt [ ] = { 10 , 20 , 30 } ; int W = 50 ; int n = sizeof ( val ) / sizeof ( val [ 0 ] ) ; cout << knapSack ( W , wt , val , n ) ; return 0 ; } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.