text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Check if all levels of two trees are anagrams or not | Iterative program to check if two trees are level by level anagram . ; A Binary Tree Node ; Returns true if trees with root1 and root2 are level by level anagram , else returns false . ; Base Cases ; start level order traversal of two trees using two queues . ; n1 ( queue size ) indicates number of Nodes at current level in first tree and n2 indicates number of nodes in current level of second tree . ; If n1 and n2 are different ; If level order traversal is over ; Dequeue all Nodes of current level and Enqueue all Nodes of next level ; Check if nodes of current levels are anagrams or not . ; Utility function to create a new tree Node ; Driver program to test above functions ; Constructing both the trees . | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { struct Node * left , * right ; int data ; } ; bool areAnagrams ( Node * root1 , Node * root2 ) { if ( root1 == NULL && root2 == NULL ) return true ; if ( root1 == NULL root2 == NULL ) return false ; queue < Node * > q1 , q2 ; q1 . push ( root1 ) ; q2 . push ( root2 ) ; while ( 1 ) { int n1 = q1 . size ( ) , n2 = q2 . size ( ) ; if ( n1 != n2 ) return false ; if ( n1 == 0 ) break ; vector < int > curr_level1 , curr_level2 ; while ( n1 > 0 ) { Node * node1 = q1 . front ( ) ; q1 . pop ( ) ; if ( node1 -> left != NULL ) q1 . push ( node1 -> left ) ; if ( node1 -> right != NULL ) q1 . push ( node1 -> right ) ; n1 -- ; Node * node2 = q2 . front ( ) ; q2 . pop ( ) ; if ( node2 -> left != NULL ) q2 . push ( node2 -> left ) ; if ( node2 -> right != NULL ) q2 . push ( node2 -> right ) ; curr_level1 . push_back ( node1 -> data ) ; curr_level2 . push_back ( node2 -> data ) ; } sort ( curr_level1 . begin ( ) , curr_level1 . end ( ) ) ; sort ( curr_level2 . begin ( ) , curr_level2 . end ( ) ) ; if ( curr_level1 != curr_level2 ) return false ; } return true ; } Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } int main ( ) { struct Node * root1 = newNode ( 1 ) ; root1 -> left = newNode ( 3 ) ; root1 -> right = newNode ( 2 ) ; root1 -> right -> left = newNode ( 5 ) ; root1 -> right -> right = newNode ( 4 ) ; struct Node * root2 = newNode ( 1 ) ; root2 -> left = newNode ( 2 ) ; root2 -> right = newNode ( 3 ) ; root2 -> left -> left = newNode ( 4 ) ; root2 -> left -> right = newNode ( 5 ) ; areAnagrams ( root1 , root2 ) ? cout << " Yes " : cout << " No " ; return 0 ; } |
Check if given Preorder , Inorder and Postorder traversals are of same tree | C ++ program to check if all three given traversals are of the same tree ; A Binary Tree Node ; Utility function to create a new tree node ; Function to find index of value in arr [ start ... end ] The function assumes that value is present in in [ ] ; Recursive function to construct binary tree of size len from Inorder traversal in [ ] and Preorder traversal pre [ ] . Initial values of inStrt and inEnd should be 0 and len - 1. The function doesn 't do any error checking for cases where inorder and preorder do not form a tree ; Pick current node from Preorder traversal using preIndex and increment preIndex ; If this node has no children then return ; Else find the index of this node in Inorder traversal ; Using index in Inorder traversal , construct left and right subtress ; function to compare Postorder traversal on constructed tree and given Postorder ; first recur on left child ; now recur on right child ; Compare if data at current index in both Postorder traversals are same ; Driver program to test above functions ; build tree from given Inorder and Preorder traversals ; compare postorder traversal on constructed tree with given Postorder traversal ; If both postorder traversals are same | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } int search ( int arr [ ] , int strt , int end , int value ) { for ( int i = strt ; i <= end ; i ++ ) { if ( arr [ i ] == value ) return i ; } } Node * buildTree ( int in [ ] , int pre [ ] , int inStrt , int inEnd ) { static int preIndex = 0 ; if ( inStrt > inEnd ) return NULL ; Node * tNode = newNode ( pre [ preIndex ++ ] ) ; if ( inStrt == inEnd ) return tNode ; int inIndex = search ( in , inStrt , inEnd , tNode -> data ) ; tNode -> left = buildTree ( in , pre , inStrt , inIndex - 1 ) ; tNode -> right = buildTree ( in , pre , inIndex + 1 , inEnd ) ; return tNode ; } int checkPostorder ( Node * node , int postOrder [ ] , int index ) { if ( node == NULL ) return index ; index = checkPostorder ( node -> left , postOrder , index ) ; index = checkPostorder ( node -> right , postOrder , index ) ; if ( node -> data == postOrder [ index ] ) index ++ ; else return -1 ; return index ; } int main ( ) { int inOrder [ ] = { 4 , 2 , 5 , 1 , 3 } ; int preOrder [ ] = { 1 , 2 , 4 , 5 , 3 } ; int postOrder [ ] = { 4 , 5 , 2 , 3 , 1 } ; int len = sizeof ( inOrder ) / sizeof ( inOrder [ 0 ] ) ; Node * root = buildTree ( inOrder , preOrder , 0 , len - 1 ) ; int index = checkPostorder ( root , postOrder , 0 ) ; if ( index == len ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Check if X can give change to every person in the Queue | C ++ program to check whether X can give change to every person in the Queue ; Function to check if every person will get the change from X ; To count the 5 $ and 10 & notes ; Serve the customer in order ; Increase the number of 5 $ note by one ; decrease the number of note 5 $ and increase 10 $ note by one ; decrease 5 $ and 10 $ note by one ; decrease 5 $ note by three ; Driver Code ; queue of customers with available notes . ; Calling function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int isChangeable ( int notes [ ] , int n ) { int fiveCount = 0 ; int tenCount = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( notes [ i ] == 5 ) fiveCount ++ ; else if ( notes [ i ] == 10 ) { if ( fiveCount > 0 ) { fiveCount -- ; tenCount ++ ; } else return 0 ; } else { if ( fiveCount > 0 && tenCount > 0 ) { fiveCount -- ; tenCount -- ; } else if ( fiveCount >= 3 ) { fiveCount -= 3 ; } else return 0 ; } } return 1 ; } int main ( ) { int a [ ] = { 5 , 5 , 5 , 10 , 20 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; if ( isChangeable ( a , n ) ) cout << " YES " ; else cout << " NO " ; return 0 ; } |
Index Mapping ( or Trivial Hashing ) with negatives allowed | CPP program to implement direct index mapping with negative values allowed . ; Since array is global , it is initialized as 0. ; searching if X is Present in the given array or not . ; if X is negative take the absolute value of X . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1000 NEW_LINE bool has [ MAX + 1 ] [ 2 ] ; bool search ( int X ) { if ( X >= 0 ) { if ( has [ X ] [ 0 ] == 1 ) return true ; else return false ; } X = abs ( X ) ; if ( has [ X ] [ 1 ] == 1 ) return true ; return false ; } void insert ( int a [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] >= 0 ) has [ a [ i ] ] [ 0 ] = 1 ; else has [ abs ( a [ i ] ) ] [ 1 ] = 1 ; } } int main ( ) { int a [ ] = { -1 , 9 , -5 , -8 , -5 , -2 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; insert ( a , n ) ; int X = -5 ; if ( search ( X ) == true ) cout << " Present " ; else cout << " Not β Present " ; return 0 ; } |
Given level order traversal of a Binary Tree , check if the Tree is a Min | C ++ program to check if a given tree is Binary Heap or not ; Returns true if given level order traversal is Min Heap . ; First non leaf node is at index ( n / 2 - 1 ) . Check whether each parent is greater than child ; Left child will be at index 2 * i + 1 Right child will be at index 2 * i + 2 ; If parent is greater than right child ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isMinHeap ( int level [ ] , int n ) { for ( int i = ( n / 2 - 1 ) ; i >= 0 ; i -- ) { if ( level [ i ] > level [ 2 * i + 1 ] ) return false ; if ( 2 * i + 2 < n ) { if ( level [ i ] > level [ 2 * i + 2 ] ) return false ; } } return true ; } int main ( ) { int level [ ] = { 10 , 15 , 14 , 25 , 30 } ; int n = sizeof ( level ) / sizeof ( level [ 0 ] ) ; if ( isMinHeap ( level , n ) ) cout << " True " ; else cout << " False " ; return 0 ; } |
Minimum delete operations to make all elements of array same | C ++ program to find minimum number of deletes required to make all elements same . ; Function to get minimum number of elements to be deleted from array to make array elements equal ; Create an hash map and store frequencies of all array elements in it using element as key and frequency as value ; Find maximum frequency among all frequencies . ; To minimize delete operations , we remove all elements but the most frequent element . ; Driver program to run the case | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minDelete ( int arr [ ] , int n ) { unordered_map < int , int > freq ; for ( int i = 0 ; i < n ; i ++ ) freq [ arr [ i ] ] ++ ; int max_freq = INT_MIN ; for ( auto itr = freq . begin ( ) ; itr != freq . end ( ) ; itr ++ ) max_freq = max ( max_freq , itr -> second ) ; return n - max_freq ; } int main ( ) { int arr [ ] = { 4 , 3 , 4 , 4 , 2 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minDelete ( arr , n ) ; return 0 ; } |
Minimum operation to make all elements equal in array | CPP program to find the minimum number of operations required to make all elements of array equal ; function for min operation ; Insert all elements in hash . ; find the max frequency ; return result ; driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperation ( int arr [ ] , int n ) { unordered_map < int , int > hash ; for ( int i = 0 ; i < n ; i ++ ) hash [ arr [ i ] ] ++ ; int max_count = 0 ; for ( auto i : hash ) if ( max_count < i . second ) max_count = i . second ; return ( n - max_count ) ; } int main ( ) { int arr [ ] = { 1 , 5 , 2 , 1 , 3 , 2 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minOperation ( arr , n ) ; return 0 ; } |
Maximum distance between two occurrences of same element in array | C ++ program to find maximum distance between two same occurrences of a number . ; Function to find maximum distance between equal elements ; Used to store element to first index mapping ; Traverse elements and find maximum distance between same occurrences with the help of map . ; If this is first occurrence of element , insert its index in map ; Else update max distance ; Driver program to run the case | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxDistance ( int arr [ ] , int n ) { unordered_map < int , int > mp ; int max_dist = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp . find ( arr [ i ] ) == mp . end ( ) ) mp [ arr [ i ] ] = i ; else max_dist = max ( max_dist , i - mp [ arr [ i ] ] ) ; } return max_dist ; } int main ( ) { int arr [ ] = { 3 , 2 , 1 , 2 , 1 , 4 , 5 , 8 , 6 , 7 , 4 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxDistance ( arr , n ) ; return 0 ; } |
Check if a given array contains duplicate elements within k distance from each other | C ++ program to Check if a given array contains duplicate elements within k distance from each other ; Creates an empty hashset ; Traverse the input array ; If already present n hash , then we found a duplicate within k distance ; Add this item to hashset ; Remove the k + 1 distant item ; Driver method to test above method | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkDuplicatesWithinK ( int arr [ ] , int n , int k ) { unordered_set < int > myset ; for ( int i = 0 ; i < n ; i ++ ) { if ( myset . find ( arr [ i ] ) != myset . end ( ) ) return true ; myset . insert ( arr [ i ] ) ; if ( i >= k ) myset . erase ( arr [ i - k ] ) ; } return false ; } int main ( ) { int arr [ ] = { 10 , 5 , 3 , 4 , 3 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( checkDuplicatesWithinK ( arr , n , 3 ) ) cout << " Yes " ; else cout << " No " ; } |
Find duplicates in a given array when elements are not limited to a range | C ++ implementation of the above approach ; Function to find the Duplicates , if duplicate occurs 2 times or more than 2 times in array so , it will print duplicate value only once at output ; Initialize ifPresent as false ; ArrayList to store the output ; Checking if element is present in the ArrayList or not if present then break ; If element is not present in the ArrayList then add it to ArrayList and make ifPresent at true ; If duplicates is present then print ArrayList ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findDuplicates ( int arr [ ] , int len ) { bool ifPresent = false ; vector < int > al ; for ( int i = 0 ; i < len - 1 ; i ++ ) { for ( int j = i + 1 ; j < len ; j ++ ) { if ( arr [ i ] == arr [ j ] ) { auto it = std :: find ( al . begin ( ) , al . end ( ) , arr [ i ] ) ; if ( it != al . end ( ) ) { break ; } else { al . push_back ( arr [ i ] ) ; ifPresent = true ; } } } } if ( ifPresent == true ) { cout << " [ " << al [ 0 ] << " , β " ; for ( int i = 1 ; i < al . size ( ) - 1 ; i ++ ) { cout << al [ i ] << " , β " ; } cout << al [ al . size ( ) - 1 ] << " ] " ; } else { cout << " No β duplicates β present β in β arrays " ; } } int main ( ) { int arr [ ] = { 12 , 11 , 40 , 12 , 5 , 6 , 5 , 12 , 11 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findDuplicates ( arr , n ) ; return 0 ; } |
Check if leaf traversal of two Binary Trees is same ? | C ++ code to check if leaf traversals of two Binary Trees are same or not . ; Binary Tree Node ; Returns new Node with data as input to below function . ; checks if a given node is leaf or not . ; iterative function . returns true if leaf traversals are same , else false . ; Create empty stacks . These stacks are going to be used for iterative traversals . ; loop until either of stacks are non - empty . ; this means one of the stacks has extra leaves , hence return false . ; Push right and left children of temp1 . Note that right child is inserted before left ; same for tree2 ; If one is null and other is not , then return false ; If both are not null and data is not same return false ; all leaves are matched ; Driver Code ; Let us create trees in above example 1 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left ; Node * right ; } ; Node * newNode ( int d ) { Node * temp = new Node ; temp -> data = d ; temp -> left = NULL ; temp -> right = NULL ; return temp ; } bool isLeaf ( Node * root ) { if ( root == NULL ) return false ; if ( ! root -> left && ! root -> right ) return true ; return false ; } bool isSame ( Node * root1 , Node * root2 ) { stack < Node * > s1 ; stack < Node * > s2 ; s1 . push ( root1 ) ; s2 . push ( root2 ) ; while ( ! s1 . empty ( ) || ! s2 . empty ( ) ) { if ( s1 . empty ( ) || s2 . empty ( ) ) return false ; Node * temp1 = s1 . top ( ) ; s1 . pop ( ) ; while ( temp1 != NULL && ! isLeaf ( temp1 ) ) { if ( temp1 -> right ) s1 . push ( temp1 -> right ) ; if ( temp1 -> left ) s1 . push ( temp1 -> left ) ; temp1 = s1 . top ( ) ; s1 . pop ( ) ; } Node * temp2 = s2 . top ( ) ; s2 . pop ( ) ; while ( temp2 != NULL && ! isLeaf ( temp2 ) ) { if ( temp2 -> right ) s2 . push ( temp2 -> right ) ; if ( temp2 -> left ) s2 . push ( temp2 -> left ) ; temp2 = s2 . top ( ) ; s2 . pop ( ) ; } if ( ! temp1 && temp2 ) return false ; if ( temp1 && ! temp2 ) return false ; if ( temp1 && temp2 ) { return temp1 -> data == temp2 -> data ; } } return true ; } int main ( ) { Node * root1 = newNode ( 1 ) ; root1 -> left = newNode ( 2 ) ; root1 -> right = newNode ( 3 ) ; root1 -> left -> left = newNode ( 4 ) ; root1 -> right -> left = newNode ( 6 ) ; root1 -> right -> right = newNode ( 7 ) ; Node * root2 = newNode ( 0 ) ; root2 -> left = newNode ( 1 ) ; root2 -> right = newNode ( 5 ) ; root2 -> left -> right = newNode ( 4 ) ; root2 -> right -> left = newNode ( 6 ) ; root2 -> right -> right = newNode ( 7 ) ; if ( isSame ( root1 , root2 ) ) cout << " Same " ; else cout << " Not β Same " ; return 0 ; } |
Most frequent element in an array | CPP program to find the most frequent element in an array . ; Sort the array ; find the max frequency using linear traversal ; If last element is most frequent ; driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int mostFrequent ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int max_count = 1 , res = arr [ 0 ] , curr_count = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] == arr [ i - 1 ] ) curr_count ++ ; else { if ( curr_count > max_count ) { max_count = curr_count ; res = arr [ i - 1 ] ; } curr_count = 1 ; } } if ( curr_count > max_count ) { max_count = curr_count ; res = arr [ n - 1 ] ; } return res ; } int main ( ) { int arr [ ] = { 1 , 5 , 2 , 1 , 3 , 2 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << mostFrequent ( arr , n ) ; return 0 ; } |
Most frequent element in an array | CPP program to find the most frequent element in an array . ; Insert all elements in hash . ; find the max frequency ; driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int mostFrequent ( int arr [ ] , int n ) { unordered_map < int , int > hash ; for ( int i = 0 ; i < n ; i ++ ) hash [ arr [ i ] ] ++ ; int max_count = 0 , res = -1 ; for ( auto i : hash ) { if ( max_count < i . second ) { res = i . first ; max_count = i . second ; } } return res ; } int main ( ) { int arr [ ] = { 1 , 5 , 2 , 1 , 3 , 2 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << mostFrequent ( arr , n ) ; return 0 ; } |
Smallest subarray with all occurrences of a most frequent element | C ++ implementation to find smallest subarray with all occurrences of a most frequent element ; To store left most occurrence of elements ; To store counts of elements ; To store maximum frequency ; To store length and starting index of smallest result window ; First occurrence of an element , store the index ; increase the frequency of elements ; Find maximum repeated element and store its last occurrence and first occurrence ; length of subsegment ; select subsegment of smallest size ; Print the subsegment with all occurrences of a most frequent element ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void smallestSubsegment ( int a [ ] , int n ) { unordered_map < int , int > left ; unordered_map < int , int > count ; int mx = 0 ; int mn , strindex ; for ( int i = 0 ; i < n ; i ++ ) { int x = a [ i ] ; if ( count [ x ] == 0 ) { left [ x ] = i ; count [ x ] = 1 ; } else count [ x ] ++ ; if ( count [ x ] > mx ) { mx = count [ x ] ; mn = i - left [ x ] + 1 ; strindex = left [ x ] ; } else if ( count [ x ] == mx && i - left [ x ] + 1 < mn ) { mn = i - left [ x ] + 1 ; strindex = left [ x ] ; } } for ( int i = strindex ; i < strindex + mn ; i ++ ) cout << a [ i ] << " β " ; } int main ( ) { int A [ ] = { 1 , 2 , 2 , 2 , 1 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; smallestSubsegment ( A , n ) ; return 0 ; } |
Given an array of pairs , find all symmetric pairs in it | A C ++ program to find all symmetric pairs in a given array of pairs ; Print all pairs that have a symmetric counterpart ; Creates an empty hashMap hM ; Traverse through the given array ; First and second elements of current pair ; If found and value in hash matches with first element of this pair , we found symmetry ; Else put sec element of this pair in hash ; Driver method | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findSymPairs ( int arr [ ] [ 2 ] , int row ) { unordered_map < int , int > hM ; for ( int i = 0 ; i < row ; i ++ ) { int first = arr [ i ] [ 0 ] ; int sec = arr [ i ] [ 1 ] ; if ( hM . find ( sec ) != hM . end ( ) && hM [ sec ] == first ) cout << " ( " << sec << " , β " << first << " ) " << endl ; else hM [ first ] = sec ; } } int main ( ) { int arr [ 5 ] [ 2 ] ; arr [ 0 ] [ 0 ] = 11 ; arr [ 0 ] [ 1 ] = 20 ; arr [ 1 ] [ 0 ] = 30 ; arr [ 1 ] [ 1 ] = 40 ; arr [ 2 ] [ 0 ] = 5 ; arr [ 2 ] [ 1 ] = 10 ; arr [ 3 ] [ 0 ] = 40 ; arr [ 3 ] [ 1 ] = 30 ; arr [ 4 ] [ 0 ] = 10 ; arr [ 4 ] [ 1 ] = 5 ; findSymPairs ( arr , 5 ) ; } |
Find any one of the multiple repeating elements in read only array | C ++ program to find one of the repeating elements in a read only array ; Function to find one of the repeating elements ; Size of blocks except the last block is sq ; Number of blocks to incorporate 1 to n values blocks are numbered from 0 to range - 1 ( both included ) ; Count array maintains the count for all blocks ; Traversing the read only array and updating count ; arr [ i ] belongs to block number ( arr [ i ] - 1 ) / sq i is considered to start from 0 ; The selected_block is set to last block by default . Rest of the blocks are checked ; after finding block with size > sq method of hashing is used to find the element repeating in this block ; checks if the element belongs to the selected_block ; repeating element found ; return - 1 if no repeating element exists ; Driver Program ; read only array , not to be modified ; array of size 6 ( n + 1 ) having elements between 1 and 5 | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findRepeatingNumber ( const int arr [ ] , int n ) { int sq = sqrt ( n ) ; int range = ( n / sq ) + 1 ; int count [ range ] = { 0 } ; for ( int i = 0 ; i <= n ; i ++ ) { count [ ( arr [ i ] - 1 ) / sq ] ++ ; } int selected_block = range - 1 ; for ( int i = 0 ; i < range - 1 ; i ++ ) { if ( count [ i ] > sq ) { selected_block = i ; break ; } } unordered_map < int , int > m ; for ( int i = 0 ; i <= n ; i ++ ) { if ( ( ( selected_block * sq ) < arr [ i ] ) && ( arr [ i ] <= ( ( selected_block + 1 ) * sq ) ) ) { m [ arr [ i ] ] ++ ; if ( m [ arr [ i ] ] > 1 ) return arr [ i ] ; } } return -1 ; } int main ( ) { const int arr [ ] = { 1 , 1 , 2 , 3 , 5 , 4 } ; int n = 5 ; cout << " One β of β the β numbers β repeated β in " " β the β array β is : β " << findRepeatingNumber ( arr , n ) << endl ; } |
Find top three repeated in array | C ++ Program to Find the top three repeated numbers ; Function to print top three repeated numbers ; There should be atleast two elements ; Count Frequency of each element ; Initialize first value of each variable of Pair type is INT_MIN ; If frequency of current element is not zero and greater than frequency of first largest element ; Update second and third largest ; Modify values of x Number ; If frequency of current element is not zero and frequency of current element is less than frequency of first largest element , but greater than y element ; Modify values of third largest ; Modify values of second largest ; If frequency of current element is not zero and frequency of current element is less than frequency of first element and second largest , but greater than third largest . ; Modify values of z Number ; Driver 's Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void top3Repeated ( int arr [ ] , int n ) { if ( n < 3 ) { cout << " Invalid β Input " ; return ; } unordered_map < int , int > fre ; for ( int i = 0 ; i < n ; i ++ ) fre [ arr [ i ] ] ++ ; pair < int , int > x , y , z ; x . first = y . first = z . first = INT_MIN ; for ( auto curr : fre ) { if ( curr . second > x . first ) { z = y ; y = x ; x . first = curr . second ; x . second = curr . first ; } else if ( curr . second > y . first ) { z = y ; y . first = curr . second ; y . second = curr . first ; } else if ( curr . second > z . first ) { z . first = curr . second ; z . second = curr . first ; } } cout << " Three β largest β elements β are β " << x . second << " β " << y . second << " β " << z . second ; } int main ( ) { int arr [ ] = { 3 , 4 , 2 , 3 , 16 , 3 , 15 , 16 , 15 , 15 , 16 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; top3Repeated ( arr , n ) ; return 0 ; } |
Group multiple occurrence of array elements ordered by first occurrence | A simple C ++ program to group multiple occurrences of individual array elements ; A simple method to group all occurrences of individual elements ; Initialize all elements as not visited ; Traverse all elements ; Check if this is first occurrence ; If yes , print it and all subsequent occurrences ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void groupElements ( int arr [ ] , int n ) { bool * visited = new bool [ n ] ; for ( int i = 0 ; i < n ; i ++ ) visited [ i ] = false ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! visited [ i ] ) { cout << arr [ i ] << " β " ; for ( int j = i + 1 ; j < n ; j ++ ) { if ( arr [ i ] == arr [ j ] ) { cout << arr [ i ] << " β " ; visited [ j ] = true ; } } } } delete [ ] visited ; } int main ( ) { int arr [ ] = { 4 , 6 , 9 , 2 , 3 , 4 , 9 , 6 , 10 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; groupElements ( arr , n ) ; return 0 ; } |
How to check if two given sets are disjoint ? | A Simple C ++ program to check if two sets are disjoint ; Returns true if set1 [ ] and set2 [ ] are disjoint , else false ; Take every element of set1 [ ] and search it in set2 ; If no element of set1 is present in set2 ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool areDisjoint ( int set1 [ ] , int set2 [ ] , int m , int n ) { for ( int i = 0 ; i < m ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) if ( set1 [ i ] == set2 [ j ] ) return false ; return true ; } int main ( ) { int set1 [ ] = { 12 , 34 , 11 , 9 , 3 } ; int set2 [ ] = { 7 , 2 , 1 , 5 } ; int m = sizeof ( set1 ) / sizeof ( set1 [ 0 ] ) ; int n = sizeof ( set2 ) / sizeof ( set2 [ 0 ] ) ; areDisjoint ( set1 , set2 , m , n ) ? cout << " Yes " : cout << " β No " ; return 0 ; } |
How to check if two given sets are disjoint ? | A Simple C ++ program to check if two sets are disjoint ; Returns true if set1 [ ] and set2 [ ] are disjoint , else false ; Sort the given two sets ; Check for same elements using merge like process ; if set1 [ i ] == set2 [ j ] ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool areDisjoint ( int set1 [ ] , int set2 [ ] , int m , int n ) { sort ( set1 , set1 + m ) ; sort ( set2 , set2 + n ) ; int i = 0 , j = 0 ; while ( i < m && j < n ) { if ( set1 [ i ] < set2 [ j ] ) i ++ ; else if ( set2 [ j ] < set1 [ i ] ) j ++ ; else return false ; } return true ; } int main ( ) { int set1 [ ] = { 12 , 34 , 11 , 9 , 3 } ; int set2 [ ] = { 7 , 2 , 1 , 5 } ; int m = sizeof ( set1 ) / sizeof ( set1 [ 0 ] ) ; int n = sizeof ( set2 ) / sizeof ( set2 [ 0 ] ) ; areDisjoint ( set1 , set2 , m , n ) ? cout << " Yes " : cout << " β No " ; return 0 ; } |
How to check if two given sets are disjoint ? | C ++ program to check if two sets are distinct or not ; This function prints all distinct elements ; Creates an empty hashset ; Traverse the first set and store its elements in hash ; Traverse the second set and check if any element of it is already in hash or not . ; Driver method to test above method | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool areDisjoint ( int set1 [ ] , int set2 [ ] , int n1 , int n2 ) { set < int > myset ; for ( int i = 0 ; i < n1 ; i ++ ) myset . insert ( set1 [ i ] ) ; for ( int i = 0 ; i < n2 ; i ++ ) if ( myset . find ( set2 [ i ] ) != myset . end ( ) ) return false ; return true ; } int main ( ) { int set1 [ ] = { 10 , 5 , 3 , 4 , 6 } ; int set2 [ ] = { 8 , 7 , 9 , 3 } ; int n1 = sizeof ( set1 ) / sizeof ( set1 [ 0 ] ) ; int n2 = sizeof ( set2 ) / sizeof ( set2 [ 0 ] ) ; if ( areDisjoint ( set1 , set2 , n1 , n2 ) ) cout << " Yes " ; else cout << " No " ; } |
Non | CPP program to find Non - overlapping sum ; function for calculating Non - overlapping sum of two array ; Insert elements of both arrays ; calculate non - overlapped sum ; driver code ; size of array ; function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findSum ( int A [ ] , int B [ ] , int n ) { unordered_map < int , int > hash ; for ( int i = 0 ; i < n ; i ++ ) { hash [ A [ i ] ] ++ ; hash [ B [ i ] ] ++ ; } int sum = 0 ; for ( auto x : hash ) if ( x . second == 1 ) sum += x . first ; return sum ; } int main ( ) { int A [ ] = { 5 , 4 , 9 , 2 , 3 } ; int B [ ] = { 2 , 8 , 7 , 6 , 3 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << findSum ( A , B , n ) ; return 0 ; } |
Find elements which are present in first array and not in second | C ++ simple program to find elements which are not present in second array ; Function for finding elements which are there in a [ ] but not in b [ ] . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findMissing ( int a [ ] , int b [ ] , int n , int m ) { for ( int i = 0 ; i < n ; i ++ ) { int j ; for ( j = 0 ; j < m ; j ++ ) if ( a [ i ] == b [ j ] ) break ; if ( j == m ) cout << a [ i ] << " β " ; } } int main ( ) { int a [ ] = { 1 , 2 , 6 , 3 , 4 , 5 } ; int b [ ] = { 2 , 4 , 3 , 1 , 0 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int m = sizeof ( b ) / sizeof ( b [ 1 ] ) ; findMissing ( a , b , n , m ) ; return 0 ; } |
Find elements which are present in first array and not in second | C ++ efficient program to find elements which are not present in second array ; Function for finding elements which are there in a [ ] but not in b [ ] . ; Store all elements of second array in a hash table ; Print all elements of first array that are not present in hash table ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findMissing ( int a [ ] , int b [ ] , int n , int m ) { unordered_set < int > s ; for ( int i = 0 ; i < m ; i ++ ) s . insert ( b [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) if ( s . find ( a [ i ] ) == s . end ( ) ) cout << a [ i ] << " β " ; } int main ( ) { int a [ ] = { 1 , 2 , 6 , 3 , 4 , 5 } ; int b [ ] = { 2 , 4 , 3 , 1 , 0 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int m = sizeof ( b ) / sizeof ( b [ 1 ] ) ; findMissing ( a , b , n , m ) ; return 0 ; } |
Check if two arrays are equal or not | C ++ program to find given two array are equal or not ; Returns true if arr1 [ 0. . n - 1 ] and arr2 [ 0. . m - 1 ] contain same elements . ; If lengths of array are not equal means array are not equal ; Sort both arrays ; Linearly compare elements ; If all elements were same . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool areEqual ( int arr1 [ ] , int arr2 [ ] , int n , int m ) { if ( n != m ) return false ; sort ( arr1 , arr1 + n ) ; sort ( arr2 , arr2 + m ) ; for ( int i = 0 ; i < n ; i ++ ) if ( arr1 [ i ] != arr2 [ i ] ) return false ; return true ; } int main ( ) { int arr1 [ ] = { 3 , 5 , 2 , 5 , 2 } ; int arr2 [ ] = { 2 , 3 , 5 , 5 , 2 } ; int n = sizeof ( arr1 ) / sizeof ( int ) ; int m = sizeof ( arr2 ) / sizeof ( int ) ; if ( areEqual ( arr1 , arr2 , n , m ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Pair with given sum and maximum shortest distance from end | C ++ code to find maximum shortest distance from endpoints ; function to find maximum shortest distance ; stores the shortest distance of every element in original array . ; shortest distance from ends ; if duplicates are found , b [ x ] is replaced with minimum of the previous and current position 's shortest distance ; similar elements ignore them cause we need distinct elements ; driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int find_maximum ( int a [ ] , int n , int k ) { unordered_map < int , int > b ; for ( int i = 0 ; i < n ; i ++ ) { int x = a [ i ] ; int d = min ( 1 + i , n - i ) ; if ( b . find ( x ) == b . end ( ) ) b [ x ] = d ; else b [ x ] = min ( d , b [ x ] ) ; } int ans = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { int x = a [ i ] ; if ( x != k - x && b . find ( k - x ) != b . end ( ) ) ans = min ( max ( b [ x ] , b [ k - x ] ) , ans ) ; } return ans ; } int main ( ) { int a [ ] = { 3 , 5 , 8 , 6 , 7 } ; int K = 11 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << find_maximum ( a , n , K ) << endl ; return 0 ; } |
Pair with given product | Set 1 ( Find if any pair exists ) | A simple C ++ program to find if there is a pair with given product . ; Returns true if there is a pair in arr [ 0. . n - 1 ] with product equal to x . ; Consider all possible pairs and check for every pair . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isProduct ( int arr [ ] , int n , int x ) { for ( int i = 0 ; i < n - 1 ; i ++ ) for ( int j = i + 1 ; i < n ; i ++ ) if ( arr [ i ] * arr [ j ] == x ) return true ; return false ; } int main ( ) { int arr [ ] = { 10 , 20 , 9 , 40 } ; int x = 400 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; isProduct ( arr , n , x ) ? cout << " Yesn " : cout << " Non " ; x = 190 ; isProduct ( arr , n , x ) ? cout << " Yesn " : cout << " Non " ; return 0 ; } |
Pair with given product | Set 1 ( Find if any pair exists ) | C ++ program to find if there is a pair with given product . ; Returns true if there is a pair in arr [ 0. . n - 1 ] with product equal to x . ; Create an empty set and insert first element into it ; Traverse remaining elements ; 0 case must be handles explicitly as x % 0 is undefined behaviour in C ++ ; x / arr [ i ] exists in hash , then we found a pair ; Insert arr [ i ] ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isProduct ( int arr [ ] , int n , int x ) { if ( n < 2 ) return false ; unordered_set < int > s ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == 0 ) { if ( x == 0 ) return true ; else continue ; } if ( x % arr [ i ] == 0 ) { if ( s . find ( x / arr [ i ] ) != s . end ( ) ) return true ; s . insert ( arr [ i ] ) ; } } return false ; } int main ( ) { int arr [ ] = { 10 , 20 , 9 , 40 } ; int x = 400 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; isProduct ( arr , n , x ) ? cout << " Yes STRNEWLINE " : cout << " Non " ; x = 190 ; isProduct ( arr , n , x ) ? cout << " Yes STRNEWLINE " : cout << " Non " ; return 0 ; } |
Check whether a given binary tree is perfect or not | C ++ program to check whether a given Binary Tree is Perfect or not ; Tree node structure ; Returns depth of leftmost leaf . ; This function tests if a binary tree is perfect or not . It basically checks for two things : 1 ) All leaves are at same level 2 ) All internal nodes have two children ; An empty tree is perfect ; If leaf node , then its depth must be same as depth of all other leaves . ; If internal node and one child is empty ; Left and right subtrees must be perfect . ; Wrapper over isPerfectRec ( ) ; Helper function that allocates a new node with the given key and NULL left and right pointer . ; Driver Program | #include <bits/stdc++.h> NEW_LINE struct Node { int key ; struct Node * left , * right ; } ; int findADepth ( Node * node ) { int d = 0 ; while ( node != NULL ) { d ++ ; node = node -> left ; } return d ; } bool isPerfectRec ( struct Node * root , int d , int level = 0 ) { if ( root == NULL ) return true ; if ( root -> left == NULL && root -> right == NULL ) return ( d == level + 1 ) ; if ( root -> left == NULL root -> right == NULL ) return false ; return isPerfectRec ( root -> left , d , level + 1 ) && isPerfectRec ( root -> right , d , level + 1 ) ; } bool isPerfect ( Node * root ) { int d = findADepth ( root ) ; return isPerfectRec ( root , d ) ; } struct Node * newNode ( int k ) { struct Node * node = new Node ; node -> key = k ; node -> right = node -> left = NULL ; return node ; } int main ( ) { struct Node * root = NULL ; root = newNode ( 10 ) ; root -> left = newNode ( 20 ) ; root -> right = newNode ( 30 ) ; root -> left -> left = newNode ( 40 ) ; root -> left -> right = newNode ( 50 ) ; root -> right -> left = newNode ( 60 ) ; root -> right -> right = newNode ( 70 ) ; if ( isPerfect ( root ) ) printf ( " Yes STRNEWLINE " ) ; else printf ( " No STRNEWLINE " ) ; return ( 0 ) ; } |
Find pair with greatest product in array | C ++ program to find a pair with product in given array . ; Function to find greatest number that us ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findGreatest ( int arr [ ] , int n ) { int result = -1 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n - 1 ; j ++ ) for ( int k = j + 1 ; k < n ; k ++ ) if ( arr [ j ] * arr [ k ] == arr [ i ] ) result = max ( result , arr [ i ] ) ; return result ; } int main ( ) { int arr [ ] = { 30 , 10 , 9 , 3 , 35 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findGreatest ( arr , n ) ; return 0 ; } |
Find pair with greatest product in array | C ++ program to find the largest product number ; Function to find greatest number ; Store occurrences of all elements in hash array ; Sort the array and traverse all elements from end . ; For every element , check if there is another element which divides it . ; Check if the result value exists in array or not if yes the return arr [ i ] ; To handle the case like arr [ i ] = 4 and arr [ j ] = 2 ; Drivers code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findGreatest ( int arr [ ] , int n ) { unordered_map < int , int > m ; for ( int i = 0 ; i < n ; i ++ ) m [ arr [ i ] ] ++ ; sort ( arr , arr + n ) ; for ( int i = n - 1 ; i > 1 ; i -- ) { for ( int j = 0 ; j < i && arr [ j ] <= sqrt ( arr [ i ] ) ; j ++ ) { if ( arr [ i ] % arr [ j ] == 0 ) { int result = arr [ i ] / arr [ j ] ; if ( result != arr [ j ] && m [ result ] > 0 ) return arr [ i ] ; else if ( result == arr [ j ] && m [ result ] > 1 ) return arr [ i ] ; } } } return -1 ; } int main ( ) { int arr [ ] = { 17 , 2 , 1 , 15 , 30 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findGreatest ( arr , n ) ; return 0 ; } |
Remove minimum number of elements such that no common element exist in both array | CPP program to find minimum element to remove so no common element exist in both array ; To find no elements to remove so no common element exist ; To store count of array element ; Count elements of a ; Count elements of b ; Traverse through all common element , and pick minimum occurrence from two arrays ; To return count of minimum elements ; Driver program to test minRemove ( ) | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minRemove ( int a [ ] , int b [ ] , int n , int m ) { unordered_map < int , int > countA , countB ; for ( int i = 0 ; i < n ; i ++ ) countA [ a [ i ] ] ++ ; for ( int i = 0 ; i < m ; i ++ ) countB [ b [ i ] ] ++ ; int res = 0 ; for ( auto x : countA ) if ( countB . find ( x . first ) != countB . end ( ) ) res += min ( x . second , countB [ x . first ] ) ; return res ; } int main ( ) { int a [ ] = { 1 , 2 , 3 , 4 } ; int b [ ] = { 2 , 3 , 4 , 5 , 8 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int m = sizeof ( b ) / sizeof ( b [ 0 ] ) ; cout << minRemove ( a , b , n , m ) ; return 0 ; } |
Count items common to both the lists but with different prices | C ++ implementation to count items common to both the lists but with different prices ; details of an item ; function to count items common to both the lists but with different prices ; for each item of ' list1' check if it is in ' list2' but with a different price ; required count of items ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct item { string name ; int price ; } ; int countItems ( item list1 [ ] , int m , item list2 [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < m ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) if ( ( list1 [ i ] . name . compare ( list2 [ j ] . name ) == 0 ) && ( list1 [ i ] . price != list2 [ j ] . price ) ) count ++ ; return count ; } int main ( ) { item list1 [ ] = { { " apple " , 60 } , { " bread " , 20 } , { " wheat " , 50 } , { " oil " , 30 } } ; item list2 [ ] = { { " milk " , 20 } , { " bread " , 15 } , { " wheat " , 40 } , { " apple " , 60 } } ; int m = sizeof ( list1 ) / sizeof ( list1 [ 0 ] ) ; int n = sizeof ( list2 ) / sizeof ( list2 [ 0 ] ) ; cout << " Count β = β " << countItems ( list1 , m , list2 , n ) ; return 0 ; } |
Count items common to both the lists but with different prices | C ++ implementation to count items common to both the lists but with different prices ; Details of an item ; comparator function used for sorting ; Function to search ' str ' in ' list2 [ ] ' . If it exists then price associated with ' str ' in ' list2 [ ] ' is being returned else - 1 is returned . Here binary serach technique is being applied for searching ; if true the item ' str ' is in ' list2' ; item ' str ' is not in ' list2' ; Function to count items common to both the lists but with different prices ; sort ' list2' in alphabetcal order of items name ; initial count ; get the price of item ' list1 [ i ] ' from ' list2' if item in not present in second list then - 1 is being obtained ; if item is present in list2 with a different price ; Required count of items ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct item { string name ; int price ; } ; bool compare ( struct item a , struct item b ) { return ( a . name . compare ( b . name ) <= 0 ) ; } int binary_search ( item list2 [ ] , int low , int high , string str ) { while ( low <= high ) { int mid = ( low + high ) / 2 ; if ( list2 [ mid ] . name . compare ( str ) == 0 ) return list2 [ mid ] . price ; else if ( list2 [ mid ] . name . compare ( str ) < 0 ) low = mid + 1 ; else high = mid - 1 ; } return -1 ; } int countItems ( item list1 [ ] , int m , item list2 [ ] , int n ) { sort ( list2 , list2 + n , compare ) ; int count = 0 ; for ( int i = 0 ; i < m ; i ++ ) { int r = binary_search ( list2 , 0 , n - 1 , list1 [ i ] . name ) ; if ( ( r != -1 ) && ( r != list1 [ i ] . price ) ) count ++ ; } return count ; } int main ( ) { item list1 [ ] = { { " apple " , 60 } , { " bread " , 20 } , { " wheat " , 50 } , { " oil " , 30 } } ; item list2 [ ] = { { " milk " , 20 } , { " bread " , 15 } , { " wheat " , 40 } , { " apple " , 60 } } ; int m = sizeof ( list1 ) / sizeof ( list1 [ 0 ] ) ; int n = sizeof ( list2 ) / sizeof ( list2 [ 0 ] ) ; cout << " Count β = β " << countItems ( list1 , m , list2 , n ) ; return 0 ; } |
Count items common to both the lists but with different prices | C ++ implementation to count items common to both the lists but with different prices ; details of an item ; function to count items common to both the lists but with different prices ; ' um ' implemented as hash table that contains item name as the key and price as the value associated with the key ; insert elements of ' list1' in ' um ' ; for each element of ' list2' check if it is present in ' um ' with a different price value ; required count of items ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct item { string name ; int price ; } ; int countItems ( item list1 [ ] , int m , item list2 [ ] , int n ) { unordered_map < string , int > um ; int count = 0 ; for ( int i = 0 ; i < m ; i ++ ) um [ list1 [ i ] . name ] = list1 [ i ] . price ; for ( int i = 0 ; i < n ; i ++ ) if ( ( um . find ( list2 [ i ] . name ) != um . end ( ) ) && ( um [ list2 [ i ] . name ] != list2 [ i ] . price ) ) count ++ ; return count ; } int main ( ) { item list1 [ ] = { { " apple " , 60 } , { " bread " , 20 } , { " wheat " , 50 } , { " oil " , 30 } } ; item list2 [ ] = { { " milk " , 20 } , { " bread " , 15 } , { " wheat " , 40 } , { " apple " , 60 } } ; int m = sizeof ( list1 ) / sizeof ( list1 [ 0 ] ) ; int n = sizeof ( list2 ) / sizeof ( list2 [ 0 ] ) ; cout << " Count β = β " << countItems ( list1 , m , list2 , n ) ; return 0 ; } |
Minimum Index Sum for Common Elements of Two Lists | ; Function to print common strings with minimum index sum ; resultant list ; iterating over sum in ascending order ; iterating over one list and check index ( Corresponding to given sum ) in other list ; put common strings in resultant list ; if common string found then break as we are considering index sums in increasing order . ; print the resultant list ; Driver code ; Creating list1 ; Creating list2 | #include <bits/stdc++.h> NEW_LINE using namespace std ; void find ( vector < string > list1 , vector < string > list2 ) { vector < string > res ; int max_possible_sum = list1 . size ( ) + list2 . size ( ) - 2 ; for ( int sum = 0 ; sum <= max_possible_sum ; sum ++ ) { for ( int i = 0 ; i <= sum ; i ++ ) if ( i < list1 . size ( ) && ( sum - i ) < list2 . size ( ) && list1 [ i ] == list2 [ sum - i ] ) res . push_back ( list1 [ i ] ) ; if ( res . size ( ) > 0 ) break ; } for ( int i = 0 ; i < res . size ( ) ; i ++ ) cout << res [ i ] << " β " ; } int main ( ) { vector < string > list1 ; list1 . push_back ( " GeeksforGeeks " ) ; list1 . push_back ( " Udemy " ) ; list1 . push_back ( " Coursera " ) ; list1 . push_back ( " edX " ) ; vector < string > list2 ; list2 . push_back ( " Codecademy " ) ; list2 . push_back ( " Khan β Academy " ) ; list2 . push_back ( " GeeksforGeeks " ) ; find ( list1 , list2 ) ; return 0 ; } |
Minimum Index Sum for Common Elements of Two Lists | Hashing based C ++ program to find common elements with minimum index sum . ; Function to print common strings with minimum index sum ; mapping strings to their indices ; resultant list ; If current sum is smaller than minsum ; if index sum is same then put this string in resultant list as well ; Print result ; Driver code ; Creating list1 ; Creating list2 | #include <bits/stdc++.h> NEW_LINE using namespace std ; void find ( vector < string > list1 , vector < string > list2 ) { unordered_map < string , int > map ; for ( int i = 0 ; i < list1 . size ( ) ; i ++ ) map [ list1 [ i ] ] = i ; vector < string > res ; int minsum = INT_MAX ; for ( int j = 0 ; j < list2 . size ( ) ; j ++ ) { if ( map . count ( list2 [ j ] ) ) { int sum = j + map [ list2 [ j ] ] ; if ( sum < minsum ) { minsum = sum ; res . clear ( ) ; res . push_back ( list2 [ j ] ) ; } else if ( sum == minsum ) res . push_back ( list2 [ j ] ) ; } } for ( int i = 0 ; i < res . size ( ) ; i ++ ) cout << res [ i ] << " β " ; } int main ( ) { vector < string > list1 ; list1 . push_back ( " GeeksforGeeks " ) ; list1 . push_back ( " Udemy " ) ; list1 . push_back ( " Coursera " ) ; list1 . push_back ( " edX " ) ; vector < string > list2 ; list2 . push_back ( " Codecademy " ) ; list2 . push_back ( " Khan β Academy " ) ; list2 . push_back ( " GeeksforGeeks " ) ; find ( list1 , list2 ) ; return 0 ; } |
Check whether a binary tree is a full binary tree or not | C ++ program to check whether a given Binary Tree is full or not ; Tree node structure ; Helper function that allocates a new node with the given key and NULL left and right pointer . ; This function tests if a binary tree is a full binary tree . ; If empty tree ; If leaf node ; If both left and right are not NULL , and left & right subtrees are full ; We reach here when none of the above if conditions work ; Driver Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * left , * right ; } ; struct Node * newNode ( char k ) { struct Node * node = new Node ; node -> key = k ; node -> right = node -> left = NULL ; return node ; } bool isFullTree ( struct Node * root ) { if ( root == NULL ) return true ; if ( root -> left == NULL && root -> right == NULL ) return true ; if ( ( root -> left ) && ( root -> right ) ) return ( isFullTree ( root -> left ) && isFullTree ( root -> right ) ) ; return false ; } int main ( ) { struct Node * root = NULL ; root = newNode ( 10 ) ; root -> left = newNode ( 20 ) ; root -> right = newNode ( 30 ) ; root -> left -> right = newNode ( 40 ) ; root -> left -> left = newNode ( 50 ) ; root -> right -> left = newNode ( 60 ) ; root -> right -> right = newNode ( 70 ) ; root -> left -> left -> left = newNode ( 80 ) ; root -> left -> left -> right = newNode ( 90 ) ; root -> left -> right -> left = newNode ( 80 ) ; root -> left -> right -> right = newNode ( 90 ) ; root -> right -> left -> left = newNode ( 80 ) ; root -> right -> left -> right = newNode ( 90 ) ; root -> right -> right -> left = newNode ( 80 ) ; root -> right -> right -> right = newNode ( 90 ) ; if ( isFullTree ( root ) ) cout << " The β Binary β Tree β is β full STRNEWLINE " ; else cout << " The β Binary β Tree β is β not β full STRNEWLINE " ; return ( 0 ) ; } |
Change the array into a permutation of numbers from 1 to n | CPP program to make a permutation of numbers from 1 to n using minimum changes . ; Store counts of all elements . ; Find next missing element to put in place of current element . ; Replace with next missing and insert the missing element in hash . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void makePermutation ( int a [ ] , int n ) { unordered_map < int , int > count ; for ( int i = 0 ; i < n ; i ++ ) count [ a [ i ] ] ++ ; int next_missing = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( count [ a [ i ] ] != 1 a [ i ] > n a [ i ] < 1 ) { count [ a [ i ] ] -- ; while ( count . find ( next_missing ) != count . end ( ) ) next_missing ++ ; a [ i ] = next_missing ; count [ next_missing ] = 1 ; } } } int main ( ) { int A [ ] = { 2 , 2 , 3 , 3 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; makePermutation ( A , n ) ; for ( int i = 0 ; i < n ; i ++ ) cout << A [ i ] << " β " ; return 0 ; } |
Count pairs with given sum | C ++ implementation of simple method to find count of pairs with given sum . ; Returns number of pairs in arr [ 0. . n - 1 ] with sum equal to ' sum ' ; Initialize result ; Consider all possible pairs and check their sums ; Driver function to test the above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getPairsCount ( int arr [ ] , int n , int sum ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( arr [ i ] + arr [ j ] == sum ) count ++ ; return count ; } int main ( ) { int arr [ ] = { 1 , 5 , 7 , -1 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int sum = 6 ; cout << " Count β of β pairs β is β " << getPairsCount ( arr , n , sum ) ; return 0 ; } |
Check whether a binary tree is a full binary tree or not | Iterative Approach | C ++ implementation to check whether a binary tree is a full binary tree or not ; structure of a node of binary tree ; function to get a new node ; allocate space ; put in the data ; function to check whether a binary tree is a full binary tree or not ; if tree is empty ; queue used for level order traversal ; push ' root ' to ' q ' ; traverse all the nodes of the binary tree level by level until queue is empty ; get the pointer to ' node ' at front of queue ; if it is a leaf node then continue ; if either of the child is not null and the other one is null , then binary tree is not a full binary tee ; push left and right childs of ' node ' on to the queue ' q ' ; binary tree is a full binary tee ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * getNode ( int data ) { Node * newNode = ( Node * ) malloc ( sizeof ( Node ) ) ; newNode -> data = data ; newNode -> left = newNode -> right = NULL ; return newNode ; } bool isFullBinaryTree ( Node * root ) { if ( ! root ) return true ; queue < Node * > q ; q . push ( root ) ; while ( ! q . empty ( ) ) { Node * node = q . front ( ) ; q . pop ( ) ; if ( node -> left == NULL && node -> right == NULL ) continue ; if ( node -> left == NULL node -> right == NULL ) return false ; q . push ( node -> left ) ; q . push ( node -> right ) ; } return true ; } int main ( ) { Node * root = getNode ( 1 ) ; root -> left = getNode ( 2 ) ; root -> right = getNode ( 3 ) ; root -> left -> left = getNode ( 4 ) ; root -> left -> right = getNode ( 5 ) ; if ( isFullBinaryTree ( root ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Analysis of Algorithms | Big | C ++ program for the above approach ; Function to find whether a key exists in an array or not using linear search ; Traverse the given array , a [ ] ; Check if a [ i ] is equal to key ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool linearSearch ( int a [ ] , int n , int key ) { for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == key ) return true ; } return false ; } int main ( ) { int arr [ ] = { 2 , 3 , 4 , 10 , 40 } ; int x = 10 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( linearSearch ( arr , n , x ) ) cout << " Element β is β present β in β array " ; else cout << " Element β is β not β present β in β array " ; return 0 ; } |
Count pairs with given sum | C ++ implementation of simple method to find count of pairs with given sum . ; Returns number of pairs in arr [ 0. . n - 1 ] with sum equal to ' sum ' ; Store counts of all elements in map m ; initializing value to 0 , if key not found ; iterate through each element and increment the count ( Notice that every pair is counted twice ) ; if ( arr [ i ] , arr [ i ] ) pair satisfies the condition , then we need to ensure that the count is decreased by one such that the ( arr [ i ] , arr [ i ] ) pair is not considered ; return the half of twice_count ; Driver function to test the above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getPairsCount ( int arr [ ] , int n , int sum ) { unordered_map < int , int > m ; for ( int i = 0 ; i < n ; i ++ ) m [ arr [ i ] ] ++ ; int twice_count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { twice_count += m [ sum - arr [ i ] ] ; if ( sum - arr [ i ] == arr [ i ] ) twice_count -- ; } return twice_count / 2 ; } int main ( ) { int arr [ ] = { 1 , 5 , 7 , -1 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int sum = 6 ; cout << " Count β of β pairs β is β " << getPairsCount ( arr , n , sum ) ; return 0 ; } |
Count pairs from two sorted arrays whose sum is equal to a given value x | C ++ implementation to count pairs from both sorted arrays whose sum is equal to a given value ; function to count all pairs from both the sorted arrays whose sum is equal to a given value ; generating pairs from both the arrays ; if sum of pair is equal to ' x ' increment count ; required count of pairs ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int arr1 [ ] , int arr2 [ ] , int m , int n , int x ) { int count = 0 ; for ( int i = 0 ; i < m ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) if ( ( arr1 [ i ] + arr2 [ j ] ) == x ) count ++ ; return count ; } int main ( ) { int arr1 [ ] = { 1 , 3 , 5 , 7 } ; int arr2 [ ] = { 2 , 3 , 5 , 8 } ; int m = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int n = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; int x = 10 ; cout << " Count β = β " << countPairs ( arr1 , arr2 , m , n , x ) ; return 0 ; } |
Count pairs from two sorted arrays whose sum is equal to a given value x | C ++ implementation to count pairs from both sorted arrays whose sum is equal to a given value ; function to search ' value ' in the given array ' arr [ ] ' it uses binary search technique as ' arr [ ] ' is sorted ; value found ; value not found ; function to count all pairs from both the sorted arrays whose sum is equal to a given value ; for each arr1 [ i ] ; check if the ' value ' is present in ' arr2 [ ] ' ; required count of pairs ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPresent ( int arr [ ] , int low , int high , int value ) { while ( low <= high ) { int mid = ( low + high ) / 2 ; if ( arr [ mid ] == value ) return true ; else if ( arr [ mid ] > value ) high = mid - 1 ; else low = mid + 1 ; } return false ; } int countPairs ( int arr1 [ ] , int arr2 [ ] , int m , int n , int x ) { int count = 0 ; for ( int i = 0 ; i < m ; i ++ ) { int value = x - arr1 [ i ] ; if ( isPresent ( arr2 , 0 , n - 1 , value ) ) count ++ ; } return count ; } int main ( ) { int arr1 [ ] = { 1 , 3 , 5 , 7 } ; int arr2 [ ] = { 2 , 3 , 5 , 8 } ; int m = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int n = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; int x = 10 ; cout << " Count β = β " << countPairs ( arr1 , arr2 , m , n , x ) ; return 0 ; } |
Count pairs from two sorted arrays whose sum is equal to a given value x | C ++ implementation to count pairs from both sorted arrays whose sum is equal to a given value ; function to count all pairs from both the sorted arrays whose sum is equal to a given value ; insert all the elements of 1 st array in the hash table ( unordered_set ' us ' ) ; for each element of 'arr2[] ; find ( x - arr2 [ j ] ) in ' us ' ; required count of pairs ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int arr1 [ ] , int arr2 [ ] , int m , int n , int x ) { int count = 0 ; unordered_set < int > us ; for ( int i = 0 ; i < m ; i ++ ) us . insert ( arr1 [ i ] ) ; for ( int j = 0 ; j < n ; j ++ ) if ( us . find ( x - arr2 [ j ] ) != us . end ( ) ) count ++ ; return count ; } int main ( ) { int arr1 [ ] = { 1 , 3 , 5 , 7 } ; int arr2 [ ] = { 2 , 3 , 5 , 8 } ; int m = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int n = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; int x = 10 ; cout << " Count β = β " << countPairs ( arr1 , arr2 , m , n , x ) ; return 0 ; } |
Count pairs from two sorted arrays whose sum is equal to a given value x | C ++ implementation to count pairs from both sorted arrays whose sum is equal to a given value ; function to count all pairs from both the sorted arrays whose sum is equal to a given value ; traverse ' arr1 [ ] ' from left to right traverse ' arr2 [ ] ' from right to left ; if this sum is equal to ' x ' , then increment ' l ' , decrement ' r ' and increment ' count ' ; if this sum is less than x , then increment l ; else decrement ' r ' ; required count of pairs ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int arr1 [ ] , int arr2 [ ] , int m , int n , int x ) { int count = 0 ; int l = 0 , r = n - 1 ; while ( l < m && r >= 0 ) { if ( ( arr1 [ l ] + arr2 [ r ] ) == x ) { l ++ ; r -- ; count ++ ; } else if ( ( arr1 [ l ] + arr2 [ r ] ) < x ) l ++ ; else r -- ; } return count ; } int main ( ) { int arr1 [ ] = { 1 , 3 , 5 , 7 } ; int arr2 [ ] = { 2 , 3 , 5 , 8 } ; int m = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int n = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; int x = 10 ; cout << " Count β = β " << countPairs ( arr1 , arr2 , m , n , x ) ; return 0 ; } |
Count quadruples from four sorted arrays whose sum is equal to a given value x | C ++ implementation to count quadruples from four sorted arrays whose sum is equal to a given value x ; find the ' value ' in the given array ' arr [ ] ' binary search technique is applied ; ' value ' found ; ' value ' not found ; function to count all quadruples from four sorted arrays whose sum is equal to a given value x ; generate all triplets from the 1 st three arrays ; calculate the sum of elements in the triplet so generated ; check if ' x - T ' is present in 4 th array or not ; increment count ; required count of quadruples ; Driver program to test above ; four sorted arrays each of size ' n ' | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPresent ( int arr [ ] , int low , int high , int value ) { while ( low <= high ) { int mid = ( low + high ) / 2 ; if ( arr [ mid ] == value ) return true ; else if ( arr [ mid ] > value ) high = mid - 1 ; else low = mid + 1 ; } return false ; } int countQuadruples ( int arr1 [ ] , int arr2 [ ] , int arr3 [ ] , int arr4 [ ] , int n , int x ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) for ( int k = 0 ; k < n ; k ++ ) { int T = arr1 [ i ] + arr2 [ j ] + arr3 [ k ] ; if ( isPresent ( arr4 , 0 , n , x - T ) ) count ++ ; } return count ; } int main ( ) { int arr1 [ ] = { 1 , 4 , 5 , 6 } ; int arr2 [ ] = { 2 , 3 , 7 , 8 } ; int arr3 [ ] = { 1 , 4 , 6 , 10 } ; int arr4 [ ] = { 2 , 4 , 7 , 8 } ; int n = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int x = 30 ; cout << " Count β = β " << countQuadruples ( arr1 , arr2 , arr3 , arr4 , n , x ) ; return 0 ; } |
Count quadruples from four sorted arrays whose sum is equal to a given value x | C ++ implementation to count quadruples from four sorted arrays whose sum is equal to a given value x ; count pairs from the two sorted array whose sum is equal to the given ' value ' ; traverse ' arr1 [ ] ' from left to right traverse ' arr2 [ ] ' from right to left ; if the ' sum ' is equal to ' value ' , then increment ' l ' , decrement ' r ' and increment ' count ' ; if the ' sum ' is greater than ' value ' , then decrement r ; else increment l ; required count of pairs ; function to count all quadruples from four sorted arrays whose sum is equal to a given value x ; generate all pairs from arr1 [ ] and arr2 [ ] ; calculate the sum of elements in the pair so generated ; count pairs in the 3 rd and 4 th array having value ' x - p _ sum ' and then accumulate it to ' count ' ; required count of quadruples ; Driver program to test above ; four sorted arrays each of size ' n ' | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int arr1 [ ] , int arr2 [ ] , int n , int value ) { int count = 0 ; int l = 0 , r = n - 1 ; while ( l < n && r >= 0 ) { int sum = arr1 [ l ] + arr2 [ r ] ; if ( sum == value ) { l ++ , r -- ; count ++ ; } else if ( sum > value ) r -- ; else l ++ ; } return count ; } int countQuadruples ( int arr1 [ ] , int arr2 [ ] , int arr3 [ ] , int arr4 [ ] , int n , int x ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) { int p_sum = arr1 [ i ] + arr2 [ j ] ; count += countPairs ( arr3 , arr4 , n , x - p_sum ) ; } return count ; } int main ( ) { int arr1 [ ] = { 1 , 4 , 5 , 6 } ; int arr2 [ ] = { 2 , 3 , 7 , 8 } ; int arr3 [ ] = { 1 , 4 , 6 , 10 } ; int arr4 [ ] = { 2 , 4 , 7 , 8 } ; int n = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int x = 30 ; cout << " Count β = β " << countQuadruples ( arr1 , arr2 , arr3 , arr4 , n , x ) ; return 0 ; } |
Count quadruples from four sorted arrays whose sum is equal to a given value x | C ++ implementation to count quadruples from four sorted arrays whose sum is equal to a given value x ; function to count all quadruples from four sorted arrays whose sum is equal to a given value x ; unordered_map ' um ' implemented as hash table for < sum , frequency > tuples ; count frequency of each sum obtained from the pairs of arr1 [ ] and arr2 [ ] and store them in ' um ' ; generate pair from arr3 [ ] and arr4 [ ] ; calculate the sum of elements in the pair so generated ; if ' x - p _ sum ' is present in ' um ' then add frequency of ' x - p _ sum ' to ' count ' ; required count of quadruples ; Driver program to test above ; four sorted arrays each of size ' n ' | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countQuadruples ( int arr1 [ ] , int arr2 [ ] , int arr3 [ ] , int arr4 [ ] , int n , int x ) { int count = 0 ; unordered_map < int , int > um ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) um [ arr1 [ i ] + arr2 [ j ] ] ++ ; for ( int k = 0 ; k < n ; k ++ ) for ( int l = 0 ; l < n ; l ++ ) { int p_sum = arr3 [ k ] + arr4 [ l ] ; if ( um . find ( x - p_sum ) != um . end ( ) ) count += um [ x - p_sum ] ; } return count ; } int main ( ) { int arr1 [ ] = { 1 , 4 , 5 , 6 } ; int arr2 [ ] = { 2 , 3 , 7 , 8 } ; int arr3 [ ] = { 1 , 4 , 6 , 10 } ; int arr4 [ ] = { 2 , 4 , 7 , 8 } ; int n = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int x = 30 ; cout << " Count β = β " << countQuadruples ( arr1 , arr2 , arr3 , arr4 , n , x ) ; return 0 ; } |
How to learn Pattern printing easily ? | ; Driver code | #include <iostream> NEW_LINE using namespace std ; int main ( ) { int N = 4 , i , j , min ; cout << " Value β of β N : β " << N << endl ; for ( i = 1 ; i <= N ; i ++ ) { for ( j = 1 ; j <= N ; j ++ ) { min = i < j ? i : j ; cout << N - min + 1 ; } cout << endl ; } return 0 ; } |
Number of subarrays having sum exactly equal to k | C ++ program for the above approach ; Calculate all subarrays ; Calculate required sum ; Check if sum is equal to required sum | #include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { int arr [ ] = { 10 , 2 , -2 , -20 , 10 } ; int k = -10 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int sum = 0 ; for ( int j = i ; j < n ; j ++ ) { sum += arr [ j ] ; if ( sum == k ) res ++ ; } } cout << ( res ) << endl ; } |
Number of subarrays having sum exactly equal to k | C ++ program to find number of subarrays with sum exactly equal to k . ; Function to find number of subarrays with sum exactly equal to k . ; STL map to store number of subarrays starting from index zero having particular value of sum . ; Sum of elements so far . ; Add current element to sum so far . ; If currsum is equal to desired sum , then a new subarray is found . So increase count of subarrays . ; currsum exceeds given sum by currsum - sum . Find number of subarrays having this sum and exclude those subarrays from currsum by increasing count by same amount . ; Add currsum value to count of different values of sum . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findSubarraySum ( int arr [ ] , int n , int sum ) { unordered_map < int , int > prevSum ; int res = 0 ; int currsum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { currsum += arr [ i ] ; if ( currsum == sum ) res ++ ; if ( prevSum . find ( currsum - sum ) != prevSum . end ( ) ) res += ( prevSum [ currsum - sum ] ) ; prevSum [ currsum ] ++ ; } return res ; } int main ( ) { int arr [ ] = { 10 , 2 , -2 , -20 , 10 } ; int sum = -10 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findSubarraySum ( arr , n , sum ) ; return 0 ; } |
Count pairs whose products exist in array | C ++ program to count pairs whose product exist in array ; Returns count of pairs whose product exists in arr [ ] ; find product in an array ; if product found increment counter ; return Count of all pair whose product exist in array ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int arr [ ] , int n ) { int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { int product = arr [ i ] * arr [ j ] ; for ( int k = 0 ; k < n ; k ++ ) { if ( arr [ k ] == product ) { result ++ ; break ; } } } } return result ; } int main ( ) { int arr [ ] = { 6 , 2 , 4 , 12 , 5 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , n ) ; return 0 ; } |
Count pairs whose products exist in array | A hashing based C ++ program to count pairs whose product exists in arr [ ] ; Returns count of pairs whose product exists in arr [ ] ; Create an empty hash - set that store all array element ; Insert all array element into set ; Generate all pairs and check is exist in ' Hash ' or not ; if product exists in set then we increment count by 1 ; return count of pairs whose product exist in array ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int arr [ ] , int n ) { int result = 0 ; set < int > Hash ; for ( int i = 0 ; i < n ; i ++ ) Hash . insert ( arr [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { int product = arr [ i ] * arr [ j ] ; if ( Hash . find ( product ) != Hash . end ( ) ) result ++ ; } } return result ; } int main ( ) { int arr [ ] = { 6 , 2 , 4 , 12 , 5 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , n ) ; return 0 ; } |
Master Theorem For Subtract and Conquer Recurrences | ; Driver Code | #include <stdio.h> NEW_LINE int fib ( int n ) { if ( n <= 1 ) return n ; return fib ( n - 1 ) + fib ( n - 2 ) ; } int main ( ) { int n = 9 ; printf ( " % d " , fib ( n ) ) ; getchar ( ) ; return 0 ; } |
Tail Recursion | ; A tail recursive function to calculate factorial ; A wrapper over factTR ; Driver program to test above function | #include <iostream> NEW_LINE using namespace std ; unsigned factTR ( unsigned int n , unsigned int a ) { if ( n == 1 ) return a ; return factTR ( n - 1 , n * a ) ; } unsigned int fact ( unsigned int n ) { return factTR ( n , 1 ) ; } int main ( ) { cout << fact ( 5 ) ; return 0 ; } |
Given two unsorted arrays , find all pairs whose sum is x | C ++ program to find all pairs in both arrays whose sum is equal to given value x ; Function to print all pairs in both arrays whose sum is equal to given value x ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findPairs ( int arr1 [ ] , int arr2 [ ] , int n , int m , int x ) { for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < m ; j ++ ) if ( arr1 [ i ] + arr2 [ j ] == x ) cout << arr1 [ i ] << " β " << arr2 [ j ] << endl ; } int main ( ) { int arr1 [ ] = { 1 , 2 , 3 , 7 , 5 , 4 } ; int arr2 [ ] = { 0 , 7 , 4 , 3 , 2 , 1 } ; int n = sizeof ( arr1 ) / sizeof ( int ) ; int m = sizeof ( arr2 ) / sizeof ( int ) ; int x = 8 ; findPairs ( arr1 , arr2 , n , m , x ) ; return 0 ; } |
Smallest possible integer K such that ceil of each Array element when divided by K is at most M | C ++ program for the above approach ; Function to check if the sum of ceil values of the arr [ ] for the K value is at most M or not ; Stores the sum of ceil values ; Update the sum ; Return true if sum is less than or equal to M , false otherwise ; Function to find the smallest possible integer K such that ceil ( arr [ 0 ] / K ) + ceil ( arr [ 1 ] / K ) + ... . + ceil ( arr [ N - 1 ] / K ) is less than or equal to M ; Stores the low value ; Stores the high value ; Stores the middle value ; Update the mid value ; Check if the mid value is K ; Update the low value ; Update the high value ; Check if low is K or high is K and return it ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isvalid ( int arr [ ] , int K , int N , int M ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += ( int ) ceil ( arr [ i ] * 1.0 / K ) ; } return sum <= M ; } int smallestValueForK ( int arr [ ] , int N , int M ) { int low = 1 ; int high = * max_element ( arr , arr + N ) ; int mid ; while ( high - low > 1 ) { mid = ( high + low ) / 2 ; if ( ! isvalid ( arr , mid , N , M ) ) low = mid + 1 ; else high = mid ; } return isvalid ( arr , low , N , M ) ? low : high ; } int main ( ) { int arr [ ] = { 4 , 3 , 2 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int M = 5 ; cout << smallestValueForK ( arr , N , M ) ; return 0 ; } |
Given two unsorted arrays , find all pairs whose sum is x | C ++ program to find all pair in both arrays whose sum is equal to given value x ; Function to find all pairs in both arrays whose sum is equal to given value x ; Insert all elements of first array in a hash ; Subtract sum from second array elements one by one and check it 's present in array first or not ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findPairs ( int arr1 [ ] , int arr2 [ ] , int n , int m , int x ) { unordered_set < int > s ; for ( int i = 0 ; i < n ; i ++ ) s . insert ( arr1 [ i ] ) ; for ( int j = 0 ; j < m ; j ++ ) if ( s . find ( x - arr2 [ j ] ) != s . end ( ) ) cout << x - arr2 [ j ] << " β " << arr2 [ j ] << endl ; } int main ( ) { int arr1 [ ] = { 1 , 0 , -4 , 7 , 6 , 4 } ; int arr2 [ ] = { 0 , 2 , 4 , -3 , 2 , 1 } ; int x = 8 ; int n = sizeof ( arr1 ) / sizeof ( int ) ; int m = sizeof ( arr2 ) / sizeof ( int ) ; findPairs ( arr1 , arr2 , n , m , x ) ; return 0 ; } |
Altitude of largest Triangle that can be inscribed in a Rectangle | C ++ program for the above approach ; Function to find the greatest altitude of the largest triangle triangle that can be inscribed in the rectangle ; If L is greater than B ; Stores the maximum altitude value ; Return res ; Driver Code ; Given Input ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int largestAltitude ( int L , int B ) { if ( L > B ) swap ( L , B ) ; int res = min ( B / 2 , L ) ; return res ; } int main ( ) { int L = 3 ; int B = 4 ; cout << largestAltitude ( L , B ) ; return 0 ; } |
Check if a given Binary Tree is height balanced like a Red | Program to check if a given Binary Tree is balanced like a Red - Black Tree ; utility that allocates a new Node with the given key ; Returns returns tree if the Binary tree is balanced like a Red - Black tree . This function also sets value in maxh and minh ( passed byreference ) . maxh and minh are set as maximum and minimum heights of root . ; Base case ; To store max and min heights of left subtree ; To store max and min heights of right subtree ; Check if left subtree is balanced , also set lmxh and lmnh ; Check if right subtree is balanced , also set rmxh and rmnh ; Set the max and min heights of this node for the parent call ; See if this node is balanced ; A wrapper over isBalancedUtil ( ) ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; Node * left , * right ; } ; Node * newNode ( int key ) { Node * node = new Node ; node -> key = key ; node -> left = node -> right = NULL ; return ( node ) ; } bool isBalancedUtil ( Node * root , int & maxh , int & minh ) { if ( root == NULL ) { maxh = minh = 0 ; return true ; } int lmxh , lmnh ; int rmxh , rmnh ; if ( isBalancedUtil ( root -> left , lmxh , lmnh ) == false ) return false ; if ( isBalancedUtil ( root -> right , rmxh , rmnh ) == false ) return false ; maxh = max ( lmxh , rmxh ) + 1 ; minh = min ( lmnh , rmnh ) + 1 ; if ( maxh <= 2 * minh ) return true ; return false ; } bool isBalanced ( Node * root ) { int maxh , minh ; return isBalancedUtil ( root , maxh , minh ) ; } int main ( ) { Node * root = newNode ( 10 ) ; root -> left = newNode ( 5 ) ; root -> right = newNode ( 100 ) ; root -> right -> left = newNode ( 50 ) ; root -> right -> right = newNode ( 150 ) ; root -> right -> left -> left = newNode ( 40 ) ; isBalanced ( root ) ? cout << " Balanced " : cout << " Not β Balanced " ; return 0 ; } |
Maximum Fixed Point ( Value equal to index ) in a given Array | C ++ implementation of the above approach ; Function to find the maximum index i such that arr [ i ] is equal to i ; Traversing the array from backwards ; If arr [ i ] is equal to i ; If there is no such index ; Driver code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findLargestIndex ( int arr [ ] , int n ) { for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( arr [ i ] == i ) { cout << i << endl ; return ; } } cout << -1 << endl ; } int main ( ) { int arr [ ] = { -10 , -5 , 0 , 3 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findLargestIndex ( arr , n ) ; return 0 ; } |
Cumulative frequency of count of each element in an unsorted array | C ++ program to print the cumulative frequency according to the order given ; Function to print the cumulative frequency according to the order given ; Insert elements and their frequencies in hash map . ; traverse in the array ; add the frequencies ; if the element has not been visited previously ; mark the hash 0 as the element 's cumulative frequency has been printed ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void countFreq ( int a [ ] , int n ) { unordered_map < int , int > hm ; for ( int i = 0 ; i < n ; i ++ ) hm [ a [ i ] ] ++ ; int cumul = 0 ; for ( int i = 0 ; i < n ; i ++ ) { cumul += hm [ a [ i ] ] ; if ( hm [ a [ i ] ] ) { cout << a [ i ] << " - > " << cumul << endl ; } hm [ a [ i ] ] = 0 ; } } int main ( ) { int a [ ] = { 1 , 3 , 2 , 4 , 2 , 1 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; countFreq ( a , n ) ; return 0 ; } |
Find pairs in array whose sums already exist in array | A simple C ++ program to find pair whose sum already exists in array ; Function to find pair whose sum exists in arr [ ] ; Driven code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findPair ( int arr [ ] , int n ) { bool found = false ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { for ( int k = 0 ; k < n ; k ++ ) { if ( arr [ i ] + arr [ j ] == arr [ k ] ) { cout << arr [ i ] << " β " << arr [ j ] << endl ; found = true ; } } } } if ( found == false ) cout << " Not β exist " << endl ; } int main ( ) { int arr [ ] = { 10 , 4 , 8 , 13 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findPair ( arr , n ) ; return 0 ; } |
Maximum number of mangoes that can be bought | C ++ program for the above approach ; Function to check if mid number of mangoes can be bought ; Store the coins ; If watermelons needed are greater than given watermelons ; Store remaining watermelons if vl watermelons are used to buy mangoes ; Store the value of coins if these watermelon get sold ; Increment coins by ex ; Number of mangoes that can be buyed if only x coins needed for one mango ; If the condition is satisfied , return true ; Otherwise return false ; Function to find the maximum number of mangoes that can be bought by selling watermelons ; Initialize the boundary values ; Store the required result ; Binary Search ; Store the mid value ; Check if it is possible to buy mid number of mangoes ; Otherwise , update r to mid - 1 ; Return the result ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int n , int m , int x , int y , int vl ) { int temp = m ; if ( vl > n ) return false ; int ex = n - vl ; ex *= y ; temp += ex ; int cr = temp / x ; if ( cr >= vl ) return true ; return false ; } int maximizeMangoes ( int n , int m , int x , int y ) { int l = 0 , r = n ; int ans = 0 ; while ( l <= r ) { int mid = l + ( r - l ) / 2 ; if ( check ( n , m , x , y , mid ) ) { ans = mid ; l = mid + 1 ; } else r = mid - 1 ; } return ans ; } int main ( ) { int W = 4 , C = 8 , x = 4 , y = 4 ; cout << maximizeMangoes ( W , C , x , y ) ; return 0 ; } |
Kth Smallest Element in a sorted array formed by reversing subarrays from a random index | C ++ program for the above approach ; Function to find the Kth element in a sorted and rotated array at random point ; Set the boundaries for binary search ; Apply binary search to find R ; Initialize the middle element ; Check in the right side of mid ; Else check in the left side ; Random point either l or h ; Return the kth smallest element ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findkthElement ( vector < int > arr , int n , int K ) { int l = 0 ; int h = n - 1 , r ; while ( l + 1 < h ) { int mid = ( l + h ) / 2 ; if ( arr [ l ] >= arr [ mid ] ) l = mid ; else h = mid ; } if ( arr [ l ] < arr [ h ] ) r = l ; else r = h ; if ( K <= r + 1 ) return arr [ r + 1 - K ] ; else return arr [ n - ( K - ( r + 1 ) ) ] ; } int main ( ) { vector < int > arr = { 10 , 8 , 6 , 5 , 2 , 1 , 13 , 12 } ; int n = arr . size ( ) ; int K = 3 ; cout << findkthElement ( arr , n , K ) ; } |
Find all pairs ( a , b ) in an array such that a % b = k | C ++ implementation to find such pairs ; Function to find pair such that ( a % b = k ) ; Consider each and every pair ; Print if their modulo equals to k ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool printPairs ( int arr [ ] , int n , int k ) { bool isPairFound = true ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( i != j && arr [ i ] % arr [ j ] == k ) { cout << " ( " << arr [ i ] << " , β " << arr [ j ] << " ) " << " β " ; isPairFound = true ; } } } return isPairFound ; } int main ( ) { int arr [ ] = { 2 , 3 , 5 , 4 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; if ( printPairs ( arr , n , k ) == false ) cout << " No β such β pair β exists " ; return 0 ; } |
Find all pairs ( a , b ) in an array such that a % b = k | C ++ program to find all pairs such that a % b = k . ; Utiltity function to find the divisors of n and store in vector v [ ] ; Vector is used to store the divisors ; If n is a square number , push only one occurrence ; Function to find pairs such that ( a % b = k ) ; Store all the elements in the map to use map as hash for finding elements in O ( 1 ) time . ; Print all the pairs with ( a , b ) as ( k , numbers greater than k ) as k % ( num ( > k ) ) = k i . e . 2 % 4 = 2 ; Now check for the current element as ' a ' how many b exists such that a % b = k ; find all the divisors of ( arr [ i ] - k ) ; Check for each divisor i . e . arr [ i ] % b = k or not , if yes then print that pair . ; Clear vector ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > findDivisors ( int n ) { vector < int > v ; for ( int i = 1 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( n / i == i ) v . push_back ( i ) ; else { v . push_back ( i ) ; v . push_back ( n / i ) ; } } } return v ; } bool printPairs ( int arr [ ] , int n , int k ) { unordered_map < int , bool > occ ; for ( int i = 0 ; i < n ; i ++ ) occ [ arr [ i ] ] = true ; bool isPairFound = false ; for ( int i = 0 ; i < n ; i ++ ) { if ( occ [ k ] && k < arr [ i ] ) { cout << " ( " << k << " , β " << arr [ i ] << " ) β " ; isPairFound = true ; } if ( arr [ i ] >= k ) { vector < int > v = findDivisors ( arr [ i ] - k ) ; for ( int j = 0 ; j < v . size ( ) ; j ++ ) { if ( arr [ i ] % v [ j ] == k && arr [ i ] != v [ j ] && occ [ v [ j ] ] ) { cout << " ( " << arr [ i ] << " , β " << v [ j ] << " ) β " ; isPairFound = true ; } } v . clear ( ) ; } } return isPairFound ; } int main ( ) { int arr [ ] = { 3 , 1 , 2 , 5 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 2 ; if ( printPairs ( arr , n , k ) == false ) cout << " No β such β pair β exists " ; return 0 ; } |
Sum of nodes in a Binary Search Tree with values from a given range | C ++ program for the above approach ; Class for node of the Tree ; Function to create a new BST node ; Return the newly created node ; Stores the sum of all nodes lying in the range [ L , R ] ; Function to perform level order traversal on the Tree and calculate the required sum ; Base Case ; Stores the nodes while performing level order traversal ; Push the root node into the queue ; Iterate until queue is empty ; Stores the front node of the queue ; If the value of the node lies in the given range ; Add it to sum ; If the left child is not NULL and exceeds low ; Insert into queue ; If the right child is not NULL and exceeds low ; Insert into queue ; Return the resultant sum ; Function to insert a new node into the Binary Search Tree ; Base Case ; If the data is less than the value of the current node ; Recur for left subtree ; Otherwise ; Recur for the right subtree ; Return the node ; Driver Code ; Let us create following BST 10 / \ 5 15 / \ \ 3 7 18 | #include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int val ; Node * left , * right ; } ; Node * newNode ( int item ) { Node * temp = new Node ( ) ; temp -> val = item ; temp -> left = temp -> right = NULL ; return temp ; } int sum = 0 ; int rangeSumBST ( Node * root , int low , int high ) { if ( root == NULL ) return 0 ; queue < Node * > q ; q . push ( root ) ; while ( q . empty ( ) == false ) { Node * curr = q . front ( ) ; q . pop ( ) ; if ( curr -> val >= low && curr -> val <= high ) { sum += curr -> val ; } if ( curr -> left != NULL && curr -> val > low ) q . push ( curr -> left ) ; if ( curr -> right != NULL && curr -> val < high ) q . push ( curr -> right ) ; } return sum ; } Node * insert ( Node * node , int data ) { if ( node == NULL ) return newNode ( data ) ; if ( data <= node -> val ) node -> left = insert ( node -> left , data ) ; else node -> right = insert ( node -> right , data ) ; return node ; } int main ( ) { Node * root = NULL ; root = insert ( root , 10 ) ; insert ( root , 5 ) ; insert ( root , 15 ) ; insert ( root , 3 ) ; insert ( root , 7 ) ; insert ( root , 18 ) ; int L = 7 , R = 15 ; cout << rangeSumBST ( root , L , R ) ; return 0 ; } |
Convert an array to reduced form | Set 1 ( Simple and Hashing ) | C ++ program to convert an array in reduced form ; Create a temp array and copy contents of arr [ ] to temp ; Sort temp array ; Create a hash table . Refer tinyurl . com / zp5wgef http : ; One by one insert elements of sorted temp [ ] and assign them values from 0 to n - 1 ; Convert array by taking positions from umap ; Driver program to test above method | #include <bits/stdc++.h> NEW_LINE using namespace std ; void convert ( int arr [ ] , int n ) { int temp [ n ] ; memcpy ( temp , arr , n * sizeof ( int ) ) ; sort ( temp , temp + n ) ; unordered_map < int , int > umap ; int val = 0 ; for ( int i = 0 ; i < n ; i ++ ) umap [ temp [ i ] ] = val ++ ; for ( int i = 0 ; i < n ; i ++ ) arr [ i ] = umap [ arr [ i ] ] ; } void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; } int main ( ) { int arr [ ] = { 10 , 20 , 15 , 12 , 11 , 50 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Given β Array β is β STRNEWLINE " ; printArr ( arr , n ) ; convert ( arr , n ) ; cout << " Converted Array is " ; printArr ( arr , n ) ; return 0 ; } |
Check if count of substrings in S with string S1 as prefix and S2 as suffix is equal to that with S2 as prefix and S1 as suffix | C ++ program for the above approach ; Function to count number of substrings that starts with string S1 and ends with string S2 ; Stores the length of each string ; Stores the count of prefixes as S1 and suffixes as S2 ; Traverse string S ; Find the prefix at index i ; Find the suffix at index i ; If the prefix is S1 ; If the suffix is S2 ; Return the count of substrings ; Function to check if the number of substrings starts with S1 and ends with S2 and vice - versa is same or not ; Count the number of substrings ; Print the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubstrings ( string S , string S1 , string S2 ) { int N = S . length ( ) ; int N1 = S1 . length ( ) ; int N2 = S2 . length ( ) ; int count = 0 , totalcount = 0 ; for ( int i = 0 ; i < N ; i ++ ) { string prefix = S . substr ( i , N1 ) ; string suffix = S . substr ( i , N2 ) ; if ( S1 == prefix ) count ++ ; if ( S2 == suffix ) totalcount += count ; } return totalcount ; } void checkSubstrings ( string S , string S1 , string S2 ) { int x = countSubstrings ( S , S1 , S2 ) ; int y = countSubstrings ( S , S2 , S1 ) ; if ( x == y ) cout << " Yes " ; else cout << " No " ; } int main ( ) { string S = " opencloseopencloseopen " ; string S1 = " open " ; string S2 = " close " ; checkSubstrings ( S , S1 , S2 ) ; return 0 ; } |
Return maximum occurring character in an input string | C ++ program to output the maximum occurring character in a string ; Create array to keep the count of individual characters and initialize the array as 0 ; Construct character count array from the input string . ; Initialize max count ; Initialize result ; Traversing through the string and maintaining the count of each character ; Driver program to test the above function | #include <bits/stdc++.h> NEW_LINE #define ASCII_SIZE 256 NEW_LINE using namespace std ; char getMaxOccuringChar ( char * str ) { int count [ ASCII_SIZE ] = { 0 } ; int len = strlen ( str ) ; int max = 0 ; char result ; for ( int i = 0 ; i < len ; i ++ ) { count [ str [ i ] ] ++ ; if ( max < count [ str [ i ] ] ) { max = count [ str [ i ] ] ; result = str [ i ] ; } } return result ; } int main ( ) { char str [ ] = " sample β string " ; cout << " Max β occurring β character β is β " << getMaxOccuringChar ( str ) ; } |
Group words with same set of characters | C ++ program to print all words that have the same unique character set ; Generates a key from given string . The key contains all unique characters of given string in sorted order consisting of only distinct elements . ; store all unique characters of current word in key ; Print all words together with same character sets . ; Stores indexes of all words that have same set of unique characters . ; Traverse all words ; print all words that have the same unique character set ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX_CHAR 26 NEW_LINE string getKey ( string & str ) { bool visited [ MAX_CHAR ] = { false } ; for ( int j = 0 ; j < str . length ( ) ; j ++ ) visited [ str [ j ] - ' a ' ] = true ; string key = " " ; for ( int j = 0 ; j < MAX_CHAR ; j ++ ) if ( visited [ j ] ) key = key + ( char ) ( ' a ' + j ) ; return key ; } void wordsWithSameCharSet ( string words [ ] , int n ) { unordered_map < string , vector < int > > Hash ; for ( int i = 0 ; i < n ; i ++ ) { string key = getKey ( words [ i ] ) ; Hash [ key ] . push_back ( i ) ; } for ( auto it = Hash . begin ( ) ; it != Hash . end ( ) ; it ++ ) { for ( auto v = ( * it ) . second . begin ( ) ; v != ( * it ) . second . end ( ) ; v ++ ) cout << words [ * v ] << " , β " ; cout << endl ; } } int main ( ) { string words [ ] = { " may " , " student " , " students " , " dog " , " studentssess " , " god " , " cat " , " act " , " tab " , " bat " , " flow " , " wolf " , " lambs " , " amy " , " yam " , " balms " , " looped " , " poodle " } ; int n = sizeof ( words ) / sizeof ( words [ 0 ] ) ; wordsWithSameCharSet ( words , n ) ; return 0 ; } |
Second most repeated word in a sequence | C ++ program to find out the second most repeated word ; Function to find the word ; Store all the words with its occurrence ; find the second largest occurrence ; Return string with occurrence equals to sec_max ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; string secMostRepeated ( vector < string > seq ) { unordered_map < string , int > occ ; for ( int i = 0 ; i < seq . size ( ) ; i ++ ) occ [ seq [ i ] ] ++ ; int first_max = INT_MIN , sec_max = INT_MIN ; for ( auto it = occ . begin ( ) ; it != occ . end ( ) ; it ++ ) { if ( it -> second > first_max ) { sec_max = first_max ; first_max = it -> second ; } else if ( it -> second > sec_max && it -> second != first_max ) sec_max = it -> second ; } for ( auto it = occ . begin ( ) ; it != occ . end ( ) ; it ++ ) if ( it -> second == sec_max ) return it -> first ; } int main ( ) { vector < string > seq = { " ccc " , " aaa " , " ccc " , " ddd " , " aaa " , " aaa " } ; cout << secMostRepeated ( seq ) ; return 0 ; } |
Check if a Binary Tree ( not BST ) has duplicate values | C ++ Program to check duplicates in Binary Tree ; A binary tree Node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new Node with the given data and NULL left and right pointers . ; If tree is empty , there are no duplicates . ; If current node 's data is already present. ; Insert current node ; Recursively check in left and right subtrees . ; To check if tree has duplicates ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left ; struct Node * right ; } ; struct Node * newNode ( int data ) { struct Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } bool checkDupUtil ( Node * root , unordered_set < int > & s ) { if ( root == NULL ) return false ; if ( s . find ( root -> data ) != s . end ( ) ) return true ; s . insert ( root -> data ) ; return checkDupUtil ( root -> left , s ) || checkDupUtil ( root -> right , s ) ; } bool checkDup ( struct Node * root ) { unordered_set < int > s ; return checkDupUtil ( root , s ) ; } int main ( ) { struct Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 2 ) ; root -> left -> left = newNode ( 3 ) ; if ( checkDup ( root ) ) printf ( " Yes " ) ; else printf ( " No " ) ; return 0 ; } |
Expression Tree | C ++ program for expression tree ; An expression tree node ; A utility function to check if ' c ' is an operator ; Utility function to do inorder traversal ; A utility function to create a new node ; Returns root of constructed tree for given postfix expression ; Traverse through every character of input expression ; If operand , simply push into stack ; operator ; Pop two top nodes Store top ; make them children ; Add this subexpression to stack ; only element will be root of expression tree ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct et { char value ; et * left , * right ; } ; bool isOperator ( char c ) { if ( c == ' + ' c == ' - ' c == ' * ' c == ' / ' c == ' ^ ' ) return true ; return false ; } void inorder ( et * t ) { if ( t ) { inorder ( t -> left ) ; printf ( " % c β " , t -> value ) ; inorder ( t -> right ) ; } } et * newNode ( char v ) { et * temp = new et ; temp -> left = temp -> right = NULL ; temp -> value = v ; return temp ; } ; et * constructTree ( char postfix [ ] ) { stack < et * > st ; et * t , * t1 , * t2 ; for ( int i = 0 ; i < strlen ( postfix ) ; i ++ ) { if ( ! isOperator ( postfix [ i ] ) ) { t = newNode ( postfix [ i ] ) ; st . push ( t ) ; } else { t = newNode ( postfix [ i ] ) ; t1 = st . top ( ) ; st . pop ( ) ; t2 = st . top ( ) ; st . pop ( ) ; t -> right = t1 ; t -> left = t2 ; st . push ( t ) ; } } t = st . top ( ) ; st . pop ( ) ; return t ; } int main ( ) { char postfix [ ] = " ab + ef * g * - " ; et * r = constructTree ( postfix ) ; printf ( " infix β expression β is β STRNEWLINE " ) ; inorder ( r ) ; return 0 ; } |
Queries to count sum of rows and columns of a Matrix present in given ranges | C ++ program for the above approach ; Function to search for the leftmost index of given number ; Initialize low , high and ans ; Stores mid ; If A [ mid ] >= num ; Function to search for the rightmost index of given number ; Initialise low , high and ans ; Stores mid ; If A [ mid ] <= num ; Update ans ; Update mid ; Update high ; Function to preprocess the matrix to execute the queries ; Stores the sum of each row ; Stores the sum of each col ; Traverse the matrix and calculate sum of each row and column ; Insert all row sums in sum_list ; Insert all column sums in sum_list ; Sort the array in ascending order ; Traverse the array queries [ ] [ ] ; Search the leftmost index of L ; Search the rightmost index of R ; Driver Code ; Given dimensions of matrix ; Given matrix ; Given number of queries ; Given queries ; Function call to count the number row - sums and column - sums present in the given ranges | #include <bits/stdc++.h> NEW_LINE using namespace std ; int left_search ( vector < int > A , int num ) { int low = 0 , high = A . size ( ) - 1 ; int ans = 0 ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( A [ mid ] >= num ) { ans = mid ; high = mid - 1 ; } else { low = mid + 1 ; } } return ans ; } int right_search ( vector < int > A , int num ) { int low = 0 , high = A . size ( ) - 1 ; int ans = high ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( A [ mid ] <= num ) { ans = mid ; low = mid + 1 ; } else { high = mid - 1 ; } } return ans ; } void totalCount ( vector < vector < int > > A , int N , int M , vector < vector < int > > queries , int Q ) { vector < int > row_sum ( N ) ; vector < int > col_sum ( N ) ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { row_sum [ i ] += A [ i ] [ j ] ; col_sum [ j ] += A [ i ] [ j ] ; } } vector < int > sum_list ; for ( int i = 0 ; i < N ; i ++ ) sum_list . push_back ( row_sum [ i ] ) ; for ( int i = 0 ; i < M ; i ++ ) sum_list . push_back ( col_sum [ i ] ) ; sort ( sum_list . begin ( ) , sum_list . end ( ) ) ; for ( int i = 0 ; i < Q ; i ++ ) { int L = queries [ i ] [ 0 ] ; int R = queries [ i ] [ 1 ] ; int l = left_search ( sum_list , L ) ; int r = right_search ( sum_list , R ) ; cout << r - l + 1 << " β " ; } } int main ( ) { int N = 3 , M = 2 ; vector < vector < int > > A = { { 13 , 3 } , { 9 , 4 } , { 6 , 10 } } ; int Q = 2 ; vector < vector < int > > queries = { { 10 , 20 } , { 25 , 35 } } ; totalCount ( A , N , M , queries , Q ) ; } |
Smallest element repeated exactly β k β times ( not limited to small range ) | C ++ program to find the smallest element with frequency exactly k . ; Map is used to store the count of elements present in the array ; Traverse the map and find minimum element with frequency k . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int smallestKFreq ( int a [ ] , int n , int k ) { unordered_map < int , int > m ; for ( int i = 0 ; i < n ; i ++ ) m [ a [ i ] ] ++ ; int res = INT_MAX ; for ( auto it = m . begin ( ) ; it != m . end ( ) ; ++ it ) if ( it -> second == k ) res = min ( res , it -> first ) ; return ( res != INT_MAX ) ? res : -1 ; } int main ( ) { int arr [ ] = { 2 , 2 , 1 , 3 , 1 } ; int k = 2 ; int n = sizeof ( arr ) / ( sizeof ( arr [ 0 ] ) ) ; cout << smallestKFreq ( arr , n , k ) ; return 0 ; } |
Maximize profit that can be earned by selling an item among N buyers | ; Function to find the maximum profit earned by selling an item among N buyers ; Stores the maximum profit ; Stores the price of the item ; Traverse the array ; Count of buyers with budget >= arr [ i ] ; Increment count ; Update the maximum profit ; Return the maximum possible price ; Driver code | #include <iostream> NEW_LINE #include <climits> NEW_LINE #include <algorithm> NEW_LINE using namespace std ; int maximumProfit ( int arr [ ] , int n ) { int ans = INT_MIN ; int price = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ i ] <= arr [ j ] ) { count ++ ; } } if ( ans < count * arr [ i ] ) { price = arr [ i ] ; ans = count * arr [ i ] ; } } return price ; } int main ( ) { int arr [ ] = { 22 , 87 , 9 , 50 , 56 , 43 } ; cout << maximumProfit ( arr , 6 ) ; return 0 ; } |
Lexicographically smallest permutation of the array possible by at most one swap | C ++ implementation of the above approach ; Function to print the elements of the array arr [ ] ; Traverse the array arr [ ] ; Function to convert given array to lexicographically smallest permutation possible by swapping at most one pair ; Stores the index of the first element which is not at its correct position ; Checks if any such array element exists or not ; Traverse the given array ; If element is found at i ; If the first array is not in correct position ; Store the index of the first elements ; Store the index of the first element ; Swap the pairs ; Print the array ; Driver code ; Given array ; Store the size of the array | #include <bits/stdc++.h> NEW_LINE #include <iostream> NEW_LINE using namespace std ; void print ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { cout << arr [ i ] << " β " ; } } void makeLexicographically ( int arr [ ] , int N ) { int index = 0 ; int temp = 0 ; int check = 0 ; int condition = 0 ; int element = 0 ; for ( int i = 0 ; i < N ; ++ i ) { if ( element == arr [ i ] ) { check = i ; break ; } else if ( arr [ i ] != i + 1 && check == 0 ) { index = i ; check = 1 ; condition = -1 ; element = i + 1 ; } } if ( condition == -1 ) { temp = arr [ index ] ; arr [ index ] = arr [ check ] ; arr [ check ] = temp ; } print ( arr , N ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; makeLexicographically ( arr , N ) ; return 0 ; } |
Check if uppercase characters in a string are used correctly or not | C ++ program for the above approach ; Function to check if the character c is in lowercase or not ; Function to check if the character c is in uppercase or not ; Utility function to check if uppercase characters are used correctly or not ; Length of string ; If the first character is in lowercase ; Otherwise ; Check if all characters are in uppercase or not ; If all characters are in uppercase ; Check if all characters except the first are in lowercase ; Function to check if uppercase characters are used correctly or not ; Stores whether the use of uppercase characters are correct or not ; If correct ; Otherwise ; Driver Code ; Given string ; Function call to check if use of uppercase characters is correct or not | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isLower ( char c ) { return c >= ' a ' and c < = ' z ' ; } bool isUpper ( char c ) { return c >= ' A ' and c < = ' Z ' ; } bool detectUppercaseUseUtil ( string S ) { int N = S . size ( ) ; int i ; if ( isLower ( S [ 0 ] ) ) { i = 1 ; while ( S [ i ] && isLower ( S [ i ] ) ) ++ i ; return i == N ? true : false ; } else { i = 1 ; while ( S [ i ] && isUpper ( S [ i ] ) ) ++ i ; if ( i == N ) return true ; else if ( i > 1 ) return false ; while ( S [ i ] && isLower ( S [ i ] ) ) ++ i ; return i == N ? true : false ; } } void detectUppercaseUse ( string S ) { bool check = detectUppercaseUseUtil ( S ) ; if ( check ) cout << " Yes " ; else cout << " No " ; } int main ( ) { string S = " GeeKs " ; detectUppercaseUse ( S ) ; return 0 ; } |
Queries to count array elements from a given range having a single set bit | C ++ implementation for above approach ; Check if N has only one set bit ; Function to build segment tree ; If se is leaf node ; Update the node ; Stores mid value of segment [ ss , se ] ; Recursive call for left Subtree ; Recursive call for right Subtree ; Update the Current Node ; Function to update a value at Xth index ; If ss is equal to X ; Update the Xth node ; Update the tree ; Stores the mid of segment [ ss , se ] ; Update current node ; Count of numbers having one set bit ; If L > se or R < ss Invalid Range ; If [ ss , se ] lies inside the [ L , R ] ; Stores the mid of segment [ ss , se ] ; Return the sum after recursively traversing left and right subtree ; Function to solve queries ; Initialise Segment tree ; Build segment tree ; Perform queries ; Driver Code ; Input ; Function call to solve queries | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int N ) { if ( N == 0 ) return 0 ; return ! ( N & ( N - 1 ) ) ; } void build_seg_tree ( int ss , int se , int si , int tree [ ] , int arr [ ] ) { if ( ss == se ) { tree [ si ] = check ( arr [ ss ] ) ; return ; } int mid = ( ss + se ) / 2 ; build_seg_tree ( ss , mid , 2 * si + 1 , tree , arr ) ; build_seg_tree ( mid + 1 , se , 2 * si + 2 , tree , arr ) ; tree [ si ] = tree [ 2 * si + 1 ] + tree [ 2 * si + 2 ] ; } void update ( int ss , int se , int si , int X , int V , int tree [ ] , int arr [ ] ) { if ( ss == se ) { if ( ss == X ) { arr [ X ] = V ; tree [ si ] = check ( V ) ; } return ; } int mid = ( ss + se ) / 2 ; if ( X <= mid ) update ( ss , mid , 2 * si + 1 , X , V , tree , arr ) ; else update ( mid + 1 , se , 2 * si + 2 , X , V , tree , arr ) ; tree [ si ] = tree [ 2 * si + 1 ] + tree [ 2 * si + 2 ] ; } int query ( int l , int r , int ss , int se , int si , int tree [ ] ) { if ( r < ss l > se ) return 0 ; if ( l <= ss && r >= se ) return tree [ si ] ; int mid = ( ss + se ) / 2 ; return query ( l , r , ss , mid , 2 * si + 1 , tree ) + query ( l , r , mid + 1 , se , 2 * si + 2 , tree ) ; } void Query ( int arr [ ] , int N , vector < vector < int > > Q ) { int tree [ 4 * N ] = { 0 } ; build_seg_tree ( 0 , N - 1 , 0 , tree , arr ) ; for ( int i = 0 ; i < ( int ) Q . size ( ) ; i ++ ) { if ( Q [ i ] [ 0 ] == 1 ) cout << query ( Q [ i ] [ 1 ] , Q [ i ] [ 2 ] , 0 , N - 1 , 0 , tree ) << " β " ; else update ( 0 , N - 1 , 0 , Q [ i ] [ 1 ] , Q [ i ] [ 2 ] , tree , arr ) ; } } int main ( ) { int arr [ ] = { 12 , 11 , 16 , 2 , 32 } ; vector < vector < int > > Q { { 1 , 0 , 2 } , { 2 , 4 , 24 } , { 1 , 1 , 4 } } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; Query ( arr , N , Q ) ; return 0 ; } |
Find the smallest value of N such that sum of first N natural numbers is Γ’ β°Β₯ X | ; Function to check if sum of first N natural numbers is >= X ; Finds minimum value of N such that sum of first N natural number >= X ; Binary Search ; Checks if sum of first ' mid ' natural numbers is greater than equal to X ; Update res ; Update high ; Update low ; Driver Code ; Input ; Finds minimum value of N such that sum of first N natural number >= X | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isGreaterEqual ( int N , int X ) { return ( N * 1LL * ( N + 1 ) / 2 ) >= X ; } int minimumPossible ( int X ) { int low = 1 , high = X , res = -1 ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( isGreaterEqual ( mid , X ) ) { res = mid ; high = mid - 1 ; } else low = mid + 1 ; } return res ; } int main ( ) { int X = 14 ; cout << minimumPossible ( X ) ; return 0 ; } |
Minimum moves required to come out of a grid safely | C ++ program to implement the above approach ; Stores size of the grid ; Function to check valid cells of the grid ; Checks for the border sides ; Function to find shortest distance between two cells of the grid ; Rows of the grid ; Column of the grid ; Stores possible move of the person ; Store possible cells visited by the person ; Store possible cells which are burning ; Traverse the grid ; If current cell is burning ; If person is in the current cell ; Stores shortest distance between two cells ; Check if a cell is visited by the person or not ; While pQ is not empty ; Update depth ; Popped all the cells from pQ and mark all adjacent cells of as visited ; Front element of the queue pQ ; Remove front element of the queue pQ ; If current cell is burning ; Find all adjacent cells ; Stores row number of adjacent cell ; Stores column number of adjacent cell ; Checks if current cell is valid ; Mark the cell as visited ; Enqueue the cell ; Checks the escape condition ; Burn all the adjacent cells of burning cells ; Front element of the queue fQ ; Delete front element of the queue fQ ; Find adjacent cells of burning cell ; Stores row number of adjacent cell ; Stores column number of adjacent cell ; Checks if current cell is valid ; Burn all the adjacent cells of current cell ; Driver Code ; Given grid | #include <bits/stdc++.h> NEW_LINE using namespace std ; int m , n ; bool valid ( int x , int y ) { return ( x >= 0 && x < m && y >= 0 && y < n ) ; } bool border ( int x , int y ) { return ( x == 0 x == m - 1 y == 0 y == n - 1 ) ; } int minStep ( vector < vector < int > > mat ) { m = mat . size ( ) ; n = mat [ 0 ] . size ( ) ; int dx [ ] = { 1 , -1 , 0 , 0 } ; int dy [ ] = { 0 , 0 , 1 , -1 } ; queue < pair < int , int > > pQ ; queue < pair < int , int > > fQ ; for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( mat [ i ] [ j ] == 2 ) fQ . push ( { i , j } ) ; else if ( mat [ i ] [ j ] == 1 ) { if ( border ( i , j ) ) return 0 ; pQ . push ( { i , j } ) ; } } } int depth = 0 ; vector < vector < int > > visited ( n , vector < int > ( m , 0 ) ) ; while ( pQ . size ( ) > 0 ) { depth ++ ; for ( int i = pQ . size ( ) ; i > 0 ; i -- ) { pair < int , int > pos = pQ . front ( ) ; pQ . pop ( ) ; if ( mat [ pos . first ] [ pos . second ] == 2 ) continue ; for ( int j = 0 ; j < 4 ; j ++ ) { int x = pos . first + dx [ j ] ; int y = pos . second + dy [ j ] ; if ( valid ( x , y ) && mat [ x ] [ y ] != 2 && ! visited [ x ] [ y ] ) { visited [ x ] [ y ] = 1 ; pQ . push ( pair < int , int > ( x , y ) ) ; if ( border ( x , y ) ) return depth ; } } } for ( int i = fQ . size ( ) ; i > 0 ; i -- ) { pair < int , int > pos = fQ . front ( ) ; fQ . pop ( ) ; for ( int j = 0 ; j < 4 ; j ++ ) { int x = pos . first + dx [ j ] ; int y = pos . second + dy [ j ] ; if ( valid ( x , y ) && mat [ x ] [ y ] != 2 ) { mat [ x ] [ y ] = 2 ; fQ . push ( pair < int , int > ( x , y ) ) ; } } } } return -1 ; } int main ( ) { vector < vector < int > > grid = { { 0 , 0 , 0 , 0 } , { 2 , 0 , 0 , 0 } , { 2 , 1 , 0 , 0 } , { 2 , 2 , 0 , 0 } } ; cout << minStep ( grid ) ; } |
Find sum of non | C ++ Find the sum of all non - repeated elements in an array ; Find the sum of all non - repeated elements in an array ; sort all elements of array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findSum ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] != arr [ i + 1 ] ) sum = sum + arr [ i ] ; } return sum ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 1 , 1 , 4 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << findSum ( arr , n ) ; return 0 ; } |
Length of the longest subsequence such that XOR of adjacent elements is equal to K | C ++ program for the above approach ; Function to find maximum length of subsequence having XOR of adjacent elements equal to K ; Store maximum length of subsequence ; Stores the dp - states ; Base case ; Iterate over the range [ 1 , N - 1 ] ; Iterate over the range [ 0 , i - 1 ] ; If arr [ i ] ^ arr [ j ] = = K ; Update the dp [ i ] ; Update the maximum subsequence length ; If length of longest subsequence is less than 2 then return 0 ; Driver Code ; Input ; Print the length of longest subsequence | #include <bits/stdc++.h> NEW_LINE using namespace std ; int xorSubsequence ( int a [ ] , int n , int k ) { int ans = 0 ; int dp [ n ] = { 0 } ; dp [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { for ( int j = i - 1 ; j >= 0 ; j -- ) { if ( ( a [ i ] ^ a [ j ] ) == k ) dp [ i ] = max ( dp [ i ] , dp [ j ] + 1 ) ; } ans = max ( ans , dp [ i ] ) ; dp [ i ] = max ( 1 , dp [ i ] ) ; } return ans >= 2 ? ans : 0 ; } int main ( ) { int arr [ ] = { 3 , 2 , 4 , 3 , 5 } ; int K = 1 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << xorSubsequence ( arr , N , K ) ; return 0 ; } |
Check if a Binary Tree contains duplicate subtrees of size 2 or more | C ++ program to find if there is a duplicate sub - tree of size 2 or more . ; Structure for a binary tree node ; A utility function to create a new node ; This function returns empty string if tree contains a duplicate subtree of size 2 or more . ; If current node is NULL , return marker ; If left subtree has a duplicate subtree . ; Do same for right subtree ; Serialize current subtree ; If current subtree already exists in hash table . [ Note that size of a serialized tree with single node is 3 as it has two marker nodes . ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; const char MARKER = ' $ ' ; struct Node { char key ; Node * left , * right ; } ; Node * newNode ( char key ) { Node * node = new Node ; node -> key = key ; node -> left = node -> right = NULL ; return node ; } unordered_set < string > subtrees ; string dupSubUtil ( Node * root ) { string s = " " ; if ( root == NULL ) return s + MARKER ; string lStr = dupSubUtil ( root -> left ) ; if ( lStr . compare ( s ) == 0 ) return s ; string rStr = dupSubUtil ( root -> right ) ; if ( rStr . compare ( s ) == 0 ) return s ; s = s + root -> key + lStr + rStr ; if ( s . length ( ) > 3 && subtrees . find ( s ) != subtrees . end ( ) ) return " " ; subtrees . insert ( s ) ; return s ; } int main ( ) { Node * root = newNode ( ' A ' ) ; root -> left = newNode ( ' B ' ) ; root -> right = newNode ( ' C ' ) ; root -> left -> left = newNode ( ' D ' ) ; root -> left -> right = newNode ( ' E ' ) ; root -> right -> right = newNode ( ' B ' ) ; root -> right -> right -> right = newNode ( ' E ' ) ; root -> right -> right -> left = newNode ( ' D ' ) ; string str = dupSubUtil ( root ) ; ( str . compare ( " " ) == 0 ) ? cout << " β Yes β " : cout << " β No β " ; return 0 ; } |
Count pairs of similar rectangles possible from a given array | C ++ Program for the hashmap Approach ; Get the count of all pairs of similar rectangles ; Initialize the result value and map to store the ratio to the rectangles ; Calculate the rectangular ratio and save them ; Calculate pairs of similar rectangles from its common ratio ; Driver code | #include <iostream> NEW_LINE #include <unordered_map> NEW_LINE using namespace std ; int getCount ( int rows , int columns , int sides [ ] [ 2 ] ) { int ans = 0 ; unordered_map < double , int > umap ; for ( int i = 0 ; i < rows ; i ++ ) { double ratio = ( double ) sides [ i ] [ 0 ] / sides [ i ] [ 1 ] ; umap [ ratio ] ++ ; } for ( auto x : umap ) { int value = x . second ; if ( value > 1 ) { ans += ( value * ( value - 1 ) ) / 2 ; } } return ans ; } int main ( ) { int sides [ 4 ] [ 2 ] = { { 4 , 8 } , { 10 , 20 } , { 15 , 30 } , { 3 , 6 } } ; int rows = 4 ; int columns = 2 ; cout << getCount ( rows , columns , sides ) ; return 0 ; } |
Non | Simple CPP program to find first non - repeating element . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int firstNonRepeating ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { int j ; for ( j = 0 ; j < n ; j ++ ) if ( i != j && arr [ i ] == arr [ j ] ) break ; if ( j == n ) return arr [ i ] ; } return -1 ; } int main ( ) { int arr [ ] = { 9 , 4 , 9 , 6 , 7 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << firstNonRepeating ( arr , n ) ; return 0 ; } |
Non | Efficient CPP program to find first non - repeating element . ; Insert all array elements in hash table ; Traverse array again and return first element with count 1. ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int firstNonRepeating ( int arr [ ] , int n ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) mp [ arr [ i ] ] ++ ; for ( int i = 0 ; i < n ; i ++ ) if ( mp [ arr [ i ] ] == 1 ) return arr [ i ] ; return -1 ; } int main ( ) { int arr [ ] = { 9 , 4 , 9 , 6 , 7 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << firstNonRepeating ( arr , n ) ; return 0 ; } |
Non | Efficient CPP program to print all non - repeating elements . ; Insert all array elements in hash table ; Traverse through map only and ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void firstNonRepeating ( int arr [ ] , int n ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) mp [ arr [ i ] ] ++ ; for ( auto x : mp ) if ( x . second == 1 ) cout << x . first << " β " ; } int main ( ) { int arr [ ] = { 9 , 4 , 9 , 6 , 7 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; firstNonRepeating ( arr , n ) ; return 0 ; } |
Minimum substring removals required to make all remaining characters of a string same | C ++ program to implement the above approach ; Function to count minimum operations required to make all characters equal by repeatedly removing substring ; Remove consecutive duplicate characters from str ; Stores length of the string ; Stores frequency of each distinct characters of the string str ; Iterate over all the characters of the string str ; Update frequency of str [ i ] ; Decrementing the frequency of the string str [ 0 ] ; Decrementing the frequency of the string str [ N - 1 ] ; Stores the required count ; Iterate over all characters of the string str ; Update ans ; Driver Code ; Given string | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minOperationNeeded ( string str ) { str = string ( str . begin ( ) , unique ( str . begin ( ) , str . end ( ) ) ) ; int N = str . length ( ) ; int res [ 256 ] = { 0 } ; for ( int i = 0 ; i < N ; ++ i ) { res [ str [ i ] ] += 1 ; } res [ str [ 0 ] ] -= 1 ; res [ str [ N - 1 ] ] -= 1 ; int ans = INT_MAX ; for ( int i = 0 ; i < N ; ++ i ) { ans = min ( ans , res [ str [ i ] ] ) ; } cout << ( ans + 1 ) << endl ; } int main ( ) { string str = " ABCDABCDABCDA " ; minOperationNeeded ( str ) ; return 0 ; } |
Print all root to leaf paths of an N | C ++ program for the above approach ; Structure of an N ary tree node ; Parameterized Constructor ; Function to print the root to leaf path of the given N - ary Tree ; Print elements in the vector ; Utility function to print all root to leaf paths of an Nary Tree ; If root is null ; Insert current node 's data into the vector ; If current node is a leaf node ; Print the path ; Pop the leaf node and return ; Recur for all children of the current node ; Recursive Function Call ; Function to print root to leaf path ; If root is null , return ; Stores the root to leaf path ; Utility function call ; Driver Code ; Given N - Ary tree ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; vector < Node * > child ; Node ( int x ) : data ( x ) { } } ; void printPath ( vector < int > vec ) { for ( int ele : vec ) { cout << ele << " β " ; } cout << endl ; } void printAllRootToLeafPaths ( Node * root , vector < int > vec ) { if ( ! root ) return ; vec . push_back ( root -> data ) ; if ( root -> child . empty ( ) ) { printPath ( vec ) ; vec . pop_back ( ) ; return ; } for ( int i = 0 ; i < root -> child . size ( ) ; i ++ ) printAllRootToLeafPaths ( root -> child [ i ] , vec ) ; } void printAllRootToLeafPaths ( Node * root ) { if ( ! root ) return ; vector < int > vec ; printAllRootToLeafPaths ( root , vec ) ; } int main ( ) { Node * root = new Node ( 1 ) ; ( root -> child ) . push_back ( new Node ( 2 ) ) ; ( root -> child ) . push_back ( new Node ( 3 ) ) ; ( root -> child [ 0 ] -> child ) . push_back ( new Node ( 4 ) ) ; ( root -> child [ 1 ] -> child ) . push_back ( new Node ( 5 ) ) ; ( root -> child [ 1 ] -> child ) . push_back ( new Node ( 6 ) ) ; ( root -> child [ 1 ] -> child [ 1 ] -> child ) . push_back ( new Node ( 7 ) ) ; ( root -> child [ 1 ] -> child [ 1 ] -> child ) . push_back ( new Node ( 8 ) ) ; printAllRootToLeafPaths ( root ) ; return 0 ; } |
Minimum removals to make a string concatenation of a substring of 0 s followed by a substring of 1 s | C ++ program for the above approach ; Function to count minimum removals required to make a given string concatenation of substring of 0 s followed by substring of 1 s ; Stores the length of the string ; Precompute the count of 0 s ; Check for the last character ; Traverse and update zeroCount array ; If current character is 0 , ; Update aCount [ i ] as aCount [ i + 1 ] + 1 ; Update as aCount [ i + 1 ] ; Keeps track of deleted 1 s ; Stores the count of removals ; Traverse the array ; If current character is 1 ; Update ans ; If all 1 s are deleted ; Return the minimum number of deletions ; Driver Code | #include <bits/stdc++.h> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int minimumDeletions ( string s ) { int n = s . size ( ) ; int zeroCount [ n ] ; zeroCount [ n - 1 ] = ( s [ n - 1 ] == '0' ) ? 1 : 0 ; for ( int i = n - 2 ; i >= 0 ; i -- ) zeroCount [ i ] = ( s [ i ] == '0' ) ? zeroCount [ i + 1 ] + 1 : zeroCount [ i + 1 ] ; int oneCount = 0 ; int ans = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == '1' ) { ans = min ( ans , oneCount + zeroCount [ i ] ) ; oneCount ++ ; } } ans = min ( ans , oneCount ) ; return ( ans == INT_MAX ) ? 0 : ans ; } int main ( ) { string stri = "00101101" ; cout << minimumDeletions ( stri ) << endl ; return 0 ; } |
Pairs of Positive Negative values in an array | Simple CPP program to find pairs of positive and negative values present in an array . ; Print pair with negative and positive value ; For each element of array . ; Try to find the negative value of arr [ i ] from i + 1 to n ; If absolute values are equal print pair . ; If size of vector is 0 , therefore there is no element with positive negative value , print "0" ; Sort the vector ; Print the pair with negative positive value . ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printPairs ( int arr [ ] , int n ) { vector < int > v ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( abs ( arr [ i ] ) == abs ( arr [ j ] ) ) v . push_back ( abs ( arr [ i ] ) ) ; if ( v . size ( ) == 0 ) return ; sort ( v . begin ( ) , v . end ( ) ) ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) cout << - v [ i ] << " β " << v [ i ] ; } int main ( ) { int arr [ ] = { 4 , 8 , 9 , -4 , 1 , -1 , -8 , -9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printPairs ( arr , n ) ; return 0 ; } |
Check if an array can be divided into pairs whose sum is divisible by k | A C ++ program to check if arr [ 0. . n - 1 ] can be divided in pairs such that every pair is divisible by k . ; Returns true if arr [ 0. . n - 1 ] can be divided into pairs with sum divisible by k . ; An odd length array cannot be divided into pairs ; Create a frequency array to count occurrences of all remainders when divided by k . ; Count occurrences of all remainders ; Traverse input array and use freq [ ] to decide if given array can be divided in pairs ; Remainder of current element ; If remainder with current element divides k into two halves . ; Then there must be even occurrences of such remainder ; If remainder is 0 , then there must be two elements with 0 remainder ; Then there must be even occurrences of such remainder ; Else number of occurrences of remainder must be equal to number of occurrences of k - remainder ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool canPairs ( int arr [ ] , int n , int k ) { if ( n & 1 ) return false ; unordered_map < int , int > freq ; for ( int i = 0 ; i < n ; i ++ ) freq [ ( ( arr [ i ] % k ) + k ) % k ] ++ ; for ( int i = 0 ; i < n ; i ++ ) { int rem = ( ( arr [ i ] % k ) + k ) % k ; if ( 2 * rem == k ) { if ( freq [ rem ] % 2 != 0 ) return false ; } else if ( rem == 0 ) { if ( freq [ rem ] & 1 ) return false ; } else if ( freq [ rem ] != freq [ k - rem ] ) return false ; } return true ; } int main ( ) { int arr [ ] = { 92 , 75 , 65 , 48 , 45 , 35 } ; int k = 10 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; canPairs ( arr , n , k ) ? cout << " True " : cout << " False " ; return 0 ; } |
Subarray with no pair sum divisible by K | CPP code to find the subarray with no pair sum divisible by K ; function to find the subarray with no pair sum divisible by k ; hash table to store the remainders obtained on dividing by K ; s : starting index of the current subarray , e : ending index of the current subarray , maxs : starting index of the maximum size subarray so far , maxe : ending index of the maximum size subarray so far ; insert the first element in the set ; Removing starting elements of current subarray while there is an element in set which makes a pair with mod [ i ] such that the pair sum is divisible . ; include the current element in the current subarray the ending index of the current subarray increments by one ; compare the size of the current subarray with the maximum size so far ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void subarrayDivisibleByK ( int arr [ ] , int n , int k ) { map < int , int > mp ; int s = 0 , e = 0 , maxs = 0 , maxe = 0 ; mp [ arr [ 0 ] % k ] ++ ; for ( int i = 1 ; i < n ; i ++ ) { int mod = arr [ i ] % k ; while ( mp [ k - mod ] != 0 || ( mod == 0 && mp [ mod ] != 0 ) ) { mp [ arr [ s ] % k ] -- ; s ++ ; } mp [ mod ] ++ ; e ++ ; if ( ( e - s ) > ( maxe - maxs ) ) { maxe = e ; maxs = s ; } } cout << " The β maximum β size β is β " << maxe - maxs + 1 << " β and β " " the β subarray β is β as β follows STRNEWLINE " ; for ( int i = maxs ; i <= maxe ; i ++ ) cout << arr [ i ] << " β " ; } int main ( ) { int k = 3 ; int arr [ ] = { 5 , 10 , 15 , 20 , 25 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; subarrayDivisibleByK ( arr , n , k ) ; return 0 ; } |
Find three element from different three arrays such that a + b + c = sum | C ++ program to find three element from different three arrays such that a + b + c is equal to given sum ; Function to check if there is an element from each array such that sum of the three elements is equal to given sum . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool findTriplet ( int a1 [ ] , int a2 [ ] , int a3 [ ] , int n1 , int n2 , int n3 , int sum ) { for ( int i = 0 ; i < n1 ; i ++ ) for ( int j = 0 ; j < n2 ; j ++ ) for ( int k = 0 ; k < n3 ; k ++ ) if ( a1 [ i ] + a2 [ j ] + a3 [ k ] == sum ) return true ; return false ; } int main ( ) { int a1 [ ] = { 1 , 2 , 3 , 4 , 5 } ; int a2 [ ] = { 2 , 3 , 6 , 1 , 2 } ; int a3 [ ] = { 3 , 2 , 4 , 5 , 6 } ; int sum = 9 ; int n1 = sizeof ( a1 ) / sizeof ( a1 [ 0 ] ) ; int n2 = sizeof ( a2 ) / sizeof ( a2 [ 0 ] ) ; int n3 = sizeof ( a3 ) / sizeof ( a3 [ 0 ] ) ; findTriplet ( a1 , a2 , a3 , n1 , n2 , n3 , sum ) ? cout << " Yes " : cout << " No " ; return 0 ; } |
Find three element from different three arrays such that a + b + c = sum | C ++ program to find three element from different three arrays such that a + b + c is equal to given sum ; Function to check if there is an element from each array such that sum of the three elements is equal to given sum . ; Store elements of first array in hash ; sum last two arrays element one by one ; Consider current pair and find if there is an element in a1 [ ] such that these three form a required triplet ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool findTriplet ( int a1 [ ] , int a2 [ ] , int a3 [ ] , int n1 , int n2 , int n3 , int sum ) { unordered_set < int > s ; for ( int i = 0 ; i < n1 ; i ++ ) s . insert ( a1 [ i ] ) ; for ( int i = 0 ; i < n2 ; i ++ ) { for ( int j = 0 ; j < n3 ; j ++ ) { if ( s . find ( sum - a2 [ i ] - a3 [ j ] ) != s . end ( ) ) return true ; } } return false ; } int main ( ) { int a1 [ ] = { 1 , 2 , 3 , 4 , 5 } ; int a2 [ ] = { 2 , 3 , 6 , 1 , 2 } ; int a3 [ ] = { 3 , 2 , 4 , 5 , 6 } ; int sum = 9 ; int n1 = sizeof ( a1 ) / sizeof ( a1 [ 0 ] ) ; int n2 = sizeof ( a2 ) / sizeof ( a2 [ 0 ] ) ; int n3 = sizeof ( a3 ) / sizeof ( a3 [ 0 ] ) ; findTriplet ( a1 , a2 , a3 , n1 , n2 , n3 , sum ) ? cout << " Yes " : cout << " No " ; return 0 ; } |
Subsets and Splits