text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Find the kth smallest number with sum of digits as m | C ++ implementation of the approach ; Recursively moving to add all the numbers upto a limit with sum of digits as m ; Max number of digits allowed in a number for this implementation ; Function to return the kth number with sum of digits as m ; The kth smallest number is found ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define int long long NEW_LINE const int N = 2005 ; set < int > ans ; void dfs ( int num , int left , int ct ) { if ( ct >= 15 ) return ; if ( left == 0 ) ans . insert ( num ) ; for ( int i = 0 ; i <= min ( left , 9LL ) ; i ++ ) dfs ( num * 10 + i , left - i , ct + 1 ) ; } int getKthNum ( int m , int k ) { dfs ( 0 , m , 0 ) ; int ct = 0 ; for ( auto it : ans ) { ct ++ ; if ( ct == k ) { return it ; } } return -1 ; } int main ( ) { int m = 5 , k = 3 ; cout << getKthNum ( m , k ) ; return 0 ; } |
Remove minimum elements from the array such that 2 * min becomes more than max | CPP program to remove minimum elements from the array such that 2 * min becomes more than max ; Function to remove minimum elements from the array such that 2 * min becomes more than max ; Sort the array ; To store the required answer ; Traverse from left to right ; Update the answer ; Return the required answer ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Removal ( vector < int > v , int n ) { sort ( v . begin ( ) , v . end ( ) ) ; int ans = INT_MAX ; for ( vector < int > :: iterator i = v . begin ( ) ; i != v . end ( ) ; i ++ ) { vector < int > :: iterator j = upper_bound ( v . begin ( ) , v . end ( ) , ( 2 * ( * i ) ) ) ; ans = min ( ans , n - ( int ) ( j - i ) ) ; } return ans ; } int main ( ) { vector < int > a = { 4 , 5 , 100 , 9 , 10 , 11 , 12 , 15 , 200 } ; int n = a . size ( ) ; cout << Removal ( a , n ) ; return 0 ; } |
Sort the Queue using Recursion | C ++ implementation of the approach ; Function to push element in last by popping from front until size becomes 0 ; Base condition ; pop front element and push this last in a queue ; Recursive call for pushing element ; Function to push an element in the queue while maintaining the sorted order ; Base condition ; If current element is less than the element at the front ; Call stack with front of queue ; Recursive call for inserting a front element of the queue to the last ; Push front element into last in a queue ; Recursive call for pushing element in a queue ; Function to sort the given queue using recursion ; Return if queue is empty ; Get the front element which will be stored in this variable throughout the recursion stack ; Remove the front element ; Recursive call ; Push the current element into the queue according to the sorting order ; Driver code ; Push elements to the queue ; Sort the queue ; Print the elements of the queue after sorting | #include <bits/stdc++.h> NEW_LINE using namespace std ; void FrontToLast ( queue < int > & q , int qsize ) { if ( qsize <= 0 ) return ; q . push ( q . front ( ) ) ; q . pop ( ) ; FrontToLast ( q , qsize - 1 ) ; } void pushInQueue ( queue < int > & q , int temp , int qsize ) { if ( q . empty ( ) qsize == 0 ) { q . push ( temp ) ; return ; } else if ( temp <= q . front ( ) ) { q . push ( temp ) ; FrontToLast ( q , qsize ) ; } else { q . push ( q . front ( ) ) ; q . pop ( ) ; pushInQueue ( q , temp , qsize - 1 ) ; } } void sortQueue ( queue < int > & q ) { if ( q . empty ( ) ) return ; int temp = q . front ( ) ; q . pop ( ) ; sortQueue ( q ) ; pushInQueue ( q , temp , q . size ( ) ) ; } int main ( ) { queue < int > qu ; qu . push ( 10 ) ; qu . push ( 7 ) ; qu . push ( 16 ) ; qu . push ( 9 ) ; qu . push ( 20 ) ; qu . push ( 5 ) ; sortQueue ( qu ) ; while ( ! qu . empty ( ) ) { cout << qu . front ( ) << " β " ; qu . pop ( ) ; } } |
Sort the character array based on ASCII % N | C ++ implementation of the approach ; A utility function to swap two elements ; This function takes last element as pivot , places the pivot element at its correct position in sorted array , and places all smaller ( smaller than pivot ) to left of pivot and all greater elements to right of pivot ; pivot ; Index of smaller element ; If current element is smaller than or equal to pivot Instead of values , ASCII % m values are compared ; Increment index of smaller element ; swap ; The main function that implements QuickSort arr [ ] -- > Array to be sorted , low -- > Starting index , high -- > Ending index ; pi is partitioning index , arr [ p ] is now at right place ; Separately sort elements before partition and after partition ; Function to print the given array ; Driver code ; Sort the given array ; Print the sorted array | #include <bits/stdc++.h> NEW_LINE using namespace std ; void swap ( char * a , char * b ) { char t = * a ; * a = * b ; * b = t ; } int partition ( char arr [ ] , int low , int high , int mod ) { char pivot = arr [ high ] ; int i = ( low - 1 ) ; int piv = pivot % mod ; for ( int j = low ; j <= high - 1 ; j ++ ) { int a = arr [ j ] % mod ; if ( a <= piv ) { i ++ ; swap ( & arr [ i ] , & arr [ j ] ) ; } } swap ( & arr [ i + 1 ] , & arr [ high ] ) ; return ( i + 1 ) ; } void quickSort ( char arr [ ] , int low , int high , int mod ) { if ( low < high ) { int pi = partition ( arr , low , high , mod ) ; quickSort ( arr , low , pi - 1 , mod ) ; quickSort ( arr , pi + 1 , high , mod ) ; } } void printArray ( char arr [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) cout << arr [ i ] << " β " ; } int main ( ) { char arr [ ] = { ' g ' , ' e ' , ' e ' , ' k ' , ' s ' } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int mod = 8 ; quickSort ( arr , 0 , n - 1 , mod ) ; printArray ( arr , n ) ; return 0 ; } |
Two nodes of a BST are swapped , correct the BST | Set | C ++ implementation of the above approach ; A binary tree node has data , pointer to left child and a pointer to right child ; Utility function for insertion sort ; Utility function to create a vector with inorder traversal of a binary tree ; Base cases ; Recursive call for left subtree ; Insert node into vector ; Recursive call for right subtree ; Function to exchange data for incorrect nodes ; Base cases ; Recursive call to find the node in left subtree ; Check if current node is incorrect and exchange ; Recursive call to find the node in right subtree ; Primary function to fix the two nodes ; Vector to store the inorder traversal of tree ; Function call to insert nodes into vector ; create a copy of the vector ; Sort the original vector thereby making it a valid BST 's inorder ; Traverse through both vectors and compare misplaced values in original BST ; Find the mismatched values and interchange them ; Find and exchange the data of the two nodes ; As it given only two values are wrong we don 't need to check further ; Return the root of corrected BST ; A utility function to print Inorder traversal ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int data ; struct node * left , * right ; node ( int x ) { data = x ; left = right = NULL ; } } ; void insertionSort ( vector < int > & v , int n ) { int i , key , j ; for ( i = 1 ; i < n ; i ++ ) { key = v [ i ] ; j = i - 1 ; while ( j >= 0 && v [ j ] > key ) { v [ j + 1 ] = v [ j ] ; j = j - 1 ; } v [ j + 1 ] = key ; } } void inorder ( node * root , vector < int > & v ) { if ( ! root ) return ; inorder ( root -> left , v ) ; v . push_back ( root -> data ) ; inorder ( root -> right , v ) ; } void find ( node * root , int res , int res2 ) { if ( ! root ) { return ; } find ( root -> left , res , res2 ) ; if ( root -> data == res ) { root -> data = res2 ; } else if ( root -> data == res2 ) { root -> data = res ; } find ( root -> right , res , res2 ) ; } struct node * correctBST ( struct node * root ) { vector < int > v ; inorder ( root , v ) ; vector < int > v1 = v ; insertionSort ( v , v . size ( ) ) ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { if ( v [ i ] != v1 [ i ] ) { find ( root , v1 [ i ] , v [ i ] ) ; break ; } } return root ; } void printInorder ( struct node * node ) { if ( node == NULL ) return ; printInorder ( node -> left ) ; printf ( " % d β " , node -> data ) ; printInorder ( node -> right ) ; } int main ( ) { struct node * root = new node ( 6 ) ; root -> left = new node ( 10 ) ; root -> right = new node ( 2 ) ; root -> left -> left = new node ( 1 ) ; root -> left -> right = new node ( 3 ) ; root -> right -> right = new node ( 12 ) ; root -> right -> left = new node ( 7 ) ; printf ( " Inorder β Traversal β of β the " ) ; printf ( " original β tree β STRNEWLINE " ) ; printInorder ( root ) ; correctBST ( root ) ; printf ( " Inorder Traversal of the " printf ( " fixed β tree β STRNEWLINE " ) ; printInorder ( root ) ; return 0 ; } |
Iterative selection sort for linked list | C ++ implementation of the approach ; Linked List Node ; Utility function to create a new Linked List Node ; Function to sort a linked list using selection sort algorithm by swapping the next pointers ; While b is not the last node ; While d is pointing to a valid node ; If d appears immediately after b ; Case 1 : b is the head of the linked list ; Move d before b ; Swap b and d pointers ; Update the head ; Skip to the next element as it is already in order ; Case 2 : b is not the head of the linked list ; Move d before b ; Swap b and d pointers ; Skip to the next element as it is already in order ; If b and d have some non - zero number of nodes in between them ; Case 3 : b is the head of the linked list ; Swap b -> next and d -> next ; Swap b and d pointers ; Skip to the next element as it is already in order ; Update the head ; Case 4 : b is not the head of the linked list ; Swap b -> next and d -> next ; Swap b and d pointers ; Skip to the next element as it is already in order ; Update c and skip to the next element as it is already in order ; Function to print the list ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * next ; } ; Node * newNode ( int val ) { Node * temp = new Node ; temp -> data = val ; temp -> next = NULL ; return temp ; } Node * selectionSort ( Node * head ) { Node * a , * b , * c , * d , * r ; a = b = head ; while ( b -> next ) { c = d = b -> next ; while ( d ) { if ( b -> data > d -> data ) { if ( b -> next == d ) { if ( b == head ) { b -> next = d -> next ; d -> next = b ; r = b ; b = d ; d = r ; c = d ; head = b ; d = d -> next ; } else { b -> next = d -> next ; d -> next = b ; a -> next = d ; r = b ; b = d ; d = r ; c = d ; d = d -> next ; } } else { if ( b == head ) { r = b -> next ; b -> next = d -> next ; d -> next = r ; c -> next = b ; r = b ; b = d ; d = r ; c = d ; d = d -> next ; head = b ; } else { r = b -> next ; b -> next = d -> next ; d -> next = r ; c -> next = b ; a -> next = d ; r = b ; b = d ; d = r ; c = d ; d = d -> next ; } } } else { c = d ; d = d -> next ; } } a = b ; b = b -> next ; } return head ; } void printList ( Node * head ) { while ( head ) { cout << head -> data << " β " ; head = head -> next ; } } int main ( ) { Node * head = newNode ( 5 ) ; head -> next = newNode ( 4 ) ; head -> next -> next = newNode ( 3 ) ; head = selectionSort ( head ) ; printList ( head ) ; return 0 ; } |
Find original numbers from gcd ( ) every pair | C ++ implementation of the approach ; Utility function to print the contents of an array ; Function to find the required numbers ; Sort array in decreasing order ; Count frequency of each element ; Size of the resultant array ; Store the highest element in the resultant array ; Decrement the frequency of that element ; Compute GCD ; Decrement GCD value by 2 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; } void findNumbers ( int arr [ ] , int n ) { sort ( arr , arr + n , greater < int > ( ) ) ; int freq [ arr [ 0 ] + 1 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) freq [ arr [ i ] ] ++ ; int size = sqrt ( n ) ; int brr [ size ] = { 0 } , x , l = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( freq [ arr [ i ] ] > 0 ) { brr [ l ] = arr [ i ] ; freq [ brr [ l ] ] -- ; l ++ ; for ( int j = 0 ; j < l ; j ++ ) { if ( i != j ) { x = __gcd ( arr [ i ] , brr [ j ] ) ; freq [ x ] -= 2 ; } } } } printArr ( brr , size ) ; } int main ( ) { int arr [ ] = { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 5 , 5 , 5 , 7 , 10 , 12 , 2 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findNumbers ( arr , n ) ; return 0 ; } |
Bitwise AND of N binary strings | C ++ implementation of the above approach ; Function to find the bitwise AND of all the binary strings ; To store the largest and the smallest string ' s β size , β We β need β this β to β add β ' 0 's in the resultant string ; Reverse each string Since we need to perform AND operation on bits from Right to Left ; Update the respective length values ; Traverse bits from 0 to smallest string 's size ; If at this bit position , there is a 0 in any of the given strings then AND operation on current bit position will be 0 ; Add resultant bit to result ; Add 0 's to the string. ; Reverse the string Since we started from LEFT to RIGHT ; Return the resultant string ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string strBitwiseAND ( string * arr , int n ) { string res ; int smallest_size = INT_MAX ; int largest_size = INT_MIN ; for ( int i = 0 ; i < n ; i ++ ) { reverse ( arr [ i ] . begin ( ) , arr [ i ] . end ( ) ) ; smallest_size = min ( smallest_size , ( int ) arr [ i ] . size ( ) ) ; largest_size = max ( largest_size , ( int ) arr [ i ] . size ( ) ) ; } for ( int i = 0 ; i < smallest_size ; i ++ ) { bool all_ones = true ; for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ j ] [ i ] == '0' ) { all_ones = false ; break ; } } res += ( all_ones ? '1' : '0' ) ; } for ( int i = 0 ; i < largest_size - smallest_size ; i ++ ) res += '0' ; reverse ( res . begin ( ) , res . end ( ) ) ; return res ; } int main ( ) { string arr [ ] = { "101" , "110110" , "111" } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << strBitwiseAND ( arr , n ) ; return 0 ; } |
Print all paths from a given source to a destination using BFS | C ++ program to print all paths of source to destination in given graph ; utility function for printing the found path in graph ; utility function to check if current vertex is already present in path ; utility function for finding paths in graph from source to destination ; create a queue which stores the paths ; path vector to store the current path ; if last vertex is the desired destination then print the path ; traverse to all the nodes connected to current vertex and push new path to queue ; driver program ; number of vertices ; construct a graph ; function for finding the paths | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printpath ( vector < int > & path ) { int size = path . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) cout << path [ i ] << " β " ; cout << endl ; } int isNotVisited ( int x , vector < int > & path ) { int size = path . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) if ( path [ i ] == x ) return 0 ; return 1 ; } void findpaths ( vector < vector < int > > & g , int src , int dst , int v ) { queue < vector < int > > q ; vector < int > path ; path . push_back ( src ) ; q . push ( path ) ; while ( ! q . empty ( ) ) { path = q . front ( ) ; q . pop ( ) ; int last = path [ path . size ( ) - 1 ] ; if ( last == dst ) printpath ( path ) ; for ( int i = 0 ; i < g [ last ] . size ( ) ; i ++ ) { if ( isNotVisited ( g [ last ] [ i ] , path ) ) { vector < int > newpath ( path ) ; newpath . push_back ( g [ last ] [ i ] ) ; q . push ( newpath ) ; } } } } int main ( ) { vector < vector < int > > g ; int v = 4 ; g . resize ( 4 ) ; g [ 0 ] . push_back ( 3 ) ; g [ 0 ] . push_back ( 1 ) ; g [ 0 ] . push_back ( 2 ) ; g [ 1 ] . push_back ( 3 ) ; g [ 2 ] . push_back ( 0 ) ; g [ 2 ] . push_back ( 1 ) ; int src = 2 , dst = 3 ; cout << " path β from β src β " << src << " β to β dst β " << dst << " β are β STRNEWLINE " ; findpaths ( g , src , dst , v ) ; return 0 ; } |
Rearrange Odd and Even values in Alternate Fashion in Ascending Order | C ++ implementation of the above approach ; Sort the array ; vector < int > v1 ; to insert even values vector < int > v2 ; to insert odd values ; Set flag to true if first element is even ; Start rearranging array ; If first element is even ; Else , first element is Odd ; Print the rearranged array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void AlternateRearrange ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] % 2 == 0 ) v1 . push_back ( arr [ i ] ) ; else v2 . push_back ( arr [ i ] ) ; int index = 0 , i = 0 , j = 0 ; bool flag = false ; if ( arr [ 0 ] % 2 == 0 ) flag = true ; while ( index < n ) { if ( flag == true ) { arr [ index ++ ] = v1 [ i ++ ] ; flag = ! flag ; } else { arr [ index ++ ] = v2 [ j ++ ] ; flag = ! flag ; } } for ( i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; } int main ( ) { int arr [ ] = { 9 , 8 , 13 , 2 , 19 , 14 } ; int n = sizeof ( arr ) / sizeof ( int ) ; AlternateRearrange ( arr , n ) ; return 0 ; } |
Convert given array to Arithmetic Progression by adding an element | C ++ implementation of the approach ; Function to return the number to be added ; If difference of the current consecutive elements is different from the common difference ; If number has already been chosen then it 's not possible to add another number ; If the current different is twice the common difference then a number can be added midway from current and previous element ; Number has been chosen ; It 's not possible to maintain the common difference ; Return last element + common difference if no element is chosen and the array is already in AP ; Else return the chosen number ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getNumToAdd ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int d = arr [ 1 ] - arr [ 0 ] ; int numToAdd = -1 ; bool numAdded = false ; for ( int i = 2 ; i < n ; i ++ ) { int diff = arr [ i ] - arr [ i - 1 ] ; if ( diff != d ) { if ( numAdded ) return -1 ; if ( diff == 2 * d ) { numToAdd = arr [ i ] - d ; numAdded = true ; } else return -1 ; } } if ( numToAdd == -1 ) return ( arr [ n - 1 ] + d ) ; return numToAdd ; } int main ( ) { int arr [ ] = { 1 , 3 , 5 , 7 , 11 , 13 , 15 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << getNumToAdd ( arr , n ) ; } |
Minimum Numbers of cells that are connected with the smallest path between 3 given cells | C ++ implementation of the approach ; Function to return the minimum cells that are connected via the minimum length path ; Array to store column number of the given cells ; Sort cells in ascending order of row number ; Middle row number ; Set pair to store required cells ; Range of column number ; Store all cells of middle row within column number range ; Final step to store all the column number of 1 st and 3 rd cell upto MidRow ; Driver Function ; vector pair to store X , Y , Z | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Minimum_Cells ( vector < pair < int , int > > v ) { int col [ 3 ] , i , j ; for ( i = 0 ; i < 3 ; i ++ ) { int column_number = v [ i ] . second ; col [ i ] = column_number ; } sort ( col , col + 3 ) ; sort ( v . begin ( ) , v . end ( ) ) ; int MidRow = v [ 1 ] . first ; set < pair < int , int > > s ; int Maxcol = col [ 2 ] , MinCol = col [ 0 ] ; for ( i = MinCol ; i <= Maxcol ; i ++ ) { s . insert ( { MidRow , i } ) ; } for ( i = 0 ; i < 3 ; i ++ ) { if ( v [ i ] . first == MidRow ) continue ; for ( j = min ( v [ i ] . first , MidRow ) ; j <= max ( v [ i ] . first , MidRow ) ; j ++ ) { s . insert ( { j , v [ i ] . second } ) ; } } return s . size ( ) ; } int main ( ) { vector < pair < int , int > > v = { { 0 , 0 } , { 1 , 1 } , { 2 , 2 } } ; cout << Minimum_Cells ( v ) ; return 0 ; } |
Get maximum items when other items of total cost of an item are free | C ++ implementation of the above approach ; Function to count the total number of items ; Sort the prices ; Choose the last element ; Initial count of item ; Sum to keep track of the total price of free items ; If total is less than or equal to z then we will add 1 to the answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int items ( int n , int a [ ] ) { sort ( a , a + n ) ; int z = a [ n - 1 ] ; int x = 1 ; int s = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { s += a [ i ] ; if ( s <= z ) x += 1 ; else break ; } return x ; } int main ( ) { int n = 5 ; int a [ ] = { 5 , 3 , 1 , 5 , 6 } ; cout << items ( n , a ) ; } |
Sorting array elements with set bits equal to K | C ++ program for sorting array elements with set bits equal to K ; Function to sort elements with set bits equal to k ; initialise two vectors ; first vector contains indices of required element ; second vector contains required elements ; sorting the elements in second vector ; replacing the elements with k set bits with the sorted elements ; printing the new sorted array elements ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sortWithSetbits ( int arr [ ] , int n , int k ) { vector < int > v1 , v2 ; for ( int i = 0 ; i < n ; i ++ ) { if ( __builtin_popcount ( arr [ i ] ) == k ) { v1 . push_back ( i ) ; v2 . push_back ( arr [ i ] ) ; } } sort ( v2 . begin ( ) , v2 . end ( ) ) ; for ( int i = 0 ; i < v1 . size ( ) ; i ++ ) arr [ v1 [ i ] ] = v2 [ i ] ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; } int main ( ) { int arr [ ] = { 14 , 255 , 1 , 7 , 13 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; sortWithSetbits ( arr , n , k ) ; return 0 ; } |
Minimum boxes required to carry all gifts | CPP implementation of above approach ; Function to return number of boxes ; Sort the boxes in ascending order ; Try to fit smallest box with current heaviest box ( from right side ) ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int numBoxes ( int A [ ] , int n , int K ) { sort ( A , A + n ) ; int i = 0 , j = n - 1 ; int ans = 0 ; while ( i <= j ) { ans ++ ; if ( A [ i ] + A [ j ] <= K ) i ++ ; j -- ; } return ans ; } int main ( ) { int A [ ] = { 3 , 2 , 2 , 1 } , K = 3 ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << numBoxes ( A , n , K ) ; return 0 ; } |
Count triplets in a sorted doubly linked list whose product is equal to a given value x | C ++ implementation to count triplets in a sorted doubly linked list whose product is equal to a given value ' x ' ; structure of node of doubly linked list ; function to count triplets in a sorted doubly linked list whose product is equal to a given value ' x ' ; unordered_map ' um ' implemented as hash table ; insert the < node data , node pointer > tuple in ' um ' ; generate all possible pairs ; p_product = product of elements in the current pair ; if ' x / p _ product ' is present in ' um ' and either of the two nodes are not equal to the ' um [ x / p _ product ] ' node ; increment count ; required count of triplets division by 3 as each triplet is counted 3 times ; A utility function to insert a new node at the beginning of doubly linked list ; allocate node ; put in the data ; Driver program to test above functions ; start with an empty doubly linked list ; insert values in sorted order | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next , * prev ; } ; int countTriplets ( struct Node * head , int x ) { struct Node * ptr , * ptr1 , * ptr2 ; int count = 0 ; unordered_map < int , Node * > um ; for ( ptr = head ; ptr != NULL ; ptr = ptr -> next ) um [ ptr -> data ] = ptr ; for ( ptr1 = head ; ptr1 != NULL ; ptr1 = ptr1 -> next ) for ( ptr2 = ptr1 -> next ; ptr2 != NULL ; ptr2 = ptr2 -> next ) { int p_product = ( ptr1 -> data * ptr2 -> data ) ; if ( um . find ( x / p_product ) != um . end ( ) && um [ x / p_product ] != ptr1 && um [ x / p_product ] != ptr2 ) count ++ ; } return ( count / 3 ) ; } void insert ( struct Node * * head , int data ) { struct Node * temp = new Node ( ) ; temp -> data = data ; temp -> next = temp -> prev = NULL ; if ( ( * head ) == NULL ) ( * head ) = temp ; else { temp -> next = * head ; ( * head ) -> prev = temp ; ( * head ) = temp ; } } int main ( ) { struct Node * head = NULL ; insert ( & head , 9 ) ; insert ( & head , 8 ) ; insert ( & head , 6 ) ; insert ( & head , 5 ) ; insert ( & head , 4 ) ; insert ( & head , 2 ) ; insert ( & head , 1 ) ; int x = 8 ; cout << " Count β = β " << countTriplets ( head , x ) ; return 0 ; } |
Maximize the profit by selling at | C ++ implementation of above approach : ; Function to find profit ; Calculating profit for each gadget ; sort the profit array in descending order ; variable to calculate total profit ; check for best M profits ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( int N , int M , int cp [ ] , int sp [ ] ) { int profit [ N ] ; for ( int i = 0 ; i < N ; i ++ ) profit [ i ] = sp [ i ] - cp [ i ] ; sort ( profit , profit + N , greater < int > ( ) ) ; int sum = 0 ; for ( int i = 0 ; i < M ; i ++ ) { if ( profit [ i ] > 0 ) sum += profit [ i ] ; else break ; } return sum ; } int main ( ) { int N = 5 , M = 3 ; int CP [ ] = { 5 , 10 , 35 , 7 , 23 } ; int SP [ ] = { 11 , 10 , 0 , 9 , 19 } ; cout << solve ( N , M , CP , SP ) ; return 0 ; } |
Find the largest number that can be formed with the given digits | C ++ program to generate largest possible number with given digits ; Function to generate largest possible number with given digits ; sort the given array in descending order ; generate the number ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaxNum ( int arr [ ] , int n ) { sort ( arr , arr + n , greater < int > ( ) ) ; int num = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { num = num * 10 + arr [ i ] ; } return num ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findMaxNum ( arr , n ) ; return 0 ; } |
Minimum partitions of maximum size 2 and sum limited by given value | C ++ program to count minimum number of partitions of size 2 and sum smaller than or equal to given key . ; sort the array ; if sum of ith smaller and jth larger element is less than key , then pack both numbers in a set otherwise pack the jth larger number alone in the set ; After ending of loop i will contain minimum number of sets ; Driver Code | #include <algorithm> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int minimumSets ( int arr [ ] , int n , int key ) { int i , j ; sort ( arr , arr + n ) ; for ( i = 0 , j = n - 1 ; i <= j ; ++ i ) if ( arr [ i ] + arr [ j ] <= key ) j -- ; return i ; } int main ( ) { int arr [ ] = { 3 , 5 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int key = 5 ; cout << minimumSets ( arr , n , key ) ; return 0 ; } |
Bubble Sort On Doubly Linked List | CPP program to sort a doubly linked list using bubble sort ; structure of a node ; Function to insert a node at the beginning of a linked list ; Function to print nodes in a given linked list ; Bubble sort the given linked list ; Checking for empty list ; Driver code ; start with empty linked list ; Create linked list from the array arr [ ] . Created linked list will be 1 -> 11 -> 2 -> 56 -> 12 ; print list before sorting ; sort the linked list ; print list after sorting | #include <iostream> NEW_LINE using namespace std ; struct Node { int data ; Node * prev ; Node * next ; } ; void insertAtTheBegin ( struct Node * * start_ref , int data ) { struct Node * ptr1 = new Node ; ptr1 -> data = data ; ptr1 -> next = * start_ref ; if ( * start_ref != NULL ) ( * start_ref ) -> prev = ptr1 ; * start_ref = ptr1 ; } void printList ( struct Node * start ) { struct Node * temp = start ; cout << endl ; while ( temp != NULL ) { cout << temp -> data << " β " ; temp = temp -> next ; } } void bubbleSort ( struct Node * start ) { int swapped , i ; struct Node * ptr1 ; struct Node * lptr = NULL ; if ( start == NULL ) return ; do { swapped = 0 ; ptr1 = start ; while ( ptr1 -> next != lptr ) { if ( ptr1 -> data > ptr1 -> next -> data ) { swap ( ptr1 -> data , ptr1 -> next -> data ) ; swapped = 1 ; } ptr1 = ptr1 -> next ; } lptr = ptr1 ; } while ( swapped ) ; } int main ( ) { int arr [ ] = { 12 , 56 , 2 , 11 , 1 , 90 } ; int list_size , i ; struct Node * start = NULL ; for ( i = 0 ; i < 6 ; i ++ ) insertAtTheBegin ( & start , arr [ i ] ) ; printf ( " Linked list before sorting " printList ( start ) ; bubbleSort ( start ) ; printf ( " Linked list after sorting " printList ( start ) ; return 0 ; } |
Substring Sort | C ++ Program to sort substrings ; sort the input array ; repeated length should be the same string ; two different strings with the same length input array cannot be sorted ; validate that each string is a substring of the following one ; get first element ; The array is valid and sorted print the strings in order ; Test 1 ; Test 2 | #include <bits/stdc++.h> NEW_LINE using namespace std ; void substringSort ( string arr [ ] , int n , int maxLen ) { int count [ maxLen ] ; string sortedArr [ maxLen ] ; for ( int i = 0 ; i < maxLen ; i ++ ) { count [ i ] = 0 ; sortedArr [ i ] = " " ; } for ( int i = 0 ; i < n ; i ++ ) { string s = arr [ i ] ; int len = s . length ( ) ; if ( count [ len - 1 ] == 0 ) { sortedArr [ len - 1 ] = s ; count [ len - 1 ] = 1 ; } else if ( sortedArr [ len - 1 ] == s ) { count [ len - 1 ] ++ ; } else { cout << " Cannot β be β sorted " ; return ; } } int index = 0 ; while ( count [ index ] == 0 ) index ++ ; int prev = index ; string prevString = sortedArr [ prev ] ; index ++ ; for ( ; index < maxLen ; index ++ ) { if ( count [ index ] != 0 ) { string current = sortedArr [ index ] ; if ( current . find ( prevString ) != string :: npos ) { prev = index ; prevString = current ; } else { cout << " Cannot β be β sorted " ; return ; } } } for ( int i = 0 ; i < maxLen ; i ++ ) { string s = sortedArr [ i ] ; for ( int j = 0 ; j < count [ i ] ; j ++ ) { cout << s << endl ; } } } int main ( ) { int maxLen = 100 ; string arr1 [ ] = { " d " , " zddsaaz " , " ds " , " ddsaa " , " dds " , " dds " } ; substringSort ( arr1 , sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) , maxLen ) ; string arr2 [ ] = { " for " , " rof " } ; substringSort ( arr2 , sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) , maxLen ) ; return 0 ; } |
Number of paths from source to destination in a directed acyclic graph | C ++ program for Number of paths from one vertex to another vertex in a Directed Acyclic Graph ; to make graph ; function to add edge in graph ; there is path from a to b . ; function to make topological sorting ; insert all vertices which don 't have any parent. ; using kahn 's algorithm for topological sorting ; insert front element of queue to vector ; go through all it 's childs ; whenever the frequency is zero then add this vertex to queue . ; Function that returns the number of paths ; make topological sorting ; to store required answer . ; answer from destination to destination is 1. ; traverse in reverse order ; Driver code ; here vertices are numbered from 0 to n - 1. ; to count number of vertex which don 't have any parents. ; to add all edges of graph ; Function that returns the number of paths | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAXN 1000005 NEW_LINE vector < int > v [ MAXN ] ; void add_edge ( int a , int b , int fre [ ] ) { v [ a ] . push_back ( b ) ; fre [ b ] ++ ; } vector < int > topological_sorting ( int fre [ ] , int n ) { queue < int > q ; for ( int i = 0 ; i < n ; i ++ ) if ( ! fre [ i ] ) q . push ( i ) ; vector < int > l ; while ( ! q . empty ( ) ) { int u = q . front ( ) ; q . pop ( ) ; l . push_back ( u ) ; for ( int i = 0 ; i < v [ u ] . size ( ) ; i ++ ) { fre [ v [ u ] [ i ] ] -- ; if ( ! fre [ v [ u ] [ i ] ] ) q . push ( v [ u ] [ i ] ) ; } } return l ; } int numberofPaths ( int source , int destination , int n , int fre [ ] ) { vector < int > s = topological_sorting ( fre , n ) ; int dp [ n ] = { 0 } ; dp [ destination ] = 1 ; for ( int i = s . size ( ) - 1 ; i >= 0 ; i -- ) { for ( int j = 0 ; j < v [ s [ i ] ] . size ( ) ; j ++ ) { dp [ s [ i ] ] += dp [ v [ s [ i ] ] [ j ] ] ; } } return dp ; } int main ( ) { int n = 5 ; int source = 0 , destination = 4 ; int fre [ n ] = { 0 } ; add_edge ( 0 , 1 , fre ) ; add_edge ( 0 , 2 , fre ) ; add_edge ( 0 , 3 , fre ) ; add_edge ( 0 , 4 , fre ) ; add_edge ( 2 , 3 , fre ) ; add_edge ( 3 , 4 , fre ) ; cout << numberofPaths ( source , destination , n , fre ) ; } |
Print all the pairs that contains the positive and negative values of an element | CPP program to find pairs of positive and negative values present in an array . ; Function ; Sort the array ; Traverse the array ; For every arr [ i ] < 0 element , do a binary search for arr [ i ] > 0. ; If found , print the pair . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printPairs ( int arr [ ] , int n ) { bool pair_exists = false ; sort ( arr , arr + n ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < 0 ) { if ( binary_search ( arr , arr + n , - arr [ i ] ) ) { cout << arr [ i ] << " , β " << - arr [ i ] << endl ; pair_exists = true ; } } else break ; } if ( pair_exists == false ) cout << " No β such β pair β exists " ; } int main ( ) { int arr [ ] = { 4 , 8 , 9 , -4 , 1 , -1 , -8 , -9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printPairs ( arr , n ) ; return 0 ; } |
Multiset Equivalence Problem | C ++ program to check if two given multisets are equivalent ; sort the elements of both multisets ; Return true if both multisets are same . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool areSame ( vector < int > & a , vector < int > & b ) { sort ( a . begin ( ) , a . end ( ) ) ; sort ( b . begin ( ) , b . end ( ) ) ; return ( a == b ) ; } int main ( ) { vector < int > a ( { 7 , 7 , 5 } ) , b ( { 7 , 5 , 5 } ) ; if ( areSame ( a , b ) ) cout << " Yes STRNEWLINE " ; else cout << " No STRNEWLINE " ; return 0 ; } |
Minimum number of edges between two vertices of a Graph | C ++ program to find minimum edge between given two vertex of Graph ; function for finding minimum no . of edge using BFS ; visited [ n ] for keeping track of visited node in BFS ; Initialize distances as 0 ; queue to do BFS . ; update distance for i ; function for addition of edge ; Driver function ; To store adjacency list of graph | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minEdgeBFS ( vector < int > edges [ ] , int u , int v , int n ) { vector < bool > visited ( n , 0 ) ; vector < int > distance ( n , 0 ) ; queue < int > Q ; distance [ u ] = 0 ; Q . push ( u ) ; visited [ u ] = true ; while ( ! Q . empty ( ) ) { int x = Q . front ( ) ; Q . pop ( ) ; for ( int i = 0 ; i < edges [ x ] . size ( ) ; i ++ ) { if ( visited [ edges [ x ] [ i ] ] ) continue ; distance [ edges [ x ] [ i ] ] = distance [ x ] + 1 ; Q . push ( edges [ x ] [ i ] ) ; visited [ edges [ x ] [ i ] ] = 1 ; } } return distance [ v ] ; } void addEdge ( vector < int > edges [ ] , int u , int v ) { edges [ u ] . push_back ( v ) ; edges [ v ] . push_back ( u ) ; } int main ( ) { int n = 9 ; vector < int > edges [ 9 ] ; addEdge ( edges , 0 , 1 ) ; addEdge ( edges , 0 , 7 ) ; addEdge ( edges , 1 , 7 ) ; addEdge ( edges , 1 , 2 ) ; addEdge ( edges , 2 , 3 ) ; addEdge ( edges , 2 , 5 ) ; addEdge ( edges , 2 , 8 ) ; addEdge ( edges , 3 , 4 ) ; addEdge ( edges , 3 , 5 ) ; addEdge ( edges , 4 , 5 ) ; addEdge ( edges , 5 , 6 ) ; addEdge ( edges , 6 , 7 ) ; addEdge ( edges , 7 , 8 ) ; int u = 0 ; int v = 5 ; cout << minEdgeBFS ( edges , u , v , n ) ; return 0 ; } |
Minimum swaps so that binary search can be applied | CPP program to find Minimum number of swaps to get the position of the element if we provide an unsorted array to binary search . ; Function to find minimum swaps . ; Here we are getting number of smaller and greater elements of k . ; Here we are calculating the actual position of k in the array . ; Implementing binary search as per the above - discussed cases . ; If we find the k . ; If we need minimum element swap . ; Else the element is at the right position . ; If we need maximum element swap . ; Else element is at the right position ; Calculating the required swaps . ; If it is impossible . ; Driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinimumSwaps ( int * arr , int n , int k ) { int pos , num_min , num_max , need_minimum , need_maximum , swaps ; num_min = num_max = need_minimum = 0 ; need_maximum = swaps = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < k ) num_min ++ ; else if ( arr [ i ] > k ) num_max ++ ; } for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == k ) { pos = i ; break ; } } int left , right , mid ; left = 0 ; right = n - 1 ; while ( left <= right ) { mid = ( left + right ) / 2 ; if ( arr [ mid ] == k ) { break ; } else if ( arr [ mid ] > k ) { if ( pos > mid ) need_minimum ++ ; else num_min -- ; left = mid + 1 ; } else { if ( pos < mid ) need_maximum ++ ; else num_max -- ; right = mid - 1 ; } } if ( need_minimum > need_maximum ) { swaps = swaps + need_maximum ; num_min = num_min - need_maximum ; need_minimum = need_minimum - need_maximum ; need_maximum = 0 ; } else { swaps = swaps + need_minimum ; num_max = num_max - need_minimum ; need_maximum = need_maximum - need_minimum ; need_minimum = 0 ; } if ( need_maximum > num_max need_minimum > num_min ) return -1 ; else return ( swaps + need_maximum + need_minimum ) ; } int main ( ) { int arr [ ] = { 3 , 10 , 6 , 7 , 2 , 5 , 4 } , k = 4 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findMinimumSwaps ( arr , n , k ) ; } |
Stable sort for descending order | C ++ program to demonstrate descending order stable sort using greater < > ( ) . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { int arr [ ] = { 1 , 5 , 8 , 9 , 6 , 7 , 3 , 4 , 2 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; stable_sort ( arr , arr + n , greater < int > ( ) ) ; cout << " Array β after β sorting β : β STRNEWLINE " ; for ( int i = 0 ; i < n ; ++ i ) cout << arr [ i ] << " β " ; return 0 ; } |
Check if both halves of the string have at least one different character | C ++ implementation to check if both halves of the string have at least one different character ; Function which break string into two halves Sorts the two halves separately Compares the two halves return true if any index has non - zero value ; Declaration and initialization of counter array ; Driver function | #include <algorithm> NEW_LINE #include <cstring> NEW_LINE #include <iostream> NEW_LINE #include <string> NEW_LINE using namespace std ; bool function ( char str [ ] ) { int l = strlen ( str ) ; sort ( str , str + ( l / 2 ) ) ; sort ( str + ( l / 2 ) , str + l ) ; for ( int i = 0 ; i < l / 2 ; i ++ ) if ( str [ i ] != str [ l / 2 + i ] ) return true ; return false ; } int main ( ) { char str [ ] = " abcasdsabcae " ; if ( function ( str ) ) cout << " Yes , β both β halves β differ β by " << " β at β least β one β character " ; else cout << " No , β both β halves β do " << " β not β differ β at β all " ; return 0 ; } |
Number of visible boxes after putting one inside another | CPP program to count number of visible boxes . ; return the minimum number of visible boxes ; New Queue of integers . ; sorting the array ; traversing the array ; checking if current element is greater than or equal to twice of front element ; Pushing each element of array ; driver Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumBox ( int arr [ ] , int n ) { queue < int > q ; queue < int > q ; sort ( arr , arr + n ) ; q . push ( arr [ 0 ] ) ; for ( int i = 1 ; i < n ; i ++ ) { int now = q . front ( ) ; if ( arr [ i ] >= 2 * now ) q . pop ( ) ; q . push ( arr [ i ] ) ; } return q . size ( ) ; } int main ( ) { int arr [ ] = { 4 , 1 , 2 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minimumBox ( arr , n ) << endl ; return 0 ; } |
Sort a binary array using one traversal | CPP program to sort a binary array ; if number is smaller than 1 then swap it with j - th number ; Driver code | #include <iostream> NEW_LINE using namespace std ; void sortBinaryArray ( int a [ ] , int n ) { int j = -1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] < 1 ) { j ++ ; swap ( a [ i ] , a [ j ] ) ; } } } int main ( ) { int a [ ] = { 1 , 0 , 0 , 1 , 0 , 1 , 0 , 1 , 1 , 1 , 1 , 1 , 1 , 0 , 0 , 1 , 1 , 0 , 1 , 0 , 0 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; sortBinaryArray ( a , n ) ; for ( int i = 0 ; i < n ; i ++ ) cout << a [ i ] << " β " ; return 0 ; } |
Smallest element in an array that is repeated exactly ' k ' times . | C ++ program to find smallest number in array that is repeated exactly ' k ' times . ; finds the smallest number in arr [ ] that is repeated k times ; Since arr [ ] has numbers in range from 1 to MAX ; set count to 1 as number is present once ; If frequency of number is equal to ' k ' ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 1000 ; int function findDuplicate ( $ arr , $ n , $ k ) { int res = MAX + 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > 0 ) { int count = 1 ; for ( int j = i + 1 ; j < n ; j ++ ) if ( arr [ i ] == arr [ j ] ) count += 1 ; if ( count == k ) res = min ( res , arr [ i ] ) ; } } return res ; } int main ( ) { int arr [ ] = { 2 , 2 , 1 , 3 , 1 } ; int k = 2 ; int n = sizeof ( arr ) / ( sizeof ( arr [ 0 ] ) ) ; cout << findDuplicate ( arr , n , k ) ; return 0 ; } |
Smallest element in an array that is repeated exactly ' k ' times . | C ++ program to find smallest number in array that is repeated exactly ' k ' times . ; finds the smallest number in arr [ ] that is repeated k times ; Sort the array ; Find the first element with exactly k occurrences . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findDuplicate ( int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; int i = 0 ; while ( i < n ) { int j , count = 1 ; for ( j = i + 1 ; j < n && arr [ j ] == arr [ i ] ; j ++ ) count ++ ; if ( count == k ) return arr [ i ] ; i = j ; } return -1 ; } int main ( ) { int arr [ ] = { 2 , 2 , 1 , 3 , 1 } ; int k = 2 ; int n = sizeof ( arr ) / ( sizeof ( arr [ 0 ] ) ) ; cout << findDuplicate ( arr , n , k ) ; return 0 ; } |
Longest Common Prefix using Sorting | C ++ program to find longest common prefix of given array of words . ; If size is 0 , return empty string ; Sort the given array ; Find the minimum length from first and last string ; find the common prefix between the first and last string ; Driver Code | #include <iostream> NEW_LINE #include <algorithm> NEW_LINE using namespace std ; string longestCommonPrefix ( string ar [ ] , int n ) { if ( n == 0 ) return " " ; if ( n == 1 ) return ar [ 0 ] ; sort ( ar , ar + n ) ; int en = min ( ar [ 0 ] . size ( ) , ar [ n - 1 ] . size ( ) ) ; string first = ar [ 0 ] , last = ar [ n - 1 ] ; int i = 0 ; while ( i < en && first [ i ] == last [ i ] ) i ++ ; string pre = first . substr ( 0 , i ) ; return pre ; } int main ( ) { string ar [ ] = { " geeksforgeeks " , " geeks " , " geek " , " geezer " } ; int n = sizeof ( ar ) / sizeof ( ar [ 0 ] ) ; cout << " The β longest β common β prefix β is : β " << longestCommonPrefix ( ar , n ) ; return 0 ; } |
Find the minimum and maximum amount to buy all N candies | C ++ implementation to find the minimum and maximum amount ; function to find the maximum and the minimum cost required ; Sort the array ; print the minimum cost ; print the maximum cost ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void find ( vector < int > arr , int n , int k ) { sort ( arr . begin ( ) , arr . end ( ) ) ; int b = ceil ( n / k * 1.0 ) ; int min_sum = 0 , max_sum = 0 ; for ( int i = 0 ; i < b ; i ++ ) min_sum += arr [ i ] ; for ( int i = 2 ; i < arr . size ( ) ; i ++ ) max_sum += arr [ i ] ; cout << " minimum β " << min_sum << endl ; cout << " maximum β " << max_sum << endl ; } int main ( ) { vector < int > arr = { 3 , 2 , 1 , 4 } ; int n = arr . size ( ) ; int k = 2 ; find ( arr , n , k ) ; } |
Check if it is possible to sort an array with conditional swapping of adjacent allowed | C ++ program to check if we can sort an array with adjacent swaps allowed ; Returns true if it is possible to sort else false / ; We need to do something only if previousl element is greater ; If difference is more than one , then not possible ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkForSorting ( int arr [ ] , int n ) { for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( arr [ i ] > arr [ i + 1 ] ) { if ( arr [ i ] - arr [ i + 1 ] == 1 ) swap ( arr [ i ] , arr [ i + 1 ] ) ; else return false ; } } return true ; } int main ( ) { int arr [ ] = { 1 , 0 , 3 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( checkForSorting ( arr , n ) ) cout << " Yes " ; else cout << " No " ; } |
Sort an array of strings according to string lengths | C ++ program to sort an Array of Strings according to their lengths ; Function to print the sorted array of string ; Function to Sort the array of string according to lengths . This function implements Insertion Sort . ; Insert s [ j ] at its correct position ; Function to print the sorted array of string ; Driver function ; Function to perform sorting ; Calling the function to print result | #include <iostream> NEW_LINE using namespace std ; void printArraystring ( string , int ) ; void sort ( string s [ ] , int n ) { for ( int i = 1 ; i < n ; i ++ ) { string temp = s [ i ] ; int j = i - 1 ; while ( j >= 0 && temp . length ( ) < s [ j ] . length ( ) ) { s [ j + 1 ] = s [ j ] ; j -- ; } s [ j + 1 ] = temp ; } } void printArraystring ( string str [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << str [ i ] << " β " ; } int main ( ) { string arr [ ] = { " GeeksforGeeks " , " I " , " from " , " am " } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sort ( arr , n ) ; printArraystring ( arr , n ) ; return 0 ; } |
Hoare 's vs Lomuto partition scheme in QuickSort | C ++ implementation of QuickSort using Hoare 's partition scheme. ; This function takes first element as pivot , and places all the elements smaller than the pivot on the left side and all the elements greater than the pivot on the right side . It returns the index of the last element on the smaller side ; Find leftmost element greater than or equal to pivot ; Find rightmost element smaller than or equal to pivot ; If two pointers met . ; The main function that implements QuickSort arr [ ] -- > Array to be sorted , low -- > Starting index , high -- > Ending index ; pi is partitioning index , arr [ p ] is now at right place ; Separately sort elements before partition and after partition ; Function to print an array ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int partition ( int arr [ ] , int low , int high ) { int pivot = arr [ low ] ; int i = low - 1 , j = high + 1 ; while ( true ) { do { i ++ ; } while ( arr [ i ] < pivot ) ; do { j -- ; } while ( arr [ j ] > pivot ) ; if ( i >= j ) return j ; swap ( arr [ i ] , arr [ j ] ) ; } } void quickSort ( int arr [ ] , int low , int high ) { if ( low < high ) { int pi = partition ( arr , low , high ) ; quickSort ( arr , low , pi ) ; quickSort ( arr , pi + 1 , high ) ; } } void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) printf ( " % d β " , arr [ i ] ) ; printf ( " STRNEWLINE " ) ; } int main ( ) { int arr [ ] = { 10 , 7 , 8 , 9 , 1 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; quickSort ( arr , 0 , n - 1 ) ; printf ( " Sorted β array : β STRNEWLINE " ) ; printArray ( arr , n ) ; return 0 ; } |
K | C ++ program to find the Kth smallest element after removing some integer from first n natural number . ; Return the K - th smallest element . ; sort ( arr , arr + n ) ; ; Checking if k lies before 1 st element ; If k is the first element of array arr [ ] . ; If k is more than last element ; If first element of array is 1. ; Reducing k by numbers before arr [ 0 ] . ; Finding k 'th smallest element after removing array elements. ; Finding count of element between i - th and ( i - 1 ) - th element . ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int ksmallest ( int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; if ( k < arr [ 0 ] ) return k ; if ( k == arr [ 0 ] ) return arr [ 0 ] + 1 ; if ( k > arr [ n - 1 ] ) return k + n ; if ( arr [ 0 ] == 1 ) k -- ; else k -= ( arr [ 0 ] - 1 ) ; for ( int i = 1 ; i < n ; i ++ ) { int c = arr [ i ] - arr [ i - 1 ] - 1 ; if ( k <= c ) return arr [ i - 1 ] + k ; else k -= c ; } return arr [ n - 1 ] + k ; } int main ( ) { int k = 1 ; int arr [ ] = { 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ksmallest ( arr , n , k ) ; return 0 ; } |
Count nodes within K | C ++ program to count nodes inside K distance range from marked nodes ; Utility bfs method to fill distance vector and returns most distant marked node from node u ; push node u in queue and initialize its distance as 0 ; loop untill all nodes are processed ; if node is marked , update lastMarked variable ; loop over all neighbors of u and update their distance before pushing in queue ; if not given value already ; return last updated marked value ; method returns count of nodes which are in K - distance range from marked nodes ; vertices in a tree are one more than number of edges ; fill vector for graph ; fill boolean array mark from marked array ; vectors to store distances ; first bfs ( from any random node ) to get one distant marked node ; second bfs to get other distant marked node and also dl is filled with distances from first chosen marked node ; third bfs to fill dr by distances from second chosen marked node ; loop over all nodes ; increase res by 1 , if current node has distance less than K from both extreme nodes ; Driver code to test above methods | #include <bits/stdc++.h> NEW_LINE using namespace std ; int bfsWithDistance ( vector < int > g [ ] , bool mark [ ] , int u , vector < int > & dis ) { int lastMarked ; queue < int > q ; q . push ( u ) ; dis [ u ] = 0 ; while ( ! q . empty ( ) ) { u = q . front ( ) ; q . pop ( ) ; if ( mark [ u ] ) lastMarked = u ; for ( int i = 0 ; i < g [ u ] . size ( ) ; i ++ ) { int v = g [ u ] [ i ] ; if ( dis [ v ] == -1 ) { dis [ v ] = dis [ u ] + 1 ; q . push ( v ) ; } } } return lastMarked ; } int nodesKDistanceFromMarked ( int edges [ ] [ 2 ] , int V , int marked [ ] , int N , int K ) { V = V + 1 ; vector < int > g [ V ] ; int u , v ; for ( int i = 0 ; i < ( V - 1 ) ; i ++ ) { u = edges [ i ] [ 0 ] ; v = edges [ i ] [ 1 ] ; g [ u ] . push_back ( v ) ; g [ v ] . push_back ( u ) ; } bool mark [ V ] = { false } ; for ( int i = 0 ; i < N ; i ++ ) mark [ marked [ i ] ] = true ; vector < int > tmp ( V , -1 ) , dl ( V , -1 ) , dr ( V , -1 ) ; u = bfsWithDistance ( g , mark , 0 , tmp ) ; v = bfsWithDistance ( g , mark , u , dl ) ; bfsWithDistance ( g , mark , v , dr ) ; int res = 0 ; for ( int i = 0 ; i < V ; i ++ ) { if ( dl [ i ] <= K && dr [ i ] <= K ) res ++ ; } return res ; } int main ( ) { int edges [ ] [ 2 ] = { { 1 , 0 } , { 0 , 3 } , { 0 , 8 } , { 2 , 3 } , { 3 , 5 } , { 3 , 6 } , { 3 , 7 } , { 4 , 5 } , { 5 , 9 } } ; int V = sizeof ( edges ) / sizeof ( edges [ 0 ] ) ; int marked [ ] = { 1 , 2 , 4 } ; int N = sizeof ( marked ) / sizeof ( marked [ 0 ] ) ; int K = 3 ; cout << nodesKDistanceFromMarked ( edges , V , marked , N , K ) ; return 0 ; } |
Check whether a given number is even or odd | A simple C ++ program to check for even or odd ; Returns true if n is even , else odd ; n & 1 is 1 , then odd , else even ; Driver code | #include <iostream> NEW_LINE using namespace std ; bool isEven ( int n ) { return ( ! ( n & 1 ) ) ; } int main ( ) { int n = 101 ; isEven ( n ) ? cout << " Even " : cout << " Odd " ; return 0 ; } |
Count distinct occurrences as a subsequence | C / C ++ program to count number of times S appears as a subsequence in T ; T can 't appear as a subsequence in S ; mat [ i ] [ j ] stores the count of occurrences of T ( 1. . i ) in S ( 1. . j ) . ; Initializing first column with all 0 s . An empty string can 't have another string as suhsequence ; Initializing first row with all 1 s . An empty string is subsequence of all . ; Fill mat [ ] [ ] in bottom up manner ; If last characters don 't match, then value is same as the value without last character in S. ; Else value is obtained considering two cases . a ) All substrings without last character in S b ) All substrings without last characters in both . ; uncomment this to print matrix mat for ( int i = 1 ; i <= m ; i ++ , cout << endl ) for ( int j = 1 ; j <= n ; j ++ ) cout << mat [ i ] [ j ] << " β " ; ; Driver code to check above method | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findSubsequenceCount ( string S , string T ) { int m = T . length ( ) , n = S . length ( ) ; if ( m > n ) return 0 ; int mat [ m + 1 ] [ n + 1 ] ; for ( int i = 1 ; i <= m ; i ++ ) mat [ i ] [ 0 ] = 0 ; for ( int j = 0 ; j <= n ; j ++ ) mat [ 0 ] [ j ] = 1 ; for ( int i = 1 ; i <= m ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( T [ i - 1 ] != S [ j - 1 ] ) mat [ i ] [ j ] = mat [ i ] [ j - 1 ] ; else mat [ i ] [ j ] = mat [ i ] [ j - 1 ] + mat [ i - 1 ] [ j - 1 ] ; } } return mat [ m ] [ n ] ; } int main ( ) { string T = " ge " ; string S = " geeksforgeeks " ; cout << findSubsequenceCount ( S , T ) << endl ; return 0 ; } |
3 | C ++ program for 3 - way quick sort ; This function partitions a [ ] in three parts a ) a [ l . . i ] contains all elements smaller than pivot b ) a [ i + 1. . j - 1 ] contains all occurrences of pivot c ) a [ j . . r ] contains all elements greater than pivot ; From left , find the first element greater than or equal to v . This loop will definitely terminate as v is last element ; From right , find the first element smaller than or equal to v ; If i and j cross , then we are done ; Swap , so that smaller goes on left greater goes on right ; Move all same left occurrence of pivot to beginning of array and keep count using p ; Move all same right occurrence of pivot to end of array and keep count using q ; Move pivot element to its correct index ; Move all left same occurrences from beginning to adjacent to arr [ i ] ; Move all right same occurrences from end to adjacent to arr [ i ] ; 3 - way partition based quick sort ; Note that i and j are passed as reference ; Recur ; A utility function to print an array ; Driver code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void partition ( int a [ ] , int l , int r , int & i , int & j ) { i = l - 1 , j = r ; int p = l - 1 , q = r ; int v = a [ r ] ; while ( true ) { while ( a [ ++ i ] < v ) ; while ( v < a [ -- j ] ) if ( j == l ) break ; if ( i >= j ) break ; swap ( a [ i ] , a [ j ] ) ; if ( a [ i ] == v ) { p ++ ; swap ( a [ p ] , a [ i ] ) ; } if ( a [ j ] == v ) { q -- ; swap ( a [ j ] , a [ q ] ) ; } } swap ( a [ i ] , a [ r ] ) ; j = i - 1 ; for ( int k = l ; k < p ; k ++ , j -- ) swap ( a [ k ] , a [ j ] ) ; i = i + 1 ; for ( int k = r - 1 ; k > q ; k -- , i ++ ) swap ( a [ i ] , a [ k ] ) ; } void quicksort ( int a [ ] , int l , int r ) { if ( r <= l ) return ; int i , j ; partition ( a , l , r , i , j ) ; quicksort ( a , l , j ) ; quicksort ( a , i , r ) ; } void printarr ( int a [ ] , int n ) { for ( int i = 0 ; i < n ; ++ i ) printf ( " % d β " , a [ i ] ) ; printf ( " STRNEWLINE " ) ; } int main ( ) { int a [ ] = { 4 , 9 , 4 , 4 , 1 , 9 , 4 , 4 , 9 , 4 , 4 , 1 , 4 } ; int size = sizeof ( a ) / sizeof ( int ) ; printarr ( a , size ) ; quicksort ( a , 0 , size - 1 ) ; printarr ( a , size ) ; return 0 ; } |
3 | C ++ program for 3 - way quick sort ; A utility function to print an array ; It uses Dutch National Flag Algorithm ; To handle 2 elements ; update i and j ; j = mid ; or high + 1 ; 3 - way partition based quick sort ; if ( low >= high ) 1 or 0 elements ; Note that i and j are passed as reference ; Recur two halves ; Driver Code ; int a [ ] = { 4 , 39 , 54 , 14 , 31 , 89 , 44 , 34 , 59 , 64 , 64 , 11 , 41 } ; int a [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 } ; int a [ ] = { 91 , 82 , 73 , 64 , 55 , 46 , 37 , 28 , 19 , 10 } ; int a [ ] = { 4 , 9 , 4 , 4 , 9 , 1 , 1 , 1 } ; ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void swap ( int * a , int * b ) { int temp = * a ; * a = * b ; * b = temp ; } void printarr ( int a [ ] , int n ) { for ( int i = 0 ; i < n ; ++ i ) printf ( " % d β " , a [ i ] ) ; printf ( " STRNEWLINE " ) ; } void partition ( int a [ ] , int low , int high , int & i , int & j ) { if ( high - low <= 1 ) { if ( a [ high ] < a [ low ] ) swap ( & a [ high ] , & a [ low ] ) ; i = low ; j = high ; return ; } int mid = low ; int pivot = a [ high ] ; while ( mid <= high ) { if ( a [ mid ] < pivot ) swap ( & a [ low ++ ] , & a [ mid ++ ] ) ; else if ( a [ mid ] == pivot ) mid ++ ; else if ( a [ mid ] > pivot ) swap ( & a [ mid ] , & a [ high -- ] ) ; } i = low - 1 ; } void quicksort ( int a [ ] , int low , int high ) { return ; int i , j ; partition ( a , low , high , i , j ) ; quicksort ( a , low , i ) ; quicksort ( a , j , high ) ; } int main ( ) { int a [ ] = { 4 , 9 , 4 , 4 , 1 , 9 , 4 , 4 , 9 , 4 , 4 , 1 , 4 } ; int size = sizeof ( a ) / sizeof ( int ) ; printarr ( a , size ) ; quicksort ( a , 0 , size - 1 ) ; printarr ( a , size ) ; return 0 ; } |
Check if a Regular Bracket Sequence can be formed with concatenation of given strings | C ++ program for the above approach ; Function to check possible RBS from the given strings ; Stores the values { sum , min_prefix } ; Iterate over the range ; Stores the total sum ; Stores the minimum prefix ; Check for minimum prefix ; Store these values in vector ; Make two pair vectors pos and neg ; Store values according to the mentioned approach ; Sort the positive vector ; Stores the extra count of open brackets ; No valid bracket sequence can be formed ; Sort the negative vector ; Stores the count of the negative elements ; No valid bracket sequence can be formed ; Check if open is equal to negative ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int checkRBS ( vector < string > S ) { int N = S . size ( ) ; vector < pair < int , int > > v ( N ) ; for ( int i = 0 ; i < N ; ++ i ) { string s = S [ i ] ; int sum = 0 ; int pre = 0 ; for ( char c : s ) { if ( c == ' ( ' ) { ++ sum ; } else { -- sum ; } pre = min ( sum , pre ) ; } v [ i ] = { sum , pre } ; } vector < pair < int , int > > pos ; vector < pair < int , int > > neg ; for ( int i = 0 ; i < N ; ++ i ) { if ( v [ i ] . first >= 0 ) { pos . push_back ( { - v [ i ] . second , v [ i ] . first } ) ; } else { neg . push_back ( { v [ i ] . first - v [ i ] . second , - v [ i ] . first } ) ; } } sort ( pos . begin ( ) , pos . end ( ) ) ; int open = 0 ; for ( auto p : pos ) { if ( open - p . first >= 0 ) { open += p . second ; } else { cout << " No " << " STRNEWLINE " ; return 0 ; } } sort ( neg . begin ( ) , neg . end ( ) ) ; int negative = 0 ; for ( auto p : neg ) { if ( negative - p . first >= 0 ) { negative += p . second ; } else { cout << " No STRNEWLINE " ; return 0 ; } } if ( open != negative ) { cout << " No STRNEWLINE " ; return 0 ; } cout << " Yes STRNEWLINE " ; return 0 ; } int main ( ) { vector < string > arr = { " ) " , " ( ) ( " } ; checkRBS ( arr ) ; return 0 ; } |
Maximize count of unique Squares that can be formed with N arbitrary points in coordinate plane | C ++ program for the above approach ; Function to find the maximum number of unique squares that can be formed from the given N points ; Stores the resultant count of squares formed ; Base Case ; Subtract the maximum possible grid size as sqrt ( N ) ; Find the total squares till now for the maximum grid ; A i * i grid contains ( i - 1 ) * ( i - 1 ) + ( i - 2 ) * ( i - 2 ) + ... + 1 * 1 squares ; When N >= len then more squares will be counted ; Return total count of squares ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumUniqueSquares ( int N ) { int ans = 0 ; if ( N < 4 ) { return 0 ; } int len = ( sqrt ( double ( N ) ) ) ; N -= len * len ; for ( int i = 1 ; i < len ; i ++ ) { ans += i * i ; } if ( N >= len ) { N -= len ; for ( int i = 1 ; i < len ; i ++ ) { ans += i ; } } for ( int i = 1 ; i < N ; i ++ ) { ans += i ; } return ans ; } int main ( ) { int N = 9 ; cout << maximumUniqueSquares ( N ) ; return 0 ; } |
Lexicographically smallest permutation number up to K having given array as a subsequence | C ++ program for the above approach ; Function to find the lexicographically smallest permutation such that the given array is a subsequence of it ; Stores the missing elements in arr in the range [ 1 , K ] ; Stores if the ith element is present in arr or not ; Loop to mark all integers present in the array as visited ; Loop to insert all the integers not visited into missing ; Append INT_MAX at end in order to prevent going out of bounds ; Pointer to the current element ; Pointer to the missing element ; Stores the required permutation ; Loop to construct the permutation using greedy approach ; If missing element is smaller that the current element insert missing element ; Insert current element ; Print the required Permutation ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findPermutation ( int K , vector < int > arr ) { vector < int > missing ; vector < bool > visited ( K + 1 , 0 ) ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { visited [ arr [ i ] ] = 1 ; } for ( int i = 1 ; i <= K ; i ++ ) { if ( ! visited [ i ] ) { missing . push_back ( i ) ; } } arr . push_back ( INT_MAX ) ; missing . push_back ( INT_MAX ) ; int p1 = 0 ; int p2 = 0 ; vector < int > ans ; while ( ans . size ( ) < K ) { if ( arr [ p1 ] < missing [ p2 ] ) { ans . push_back ( arr [ p1 ] ) ; p1 ++ ; } else { ans . push_back ( missing [ p2 ] ) ; p2 ++ ; } } for ( int i = 0 ; i < K ; i ++ ) { cout << ans [ i ] << " β " ; } } int main ( ) { int K = 7 ; vector < int > arr = { 6 , 4 , 2 , 1 } ; findPermutation ( K , arr ) ; return 0 ; } |
Last element remaining after repeated removal of Array elements at perfect square indices | C ++ program for the above approach ; Function to find last remaining index after repeated removal of perfect square indices ; Initialize the ans variable as N ; Iterate a while loop and discard the possible values ; Total discarded values ; Check if this forms a perfect square ; Decrease answer by 1 ; Subtract the value from the current value of N ; Return the value remained ; Function to find last remaining element after repeated removal of array element at perfect square indices ; Find the remaining index ; Print the element at that index as the result ; Driver Code ; Given input | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findRemainingIndex ( int N ) { int ans = N ; while ( N > 1 ) { int discard = int ( sqrt ( N ) ) ; if ( discard * discard == N ) { ans -- ; } N -= discard ; } return ans ; } void findRemainingElement ( int arr [ ] , int N ) { int remainingIndex = findRemainingIndex ( N ) ; cout << arr [ remainingIndex - 1 ] ; } signed main ( ) { int arr [ ] = { 2 , 3 , 4 , 4 , 2 , 4 , -3 , 1 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findRemainingElement ( arr , N ) ; return 0 ; } |
Minimum time to reach from Node 1 to N if travel is allowed only when node is Green | Import library for Queue ; Function to find min edge ; Initialize queue and push [ 1 , 0 ] ; Create visited array to keep the track if node is visited or not ; Run infinite loop ; If node is N , terminate loop ; Travel adjacent nodes of crnt ; Check whether we visited previously or not ; Push into queue and make as true ; Function to Find time required to reach 1 to N ; Check color of node is red or green ; Add C sec from next green color time ; Add C ; Return the answer ; Driver Code ; Given Input ; Function Call ; Print total time | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minEdge ( vector < vector < int > > X , int N , int M , int T , int C ) { queue < pair < int , int > > Q ; Q . push ( { 1 , 0 } ) ; vector < int > V ( N + 1 , false ) ; int crnt , c ; while ( 1 ) { crnt = Q . front ( ) . first ; c = Q . front ( ) . second ; Q . pop ( ) ; if ( crnt == N ) break ; for ( int _ : X [ crnt ] ) { if ( ! V [ _ ] ) { Q . push ( { _ , c + 1 } ) ; V [ _ ] = true ; } } } return c ; } int findTime ( int T , int C , int c ) { int ans = 0 ; for ( int _ = 0 ; _ < c ; _ ++ ) { if ( ( ans / T ) % 2 ) ans = ( ans / T + 1 ) * T + C ; else ans += C ; } return ans ; } int main ( ) { int N = 5 ; int M = 5 ; int T = 3 ; int C = 5 ; vector < vector < int > > X { { } , { 2 , 3 , 4 } , { 4 , 5 } , { 1 } , { 1 , 2 } , { 2 } } ; int c = minEdge ( X , N , M , T , C ) ; int ans = findTime ( T , C , c ) ; cout << ( ans ) << endl ; return 0 ; } |
Lexicographically largest possible by merging two strings by adding one character at a time | C ++ program for the approach ; Recursive bfunction for finding the lexicographically largest string ; If either of the string length is 0 , return the other string ; If s1 is lexicographically larger than s2 ; Take first character of s1 and call the function ; Take first character of s2 and recursively call function for remaining string ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; string largestMerge ( string s1 , string s2 ) { if ( s1 . size ( ) == 0 || s2 . size ( ) == 0 ) return s1 + s2 ; if ( s1 > s2 ) { return s1 [ 0 ] + largestMerge ( s1 . substr ( 1 ) , s2 ) ; } return s2 [ 0 ] + largestMerge ( s1 , s2 . substr ( 1 ) ) ; } int main ( ) { string s1 = " geeks " ; string s2 = " forgeeks " ; cout << largestMerge ( s1 , s2 ) << endl ; return 0 ; } |
Number of open doors | TCS Coding Question | C ++ program for the above approach ; Function that counts the number of doors opens after the Nth turn ; Find the number of open doors ; Return the resultant count of open doors ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countOpenDoors ( int N ) { int doorsOpen = sqrt ( N ) ; return doorsOpen ; } int main ( ) { int N = 100 ; cout << countOpenDoors ( N ) ; return 0 ; } |
Minimum number of candies required to distribute among children based on given conditions | C ++ program for the above approach ; Function to count the minimum number of candies that is to be distributed ; Stores total count of candies ; Stores the amount of candies allocated to a student ; If the value of N is 1 ; Initialize with 1 all array element ; Traverse the array arr [ ] ; If arr [ i + 1 ] is greater than arr [ i ] and ans [ i + 1 ] is at most ans [ i ] ; Assign ans [ i ] + 1 to ans [ i + 1 ] ; Iterate until i is atleast 0 ; If arr [ i ] is greater than arr [ i + 1 ] and ans [ i ] is at most ans [ i + 1 ] ; Assign ans [ i + 1 ] + 1 to ans [ i ] ; If arr [ i ] is equals arr [ i + 1 ] and ans [ i ] is less than ans [ i + 1 ] ; Assign ans [ i + 1 ] + 1 to ans [ i ] ; Increment the sum by ans [ i ] ; Return the resultant sum ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countCandies ( int arr [ ] , int n ) { int sum = 0 ; int ans [ n ] ; if ( n == 1 ) { return 1 ; } for ( int i = 0 ; i < n ; i ++ ) ans [ i ] = 1 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( arr [ i + 1 ] > arr [ i ] && ans [ i + 1 ] <= ans [ i ] ) { ans [ i + 1 ] = ans [ i ] + 1 ; } } for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] > arr [ i + 1 ] && ans [ i ] <= ans [ i + 1 ] ) { ans [ i ] = ans [ i + 1 ] + 1 ; } else if ( arr [ i ] == arr [ i + 1 ] && ans [ i ] < ans [ i + 1 ] ) { ans [ i ] = ans [ i + 1 ] + 1 ; } sum += ans [ i ] ; } sum += ans [ n - 1 ] ; return sum ; } int main ( ) { int arr [ ] = { 1 , 0 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countCandies ( arr , N ) ; return 0 ; } |
Maximize profit possible by selling M products such that profit of a product is the number of products left of that supplier | C ++ program for the above approach ; Function to find the maximum profit by selling M number of products ; Initialize a Max - Heap to keep track of the maximum value ; Stores the maximum profit ; Traverse the array and push all the elements in max_heap ; Iterate a loop until M > 0 ; Decrement the value of M by 1 ; Pop the maximum element from the heap ; Update the maxProfit ; Push ( X - 1 ) to max heap ; Print the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findMaximumProfit ( int arr [ ] , int M , int N ) { priority_queue < int > max_heap ; int maxProfit = 0 ; for ( int i = 0 ; i < N ; i ++ ) max_heap . push ( arr [ i ] ) ; while ( M > 0 ) { M -- ; int X = max_heap . top ( ) ; max_heap . pop ( ) ; maxProfit += X ; max_heap . push ( X - 1 ) ; } cout << maxProfit ; } int main ( ) { int arr [ ] = { 4 , 6 } ; int M = 4 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findMaximumProfit ( arr , M , N ) ; } |
Generate an array with K positive numbers such that arr [ i ] is either | C ++ program for the above approach ; Function to generate the resultant sequence of first N natural numbers ; Initialize an array of size N ; Stores the sum of positive and negative elements ; Mark the first N - K elements as negative ; Update the value of arr [ i ] ; Update the value of sumNeg ; Mark the remaining K elements as positive ; Update the value of arr [ i ] ; Update the value of sumPos ; If the sum of the sequence is negative , then print - 1 ; Print the required sequence ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findSequence ( int n , int k ) { int arr [ n ] ; int sumPos = 0 , sumNeg = 0 ; for ( int i = 0 ; i < n - k ; i ++ ) { arr [ i ] = - ( i + 1 ) ; sumNeg += arr [ i ] ; } for ( int i = n - k ; i < n ; i ++ ) { arr [ i ] = i + 1 ; sumPos += arr [ i ] ; } if ( abs ( sumNeg ) >= sumPos ) { cout << -1 ; return ; } for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; } int main ( ) { int N = 10 , K = 6 ; findSequence ( N , K ) ; return 0 ; } |
Print the indices for every row of a grid from which escaping from the grid is possible | C ++ program for the above approach ; Function to find the row index for every row of a matrix from which one can exit the grid after entering from left ; Iterate over the range [ 0 , M - 1 ] ; Stores the direction from which a person enters a cell ; Row index from which one enters the grid ; Column index from which one enters the grid ; Iterate until j is atleast N - 1 ; If Mat [ i ] [ j ] is equal to 1 ; If entry is from left cell ; Decrement i by 1 ; Assign ' D ' to dir ; If entry is from upper cell ; Decrement j by 1 ; Assign ' R ' to dir ; If entry is from right cell ; Increment i by 1 ; Assign ' U ' to dir ; If entry is from bottom cell ; Increment j by 1 ; Assign ' L ' to dir ; Otherwise , ; If entry is from left cell ; Increment i by 1 ; Assign ' U ' to dir ; If entry is from upper cell ; Increment j by 1 ; Assign ' L ' to dir ; If entry is from right cell ; Decrement i by 1 ; Assign ' D ' to dir ; If entry is from lower cell ; Decrement j by 1 ; Assign ' R ' to dir ; If i or j is less than 0 or i is equal to M or j is equal to N ; If j is equal to N ; Otherwise ; Driver Code ; Input ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findPath ( vector < vector < int > > & arr , int M , int N ) { for ( int row = 0 ; row < M ; row ++ ) { char dir = ' L ' ; int i = row ; int j = 0 ; while ( j < N ) { if ( arr [ i ] [ j ] == 1 ) { if ( dir == ' L ' ) { i -- ; dir = ' D ' ; } else if ( dir == ' U ' ) { j -- ; dir = ' R ' ; } else if ( dir == ' R ' ) { i ++ ; dir = ' U ' ; } else if ( dir == ' D ' ) { j ++ ; dir = ' L ' ; } } else { if ( dir == ' L ' ) { i ++ ; dir = ' U ' ; } else if ( dir == ' U ' ) { j ++ ; dir = ' L ' ; } else if ( dir == ' R ' ) { i -- ; dir = ' D ' ; } else if ( dir == ' D ' ) { j -- ; dir = ' R ' ; } } if ( i < 0 i == M j < 0 j == N ) break ; } if ( j == N ) cout << i << " β " ; else cout << -1 << " β " ; } } int main ( ) { vector < vector < int > > arr = { { 1 , 1 , 0 , 1 } , { 1 , 1 , 0 , 0 } , { 1 , 0 , 0 , 0 } , { 1 , 1 , 0 , 1 } , { 0 , 1 , 0 , 1 } } ; int M = arr . size ( ) ; int N = arr [ 0 ] . size ( ) ; findPath ( arr , M , N ) ; } |
Maximize sum of array by repeatedly removing an element from pairs whose concatenation is a multiple of 3 | C ++ approach for the above approach ; Function to calculate sum of digits of an integer ; Function to calculate maximum sum of array after removing pairs whose concatenation is divisible by 3 ; Stores the sum of digits of array element ; Find the sum of digits ; If i is divisible by 3 ; Otherwise , if i modulo 3 is 1 ; Otherwise , if i modulo 3 is 2 ; Return the resultant sum of array elements ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getSum ( int n ) { int ans = 0 ; string arr = to_string ( n ) ; for ( int i = 0 ; i < arr . length ( ) ; i ++ ) { ans += int ( arr [ i ] ) ; } return ans ; } void getMax ( int arr [ ] , int n ) { int maxRem0 = 0 ; int rem1 = 0 ; int rem2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int digitSum = getSum ( arr [ i ] ) ; if ( digitSum % 3 == 0 ) maxRem0 = max ( maxRem0 , arr [ i ] ) ; else if ( digitSum % 3 == 1 ) rem1 += arr [ i ] ; else rem2 += arr [ i ] ; } cout << ( maxRem0 + max ( rem1 , rem2 ) ) ; } int main ( ) { int arr [ ] = { 23 , 12 , 43 , 3 , 56 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; getMax ( arr , n ) ; } |
Minimum edge reversals to make a root | C ++ program to find min edge reversal to make every node reachable from root ; method to dfs in tree and populates disRev values ; visit current node ; looping over all neighbors ; distance of v will be one more than distance of u ; initialize back edge count same as parent node 's count ; if there is a reverse edge from u to i , then only update ; return total reversal in subtree rooted at u ; method prints root and minimum number of edge reversal ; number of nodes are one more than number of edges ; data structure to store directed tree ; disRev stores two values - distance and back edge count from root node ; add 0 weight in direction of u to v ; add 1 weight in reverse direction ; initialize all variables ; dfs populates disRev data structure and store total reverse edge counts ; for ( int i = 0 ; i < V ; i ++ ) { cout << i << " β : β " << disRev [ i ] . first << " β " << disRev [ i ] . second << endl ; } ; loop over all nodes to choose minimum edge reversal ; ( reversal in path to i ) + ( reversal in all other tree parts ) ; choose minimum among all values ; print the designated root and total edge reversal made ; Driver code to test above methods | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dfs ( vector < pair < int , int > > g [ ] , pair < int , int > disRev [ ] , bool visit [ ] , int u ) { visit [ u ] = true ; int totalRev = 0 ; for ( int i = 0 ; i < g [ u ] . size ( ) ; i ++ ) { int v = g [ u ] [ i ] . first ; if ( ! visit [ v ] ) { disRev [ v ] . first = disRev [ u ] . first + 1 ; disRev [ v ] . second = disRev [ u ] . second ; if ( g [ u ] [ i ] . second ) { disRev [ v ] . second = disRev [ u ] . second + 1 ; totalRev ++ ; } totalRev += dfs ( g , disRev , visit , v ) ; } } return totalRev ; } void printMinEdgeReverseForRootNode ( int edges [ ] [ 2 ] , int e ) { int V = e + 1 ; vector < pair < int , int > > g [ V ] ; pair < int , int > disRev [ V ] ; bool visit [ V ] ; int u , v ; for ( int i = 0 ; i < e ; i ++ ) { u = edges [ i ] [ 0 ] ; v = edges [ i ] [ 1 ] ; g [ u ] . push_back ( make_pair ( v , 0 ) ) ; g [ v ] . push_back ( make_pair ( u , 1 ) ) ; } for ( int i = 0 ; i < V ; i ++ ) { visit [ i ] = false ; disRev [ i ] . first = disRev [ i ] . second = 0 ; } int root = 0 ; int totalRev = dfs ( g , disRev , visit , root ) ; int res = INT_MAX ; for ( int i = 0 ; i < V ; i ++ ) { int edgesToRev = ( totalRev - disRev [ i ] . second ) + ( disRev [ i ] . first - disRev [ i ] . second ) ; if ( edgesToRev < res ) { res = edgesToRev ; root = i ; } } cout << root << " β " << res << endl ; } int main ( ) { int edges [ ] [ 2 ] = { { 0 , 1 } , { 2 , 1 } , { 3 , 2 } , { 3 , 4 } , { 5 , 4 } , { 5 , 6 } , { 7 , 6 } } ; int e = sizeof ( edges ) / sizeof ( edges [ 0 ] ) ; printMinEdgeReverseForRootNode ( edges , e ) ; return 0 ; } |
Check if 2 * K + 1 non | C ++ program for the above approach ; Function to check if the string S can be obtained by ( K + 1 ) non - empty substrings whose concatenation and concatenation of the reverse of these K strings ; Stores the size of the string ; If n is less than 2 * k + 1 ; Stores the first K characters ; Stores the last K characters ; Reverse the string ; If both the strings are equal ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void checkString ( string s , int k ) { int n = s . size ( ) ; if ( 2 * k + 1 > n ) { cout << " No " ; return ; } string a = s . substr ( 0 , k ) ; string b = s . substr ( n - k , k ) ; reverse ( b . begin ( ) , b . end ( ) ) ; if ( a == b ) cout << " Yes " ; else cout << " No " ; } int main ( ) { string S = " qwqwq " ; int K = 1 ; checkString ( S , K ) ; return 0 ; } |
Minimum number of socks required to picked to have at least K pairs of the same color | C ++ program for the above approach ; Function to count the minimum number of socks to be picked ; Stores the total count of pairs of socks ; Find the total count of pairs ; If K is greater than pairs ; Otherwise ; Driver Code | #include <iostream> NEW_LINE using namespace std ; int findMin ( int arr [ ] , int N , int k ) { int pairs = 0 ; for ( int i = 0 ; i < N ; i ++ ) { pairs += arr [ i ] / 2 ; } if ( k > pairs ) return -1 ; else return 2 * k + N - 1 ; } int main ( ) { int arr [ 3 ] = { 4 , 5 , 6 } ; int K = 3 ; cout << findMin ( arr , 3 , K ) ; return 0 ; } |
Minimum number of bits required to be flipped such that Bitwise OR of A and B is equal to C | C ++ program for the above approach ; Function to count the number of bit flips required on A and B such that Bitwise OR of A and B is C ; Stores the count of flipped bit ; Iterate over the range [ 0 , 32 ] ; Check if i - th bit of A is set ; Check if i - th bit of B is set or not ; Check if i - th bit of C is set or not ; If i - th bit of C is unset ; Check if i - th bit of A is set or not ; Check if i - th bit of B is set or not ; Check if i - th bit of C is set or not ; Check if i - th bit of both A and B is set ; Return the count of bits flipped ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumFlips ( int A , int B , int C ) { int res = 0 ; for ( int i = 0 ; i < 32 ; i ++ ) { int x = 0 , y = 0 , z = 0 ; if ( A & ( 1 << i ) ) { x = 1 ; } if ( B & ( 1 << i ) ) { y = 1 ; } if ( C & ( 1 << i ) ) { z = 1 ; } if ( z == 0 ) { if ( x ) { res ++ ; } if ( y ) { res ++ ; } } if ( z == 1 ) { if ( x == 0 && y == 0 ) { res ++ ; } } } return res ; } int main ( ) { int A = 2 , B = 6 , C = 5 ; cout << minimumFlips ( A , B , C ) ; return 0 ; } |
Queries to calculate Bitwise AND of an array with updates | C ++ program for the above approach ; Store the number of set bits at each position ; Function to precompute the prefix count array ; Iterate over the range [ 0 , 31 ] ; Set the bit at position i if arr [ 0 ] is set at position i ; Traverse the array and take prefix sum ; Update prefixCount [ i ] [ j ] ; Function to find the Bitwise AND of all array elements ; Stores the required result ; Iterate over the range [ 0 , 31 ] ; Stores the number of set bits at position i ; If temp is N , then set ith position in the result ; Print the result ; Function to update the prefix count array in each query ; Iterate through all the bits of the current number ; Store the bit at position i in the current value and the new value ; If bit2 is set and bit1 is unset , then increase the set bits at position i by 1 ; If bit1 is set and bit2 is unset , then decrease the set bits at position i by 1 ; Function to find the bitwise AND of the array after each query ; Fill the prefix count array ; Traverse the queries ; Store the index and the new value ; Store the current element at the index ; Update the array element ; Apply the changes to the prefix count array ; Print the bitwise AND of the modified array ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int prefixCount [ 32 ] [ 10000 ] ; void findPrefixCount ( vector < int > arr , int size ) { for ( int i = 0 ; i < 32 ; i ++ ) { prefixCount [ i ] [ 0 ] = ( ( arr [ 0 ] >> i ) & 1 ) ; for ( int j = 1 ; j < size ; j ++ ) { prefixCount [ i ] [ j ] = ( ( arr [ j ] >> i ) & 1 ) ; prefixCount [ i ] [ j ] += prefixCount [ i ] [ j - 1 ] ; } } } void arrayBitwiseAND ( int size ) { int result = 0 ; for ( int i = 0 ; i < 32 ; i ++ ) { int temp = prefixCount [ i ] [ size - 1 ] ; if ( temp == size ) result = ( result | ( 1 << i ) ) ; } cout << result << " β " ; } void applyQuery ( int currentVal , int newVal , int size ) { for ( int i = 0 ; i < 32 ; i ++ ) { int bit1 = ( ( currentVal >> i ) & 1 ) ; int bit2 = ( ( newVal >> i ) & 1 ) ; if ( bit2 > 0 && bit1 == 0 ) prefixCount [ i ] [ size - 1 ] ++ ; else if ( bit1 > 0 && bit2 == 0 ) prefixCount [ i ] [ size - 1 ] -- ; } } void findbitwiseAND ( vector < vector < int > > queries , vector < int > arr , int N , int M ) { findPrefixCount ( arr , N ) ; for ( int i = 0 ; i < M ; i ++ ) { int id = queries [ i ] [ 0 ] ; int newVal = queries [ i ] [ 1 ] ; int currentVal = arr [ id ] ; arr [ id ] = newVal ; applyQuery ( currentVal , newVal , N ) ; arrayBitwiseAND ( N ) ; } } int main ( ) { vector < int > arr { 1 , 2 , 3 , 4 , 5 } ; vector < vector < int > > queries { { 0 , 2 } , { 3 , 3 } , { 4 , 2 } } ; int N = arr . size ( ) ; int M = queries . size ( ) ; findbitwiseAND ( queries , arr , N , M ) ; return 0 ; } |
Find the winner of a game of donating i candies in every i | C ++ Program for the above approach ; Function to find the winning player in a game of donating i candies to opponent in i - th move ; Steps in which number of candies of player A finishes ; Steps in which number of candies of player B finishes ; If A 's candies finishes first ; Otherwise ; Driver Code ; Candies possessed by player A ; Candies possessed by player B | #include <bits/stdc++.h> NEW_LINE using namespace std ; int stepscount ( int a , int b ) { int chanceA = 2 * a - 1 ; int chanceB = 2 * b ; if ( chanceA < chanceB ) { cout << " B " ; } else if ( chanceB < chanceA ) { cout << " A " ; } return 0 ; } int main ( ) { int A = 2 ; int B = 3 ; stepscount ( A , B ) ; return 0 ; } |
Check if a point is inside , outside or on a Hyperbola | C ++ program for the above approach ; Function to check if the point ( x , y ) lies inside , on or outside the given hyperbola ; Stores the value of the equation ; Generate output based on value of p ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void checkpoint ( int h , int k , int x , int y , int a , int b ) { int p = ( pow ( ( x - h ) , 2 ) / pow ( a , 2 ) ) - ( pow ( ( y - k ) , 2 ) / pow ( b , 2 ) ) ; if ( p > 1 ) { cout << " Outside " ; } else if ( p == 1 ) { cout << " On β the β Hyperbola " ; } else { cout << " Inside " ; } } int main ( ) { int h = 0 , k = 0 , x = 2 ; int y = 1 , a = 4 , b = 5 ; checkpoint ( h , k , x , y , a , b ) ; return 0 ; } |
Count subarrays having even Bitwise XOR | C ++ program for the above approach ; Function to count the number of subarrays having even Bitwise XOR ; Store the required result ; Generate subarrays with arr [ i ] as the first element ; Store XOR of current subarray ; Generate subarrays with arr [ j ] as the last element ; Calculate Bitwise XOR of the current subarray ; If XOR is even , increase ans by 1 ; Print the result ; Driver Code ; Given array ; Stores the size of the array ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void evenXorSubarray ( int arr [ ] , int n ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int XOR = 0 ; for ( int j = i ; j < n ; j ++ ) { XOR = XOR ^ arr [ j ] ; if ( ( XOR & 1 ) == 0 ) ans ++ ; } } cout << ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; evenXorSubarray ( arr , N ) ; return 0 ; } |
Kth element in permutation of first N natural numbers having all even numbers placed before odd numbers in increasing order | C ++ program for the above approach ; Function to find the Kth element in the required permutation ; Store the required result ; If K is in the first N / 2 elements , print K * 2 ; Otherwise , K is greater than N / 2 ; If N is even ; If N is odd ; Print the required result ; Driver Code ; functions call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findKthElement ( int N , int K ) { int ans = 0 ; if ( K <= N / 2 ) { ans = K * 2 ; } else { if ( N % 2 == 0 ) { ans = ( K * 2 ) - N - 1 ; } else { ans = ( K * 2 ) - N ; } } cout << ans ; } int main ( ) { int N = 10 , K = 3 ; findKthElement ( N , K ) ; return 0 ; } |
Minimize replacements with values up to K to make sum of two given arrays equal | C ++ program for the above approach ; Function to find minimum number of replacements required to make the sum of two arrays equal ; Stores the sum of a [ ] ; Stores the sum of b [ ] ; Calculate sum of the array a [ ] ; Calculate sum of the array b [ ] ; Stores the difference between a [ ] and b [ ] ; Left and Right pointer to traverse the array a [ ] ; Left and Right pointer to traverse the array b [ ] ; Stores the count of moves ; Sort the arrays in ascending order ; Iterate while diff != 0 and l1 <= r1 or l2 <= r2 ; If diff is greater than 0 ; If all pointers are valid ; Otherwise , if only pointers of array a [ ] is valid ; Otherwise ; If diff is less than 0 ; If all pointers are valid ; Otherwise , if only pointers of array a [ ] is valid ; Otherwise ; Increment count of res by one ; If diff is 0 , then return res ; Otherwise , return - 1 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int makeSumEqual ( vector < int > a , vector < int > b , int K , int M , int N ) { int sum1 = 0 ; int sum2 = 0 ; for ( int el : a ) sum1 += el ; for ( int el : b ) sum2 += el ; int diff = sum1 - sum2 ; int l1 = 0 , r1 = M - 1 ; int l2 = 0 , r2 = N - 1 ; int res = 0 ; sort ( a . begin ( ) , a . end ( ) ) ; sort ( b . begin ( ) , b . end ( ) ) ; while ( l1 <= r1 l2 <= r2 ) { if ( diff == 0 ) { break ; } if ( diff > 0 ) { if ( l2 <= r2 && l1 <= r1 ) { if ( K - b [ l2 ] < a [ r1 ] - 1 ) { int sub = min ( a [ r1 ] - 1 , diff ) ; diff -= sub ; a [ r1 ] -= sub ; r1 -- ; } else { int sub = min ( K - b [ l2 ] , diff ) ; diff -= sub ; b [ l2 ] += sub ; l2 ++ ; } } else if ( l1 <= r1 ) { int sub = min ( a [ r1 ] - 1 , diff ) ; diff -= sub ; a [ r1 ] -= sub ; r1 -- ; } else { int sub = min ( K - b [ l2 ] , diff ) ; diff -= sub ; b [ l2 ] += sub ; l2 ++ ; } } else { if ( l1 <= r1 && l2 <= r2 ) { if ( K - a [ l1 ] < b [ r2 ] - 1 ) { int sub = min ( b [ r2 ] - 1 , -1 * diff ) ; diff += sub ; b [ r2 ] -= sub ; r2 -- ; } else { int sub = min ( K - a [ l1 ] , -1 * diff ) ; diff += sub ; a [ l1 ] -= sub ; l1 ++ ; } } else if ( l2 <= r2 ) { int sub = min ( b [ r2 ] - 1 , -1 * diff ) ; diff += sub ; b [ r2 ] -= sub ; r2 -- ; } else { int sub = min ( K - a [ l1 ] , diff ) ; diff += sub ; a [ l1 ] += sub ; l1 ++ ; } } res ++ ; } if ( diff == 0 ) return res ; else return -1 ; } int main ( ) { vector < int > A = { 1 , 4 , 3 } ; vector < int > B = { 6 , 6 , 6 } ; int M = A . size ( ) ; int N = B . size ( ) ; int K = 6 ; cout << makeSumEqual ( A , B , K , M , N ) ; return 0 ; } |
Modify a Binary String by flipping characters such that any pair of indices consisting of 1 s are neither co | Function to modify a string such that there doesn 't exist any pair of indices consisting of 1s, whose GCD is 1 and are divisible by each other ; Flips characters at indices 4 N , 4 N - 2 , 4 N - 4 . ... upto N terms ; Print the string ; Driver code ; Initialize the string S ; function call | #include <iostream> NEW_LINE using namespace std ; void findString ( char S [ ] , int N ) { int strLen = 4 * N ; for ( int i = 1 ; i <= N ; i ++ ) { S [ strLen - 1 ] = '1' ; strLen -= 2 ; } for ( int i = 0 ; i < 4 * N ; i ++ ) { cout << S [ i ] ; } } int main ( ) { int N = 2 ; char S [ 4 * N ] ; for ( int i = 0 ; i < 4 * N ; i ++ ) S [ i ] = '0' ; findString ( S , N ) ; return 0 ; } |
Check if a string can be split into two substrings with equal number of vowels | C ++ program for the above approach ; Function to check if any character is a vowel or not ; Lowercase vowels ; Uppercase vowels ; Otherwise ; Function to check if string S can be split into two substrings with equal number of vowels ; Stores the count of vowels in the string S ; Traverse over the string ; If S [ i ] is vowel ; Stores the count of vowels upto the current index ; Traverse over the string ; If S [ i ] is vowel ; If vowelsTillNow and totalVowels are equal ; Otherwise ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isVowel ( char ch ) { if ( ch == ' a ' ch == ' e ' ch == ' i ' ch == ' o ' ch == ' u ' ) return true ; if ( ch == ' A ' ch == ' E ' ch == ' I ' ch == ' O ' ch == ' U ' ) return true ; return false ; } string containsEqualStrings ( string S ) { int totalVowels = 0 ; for ( int i = 0 ; i < S . size ( ) ; i ++ ) { if ( isVowel ( S [ i ] ) ) totalVowels ++ ; } int vowelsTillNow = 0 ; for ( int i = 0 ; i < S . size ( ) ; i ++ ) { if ( isVowel ( S [ i ] ) ) { vowelsTillNow ++ ; totalVowels -- ; if ( vowelsTillNow == totalVowels ) { return " Yes " ; } } } return " No " ; } int main ( ) { string S = " geeks " ; cout << ( containsEqualStrings ( S ) ) ; } |
Maximize matrix sum by repeatedly multiplying pairs of adjacent elements with | C ++ program to implement the above approach ; Function to calculate maximum sum possible of a matrix by multiplying pairs of adjacent elements with - 1 any number of times ( possibly zero ) ; Store the maximum sum of matrix possible ; Stores the count of negative values in the matrix ; Store minimum absolute value present in the matrix ; Traverse the matrix row - wise ; Update sum ; If current element is negative , increment the negative count ; If current value is less than the overall minimum in A [ ] , update the overall minimum ; If there are odd number of negative values , then the answer will be sum of the absolute values of all elements - 2 * minVal ; Print maximum sum ; Driver Code ; Given matrix ; Dimensions of matrix | #include <bits/stdc++.h> NEW_LINE using namespace std ; void getMaxSum ( vector < vector < int > > A , int M , int N ) { int sum = 0 ; int negative = 0 ; int minVal = INT_MAX ; for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { sum += abs ( A [ i ] [ j ] ) ; if ( A [ i ] [ j ] < 0 ) { negative ++ ; } minVal = min ( minVal , abs ( A [ i ] [ j ] ) ) ; } } if ( negative % 2 ) { sum -= 2 * minVal ; } cout << sum ; } int main ( ) { vector < vector < int > > A = { { 4 , -8 , 6 } , { 3 , 7 , 2 } } ; int M = A . size ( ) ; int N = A [ 0 ] . size ( ) ; getMaxSum ( A , M , N ) ; return 0 ; } |
Calculate total wall area of houses painted | C ++ program for the above approach ; Function to find the total area of walls painted in N row - houses ; Stores total area of N row - houses that needs to be painted ; Traverse the array of wall heights ; Update total area painted ; Update total ; Traverse all the houses and print the shared walls ; Update total ; Print total area needs to paint ; Driver Code ; Given N , W & L ; Given heights of houses ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void areaToPaint ( int N , int W , int L , int Heights [ ] ) { int total = 0 ; for ( int i = 0 ; i < N ; i ++ ) { total += 2 * Heights [ i ] * W ; } total += L * ( Heights [ 0 ] + Heights [ N - 1 ] ) ; for ( int i = 1 ; i < N ; i ++ ) { total += L * abs ( Heights [ i ] - Heights [ i - 1 ] ) ; } cout << total ; } int main ( ) { int N = 7 , W = 1 , L = 1 ; int Heights [ N ] = { 4 , 3 , 1 , 2 , 3 , 4 , 2 } ; areaToPaint ( N , W , L , Heights ) ; } |
Generate a matrix with each row and column of given sum | C ++ program for the above approach ; Function to generate a matrix with sum of each row equal to sum of r [ ] and sum of each column equal to sum of c [ ] ; Initialize a matrix ; Traverse each cell ( i , j ) of the matrix ; Assign the minimum of the row or column value ; Subtract the minimum from both row and column sum ; Print the matrix obtained ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < vector < int > > restoreGem ( vector < int > & r , vector < int > & c ) { vector < vector < int > > dp ( r . size ( ) , vector < int > ( c . size ( ) , 0 ) ) ; for ( int i = 0 ; i < r . size ( ) ; i ++ ) { for ( int j = 0 ; j < c . size ( ) ; j ++ ) { int m = min ( r [ i ] , c [ j ] ) ; dp [ i ] [ j ] = m ; r [ i ] -= m ; c [ j ] -= m ; } } return dp ; } void printMatrix ( vector < vector < int > > ans , int N , int M ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { cout << ans [ i ] [ j ] << " β " ; } cout << endl ; } } int main ( ) { vector < int > rowSum = { 5 , 7 , 10 } ; vector < int > colSum = { 8 , 6 , 8 } ; vector < vector < int > > ans = restoreGem ( rowSum , colSum ) ; printMatrix ( ans , rowSum . size ( ) , colSum . size ( ) ) ; } |
Maximize sum of count of distinct prime factors of K array elements | C ++ program for the above approach ; Function to find the maximum sum of count of distinct prime factors of K array elements ; Stores the count of distinct primes ; Stores 1 and 0 at prime and non - prime indices respectively ; Initialize the count of factors to 0 ; Sieve of Eratosthenes ; Count of factors of a prime number is 1 ; Increment CountDistinct of all multiples of i ; Mark its multiples non - prime ; Stores the maximum sum of distinct prime factors of K array elements ; Stores the count of all distinct prime factors ; Traverse the array to find count of all array elements ; Maximum sum of K prime factors of array elements ; Check for the largest prime factor ; Increment sum ; Decrement its count and K ; Print the maximum sum ; Driver code ; Given array ; Size of the array ; Given value of K | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1000000 NEW_LINE int maxSumOfDistinctPrimeFactors ( int arr [ ] , int N , int K ) { int CountDistinct [ MAX + 1 ] ; bool prime [ MAX + 1 ] ; for ( int i = 0 ; i <= MAX ; i ++ ) { CountDistinct [ i ] = 0 ; prime [ i ] = true ; } for ( long long int i = 2 ; i <= MAX ; i ++ ) { if ( prime [ i ] == true ) { CountDistinct [ i ] = 1 ; for ( long long int j = i * 2 ; j <= MAX ; j += i ) { CountDistinct [ j ] ++ ; prime [ j ] = false ; } } } int sum = 0 ; int PrimeFactor [ 20 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { PrimeFactor [ CountDistinct [ arr [ i ] ] ] ++ ; } for ( int i = 19 ; i >= 1 ; i -- ) { while ( PrimeFactor [ i ] > 0 ) { sum += i ; PrimeFactor [ i ] -- ; K -- ; if ( K == 0 ) break ; } if ( K == 0 ) break ; } cout << sum ; } int main ( ) { int arr [ ] = { 6 , 9 , 12 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 2 ; maxSumOfDistinctPrimeFactors ( arr , N , K ) ; return 0 ; } |
Minimum replacements such that no palindromic substring of length exceeding 1 is present in the given string | C ++ Program to implement the above approach ; Function to count the changes required such that no palindromic substring of length exceeding 1 is present in the string ; Base Case ; Stores the count ; Iterate over the string ; Palindromic Substring of Length 2 ; Replace the next character ; Increment changes ; Palindromic Substring of Length 3 ; Replace the next character ; Increment changes ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxChange ( string str ) { if ( str . size ( ) <= 1 ) { return 0 ; } int minChanges = 0 ; for ( int i = 0 ; i < str . size ( ) - 1 ; i ++ ) { if ( str [ i ] == str [ i + 1 ] ) { str [ i + 1 ] = ' N ' ; minChanges += 1 ; } else if ( i > 0 && str [ i - 1 ] == str [ i + 1 ] ) { str [ i + 1 ] = ' N ' ; minChanges += 1 ; } } return minChanges ; } int main ( ) { string str = " bbbbbbb " ; cout << maxChange ( str ) ; return 0 ; } |
Smallest positive integer K such that all array elements can be made equal by incrementing or decrementing by at most K | C ++ program for the above approach ; Function to find smallest integer K such that incrementing or decrementing each element by K at most once makes all elements equal ; Store distinct array elements ; Traverse the array , A [ ] ; Count elements into the set ; Iterator to store first element of B ; If M is greater than 3 ; If M is equal to 3 ; Stores the first smallest element ; Stores the second smallest element ; Stores the largest element ; IF difference between B_2 and B_1 is equal to B_3 and B_2 ; If M is equal to 2 ; Stores the smallest element ; Stores the largest element ; If difference is an even ; If M is equal to 1 ; Driver Code ; Given array ; Given size ; Print the required smallest integer | #include <iostream> NEW_LINE #include <set> NEW_LINE using namespace std ; void findMinKToMakeAllEqual ( int N , int A [ ] ) { set < int > B ; for ( int i = 0 ; i < N ; i ++ ) B . insert ( A [ i ] ) ; int M = B . size ( ) ; set < int > :: iterator itr = B . begin ( ) ; if ( M > 3 ) printf ( " - 1" ) ; else if ( M == 3 ) { int B_1 = * itr ; int B_2 = * ( ++ itr ) ; int B_3 = * ( ++ itr ) ; if ( B_2 - B_1 == B_3 - B_2 ) printf ( " % d " , B_2 - B_1 ) ; else printf ( " - 1" ) ; } else if ( M == 2 ) { int B_1 = * itr ; int B_2 = * ( ++ itr ) ; if ( ( B_2 - B_1 ) % 2 == 0 ) printf ( " % d " , ( B_2 - B_1 ) / 2 ) ; else printf ( " % d " , B_2 - B_1 ) ; } else printf ( " % d " , 0 ) ; } int main ( ) { int A [ ] = { 1 , 3 , 5 , 1 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; findMinKToMakeAllEqual ( N , A ) ; } |
Maximum number of times a given string needs to be concatenated to form a substring of another string | C ++ program for the above approach ; Function to find lps [ ] for given pattern pat [ 0. . M - 1 ] ; Length of the previous longest prefix suffix ; lps [ 0 ] is always 0 ; Iterate string to calculate lps [ i ] ; If the current character of the pattern matches ; Otherwise ; Otherwise ; Function to implement KMP algorithm ; Stores the longest prefix and suffix values for pattern ; Preprocess the pattern and find the lps [ ] array ; Index for txt [ ] ; Index for pat [ ] ; If pattern is found return 1 ; Mismatch after j matches ; Don 't match lps[0, lps[j - 1]] characters they will match anyway ; Return 0 if the pattern is not found ; Function to find the maximum value K for which string S2 concatenated K times is a substring of string S1 ; Store the required maximum number ; Create a temporary string to store string word ; Store the maximum number of times string S2 can occur in string S1 ; Traverse in range [ 0 , numWords - 1 ] ; If curWord is found in sequence ; Concatenate word to curWord ; Increment resCount by 1 ; Otherwise break the loop ; Print the answer ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void computeLPSArray ( string pat , int M , int * lps ) { int len = 0 ; lps [ 0 ] = 0 ; int i = 1 ; while ( i < M ) { if ( pat [ i ] == pat [ len ] ) { len ++ ; lps [ i ] = len ; i ++ ; } else { if ( len != 0 ) { len = lps [ len - 1 ] ; } else { lps [ i ] = 0 ; i ++ ; } } } } int KMPSearch ( string pat , string txt ) { int M = pat . size ( ) ; int N = txt . size ( ) ; int lps [ M ] ; computeLPSArray ( pat , M , lps ) ; int i = 0 ; int j = 0 ; while ( i < N ) { if ( pat [ j ] == txt [ i ] ) { j ++ ; i ++ ; } if ( j == M ) { return 1 ; j = lps [ j - 1 ] ; } else if ( i < N && pat [ j ] != txt [ i ] ) { if ( j != 0 ) j = lps [ j - 1 ] ; else i = i + 1 ; } } return 0 ; } void maxRepeating ( string seq , string word ) { int resCount = 0 ; string curWord = word ; int numWords = seq . length ( ) / word . length ( ) ; for ( int i = 0 ; i < numWords ; i ++ ) { if ( KMPSearch ( curWord , seq ) ) { curWord += word ; resCount ++ ; } else break ; } cout << resCount ; } int main ( ) { string S1 = " ababc " , S2 = " ab " ; maxRepeating ( S1 , S2 ) ; return 0 ; } |
Count all possible strings that can be generated by placing spaces | C ++ Program to implement the above approach ; Function to count the number of strings that can be generated by placing spaces between pair of adjacent characters ; Length of the string ; Count of positions for spaces ; Count of possible strings ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long int countNumberOfStrings ( string s ) { int length = s . length ( ) ; int n = length - 1 ; long long int count = pow ( 2 , n ) ; return count ; } int main ( ) { string S = " ABCD " ; cout << countNumberOfStrings ( S ) ; return 0 ; } |
Minimum time required to reach a given score | C ++ program for the above approach ; Function to calculate minimum time required to achieve given score target ; Store the frequency of elements ; Traverse the array p [ ] ; Update the frequency ; Stores the minimim time required ; Store the current score at any time instant t ; Iterate until sum is at least equal to target ; Increment time with every iteration ; Traverse the map ; Increment the points ; Print the time required ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findMinimumTime ( int * p , int n , int target ) { unordered_map < int , int > um ; for ( int i = 0 ; i < n ; i ++ ) { um [ p [ i ] ] ++ ; } int time = 0 ; int sum = 0 ; while ( sum < target ) { sum = 0 ; time ++ ; for ( auto & it : um ) { sum += it . second * ( time / it . first ) ; } } cout << time ; } int main ( ) { int arr [ ] = { 1 , 3 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int target = 10 ; findMinimumTime ( arr , N , target ) ; return 0 ; } |
Construct MEX array from the given array | C ++ program for the above approach ; Function to construct array B [ ] that stores MEX of array A [ ] excluding A [ i ] ; Stores elements present in arr [ ] ; Mark all values 1 , if present ; Initialize variable to store MEX ; Find MEX of arr [ ] ; Stores MEX for all indices ; Traverse the given array ; Update MEX ; MEX default ; Print the array B ; Driver Code ; Given array ; Given size ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAXN 100001 NEW_LINE void constructMEX ( int arr [ ] , int N ) { int hash [ MAXN ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { hash [ arr [ i ] ] = 1 ; } int MexOfArr ; for ( int i = 1 ; i < MAXN ; i ++ ) { if ( hash [ i ] == 0 ) { MexOfArr = i ; break ; } } int B [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] < MexOfArr ) B [ i ] = arr [ i ] ; else B [ i ] = MexOfArr ; } for ( int i = 0 ; i < N ; i ++ ) cout << B [ i ] << ' β ' ; } int main ( ) { int arr [ ] = { 2 , 1 , 5 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; constructMEX ( arr , N ) ; return 0 ; } |
Minimize remaining array element by repeatedly replacing pairs by half of one more than their sum | C ++ program to implement the above approach ; Function to print the smallest element left in the array and the pairs by given operation ; Stores array elements and return the minimum element of arr [ ] in O ( 1 ) ; Stores all the pairs that can be selected by the given operations ; Traverse the array arr [ ] ; Traverse pq while count of elements left in pq greater than 1 ; Stores top element of pq ; Pop top element of pq ; Stores top element of pq ; Pop top element of pq ; Insert ( X + Y + 1 ) / 2 in pq ; Insert the pair ( X , Y ) in pairsArr [ ] ; Print the element left in pq by performing the given operations ; Stores count of elements in pairsArr [ ] ; Print all the pairs that can be selected in given operations ; If i is the first index of pairsArr [ ] ; Print current pairs of pairsArr [ ] ; If i is not the last index of pairsArr [ ] ; If i is the last index of pairsArr [ ] ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void smallestNumberLeftInPQ ( int arr [ ] , int N ) { priority_queue < int > pq ; vector < pair < int , int > > pairsArr ; for ( int i = 0 ; i < N ; i ++ ) { pq . push ( arr [ i ] ) ; } while ( pq . size ( ) > 1 ) { int X = pq . top ( ) ; pq . pop ( ) ; int Y = pq . top ( ) ; pq . pop ( ) ; pq . push ( ( X + Y + 1 ) / 2 ) ; pairsArr . push_back ( { X , Y } ) ; } cout << " { " << pq . top ( ) << " } , β " ; int sz = pairsArr . size ( ) ; for ( int i = 0 ; i < sz ; i ++ ) { if ( i == 0 ) { cout << " { β " ; } cout << " ( " << pairsArr [ i ] . first << " , β " << pairsArr [ i ] . second << " ) " ; if ( i != sz - 1 ) { cout << " , β " ; } if ( i == sz - 1 ) { cout << " β } " ; } } } int main ( ) { int arr [ ] = { 3 , 2 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; smallestNumberLeftInPQ ( arr , N ) ; } |
Move weighting scale alternate under given constraints | C ++ program to print weights for alternating the weighting scale ; DFS method to traverse among states of weighting scales ; If we reach to more than required steps , return true ; Try all possible weights and choose one which returns 1 afterwards ; Try this weight only if it is greater than current residueand not same as previous chosen weight ; assign this weight to array and recur for next state ; if any weight is not possible , return false ; method prints weights for alternating scale and if not possible prints ' not β possible ' ; call dfs with current residue as 0 and current steps as 0 ; Driver code to test above methods | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool dfs ( int residue , int curStep , int wt [ ] , int arr [ ] , int N , int steps ) { if ( curStep > steps ) return true ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] > residue && arr [ i ] != wt [ curStep - 1 ] ) { wt [ curStep ] = arr [ i ] ; if ( dfs ( arr [ i ] - residue , curStep + 1 , wt , arr , N , steps ) ) return true ; } } return false ; } void printWeightsOnScale ( int arr [ ] , int N , int steps ) { int wt [ steps ] ; if ( dfs ( 0 , 0 , wt , arr , N , steps ) ) { for ( int i = 0 ; i < steps ; i ++ ) cout << wt [ i ] << " β " ; cout << endl ; } else cout << " Not β possible STRNEWLINE " ; } int main ( ) { int arr [ ] = { 2 , 3 , 5 , 6 } ; int N = sizeof ( arr ) / sizeof ( int ) ; int steps = 10 ; printWeightsOnScale ( arr , N , steps ) ; return 0 ; } |
Minimum removals required such that sum of remaining array modulo M is X | C ++ program for the above approach ; Function to find the minimum elements having sum x ; Initialize dp table ; Pre - compute subproblems ; If mod is smaller than element ; Minimum elements with sum j upto index i ; Return answer ; Function to find minimum number of removals to make sum % M in remaining array is equal to X ; Sum of all elements ; Sum to be removed ; Print answer ; Driver Code ; Given array ; Given size ; Given mod and x ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findSum ( vector < int > S , int n , int x ) { vector < vector < int > > table ( n + 1 , vector < int > ( x + 1 , 0 ) ) ; for ( int i = 1 ; i <= x ; i ++ ) { table [ 0 ] [ i ] = INT_MAX - 1 ; } for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= x ; j ++ ) { if ( S [ i - 1 ] > j ) { table [ i ] [ j ] = table [ i - 1 ] [ j ] ; } else { table [ i ] [ j ] = min ( table [ i - 1 ] [ j ] , table [ i ] [ j - S [ i - 1 ] ] + 1 ) ; } } } return ( table [ n ] [ x ] > n ) ? -1 : table [ n ] [ x ] ; } void minRemovals ( vector < int > arr , int n , int m , int x ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; } int requied_Sum = 0 ; if ( sum % m < x ) requied_Sum = m + sum % m - x ; else requied_Sum = sum % m - x ; cout << findSum ( arr , n , requied_Sum ) ; } int main ( ) { vector < int > arr = { 3 , 2 , 1 , 2 } ; int n = arr . size ( ) ; int m = 4 , x = 2 ; minRemovals ( arr , n , m , x % m ) ; return 0 ; } |
Count minimum character replacements required such that given string satisfies the given conditions | C ++ program for the above approach ; Function that finds the minimum count of steps required to make the string special ; Stores the frequency of the left & right half of string ; Find frequency of left half ; Find frequency of left half ; Make all characters equal to character c ; Case 1 : For s [ i ] < s [ j ] ; Subtract all the characters on left side that are <= d ; Adding all characters on the right side that same as d ; Find minimum value of count ; Similarly for Case 2 : s [ i ] > s [ j ] ; Return the minimum changes ; Driver Code ; Given string S ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minChange ( string s , int n ) { int L [ 26 ] = { 0 } ; int R [ 26 ] = { 0 } ; for ( int i = 0 ; i < n / 2 ; i ++ ) { char ch = s [ i ] ; L [ ch - ' a ' ] ++ ; } for ( int i = n / 2 ; i < n ; i ++ ) { char ch = s [ i ] ; R [ ch - ' a ' ] ++ ; } int count = n ; for ( char ch = ' a ' ; ch <= ' z ' ; ch ++ ) { count = min ( count , n - L [ ch - ' a ' ] - R [ ch - ' a ' ] ) ; } int change = n / 2 ; for ( int d = 0 ; d + 1 < 26 ; d ++ ) { change -= L [ d ] ; change += R [ d ] ; count = min ( count , change ) ; } change = n / 2 ; for ( int d = 0 ; d + 1 < 26 ; d ++ ) { change -= R [ d ] ; change += L [ d ] ; count = min ( change , count ) ; } return count ; } int main ( ) { string S = " aababc " ; int N = S . length ( ) ; cout << minChange ( S , N ) << " STRNEWLINE " ; } |
Rearrange string to obtain Longest Palindromic Substring | C ++ program to implement the above approach ; Function to rearrange the string to get the longest palindromic substring ; Stores the length of str ; Store the count of occurrence of each character ; Traverse the string , str ; Count occurrence of each character ; Store the left half of the longest palindromic substring ; Store the right half of the longest palindromic substring ; Traverse the array , hash [ ] ; Append half of the characters to res1 ; Append half of the characters to res2 ; reverse string res2 to make res1 + res2 palindrome ; Store the remaining characters ; Check If any odd character appended to the middle of the resultant string or not ; Append all the character which occurs odd number of times ; If count of occurrence of characters is odd ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string longestPalinSub ( string str ) { int N = str . length ( ) ; int hash [ 256 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { hash [ str [ i ] ] ++ ; } string res1 = " " ; string res2 = " " ; for ( int i = 0 ; i < 256 ; i ++ ) { for ( int j = 0 ; j < hash [ i ] / 2 ; j ++ ) { res1 . push_back ( i ) ; } for ( int j = ( hash [ i ] + 1 ) / 2 ; j < hash [ i ] ; j ++ ) { res2 . push_back ( i ) ; } } reverse ( res2 . begin ( ) , res2 . end ( ) ) ; string res3 ; bool f = false ; for ( int i = 0 ; i < 256 ; i ++ ) { if ( hash [ i ] % 2 ) { if ( ! f ) { res1 . push_back ( i ) ; f = true ; } else { res3 . push_back ( i ) ; } } } return ( res1 + res2 + res3 ) ; } int main ( ) { string str = " geeksforgeeks " ; cout << longestPalinSub ( str ) ; } |
Maximize subsequences having array elements not exceeding length of the subsequence | C ++ program for the above approach ; Function to calculate the number of subsequences that can be formed ; Stores the number of subsequences ; Iterate over the map ; Count the number of subsequences that can be formed from x . first ; Number of occurrences of x . first which are left ; Return the number of subsequences ; Function to create the maximum count of subsequences that can be formed ; Stores the frequency of arr [ ] ; Update the frequency ; Print the number of subsequences ; Driver Code ; Given array arr [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int No_Of_subsequences ( map < int , int > mp ) { int count = 0 ; int left = 0 ; for ( auto x : mp ) { x . second += left ; count += ( x . second / x . first ) ; left = x . second % x . first ; } return count ; } void maximumsubsequences ( int arr [ ] , int n ) { map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) mp [ arr [ i ] ] ++ ; cout << No_Of_subsequences ( mp ) ; } int main ( ) { int arr [ ] = { 1 , 1 , 1 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maximumsubsequences ( arr , N ) ; return 0 ; } |
Check if concatenation of any permutation of given list of arrays generates the given array | C ++ program for the above approach ; Function to check if it is possible to obtain array by concatenating the arrays in list pieces [ ] ; Stores the index of element in the given array arr [ ] ; Traverse over the list pieces ; If item size is 1 and exists in map ; If item contains > 1 element then check order of element ; If end of the array ; Check the order of elements ; If order is same as the array elements ; Increment idx ; If order breaks ; Otherwise ; Return false if the first element doesn 't exist in m ; Return true ; Driver Code ; Given target list ; Given array of list ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( vector < int > & arr , vector < vector < int > > & pieces ) { unordered_map < int , int > m ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) m [ arr [ i ] ] = i + 1 ; for ( int i = 0 ; i < pieces . size ( ) ; i ++ ) { if ( pieces [ i ] . size ( ) == 1 && m [ pieces [ i ] [ 0 ] ] != 0 ) { continue ; } else if ( pieces [ i ] . size ( ) > 1 && m [ pieces [ i ] [ 0 ] ] != 0 ) { int idx = m [ pieces [ i ] [ 0 ] ] - 1 ; idx ++ ; if ( idx >= arr . size ( ) ) return false ; for ( int j = 1 ; j < pieces [ i ] . size ( ) ; j ++ ) { if ( arr [ idx ] == pieces [ i ] [ j ] ) { idx ++ ; if ( idx >= arr . size ( ) && j < pieces [ i ] . size ( ) - 1 ) return false ; } else { return false ; } } } else { return false ; } } return true ; } int main ( ) { vector < int > arr = { 1 , 2 , 4 , 3 } ; vector < vector < int > > pieces { { 1 } , { 4 , 3 } , { 2 } } ; if ( check ( arr , pieces ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; } |
Modify given array to make sum of odd and even indexed elements same | C ++ program for the above approach ; Function to modify array to make sum of odd and even indexed elements equal ; Stores the count of 0 s , 1 s ; Stores sum of odd and even indexed elements respectively ; Count 0 s ; Count 1 s ; Calculate odd_sum and even_sum ; If both are equal ; Print the original array ; Otherwise ; Print all the 0 s ; For checking even or odd ; Update total count of 1 s ; Print all 1 s ; Driver Code ; Given array arr [ ] ; Function Call | #include <iostream> NEW_LINE using namespace std ; void makeArraySumEqual ( int a [ ] , int N ) { int count_0 = 0 , count_1 = 0 ; int odd_sum = 0 , even_sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( a [ i ] == 0 ) count_0 ++ ; else count_1 ++ ; if ( ( i + 1 ) % 2 == 0 ) even_sum += a [ i ] ; else if ( ( i + 1 ) % 2 > 0 ) odd_sum += a [ i ] ; } if ( odd_sum == even_sum ) { for ( int i = 0 ; i < N ; i ++ ) cout << " β " << a [ i ] ; } else { if ( count_0 >= N / 2 ) { for ( int i = 0 ; i < count_0 ; i ++ ) cout << "0 β " ; } else { int is_Odd = count_1 % 2 ; count_1 -= is_Odd ; for ( int i = 0 ; i < count_1 ; i ++ ) cout << "1 β " ; } } } int main ( ) { int arr [ ] = { 1 , 1 , 1 , 0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; makeArraySumEqual ( arr , N ) ; return 0 ; } |
Minimum replacement of pairs by their LCM required to reduce given array to its LCM | C ++ program for the above approach ; Boolean array to set or unset prime non - prime indices ; Stores the prefix sum of the count of prime numbers ; Function to check if a number is prime or not from 0 to N ; If p is a prime ; Set its multiples as non - prime ; Function to store the count of prime numbers ; Function to count the operations to reduce the array to one element by replacing each pair with its LCM ; Generating Prime Number ; Corner Case ; Driver Code ; Given array arr [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int maxm = 10001 ; bool prime [ maxm ] ; int prime_number [ maxm ] ; void SieveOfEratosthenes ( ) { memset ( prime , true , sizeof ( prime ) ) ; for ( int p = 2 ; p * p < maxm ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i < maxm ; i += p ) prime [ i ] = false ; } } prime [ 0 ] = false ; prime [ 1 ] = false ; } void num_prime ( ) { prime_number [ 0 ] = 0 ; for ( int i = 1 ; i <= maxm ; i ++ ) prime_number [ i ] = prime_number [ i - 1 ] + prime [ i ] ; } void min_steps ( int arr [ ] , int n ) { SieveOfEratosthenes ( ) ; num_prime ( ) ; if ( n == 1 ) cout << "0 STRNEWLINE " ; else if ( n == 2 ) cout << "1 STRNEWLINE " ; else cout << prime_number [ n ] - 1 + ( n - 2 ) ; } int main ( ) { int arr [ ] = { 5 , 4 , 3 , 2 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; min_steps ( arr , N ) ; return 0 ; } |
Find the winner of a game of removing any number of stones from the least indexed non | C ++ program for the above approach ; Function to find the winner of game between A and B ; win = 1 means B is winner win = 0 means A is winner ; If size is even , winner is B ; If size is odd , winner is A ; Stone will be removed by B ; B will take n - 1 stones from current pile having n stones and force A to pick 1 stone ; Stone will be removed by A ; A will take n - 1 stones from current pile having n stones and force B to pick 1 stone ; Print the winner accordingly ; Driver Code ; Given piles of stone ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findWinner ( int a [ ] , int n ) { int win = 0 ; if ( n % 2 == 0 ) win = 1 ; else win = 0 ; for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( i % 2 == 1 ) { if ( win == 0 && a [ i ] > 1 ) win = 1 ; } else { if ( win == 1 && a [ i ] > 1 ) win = 0 ; } } if ( win == 0 ) cout << " A " ; else cout << " B " ; } int main ( ) { int arr [ ] = { 1 , 1 , 1 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findWinner ( arr , N ) ; return 0 ; } |
Check if a destination is reachable from source with two movements allowed | Set 2 | C ++ program to implement the above approach ; Check if ( x2 , y2 ) can be reached from ( x1 , y1 ) ; Reduce x2 by y2 until it is less than or equal to x1 ; Reduce y2 by x2 until it is less than or equal to y1 ; If x2 is reduced to x1 ; Check if y2 can be reduced to y1 or not ; If y2 is reduced to y1 ; Check if x2 can be reduced to x1 or not ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isReachable ( long long x1 , long long y1 , long long x2 , long long y2 ) { while ( x2 > x1 && y2 > y1 ) { if ( x2 > y2 ) x2 %= y2 ; else y2 %= x2 ; } if ( x2 == x1 ) return ( y2 - y1 ) >= 0 && ( y2 - y1 ) % x1 == 0 ; else if ( y2 == y1 ) return ( x2 - x1 ) >= 0 && ( x2 - x1 ) % y1 == 0 ; else return 0 ; } int main ( ) { long long source_x = 2 , source_y = 10 ; long long dest_x = 26 , dest_y = 12 ; if ( isReachable ( source_x , source_y , dest_x , dest_y ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Find the player who wins the game by removing the last of given N cards | C ++ Program to implement the above approach ; Function to check which player can win the game ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void checkWinner ( int N , int K ) { if ( N % ( K + 1 ) ) { cout << " A " ; } else { cout << " B " ; } } int main ( ) { int N = 50 ; int K = 10 ; checkWinner ( N , K ) ; } |
Length of longest subarray having only K distinct Prime Numbers | C ++ program for the above approach ; Function to precalculate all the prime up to 10 ^ 6 ; Initialize prime to true ; Iterate [ 2 , sqrt ( N ) ] ; If p is prime ; Mark all multiple of p as true ; Function that finds the length of longest subarray K distinct primes ; Precompute all prime up to 2 * 10 ^ 6 ; Keep track occurrence of prime ; Initialize result to - 1 ; If number is prime then increment its count and decrease k ; Decrement K ; Remove required elements till k become non - negative ; Decrease count so that it may appear in another subarray appearing after this present subarray ; Increment K ; Take the max value as length of subarray ; Return the final length ; Driver Code ; Given array arr [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isprime [ 2000010 ] ; void SieveOfEratosthenes ( int n ) { memset ( isprime , true , sizeof ( isprime ) ) ; isprime [ 1 ] = false ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( isprime [ p ] == true ) { for ( int i = p * p ; i <= n ; i += p ) isprime [ i ] = false ; } } } int KDistinctPrime ( int arr [ ] , int n , int k ) { SieveOfEratosthenes ( 2000000 ) ; map < int , int > cnt ; int result = -1 ; for ( int i = 0 , j = -1 ; i < n ; ++ i ) { int x = arr [ i ] ; if ( isprime [ x ] ) { if ( ++ cnt [ x ] == 1 ) { -- k ; } } while ( k < 0 ) { x = arr [ ++ j ] ; if ( isprime [ x ] ) { if ( -- cnt [ x ] == 0 ) { ++ k ; } } } if ( k == 0 ) result = max ( result , i - j ) ; } return result ; } int main ( void ) { int arr [ ] = { 1 , 2 , 3 , 3 , 4 , 5 , 6 , 7 , 8 , 9 } ; int K = 3 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << KDistinctPrime ( arr , N , K ) ; return 0 ; } |
Smallest composite number not divisible by first N prime numbers | C ++ Program to implement the above approach ; Initializing the max value ; Function to generate N prime numbers using Sieve of Eratosthenes ; Stores the primes ; Setting all numbers to be prime initially ; If a prime number is encountered ; Set all its multiples as composites ; Store all the prime numbers ; Function to find the square of the ( N + 1 ) - th prime number ; Driver Code ; Stores all prime numbers | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX_SIZE 1000005 NEW_LINE void SieveOfEratosthenes ( vector < int > & StorePrimes ) { bool IsPrime [ MAX_SIZE ] ; memset ( IsPrime , true , sizeof ( IsPrime ) ) ; for ( int p = 2 ; p * p < MAX_SIZE ; p ++ ) { if ( IsPrime [ p ] == true ) { for ( int i = p * p ; i < MAX_SIZE ; i += p ) IsPrime [ i ] = false ; } } for ( int p = 2 ; p < MAX_SIZE ; p ++ ) if ( IsPrime [ p ] ) StorePrimes . push_back ( p ) ; } int Smallest_non_Prime ( vector < int > StorePrimes , int N ) { int x = StorePrimes [ N ] ; return x * x ; } int main ( ) { int N = 3 ; vector < int > StorePrimes ; SieveOfEratosthenes ( StorePrimes ) ; cout << Smallest_non_Prime ( StorePrimes , N ) ; return 0 ; } |
Nth Subset of the Sequence consisting of powers of K in increasing order of their Sum | C ++ program for the above approach ; Function to print the required N - th subset ; Nearest power of 2 <= N ; Now insert k ^ p in the answer ; update n ; Print the ans in sorted order ; Driver Code | #include <bits/stdc++.h> NEW_LINE #include <stdio.h> NEW_LINE using namespace std ; #define lli long long int NEW_LINE void printSubset ( lli n , int k ) { vector < lli > answer ; while ( n > 0 ) { lli p = log2 ( n ) ; answer . push_back ( pow ( k , p ) ) ; n %= ( int ) pow ( 2 , p ) ; } reverse ( answer . begin ( ) , answer . end ( ) ) ; for ( auto x : answer ) { cout << x << " β " ; } } int main ( ) { lli n = 5 ; int k = 4 ; printSubset ( n , k ) ; } |
Minimum time taken by each job to be completed given by a Directed Acyclic Graph | C ++ program for the above approach ; Adjacency List to store the graph ; Array to store the in - degree of node ; Array to store the time in which the job i can be done ; Function to add directed edge between two vertices ; Insert edge from u to v ; Increasing the indegree of vertex v ; Function to find the minimum time needed by each node to get the task ; Queue to store the nodes while processing ; Update the time of the jobs who don 't require any job to be completed before this job ; Iterate until queue is empty ; Get front element of queue ; Pop the front element ; Decrease in - degree of the current node ; Push its adjacent elements ; Print the time to complete the job ; Driver Code ; Given Nodes N and edges M ; Given Directed Edges of graph ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define maxN 100000 NEW_LINE vector < int > graph [ maxN ] ; int indegree [ maxN ] ; int job [ maxN ] ; void addEdge ( int u , int v ) { graph [ u ] . push_back ( v ) ; indegree [ v ] ++ ; } void printOrder ( int n , int m ) { queue < int > q ; for ( int i = 1 ; i <= n ; i ++ ) { if ( indegree [ i ] == 0 ) { q . push ( i ) ; job [ i ] = 1 ; } } while ( ! q . empty ( ) ) { int cur = q . front ( ) ; q . pop ( ) ; for ( int adj : graph [ cur ] ) { indegree [ adj ] -- ; if ( indegree [ adj ] == 0 ) { job [ adj ] = job [ cur ] + 1 ; q . push ( adj ) ; } } } for ( int i = 1 ; i <= n ; i ++ ) cout << job [ i ] << " β " ; cout << " STRNEWLINE " ; } int main ( ) { int n , m ; n = 10 ; m = 13 ; addEdge ( 1 , 3 ) ; addEdge ( 1 , 4 ) ; addEdge ( 1 , 5 ) ; addEdge ( 2 , 3 ) ; addEdge ( 2 , 8 ) ; addEdge ( 2 , 9 ) ; addEdge ( 3 , 6 ) ; addEdge ( 4 , 6 ) ; addEdge ( 4 , 8 ) ; addEdge ( 5 , 8 ) ; addEdge ( 6 , 7 ) ; addEdge ( 7 , 8 ) ; addEdge ( 8 , 10 ) ; printOrder ( n , m ) ; return 0 ; } |
Permutation of Array such that products of all adjacent elements are even | C ++ program to Permutation of Array such that product of all adjacent elements is even ; Function to print the required permutation ; push odd elements in ' odd ' and even elements in ' even ' ; Check if it possible to arrange the elements ; else print the permutation ; Print remaining odds are even . and even elements ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printPermutation ( int arr [ ] , int n ) { vector < int > odd , even ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % 2 == 0 ) even . push_back ( arr [ i ] ) ; else odd . push_back ( arr [ i ] ) ; } int size_odd = odd . size ( ) ; int size_even = even . size ( ) ; if ( size_odd > size_even + 1 ) cout << -1 << endl ; else { int i = 0 ; int j = 0 ; while ( i < size_odd && j < size_even ) { cout << odd [ i ] << " β " ; ++ i ; cout << even [ j ] << " β " ; ++ j ; } while ( i < size_odd ) { cout << odd [ i ] << " β " ; ++ i ; } while ( j < size_even ) { cout << even [ j ] << " β " ; } } } int main ( ) { int arr [ ] = { 6 , 7 , 9 , 8 , 10 , 11 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printPermutation ( arr , N ) ; return 0 ; } |
Maximize GCD of all possible pairs from 1 to N | C ++ Program to implement the approach ; Function to obtain the maximum gcd of all pairs from 1 to n ; Print the answer ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void find ( int n ) { cout << n / 2 << endl ; } int main ( ) { int n = 5 ; find ( n ) ; return 0 ; } |
Count of pairs of Array elements which are divisible by K when concatenated | C ++ Program to count pairs of array elements which are divisible by K when concatenated ; Function to calculate and return the count of pairs ; Compute power of 10 modulo k ; Calculate length of a [ i ] ; Increase count of remainder ; Calculate ( a [ i ] * 10 ^ lenj ) % k ; Calculate ( k - ( a [ i ] * 10 ^ lenj ) % k ) % k ; Increase answer by count ; If a pair ( a [ i ] , a [ i ] ) is counted ; Return the count of pairs ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; map < int , int > rem [ 11 ] ; int countPairs ( vector < int > a , int n , int k ) { vector < int > len ( n ) ; vector < int > p ( 11 ) ; p [ 0 ] = 1 ; for ( int i = 1 ; i <= 10 ; i ++ ) { p [ i ] = ( p [ i - 1 ] * 10 ) % k ; } for ( int i = 0 ; i < n ; i ++ ) { int x = a [ i ] ; while ( x > 0 ) { len [ i ] ++ ; x /= 10 ; } rem [ len [ i ] ] [ a [ i ] % k ] ++ ; } int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 1 ; j <= 10 ; j ++ ) { int r = ( a [ i ] * p [ j ] ) % k ; int xr = ( k - r ) % k ; ans += rem [ j ] [ xr ] ; if ( len [ i ] == j && ( r + a [ i ] % k ) % k == 0 ) ans -- ; } } return ans ; } int main ( ) { vector < int > a = { 4 , 5 , 2 } ; int n = a . size ( ) , k = 2 ; cout << countPairs ( a , n , k ) ; } |
Count of N digit Numbers whose sum of every K consecutive digits is equal | C ++ program for the above approach ; Function to count the number of N - digit numbers such that sum of every k consecutive digits are equal ; Range of numbers ; Extract digits of the number ; Store the sum of first K digits ; Check for every k - consecutive digits using sliding window ; Driver Code ; Given integer N and K | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countDigitSum ( int N , int K ) { int l = ( int ) pow ( 10 , N - 1 ) , r = ( int ) pow ( 10 , N ) - 1 ; int count = 0 ; for ( int i = l ; i <= r ; i ++ ) { int num = i ; int digits [ N ] ; for ( int j = N - 1 ; j >= 0 ; j -- ) { digits [ j ] = num % 10 ; num /= 10 ; } int sum = 0 , flag = 0 ; for ( int j = 0 ; j < K ; j ++ ) sum += digits [ j ] ; for ( int j = K ; j < N ; j ++ ) { if ( sum - digits [ j - K ] + digits [ j ] != sum ) { flag = 1 ; break ; } } if ( flag == 0 ) count ++ ; } return count ; } int main ( ) { int N = 2 , K = 1 ; cout << countDigitSum ( N , K ) << endl ; return 0 ; } |
Array formed using sum of absolute differences of that element with all other elements | C ++ program for the above approach ; Function to return the new array ; Initialize the Arraylist ; Sum of absolute differences of element with all elements ; Initialize int sum to 0 ; Add the value of sum to ans ; Return the final ans ; Driver Code ; Given array arr [ ] ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > calculate ( int * arr , int n ) { vector < int > ans ; for ( int i = 0 ; i < n ; i ++ ) { int sum = 0 ; for ( int j = 0 ; j < n ; j ++ ) { sum += abs ( arr [ i ] - arr [ j ] ) ; } ans . push_back ( sum ) ; } return ans ; } int main ( ) { int arr [ ] = { 2 , 3 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; vector < int > ans = calculate ( arr , n ) ; cout << " [ " ; for ( auto itr : ans ) cout << itr << " , β " ; cout << " ] " ; return 0 ; } |
Number of pair of positions in matrix which are not accessible | C ++ program to count number of pair of positions in matrix which are not accessible ; Counts number of vertices connected in a component containing x . Stores the count in k . ; Incrementing the number of node in a connected component . ; Return the number of count of non - accessible cells . ; Initialize count of connected vertices found by DFS starting from i . ; Update result ; Inserting the edge between edge . ; Mapping the cell coordinate into node number . ; Inserting the edge . ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void dfs ( vector < int > graph [ ] , bool visited [ ] , int x , int * k ) { for ( int i = 0 ; i < graph [ x ] . size ( ) ; i ++ ) { if ( ! visited [ graph [ x ] [ i ] ] ) { ( * k ) ++ ; visited [ graph [ x ] [ i ] ] = true ; dfs ( graph , visited , graph [ x ] [ i ] , k ) ; } } } int countNonAccessible ( vector < int > graph [ ] , int N ) { bool visited [ N * N + N ] ; memset ( visited , false , sizeof ( visited ) ) ; int ans = 0 ; for ( int i = 1 ; i <= N * N ; i ++ ) { if ( ! visited [ i ] ) { visited [ i ] = true ; int k = 1 ; dfs ( graph , visited , i , & k ) ; ans += k * ( N * N - k ) ; } } return ans ; } void insertpath ( vector < int > graph [ ] , int N , int x1 , int y1 , int x2 , int y2 ) { int a = ( x1 - 1 ) * N + y1 ; int b = ( x2 - 1 ) * N + y2 ; graph [ a ] . push_back ( b ) ; graph [ b ] . push_back ( a ) ; } int main ( ) { int N = 2 ; vector < int > graph [ N * N + 1 ] ; insertpath ( graph , N , 1 , 1 , 1 , 2 ) ; insertpath ( graph , N , 1 , 2 , 2 , 2 ) ; cout << countNonAccessible ( graph , N ) << endl ; return 0 ; } |
Minimum number of distinct powers of 2 required to express a given binary number | C ++ Program to implement the above approach ; Function to return the minimum distinct powers of 2 required to express s ; Reverse the string to start from lower powers ; Check if the character is 1 ; Add in range provided range ; Initialize the counter ; Check if the character is not 0 ; Increment the counter ; Print the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findMinimum ( string s ) { int n = s . size ( ) ; int x [ n + 1 ] = { 0 } ; reverse ( s . begin ( ) , s . end ( ) ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == '1' ) { if ( x [ i ] == 1 ) { x [ i + 1 ] = 1 ; x [ i ] = 0 ; } else if ( i and x [ i - 1 ] == 1 ) { x [ i + 1 ] = 1 ; x [ i - 1 ] = -1 ; } else x [ i ] = 1 ; } } int c = 0 ; for ( int i = 0 ; i <= n ; i ++ ) { if ( x [ i ] != 0 ) c ++ ; } cout << c << endl ; } int main ( ) { string str = "111" ; findMinimum ( str ) ; return 0 ; } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.