text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Concatenate the strings in an order which maximises the occurrence of subsequence " ab " | C ++ implementation of the approach ; Custom sort function to sort the given string in the order which maximises the final score ; To store the count of occurrences of ' a ' and ' b ' in s1 ; Count the number of occurrences of ' a ' and ' b ' in s1 ; To store the count of occurrences of ' a ' and ' b ' in s2 ; Count the number of occurrences of ' a ' and ' b ' in s2 ; Since the number of subsequences ' ab ' is more when s1 is placed before s2 we return 1 so that s1 occurs before s2 in the combined string ; Function that return the concatenated string as S [ 0 ] + S [ 1 ] + ... + S [ N - 1 ] ; To store the concatenated string ; Concatenate every string in the order of appearance ; Return the concatenated string ; Function to return the maximum required score ; Sort the strings in the order which maximizes the score that we can get ; Get the concatenated string combined string ; Calculate the score of the combined string i . e . the count of occurrences of " ab " as subsequences ; Number of ' a ' has increased by one ; There are count_a number of ' a ' that can form subsequence ' ab ' with this ' b ' ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool customSort ( string s1 , string s2 ) { int count_a1 = 0 , count_b1 = 0 ; for ( int i = 0 ; i < s1 . size ( ) ; i ++ ) { if ( s1 [ i ] == ' a ' ) count_a1 ++ ; else count_b1 ++ ; } int count_a2 = 0 , count_b2 = 0 ; for ( int i = 0 ; i < s2 . size ( ) ; i ++ ) { if ( s2 [ i ] == ' a ' ) count_a2 ++ ; else count_b2 ++ ; } if ( count_a1 * count_b2 > count_b1 * count_a2 ) { return 1 ; } else { return 0 ; } } string concatenateStrings ( string S [ ] , int N ) { string str = " " ; for ( int i = 0 ; i < N ; i ++ ) str += S [ i ] ; return str ; } int getMaxScore ( string S [ ] , int N ) { sort ( S , S + N , customSort ) ; string combined_string = concatenateStrings ( S , N ) ; int final_score = 0 , count_a = 0 ; for ( int i = 0 ; i < combined_string . size ( ) ; i ++ ) { if ( combined_string [ i ] == ' a ' ) { count_a ++ ; } else { final_score += count_a ; } } return final_score ; } int main ( ) { string S [ ] = { " bab " , " aa " , " ba " , " b " } ; int N = sizeof ( S ) / sizeof ( string ) ; cout << getMaxScore ( S , N ) ; return 0 ; } |
Minimum increment operations to make K elements equal | C ++ implementation of the approach ; Function to return the minimum number of increment operations required to make any k elements of the array equal ; Sort the array in increasing order ; Calculate the number of operations needed to make 1 st k elements equal to the kth element i . e . the 1 st window ; Answer will be the minimum of all possible k sized windows ; Find the operations needed to make k elements equal to ith element ; Slide the window to the right and subtract increments spent on leftmost element of the previous window ; Add increments needed to make the 1 st k - 1 elements of this window equal to the kth element of the current window ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperations ( vector < int > ar , int k ) { sort ( ar . begin ( ) , ar . end ( ) ) ; int opsNeeded = 0 ; for ( int i = 0 ; i < k ; i ++ ) { opsNeeded += ar [ k - 1 ] - ar [ i ] ; } int ans = opsNeeded ; for ( int i = k ; i < ar . size ( ) ; i ++ ) { opsNeeded = opsNeeded - ( ar [ i - 1 ] - ar [ i - k ] ) ; opsNeeded += ( k - 1 ) * ( ar [ i ] - ar [ i - 1 ] ) ; ans = min ( ans , opsNeeded ) ; } return ans ; } int main ( ) { vector < int > arr = { 3 , 1 , 9 , 100 } ; int n = arr . size ( ) ; int k = 3 ; cout << minOperations ( arr , k ) ; return 0 ; } |
Lexicographical ordering using Heap Sort | C ++ implementation to print the string in Lexicographical order ; Used for index in heap ; Predefining the heap array ; Defining formation of the heap ; Iterative heapiFy ; Just swapping if the element is smaller than already stored element ; Swapping the current index with its child ; Moving upward in the heap ; Defining heap sort ; Taking output of the minimum element ; Set first element as a last one ; Decrement of the size of the string ; Initializing the left and right index ; Process of heap sort If root element is minimum than its both of the child then break ; Otherwise checking that the child which one is smaller , swap them with parent element ; Swapping ; Changing the left index and right index ; Utility function ; To heapiFy ; Calling heap sort function ; Driver Code | #include <iostream> NEW_LINE #include <string> NEW_LINE using namespace std ; int x = -1 ; string heap [ 1000 ] ; void heapForm ( string k ) { x ++ ; heap [ x ] = k ; int child = x ; string tmp ; int index = x / 2 ; while ( index >= 0 ) { if ( heap [ index ] > heap [ child ] ) { tmp = heap [ index ] ; heap [ index ] = heap [ child ] ; heap [ child ] = tmp ; child = index ; index = index / 2 ; } else { break ; } } } void heapSort ( ) { int left1 , right1 ; while ( x >= 0 ) { string k ; k = heap [ 0 ] ; cout << k << " β " ; heap [ 0 ] = heap [ x ] ; x = x - 1 ; string tmp ; int index = 0 ; int length = x ; left1 = 1 ; right1 = left1 + 1 ; while ( left1 <= length ) { if ( heap [ index ] <= heap [ left1 ] && heap [ index ] <= heap [ right1 ] ) { break ; } else { if ( heap [ left1 ] < heap [ right1 ] ) { tmp = heap [ index ] ; heap [ index ] = heap [ left1 ] ; heap [ left1 ] = tmp ; index = left1 ; } else { tmp = heap [ index ] ; heap [ index ] = heap [ right1 ] ; heap [ right1 ] = tmp ; index = right1 ; } } left1 = 2 * left1 ; right1 = left1 + 1 ; } } } void sort ( string k [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { heapForm ( k [ i ] ) ; } heapSort ( ) ; } int main ( ) { string arr [ ] = { " banana " , " orange " , " apple " , " pineapple " , " berries " , " lichi " } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sort ( arr , n ) ; } |
Find Kth element in an array containing odd elements first and then even elements | C ++ implementation of the approach ; Function to return the kth element in the modified array ; First odd number ; Insert the odd number ; Next odd number ; First even number ; Insert the even number ; Next even number ; Return the kth element ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getNumber ( int n , int k ) { int arr [ n ] ; int i = 0 ; int odd = 1 ; while ( odd <= n ) { arr [ i ++ ] = odd ; odd += 2 ; } int even = 2 ; while ( even <= n ) { arr [ i ++ ] = even ; even += 2 ; } return arr [ k - 1 ] ; } int main ( ) { int n = 8 , k = 5 ; cout << getNumber ( n , k ) ; return 0 ; } |
Swap Alternate Boundary Pairs | C ++ implementation of the approach ; Utility function to print the contents of an array ; Function to update the array ; Initialize the pointers ; While there are elements to swap ; Update the pointers ; Print the updated array ; 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 UpdateArr ( int arr [ ] , int n ) { int i = 0 , j = n - 1 ; while ( i < j ) { int temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; i += 2 ; j -= 2 ; } printArr ( arr , n ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; UpdateArr ( arr , n ) ; return 0 ; } |
Count permutation such that sequence is non decreasing | C ++ implementation of the approach ; To store the factorials ; Function to update fact [ ] array such that fact [ i ] = i ! ; 0 ! = 1 ; i ! = i * ( i - 1 ) ! ; Function to return the count of possible permutations ; To store the result ; Sort the array ; Initial size of the block ; Increase the size of block ; Update the result for the previous block ; Reset the size to 1 ; Update the result for the last block ; Driver code ; Pre - calculating factorials | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 20 NEW_LINE int fact [ N ] ; void pre ( ) { fact [ 0 ] = 1 ; for ( int i = 1 ; i < N ; i ++ ) { fact [ i ] = i * fact [ i - 1 ] ; } } int CountPermutation ( int a [ ] , int n ) { int ways = 1 ; sort ( a , a + n ) ; int size = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( a [ i ] == a [ i - 1 ] ) { size ++ ; } else { ways *= fact [ size ] ; size = 1 ; } } ways *= fact [ size ] ; return ways ; } int main ( ) { int a [ ] = { 1 , 2 , 4 , 4 , 2 , 4 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; pre ( ) ; cout << CountPermutation ( a , n ) ; return 0 ; } |
Smallest element greater than X not present in the array | C ++ implementation of the approach ; Function to return the smallest element greater than x which is not present in a [ ] ; Sort the array ; Continue until low is less than or equals to high ; Find mid ; If element at mid is less than or equals to searching element ; If mid is equals to searching element ; Increment searching element ; Make high as N - 1 ; Make low as mid + 1 ; Make high as mid - 1 ; Return the next greater element ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Next_greater ( int a [ ] , int n , int x ) { sort ( a , a + n ) ; int low = 0 , high = n - 1 , ans = x + 1 ; while ( low <= high ) { int mid = ( low + high ) / 2 ; if ( a [ mid ] <= ans ) { if ( a [ mid ] == ans ) { ans ++ ; high = n - 1 ; } low = mid + 1 ; } else high = mid - 1 ; } return ans ; } int main ( ) { int a [ ] = { 1 , 5 , 10 , 4 , 7 } , x = 4 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << Next_greater ( a , n , x ) ; return 0 ; } |
Alternate XOR operations on sorted array | C ++ implementation of the approach ; Function to find the maximum and the minimum elements from the array after performing the given operation k times ; To store the current sequence of elements ; To store the next sequence of elements after xoring with current elements ; Store the frequency of elements of arr [ ] in arr1 [ ] ; Storing all precomputed XOR values so that we don 't have to do it again and again as XOR is a costly operation ; Perform the operations k times ; The value of count decide on how many elements we have to apply XOR operation ; If current element is present in the array to be modified ; Suppose i = m and arr1 [ i ] = num , it means ' m ' appears ' num ' times If the count is even we have to perform XOR operation on alternate ' m ' starting from the 0 th index because count is even and we have to perform XOR operations starting with initial ' m ' Hence there will be ceil ( num / 2 ) operations on ' m ' that will change ' m ' to xor_val [ m ] i . e . m ^ x ; Decrease the frequency of ' m ' from arr1 [ ] ; Increase the frequency of ' m ^ x ' in arr2 [ ] ; If the count is odd we have to perform XOR operation on alternate ' m ' starting from the 1 st index because count is odd and we have to leave the 0 th ' m ' Hence there will be ( num / 2 ) XOR operations on ' m ' that will change ' m ' to xor_val [ m ] i . e . m ^ x ; Updating the count by frequency of the current elements as we have processed that many elements ; Updating arr1 [ ] which will now store the next sequence of elements At this time , arr1 [ ] stores the remaining ' m ' on which XOR was not performed and arr2 [ ] stores the frequency of ' m ^ x ' i . e . those ' m ' on which operation was performed Updating arr1 [ ] with frequency of remaining ' m ' & frequency of ' m ^ x ' from arr2 [ ] With help of arr2 [ ] , we prevent sorting of the array again and again ; Resetting arr2 [ ] for next iteration ; Finding the maximum and the minimum element from the modified array after the operations ; Printing the max and the min element ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100000 NEW_LINE void xorOnSortedArray ( int arr [ ] , int n , int k , int x ) { int arr1 [ MAX + 1 ] = { 0 } ; int arr2 [ MAX + 1 ] = { 0 } ; int xor_val [ MAX + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) arr1 [ arr [ i ] ] ++ ; for ( int i = 0 ; i <= MAX ; i ++ ) xor_val [ i ] = i ^ x ; while ( k -- ) { int count = 0 ; for ( int i = 0 ; i <= MAX ; i ++ ) { int store = arr1 [ i ] ; if ( arr1 [ i ] > 0 ) { if ( count % 2 == 0 ) { int div = ceil ( ( float ) arr1 [ i ] / 2 ) ; arr1 [ i ] = arr1 [ i ] - div ; arr2 [ xor_val [ i ] ] += div ; } else if ( count % 2 != 0 ) { int div = arr1 [ i ] / 2 ; arr1 [ i ] = arr1 [ i ] - div ; arr2 [ xor_val [ i ] ] += div ; } } count = count + store ; } for ( int i = 0 ; i <= MAX ; i ++ ) { arr1 [ i ] = arr1 [ i ] + arr2 [ i ] ; arr2 [ i ] = 0 ; } } int min = INT_MAX ; int max = INT_MIN ; for ( int i = 0 ; i <= MAX ; i ++ ) { if ( arr1 [ i ] > 0 ) { if ( min > i ) min = i ; if ( max < i ) max = i ; } } cout << min << " β " << max << endl ; } int main ( ) { int arr [ ] = { 605 , 986 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 548 , x = 569 ; xorOnSortedArray ( arr , n , k , x ) ; return 0 ; } |
Arrange N elements in circular fashion such that all elements are strictly less than sum of adjacent elements | C ++ implementation of the approach ; Function to print the arrangement that satisifes the given condition ; Sort the array initially ; Array that stores the arrangement ; Once the array is sorted Re - fill the array again in the mentioned way in the approach ; Iterate in the array and check if the arrangement made satisfies the given condition or not ; For the first element the adjacents will be a [ 1 ] and a [ n - 1 ] ; For the last element the adjacents will be a [ 0 ] and a [ n - 2 ] ; If we reach this position then the arrangement is possible ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printArrangement ( int a [ ] , int n ) { sort ( a , a + n ) ; int b [ n ] ; int low = 0 , high = n - 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) b [ low ++ ] = a [ i ] ; else b [ high -- ] = a [ i ] ; } for ( int i = 0 ; i < n ; i ++ ) { if ( i == 0 ) { if ( b [ n - 1 ] + b [ 1 ] <= b [ i ] ) { cout << -1 ; return ; } } else if ( i == ( n - 1 ) ) { if ( b [ n - 2 ] + b [ 0 ] <= b [ i ] ) { cout << -1 ; return ; } } else { if ( b [ i - 1 ] + b [ i + 1 ] <= b [ i ] ) { cout << -1 ; return ; } } } for ( int i = 0 ; i < n ; i ++ ) cout << b [ i ] << " β " ; } int main ( ) { int a [ ] = { 1 , 4 , 4 , 3 , 2 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; printArrangement ( a , n ) ; return 0 ; } |
Greatest contiguous sub | C ++ implementation of the approach ; Function that returns the sub - array ; Data - structure to store all the sub - arrays of size K ; Iterate to find all the sub - arrays ; Store the sub - array elements in the array ; Push the vector in the container ; Sort the vector of elements ; The last sub - array in the sorted order will be the answer ; Driver code ; Get the sub - array | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > findSubarray ( int a [ ] , int k , int n ) { vector < vector < int > > vec ; for ( int i = 0 ; i < n - k + 1 ; i ++ ) { vector < int > temp ; for ( int j = i ; j < i + k ; j ++ ) { temp . push_back ( a [ j ] ) ; } vec . push_back ( temp ) ; } sort ( vec . begin ( ) , vec . end ( ) ) ; return vec [ vec . size ( ) - 1 ] ; } int main ( ) { int a [ ] = { 1 , 4 , 3 , 2 , 5 } ; int k = 4 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; vector < int > ans = findSubarray ( a , k , n ) ; for ( auto it : ans ) cout << it << " β " ; } |
Maximum Length Chain of Pairs | Set | C ++ implementation of the above approach ; Structure for storing pairs of first and second values . ; Comparator function which can compare the second element of structure used to sort pairs in increasing order of second value . ; Function for finding max length chain ; Initialize length l = 1 ; Sort all pair in increasing order according to second no of pair ; Pick up the first pair and assign the value of second element fo pair to a temporary variable s ; Iterate from second pair ( index of the second pair is 1 ) to the last pair ; If first of current pair is greater than previously selected pair then select current pair and update value of l and s ; Return maximum length ; Driver Code ; Declaration of array of structure ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct val { int first ; int second ; } ; bool comparator ( struct val p1 , struct val p2 ) { return ( p1 . second < p2 . second ) ; } int maxChainLen ( struct val p [ ] , int n ) { int l = 1 ; sort ( p , p + n , comparator ) ; int s = p [ 0 ] . second ; for ( int i = 1 ; i < n ; i ++ ) { if ( p [ i ] . first > s ) { l ++ ; s = p [ i ] . second ; } } return l ; } int main ( ) { val p [ ] = { { 5 , 24 } , { 39 , 60 } , { 15 , 28 } , { 27 , 40 } , { 50 , 90 } } ; int n = sizeof ( p ) / sizeof ( p [ 0 ] ) ; cout << maxChainLen ( p , n ) << endl ; return 0 ; } |
Unbounded Fractional Knapsack | C ++ implementation of the approach ; Function to return the maximum required value ; maxratio will store the maximum value to weight ratio we can have for any item and maxindex will store the index of that element ; Find the maximum ratio ; The item with the maximum value to weight ratio will be put into the knapsack repeatedly until full ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; float knapSack ( int W , float wt [ ] , float val [ ] , int n ) { float maxratio = INT_MIN ; int maxindex = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( val [ i ] / wt [ i ] ) > maxratio ) { maxratio = ( val [ i ] / wt [ i ] ) ; maxindex = i ; } } return ( W * maxratio ) ; } int main ( ) { float val [ ] = { 14 , 27 , 44 , 19 } ; float wt [ ] = { 6 , 7 , 9 , 8 } ; int n = sizeof ( val ) / sizeof ( val [ 0 ] ) ; int W = 50 ; cout << knapSack ( W , wt , val , n ) ; return 0 ; } |
Sort an array without changing position of negative numbers | C ++ implementation of the approach ; Function to sort the array such that negative values do not get affected ; Store all non - negative values ; Sort non - negative values ; If current element is non - negative then update it such that all the non - negative values are sorted ; Print the sorted array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sortArray ( int a [ ] , int n ) { vector < int > ans ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] >= 0 ) ans . push_back ( a [ i ] ) ; } sort ( ans . begin ( ) , ans . end ( ) ) ; int j = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] >= 0 ) { a [ i ] = ans [ j ] ; j ++ ; } } for ( int i = 0 ; i < n ; i ++ ) cout << a [ i ] << " β " ; } int main ( ) { int arr [ ] = { 2 , -6 , -3 , 8 , 4 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortArray ( arr , n ) ; return 0 ; } |
Find a triplet in an array whose sum is closest to a given number | C ++ implementation of the approach ; Function to return the sum of a triplet which is closest to x ; Sort the array ; To store the closest sum not using INT_MAX to avoid overflowing condition ; Fix the smallest number among the three integers ; Two pointers initially pointing at the last and the element next to the fixed element ; While there could be more pairs to check ; Calculate the sum of the current triplet ; If the sum is more closer than the current closest sum ; If sum is greater then x then decrement the second pointer to get a smaller sum ; Else increment the first pointer to get a larger sum ; Return the closest sum found ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int solution ( vector < int > & arr , int x ) { sort ( arr . begin ( ) , arr . end ( ) ) ; int closestSum = 1000000000 ; for ( int i = 0 ; i < arr . size ( ) - 2 ; i ++ ) { int ptr1 = i + 1 , ptr2 = arr . size ( ) - 1 ; while ( ptr1 < ptr2 ) { int sum = arr [ i ] + arr [ ptr1 ] + arr [ ptr2 ] ; if ( abs ( 1LL * x - sum ) < abs ( 1LL * x - closestSum ) ) { closestSum = sum ; } if ( sum > x ) { ptr2 -- ; } else { ptr1 ++ ; } } } return closestSum ; } int main ( ) { vector < int > arr = { -1 , 2 , 1 , -4 } ; int x = 1 ; cout << solution ( arr , x ) ; return 0 ; } |
Merge two BSTs with constant extra space | C ++ implementation of above approach ; Structure of a BST Node ; A utility function to print Inorder traversal of a Binary Tree ; The function to print data of two BSTs in sorted order ; Base cases ; If the first tree is exhausted simply print the inorder traversal of the second tree ; If second tree is exhausted simply print the inoreder traversal of the first tree ; A temporary pointer currently pointing to root of first tree ; previous pointer to store the parent of temporary pointer ; Traverse through the first tree until you reach the leftmost element , which is the first element of the tree in the inorder traversal . This is the least element of the tree ; Another temporary pointer currently pointing to root of second tree ; Previous pointer to store the parent of second temporary pointer ; Traverse through the second tree until you reach the leftmost element , which is the first element of the tree in inorder traversal . This is the least element of the tree . ; Compare the least current least elements of both the tree ; If first tree 's element is smaller print it ; If the node has no parent , that means this node is the root ; Simply make the right child of the root as new root ; If node has a parent ; As this node is the leftmost node , it is certain that it will not have a let child so we simply assign this node ' s β right β pointer , β which β can β be β β either β null β or β not , β to β its β parent ' s left pointer . This statement is just doing the task of deleting the node ; recursively call the merge function with updated tree ; If the node has no parent , that means this node is the root ; Simply make the right child of root as new root ; If node has a parent ; Recursively call the merge function with updated tree ; Driver Code ; Print sorted nodes of both trees | #include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * left ; Node * right ; Node ( int x ) { data = x ; left = right = NULL ; } } ; void inorder ( Node * root ) { if ( root != NULL ) { inorder ( root -> left ) ; cout << root -> data << " β " ; inorder ( root -> right ) ; } } void merge ( Node * root1 , Node * root2 ) { if ( ! root1 && ! root2 ) return ; if ( ! root1 ) { inorder ( root2 ) ; return ; } if ( ! root2 ) { inorder ( root1 ) ; return ; } Node * temp1 = root1 ; Node * prev1 = NULL ; while ( temp1 -> left ) { prev1 = temp1 ; temp1 = temp1 -> left ; } Node * temp2 = root2 ; Node * prev2 = NULL ; while ( temp2 -> left ) { prev2 = temp2 ; temp2 = temp2 -> left ; } if ( temp1 -> data <= temp2 -> data ) { cout << temp1 -> data << " β " ; if ( prev1 == NULL ) { merge ( root1 -> right , root2 ) ; } else { prev1 -> left = temp1 -> right ; merge ( root1 , root2 ) ; } } else { cout << temp2 -> data << " β " ; if ( prev2 == NULL ) { merge ( root1 , root2 -> right ) ; } else { prev2 -> left = temp2 -> right ; merge ( root1 , root2 ) ; } } } int main ( ) { Node * root1 = NULL , * root2 = NULL ; root1 = new Node ( 3 ) ; root1 -> left = new Node ( 1 ) ; root1 -> right = new Node ( 5 ) ; root2 = new Node ( 4 ) ; root2 -> left = new Node ( 2 ) ; root2 -> right = new Node ( 6 ) ; merge ( root1 , root2 ) ; return 0 ; } |
Print elements of an array according to the order defined by another array | set 2 | A C ++ program to print an array according to the order defined by another array ; Function to print an array according to the order defined by another array ; Declaring map and iterator ; Store the frequency of each number of a1 [ ] int the map ; Traverse through a2 [ ] ; Check whether number is present in map or not ; Print that number that many times of its frequency ; Print those numbers that are not present in a2 [ ] ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void print_in_order ( int a1 [ ] , int a2 [ ] , int n , int m ) { map < int , int > mp ; map < int , int > :: iterator itr ; for ( int i = 0 ; i < n ; i ++ ) mp [ a1 [ i ] ] ++ ; for ( int i = 0 ; i < m ; i ++ ) { if ( mp . find ( a2 [ i ] ) != mp . end ( ) ) { itr = mp . find ( a2 [ i ] ) ; for ( int j = 0 ; j < itr -> second ; j ++ ) cout << itr -> first << " β " ; mp . erase ( a2 [ i ] ) ; } } for ( itr = mp . begin ( ) ; itr != mp . end ( ) ; itr ++ ) { for ( int j = 0 ; j < itr -> second ; j ++ ) cout << itr -> first << " β " ; } cout << endl ; } int main ( ) { int a1 [ ] = { 2 , 1 , 2 , 5 , 7 , 1 , 9 , 3 , 6 , 8 , 8 } ; int a2 [ ] = { 2 , 1 , 8 , 3 } ; int n = sizeof ( a1 ) / sizeof ( a1 [ 0 ] ) ; int m = sizeof ( a2 ) / sizeof ( a2 [ 0 ] ) ; print_in_order ( a1 , a2 , n , m ) ; return 0 ; } |
Check whether we can sort two arrays by swapping A [ i ] and B [ i ] | C ++ implementation of above approach ; Function to check whether both the array can be sorted in ( strictly increasing ) ascending order ; Traverse through the array and find out the min and max variable at each position make one array of min variables and another of maximum variable ; Maximum and minimum variable ; Assign min value to B [ i ] and max value to A [ i ] ; Now check whether the array is sorted or not ; Driver code | #include <iostream> NEW_LINE using namespace std ; bool IsSorted ( int A [ ] , int B [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { int x , y ; x = max ( A [ i ] , B [ i ] ) ; y = min ( A [ i ] , B [ i ] ) ; A [ i ] = x ; B [ i ] = y ; } for ( int i = 1 ; i < n ; i ++ ) { if ( A [ i ] <= A [ i - 1 ] B [ i ] <= B [ i - 1 ] ) return false ; } return true ; } int main ( ) { int A [ ] = { 1 , 4 , 3 , 5 , 7 } ; int B [ ] = { 2 , 2 , 5 , 8 , 9 } ; int n = sizeof ( A ) / sizeof ( int ) ; cout << ( IsSorted ( A , B , n ) ? " True " : " False " ) ; return 0 ; } |
Find the largest possible k | C ++ program to find the largest possible k - multiple set ; Function to find the largest possible k - multiple set ; Sort the given array ; To store k - multiple set ; Traverse through the whole array ; Check if x / k is already present or not ; Print the k - multiple set ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void K_multiple ( int a [ ] , int n , int k ) { sort ( a , a + n ) ; set < int > s ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( a [ i ] % k == 0 && s . find ( a [ i ] / k ) == s . end ( ) ) a [ i ] % k != 0 ) s . insert ( a [ i ] ) ; } for ( auto i = s . begin ( ) ; i != s . end ( ) ; i ++ ) { cout << * i << " β " ; } } int main ( ) { int a [ ] = { 2 , 3 , 4 , 5 , 6 , 10 } ; int k = 2 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; K_multiple ( a , n , k ) ; return 0 ; } |
Maximum water that can be stored between two buildings | C ++ implementation of the approach ; Return the maximum water that can be stored ; To store the maximum water so far ; Both the pointers are pointing at the first and the last buildings respectively ; While the water can be stored between the currently chosen buildings ; Update maximum water so far and increment i ; Update maximum water so far and decrement j ; Any of the pointers can be updated ( or both ) ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxWater ( int height [ ] , int n ) { int maximum = 0 ; int i = 0 , j = n - 1 ; while ( i < j ) { if ( height [ i ] < height [ j ] ) { maximum = max ( maximum , ( j - i - 1 ) * height [ i ] ) ; i ++ ; } else if ( height [ j ] < height [ i ] ) { maximum = max ( maximum , ( j - i - 1 ) * height [ j ] ) ; j -- ; } else { maximum = max ( maximum , ( j - i - 1 ) * height [ i ] ) ; i ++ ; j -- ; } } return maximum ; } int main ( ) { int height [ ] = { 2 , 1 , 3 , 4 , 6 , 5 } ; int n = sizeof ( height ) / sizeof ( height [ 0 ] ) ; cout << ( maxWater ( height , n ) ) ; } |
Count the maximum number of elements that can be selected from the array | C ++ implementation of the approach ; Function to return the maximum count of selection possible from the given array following the given process ; Initialize result ; Sorting the array ; Initialize the select variable ; Loop through array ; If selection is possible ; Increment result ; Increment selection variable ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSelectionCount ( int a [ ] , int n ) { int res = 0 ; sort ( a , a + n ) ; int select = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] >= select ) { res ++ ; select ++ ; } } return res ; } int main ( ) { int arr [ ] = { 4 , 2 , 1 , 3 , 5 , 1 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxSelectionCount ( arr , N ) ; return 0 ; } |
Print combinations of distinct numbers which add up to give sum N | C ++ implementation of the approach ; arr [ ] to store all the distinct elements index - next location in array num - given number reducedNum - reduced number ; Set to store all the distinct elements ; Base condition ; Iterate over all the elements and store it into the set ; Calculate the sum of all the elements of the set ; Compare whether the sum is equal to n or not , if it is equal to n print the numbers ; Find previous number stored in the array ; Store all the numbers recursively into the arr [ ] ; Function to find all the distinct combinations of n ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findCombinationsUtil ( int arr [ ] , int index , int n , int red_num ) { set < int > s ; int sum = 0 ; if ( red_num < 0 ) { return ; } if ( red_num == 0 ) { for ( int i = 0 ; i < index ; i ++ ) { s . insert ( arr [ i ] ) ; } for ( auto itr = s . begin ( ) ; itr != s . end ( ) ; itr ++ ) { sum = sum + ( * itr ) ; } if ( sum == n ) { for ( auto i = s . begin ( ) ; i != s . end ( ) ; i ++ ) { cout << * i << " β " ; } cout << endl ; return ; } } int prev = ( index == 0 ) ? 1 : arr [ index - 1 ] ; for ( int k = prev ; k <= n ; k ++ ) { arr [ index ] = k ; findCombinationsUtil ( arr , index + 1 , n , red_num - k ) ; } } void findCombinations ( int n ) { int a [ n ] ; findCombinationsUtil ( a , 0 , n , n ) ; } int main ( ) { int n = 7 ; findCombinations ( n ) ; return 0 ; } |
Check whether an array can be made strictly increasing by modifying atmost one element | C ++ implementation of the approach ; Function that returns true if arr [ ] can be made strictly increasing after modifying at most one element ; To store the number of modifications required to make the array strictly increasing ; Check whether the first element needs to be modify or not ; Loop from 2 nd element to the 2 nd last element ; Check whether arr [ i ] needs to be modified ; Modifying arr [ i ] ; Check if arr [ i ] is equal to any of arr [ i - 1 ] or arr [ i + 1 ] ; Check whether the last element needs to be modify or not ; If more than 1 modification is required ; Driver code | #include <iostream> NEW_LINE using namespace std ; bool check ( int arr [ ] , int n ) { int modify = 0 ; if ( arr [ 0 ] > arr [ 1 ] ) { arr [ 0 ] = arr [ 1 ] / 2 ; modify ++ ; } for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( ( arr [ i - 1 ] < arr [ i ] && arr [ i + 1 ] < arr [ i ] ) || ( arr [ i - 1 ] > arr [ i ] && arr [ i + 1 ] > arr [ i ] ) ) { arr [ i ] = ( arr [ i - 1 ] + arr [ i + 1 ] ) / 2 ; if ( arr [ i ] == arr [ i - 1 ] arr [ i ] == arr [ i + 1 ] ) return false ; modify ++ ; } } if ( arr [ n - 1 ] < arr [ n - 2 ] ) modify ++ ; if ( modify > 1 ) return false ; return true ; } int main ( ) { int arr [ ] = { 2 , 4 , 8 , 6 , 9 , 12 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( check ( arr , n ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; } |
Check if the given matrix is increasing row and column wise | C ++ implementation of the approach ; Function that returns true if the matrix is strictly increasing ; Check if the matrix is strictly increasing ; Out of bound condition ; Out of bound condition ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 2 NEW_LINE #define M 2 NEW_LINE bool isMatrixInc ( int a [ N ] [ M ] ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( i - 1 >= 0 ) { if ( a [ i ] [ j ] <= a [ i - 1 ] [ j ] ) return false ; } if ( j - 1 >= 0 ) { if ( a [ i ] [ j ] <= a [ i ] [ j - 1 ] ) return false ; } } } return true ; } int main ( ) { int a [ N ] [ M ] = { { 2 , 10 } , { 11 , 20 } } ; if ( isMatrixInc ( a ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Maximize the size of array by deleting exactly k sub | C ++ implementation of the approach ; Sieve of Eratosthenes ; Function to return the size of the maximized array ; Insert the indices of composite numbers ; Compute the number of prime between two consecutive composite ; Sort the diff vector ; Compute the prefix sum of diff vector ; Impossible case ; Delete sub - arrays of length 1 ; Find the number of primes to be deleted when deleting the sub - arrays ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 1e7 + 5 ; bool prime [ N ] ; void seive ( ) { for ( int i = 2 ; i < N ; i ++ ) { if ( ! prime [ i ] ) { for ( int j = i + i ; j < N ; j += i ) { prime [ j ] = 1 ; } } } prime [ 1 ] = 1 ; } int maxSizeArr ( int * arr , int n , int k ) { vector < int > v , diff ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ arr [ i ] ] ) v . push_back ( i ) ; } for ( int i = 1 ; i < v . size ( ) ; i ++ ) { diff . push_back ( v [ i ] - v [ i - 1 ] - 1 ) ; } sort ( diff . begin ( ) , diff . end ( ) ) ; for ( int i = 1 ; i < diff . size ( ) ; i ++ ) { diff [ i ] += diff [ i - 1 ] ; } if ( k > n || ( k == 0 && v . size ( ) ) ) { return -1 ; } else if ( v . size ( ) <= k ) { return ( n - k ) ; } else if ( v . size ( ) > k ) { int tt = v . size ( ) - k ; int sum = 0 ; sum += diff [ tt - 1 ] ; int res = n - ( v . size ( ) + sum ) ; return res ; } } int main ( ) { seive ( ) ; int arr [ ] = { 2 , 4 , 2 , 2 , 4 , 2 , 4 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 2 ; cout << maxSizeArr ( arr , n , k ) ; return 0 ; } |
Sort an array according to count of set bits | Set 2 | C ++ implementation of the approach ; function to sort the array according to the number of set bits in elements ; Counting no of setBits in arr [ i ] ; The count is subtracted from 32 because the result needs to be in descending order ; Printing the numbers in descending order of set bit count ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sortArr ( int arr [ ] , int n ) { multimap < int , int > map ; for ( int i = 0 ; i < n ; i ++ ) { int count = 0 ; int k = arr [ i ] ; while ( k ) { k = k & k - 1 ; count ++ ; } map . insert ( make_pair ( 32 - count , arr [ i ] ) ) ; } for ( auto it = map . begin ( ) ; it != map . end ( ) ; it ++ ) { cout << ( * it ) . second << " β " ; } } int main ( ) { int arr [ ] = { 5 , 2 , 3 , 9 , 4 , 6 , 7 , 15 , 32 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortArr ( arr , n ) ; return 0 ; } |
Smallest multiple of N formed using the given set of digits | C ++ implementation of the approach ; Function to return the required number ; Initialize both vectors with their initial values ; Sort the vector of digits ; Initialize the queue ; If modulus value is not present in the queue ; Compute digits modulus given number and update the queue and vectors ; While queue is not empty ; Remove the first element of the queue ; Compute new modulus values by using old queue values and each digit of the set ; If value is not present in the queue ; If required condition can 't be satisfied ; Initialize new vector ; Constructing the solution by backtracking ; Reverse the vector ; Return the required number ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findSmallestNumber ( vector < int > & arr , int n ) { vector < int > dp ( n , numeric_limits < int > :: max ( ) - 5 ) ; vector < pair < int , int > > result ( n , make_pair ( -1 , 0 ) ) ; sort ( arr . begin ( ) , arr . end ( ) ) ; queue < int > q ; for ( auto i : arr ) { if ( i != 0 ) { if ( dp [ i % n ] > 1e9 ) { q . push ( i % n ) ; dp [ i % n ] = 1 ; result [ i % n ] = { -1 , i } ; } } } while ( ! q . empty ( ) ) { int u = q . front ( ) ; q . pop ( ) ; for ( auto i : arr ) { int v = ( u * 10 + i ) % n ; if ( dp [ u ] + 1 < dp [ v ] ) { dp [ v ] = dp [ u ] + 1 ; q . push ( v ) ; result [ v ] = { u , i } ; } } } if ( dp [ 0 ] > 1e9 ) return -1 ; else { vector < int > ans ; int u = 0 ; while ( u != -1 ) { ans . push_back ( result [ u ] . second ) ; u = result [ u ] . first ; } reverse ( ans . begin ( ) , ans . end ( ) ) ; for ( auto i : ans ) { return i ; } } } int main ( ) { vector < int > arr = { 5 , 2 , 3 } ; int n = 12 ; cout << findSmallestNumber ( arr , n ) ; return 0 ; } |
Count number of subsets whose median is also present in the same subset | C ++ implementation of the approach ; Function to return the factorial of a number ; Function to return the value of nCr ; Function to return a raised to the power n with complexity O ( log ( n ) ) ; Function to return the number of sub - sets whose median is also present in the set ; Number of odd length sub - sets ; Sort the array ; Checking each element for leftmost middle element while they are equal ; Calculate the number of elements in right of rightmost middle element ; Calculate the number of elements in left of leftmost middle element ; Add selected even length subsets to the answer ; Driver code | #include <algorithm> NEW_LINE #include <iostream> NEW_LINE using namespace std ; long long mod = 1000000007 ; int fact ( int n ) { int res = 1 ; for ( int i = 2 ; i <= n ; i ++ ) res = res * i ; return res ; } int nCr ( int n , int r ) { return fact ( n ) / ( fact ( r ) * fact ( n - r ) ) ; } long long powmod ( long long a , long long n ) { if ( ! n ) return 1 ; long long pt = powmod ( a , n / 2 ) ; pt = ( pt * pt ) % mod ; if ( n % 2 ) return ( pt * a ) % mod ; else return pt ; } long long CountSubset ( int * arr , int n ) { long long ans = powmod ( 2 , n - 1 ) ; sort ( arr , arr + n ) ; for ( int i = 0 ; i < n ; ++ i ) { int j = i + 1 ; while ( j < n && arr [ j ] == arr [ i ] ) { int r = n - 1 - j ; int l = i ; ans = ( ans + nCr ( l + r , l ) ) % mod ; j ++ ; } } return ans ; } int main ( ) { int arr [ ] = { 2 , 3 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << CountSubset ( arr , n ) << endl ; return 0 ; } |
Count number of subsets whose median is also present in the same subset | C ++ implementation of the approach ; Function to store pascal triangle in 2 - d array ; Function to return a raised to the power n with complexity O ( log ( n ) ) ; Function to return the number of sub - sets whose median is also present in the set ; Number of odd length sub - sets ; Sort the array ; Checking each element for leftmost middle element while they are equal ; Calculate the number of elements in right of rightmost middle element ; Calculate the number of elements in left of leftmost middle element ; Add selected even length subsets to the answer ; Driver code | #include <algorithm> NEW_LINE #include <iostream> NEW_LINE using namespace std ; long long mod = 1000000007 ; long long arr [ 1001 ] [ 1001 ] ; void Preprocess ( ) { arr [ 0 ] [ 0 ] = 1 ; for ( int i = 1 ; i <= 1000 ; ++ i ) { arr [ i ] [ 0 ] = 1 ; for ( int j = 1 ; j < i ; ++ j ) { arr [ i ] [ j ] = ( arr [ i - 1 ] [ j - 1 ] + arr [ i - 1 ] [ j ] ) % mod ; } arr [ i ] [ i ] = 1 ; } } long long powmod ( long long a , long long n ) { if ( ! n ) return 1 ; long long pt = powmod ( a , n / 2 ) ; pt = ( pt * pt ) % mod ; if ( n % 2 ) return ( pt * a ) % mod ; else return pt ; } long long CountSubset ( int * val , int n ) { long long ans = powmod ( 2 , n - 1 ) ; sort ( val , val + n ) ; for ( int i = 0 ; i < n ; ++ i ) { int j = i + 1 ; while ( j < n && val [ j ] == val [ i ] ) { int r = n - 1 - j ; int l = i ; ans = ( ans + arr [ l + r ] [ l ] ) % mod ; j ++ ; } } return ans ; } int main ( ) { Preprocess ( ) ; int val [ ] = { 2 , 3 , 2 } ; int n = sizeof ( val ) / sizeof ( val [ 0 ] ) ; cout << CountSubset ( val , n ) << endl ; return 0 ; } |
Reorder the position of the words in alphabetical order | CPP implementation of the approach ; Function to print the ordering of words ; Creating list of words and assigning them index numbers ; Sort the list of words lexicographically ; Print the ordering ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void reArrange ( string words [ ] , int n ) { map < string , int > mp ; for ( int i = 0 ; i < n ; i ++ ) mp [ words [ i ] ] = i + 1 ; sort ( words , words + n ) ; for ( int i = 0 ; i < n ; i ++ ) cout << mp [ words [ i ] ] << " β " ; } int main ( ) { string words [ ] = { " live " , " place " , " travel " , " word " , " sky " } ; int n = sizeof ( words ) / sizeof ( words [ 0 ] ) ; reArrange ( words , n ) ; } |
Sum of elements in 1 st array such that number of elements less than or equal to them in 2 nd array is maximum | C ++ implementation of the approach ; Function to return the required sum ; Creating hash array initially filled with zero ; Calculate the frequency of elements of arr2 [ ] ; Running sum of hash array such that hash [ i ] will give count of elements less than or equal to i in arr2 [ ] ; To store the maximum value of the number of elements in arr2 [ ] which are smaller than or equal to some element of arr1 [ ] ; Calculate the sum of elements from arr1 [ ] corresponding to maximum frequency ; Return the required sum ; Driver code | #include <iostream> NEW_LINE using namespace std ; #define MAX 100000 NEW_LINE int findSumofEle ( int arr1 [ ] , int m , int arr2 [ ] , int n ) { int hash [ MAX ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) hash [ arr2 [ i ] ] ++ ; for ( int i = 1 ; i < MAX ; i ++ ) hash [ i ] = hash [ i ] + hash [ i - 1 ] ; int maximumFreq = 0 ; for ( int i = 0 ; i < m ; i ++ ) maximumFreq = max ( maximumFreq , hash [ arr1 [ i ] ] ) ; int sumOfElements = 0 ; for ( int i = 0 ; i < m ; i ++ ) sumOfElements += ( maximumFreq == hash [ arr1 [ i ] ] ) ? arr1 [ i ] : 0 ; return sumOfElements ; } int main ( ) { int arr1 [ ] = { 2 , 5 , 6 , 8 } ; int arr2 [ ] = { 4 , 10 } ; int m = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int n = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; cout << findSumofEle ( arr1 , m , arr2 , n ) ; return 0 ; } |
Print 2 | C ++ implementation of the approach ; Function to print the coordinates along with their frequency in ascending order ; map to store the pairs and their frequencies ; Store the coordinates along with their frequencies ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void Print ( int x [ ] , int y [ ] , int n ) { map < pair < int , int > , int > m ; for ( int i = 0 ; i < n ; i ++ ) m [ make_pair ( x [ i ] , y [ i ] ) ] ++ ; map < pair < int , int > , int > :: iterator i ; for ( i = m . begin ( ) ; i != m . end ( ) ; i ++ ) { cout << ( i -> first ) . first << " β " << ( i -> first ) . second << " β " << i -> second << " STRNEWLINE " ; } } int main ( ) { int x [ ] = { 1 , 2 , 1 , 1 , 1 } ; int y [ ] = { 1 , 1 , 3 , 1 , 3 } ; int n = sizeof ( x ) / sizeof ( int ) ; Print ( x , y , n ) ; return 0 ; } |
Split the array elements into strictly increasing and decreasing sequence | C ++ program to implement the above approach ; Function to print both the arrays ; Store both arrays ; Used for hashing ; Iterate for every element ; Increase the count ; If first occurrence ; If second occurrence ; If occurs more than 2 times ; Sort in increasing order ; Print the increasing array ; Sort in reverse order ; Print the decreasing array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void PrintBothArrays ( int a [ ] , int n ) { vector < int > v1 , v2 ; unordered_map < int , int > mpp ; for ( int i = 0 ; i < n ; i ++ ) { mpp [ a [ i ] ] ++ ; if ( mpp [ a [ i ] ] == 1 ) v1 . push_back ( a [ i ] ) ; else if ( mpp [ a [ i ] ] == 2 ) v2 . push_back ( a [ i ] ) ; else { cout << " Not β possible " ; return ; } } sort ( v1 . begin ( ) , v1 . end ( ) ) ; cout << " Strictly β increasing β array β is : STRNEWLINE " ; for ( auto it : v1 ) cout << it << " β " ; sort ( v2 . begin ( ) , v2 . end ( ) , greater < int > ( ) ) ; cout << " Strictly decreasing array is : " for ( auto it : v2 ) cout << it << " β " ; } int main ( ) { int a [ ] = { 7 , 2 , 7 , 3 , 3 , 1 , 4 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; PrintBothArrays ( a , n ) ; return 0 ; } |
Bubble Sort for Linked List by Swapping nodes | C ++ program to sort Linked List using Bubble Sort by swapping nodes ; structure for a node ; Function to swap the nodes ; Function to sort the list ; update the link after swapping ; break if the loop ended without any swap ; Function to print the list ; Function to insert a struct Node at the beginning of a linked list ; Driver Code ; start with empty linked list ; Create linked list from the array arr [ ] ; print list before sorting ; sort the linked list ; print list after sorting | #include <iostream> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } Node ; struct Node * swap ( struct Node * ptr1 , struct Node * ptr2 ) { struct Node * tmp = ptr2 -> next ; ptr2 -> next = ptr1 ; ptr1 -> next = tmp ; return ptr2 ; } int bubbleSort ( struct Node * * head , int count ) { struct Node * * h ; int i , j , swapped ; for ( i = 0 ; i <= count ; i ++ ) { h = head ; swapped = 0 ; for ( j = 0 ; j < count - i - 1 ; j ++ ) { struct Node * p1 = * h ; struct Node * p2 = p1 -> next ; if ( p1 -> data > p2 -> data ) { * h = swap ( p1 , p2 ) ; swapped = 1 ; } h = & ( * h ) -> next ; } if ( swapped == 0 ) break ; } } void printList ( struct Node * n ) { while ( n != NULL ) { cout << n -> data << " β - > β " ; n = n -> next ; } cout << endl ; } void insertAtTheBegin ( struct Node * * start_ref , int data ) { struct Node * ptr1 = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; ptr1 -> data = data ; ptr1 -> next = * start_ref ; * start_ref = ptr1 ; } int main ( ) { int arr [ ] = { 78 , 20 , 10 , 32 , 1 , 5 } ; int list_size , i ; struct Node * start = NULL ; list_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; for ( i = 0 ; i < list_size ; i ++ ) insertAtTheBegin ( & start , arr [ i ] ) ; cout << " Linked β list β before β sorting STRNEWLINE " ; printList ( start ) ; bubbleSort ( & start , list_size ) ; cout << " Linked β list β after β sorting STRNEWLINE " ; printList ( start ) ; return 0 ; } |
Iterative selection sort for linked list | ; Traverse the List ; Traverse the unsorted sublist ; Swap Data | void selectionSort ( node * head ) { node * temp = head ; while ( temp ) { node * min = temp ; node * r = temp -> next ; while ( r ) { if ( min -> data > r -> data ) min = r ; r = r -> next ; } int x = temp -> data ; temp -> data = min -> data ; min -> data = x ; temp = temp -> next ; } } |
Sort ugly numbers in an array at their relative positions | CPP implementation of the approach ; Function that returns true if n is an ugly number ; While divisible by 2 , keep dividing ; While divisible by 3 , keep dividing ; While divisible by 5 , keep dividing ; n must be 1 if it was ugly ; Function to sort ugly numbers in their relative positions ; To store the ugly numbers from the array ; If current element is an ugly number ; Add it to the ArrayList and set arr [ i ] to - 1 ; Sort the ugly numbers ; Position of an ugly number ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isUgly ( int n ) { while ( n % 2 == 0 ) n = n / 2 ; while ( n % 3 == 0 ) n = n / 3 ; while ( n % 5 == 0 ) n = n / 5 ; if ( n == 1 ) return true ; return false ; } void sortUglyNumbers ( int arr [ ] , int n ) { vector < int > list ; int i ; for ( i = 0 ; i < n ; i ++ ) { if ( isUgly ( arr [ i ] ) ) { list . push_back ( arr [ i ] ) ; arr [ i ] = -1 ; } } sort ( list . begin ( ) , list . end ( ) ) ; int j = 0 ; for ( i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == -1 ) cout << list [ j ++ ] << " β " ; else cout << arr [ i ] << " β " ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 7 , 12 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortUglyNumbers ( arr , n ) ; } |
Sort elements of the array that occurs in between multiples of K | C ++ implementation of the approach ; Utility function to print the contents of an array ; Function to sort elements in between multiples of k ; To store the index of previous multiple of k ; If it is not the first multiple of k ; Sort the elements in between the previous and the current multiple of k ; Update previous to be current ; Print the updated array ; 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 sortArr ( int arr [ ] , int n , int k ) { int prev = -1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % k == 0 ) { if ( prev != -1 ) sort ( arr + prev + 1 , arr + i ) ; prev = i ; } } printArr ( arr , n ) ; } int main ( ) { int arr [ ] = { 2 , 1 , 13 , 3 , 7 , 8 , 21 , 13 , 12 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 2 ; sortArr ( arr , n , k ) ; } |
Find A and B from list of divisors | C ++ implementation of the approach ; Function to print A and B all of whose divisors are present in the given array ; Sort the array ; A is the largest element from the array ; Iterate from the second largest element ; If current element is not a divisor of A then it must be B ; If current element occurs more than once ; Print A and B ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printNumbers ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int A = arr [ n - 1 ] , B = -1 ; for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( A % arr [ i ] != 0 ) { B = arr [ i ] ; break ; } if ( i - 1 >= 0 && arr [ i ] == arr [ i - 1 ] ) { B = arr [ i ] ; break ; } } cout << " A β = β " << A << " , β B β = β " << B ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 8 , 16 , 1 , 2 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printNumbers ( arr , n ) ; return 0 ; } |
Find the modified array after performing k operations of given type | C ++ implementation of the approach ; Utility function to print the contents of an array ; Function to remove the minimum value of the array from every element of the array ; Get the minimum value from the array ; Remove the minimum value from every element of the array ; Function to remove every element of the array from the maximum value of the array ; Get the maximum value from the array ; Remove every element of the array from the maximum value of the array ; Function to print the modified array after k operations ; If k is odd then remove the minimum element of the array from every element of the array ; Else remove every element of the array from the maximum value from the array ; Print the modified array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; } void removeMin ( int arr [ ] , int n ) { int i , minVal = arr [ 0 ] ; for ( i = 1 ; i < n ; i ++ ) minVal = min ( minVal , arr [ i ] ) ; for ( i = 0 ; i < n ; i ++ ) arr [ i ] = arr [ i ] - minVal ; } void removeFromMax ( int arr [ ] , int n ) { int i , maxVal = arr [ 0 ] ; for ( i = 1 ; i < n ; i ++ ) maxVal = max ( maxVal , arr [ i ] ) ; for ( i = 0 ; i < n ; i ++ ) arr [ i ] = maxVal - arr [ i ] ; } void modifyArray ( int arr [ ] , int n , int k ) { if ( k % 2 == 0 ) removeMin ( arr , n ) ; else removeFromMax ( arr , n ) ; printArray ( arr , n ) ; } int main ( ) { int arr [ ] = { 4 , 8 , 12 , 16 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 2 ; modifyArray ( arr , n , k ) ; return 0 ; } |
Maximum product from array such that frequency sum of all repeating elements in product is less than or equal to 2 * k | C ++ implementation of the approach ; Function to return the maximum product value ; To store the product ; Sort the array ; Efficiently finding product including every element once ; Storing values in hash map ; Including the greater repeating values so that product can be maximized ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE ll maxProd ( int arr [ ] , int n , int k ) { ll product = 1 ; unordered_map < int , int > s ; sort ( arr , arr + n ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ arr [ i ] ] == 0 ) { product = product * arr [ i ] ; } s [ arr [ i ] ] = s [ arr [ i ] ] + 1 ; } for ( int j = n - 1 ; j >= 0 && k > 0 ; j -- ) { if ( ( k > ( s [ arr [ j ] ] - 1 ) ) && ( ( s [ arr [ j ] ] - 1 ) > 0 ) ) { product *= pow ( arr [ j ] , s [ arr [ j ] ] - 1 ) ; k = k - s [ arr [ j ] ] + 1 ; s [ arr [ j ] ] = 0 ; } if ( k <= ( s [ arr [ j ] ] - 1 ) && ( ( s [ arr [ j ] ] - 1 ) > 0 ) ) { product *= pow ( arr [ j ] , k ) ; break ; } } return product ; } int main ( ) { int arr [ ] = { 5 , 6 , 7 , 8 , 2 , 5 , 6 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 2 ; cout << maxProd ( arr , n , k ) ; return 0 ; } |
Merge K sorted arrays of different sizes | ( Divide and Conquer Approach ) | C ++ program to merge K sorted arrays of different arrays ; Function to merge two arrays ; array to store the result after merging l and r ; variables to store the current pointers for l and r ; loop to merge l and r using two pointer ; Function to merge all the arrays ; 2D - array to store the results of a step temporarily ; Loop to make pairs of arrays and merge them ; To clear the data of previous steps ; Returning the required output array ; Driver Code ; Input arrays ; Merged sorted array | #include <iostream> NEW_LINE #include <vector> NEW_LINE using namespace std ; vector < int > mergeTwoArrays ( vector < int > l , vector < int > r ) { vector < int > ret ; int l_in = 0 , r_in = 0 ; while ( l_in + r_in < l . size ( ) + r . size ( ) ) { if ( l_in != l . size ( ) && ( r_in == r . size ( ) l [ l_in ] < r [ r_in ] ) ) { ret . push_back ( l [ l_in ] ) ; l_in ++ ; } else { ret . push_back ( r [ r_in ] ) ; r_in ++ ; } } return ret ; } vector < int > mergeArrays ( vector < vector < int > > arr ) { vector < vector < int > > arr_s ; while ( arr . size ( ) != 1 ) { arr_s . clear ( ) ; for ( int i = 0 ; i < arr . size ( ) ; i += 2 ) { if ( i == arr . size ( ) - 1 ) arr_s . push_back ( arr [ i ] ) ; else arr_s . push_back ( mergeTwoArrays ( arr [ i ] , arr [ i + 1 ] ) ) ; } arr = arr_s ; } return arr [ 0 ] ; } int main ( ) { vector < vector < int > > arr { { 3 , 13 } , { 8 , 10 , 11 } , { 9 , 15 } } ; vector < int > output = mergeArrays ( arr ) ; for ( int i = 0 ; i < output . size ( ) ; i ++ ) cout << output [ i ] << " β " ; return 0 ; } |
Minimize the sum of the squares of the sum of elements of each group the array is divided into | C ++ implementation of the approach ; Function to return the minimized sum ; Sort the array to pair the elements ; Variable to hold the answer ; Pair smallest with largest , second smallest with second largest , and so on ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned long long findAnswer ( int n , vector < int > & arr ) { sort ( arr . begin ( ) , arr . end ( ) ) ; unsigned long long sum = 0 ; for ( int i = 0 ; i < n / 2 ; ++ i ) { sum += ( arr [ i ] + arr [ n - i - 1 ] ) * ( arr [ i ] + arr [ n - i - 1 ] ) ; } return sum ; } int main ( ) { std :: vector < int > arr = { 53 , 28 , 143 , 5 } ; int n = arr . size ( ) ; cout << findAnswer ( n , arr ) ; } |
Merge K sorted arrays | Set 3 ( Using Divide and Conquer Approach ) | C ++ program to merge K sorted arrays ; Function to perform merge operation ; to store the starting point of left and right array ; To store the size of left and right array ; array to temporarily store left and right array ; storing data in left array ; storing data in right array ; to store the current index of temporary left and right array ; to store the current index for output array ; two pointer merge for two sorted arrays ; Code to drive merge - sort and create recursion tree ; base step to initialize the output array before performing merge operation ; To sort left half ; To sort right half ; Merge the left and right half ; Driver Function ; input 2D - array ; Number of arrays ; Output array ; Print merged array | #include <iostream> NEW_LINE #define n 4 NEW_LINE using namespace std ; void merge ( int l , int r , int * output ) { int l_in = l * n , r_in = ( ( l + r ) / 2 + 1 ) * n ; int l_c = ( ( l + r ) / 2 - l + 1 ) * n ; int r_c = ( r - ( l + r ) / 2 ) * n ; int l_arr [ l_c ] , r_arr [ r_c ] ; for ( int i = 0 ; i < l_c ; i ++ ) l_arr [ i ] = output [ l_in + i ] ; for ( int i = 0 ; i < r_c ; i ++ ) r_arr [ i ] = output [ r_in + i ] ; int l_curr = 0 , r_curr = 0 ; int in = l_in ; while ( l_curr + r_curr < l_c + r_c ) { if ( r_curr == r_c || ( l_curr != l_c && l_arr [ l_curr ] < r_arr [ r_curr ] ) ) output [ in ] = l_arr [ l_curr ] , l_curr ++ , in ++ ; else output [ in ] = r_arr [ r_curr ] , r_curr ++ , in ++ ; } } void divide ( int l , int r , int * output , int arr [ ] [ n ] ) { if ( l == r ) { for ( int i = 0 ; i < n ; i ++ ) output [ l * n + i ] = arr [ l ] [ i ] ; return ; } divide ( l , ( l + r ) / 2 , output , arr ) ; divide ( ( l + r ) / 2 + 1 , r , output , arr ) ; merge ( l , r , output ) ; } int main ( ) { int arr [ ] [ n ] = { { 5 , 7 , 15 , 18 } , { 1 , 8 , 9 , 17 } , { 1 , 4 , 7 , 7 } } ; int k = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int * output = new int [ n * k ] ; divide ( 0 , k - 1 , output , arr ) ; for ( int i = 0 ; i < n * k ; i ++ ) cout << output [ i ] << " β " ; return 0 ; } |
Make palindromic string non | CPP Program to rearrange letters of string to find a non - palindromic string if it exists ; Function to print the non - palindromic string if it exists , otherwise prints - 1 ; If all characters are not same , set flag to 1 ; Update frequency of the current character ; If all characters are same ; Print characters in sorted manner ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findNonPalinString ( string s ) { int freq [ 26 ] = { 0 } , flag = 0 ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { if ( s [ i ] != s [ 0 ] ) flag = 1 ; freq [ s [ i ] - ' a ' ] ++ ; } if ( ! flag ) cout << " - 1" ; else { for ( int i = 0 ; i < 26 ; i ++ ) for ( int j = 0 ; j < freq [ i ] ; j ++ ) cout << char ( ' a ' + i ) ; } } int main ( ) { string s = " abba " ; findNonPalinString ( s ) ; return 0 ; } |
Minimum operations of given type to make all elements of a matrix equal | C ++ implementation of the approach ; Function to return the minimum number of operations required ; Create another array to store the elements of matrix ; If not possible ; Sort the array to get median ; To count the minimum operations ; If there are even elements , then there are two medians . We consider the best of two as answer . ; Return minimum operations required ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperations ( int n , int m , int k , vector < vector < int > > & matrix ) { vector < int > arr ( n * m , 0 ) ; int mod = matrix [ 0 ] [ 0 ] % k ; for ( int i = 0 ; i < n ; ++ i ) { for ( int j = 0 ; j < m ; ++ j ) { arr [ i * m + j ] = matrix [ i ] [ j ] ; if ( matrix [ i ] [ j ] % k != mod ) { return -1 ; } } } sort ( arr . begin ( ) , arr . end ( ) ) ; int median = arr [ ( n * m ) / 2 ] ; int minOperations = 0 ; for ( int i = 0 ; i < n * m ; ++ i ) minOperations += abs ( arr [ i ] - median ) / k ; if ( ( n * m ) % 2 == 0 ) { int median2 = arr [ ( ( n * m ) / 2 ) - 1 ] ; int minOperations2 = 0 ; for ( int i = 0 ; i < n * m ; ++ i ) minOperations2 += abs ( arr [ i ] - median2 ) / k ; minOperations = min ( minOperations , minOperations2 ) ; } return minOperations ; } int main ( ) { vector < vector < int > > matrix = { { 2 , 4 , 6 } , { 8 , 10 , 12 } , { 14 , 16 , 18 } , { 20 , 22 , 24 } } ; int n = matrix . size ( ) ; int m = matrix [ 0 ] . size ( ) ; int k = 2 ; cout << minOperations ( n , m , k , matrix ) ; return 0 ; } |
Count distinct elements in an array | C ++ program to count distinct elements in a given array ; Pick all elements one by one ; If not printed earlier , then print it ; Driver program to test above function | #include <iostream> NEW_LINE using namespace std ; int countDistinct ( int arr [ ] , int n ) { int res = 1 ; for ( int i = 1 ; i < n ; i ++ ) { int j = 0 ; for ( j = 0 ; j < i ; j ++ ) if ( arr [ i ] == arr [ j ] ) break ; if ( i == j ) res ++ ; } return res ; } int main ( ) { int arr [ ] = { 12 , 10 , 9 , 45 , 2 , 10 , 10 , 45 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countDistinct ( arr , n ) ; return 0 ; } |
Count distinct elements in an array | C ++ program to count all distinct elements in a given array ; First sort the array so that all occurrences become consecutive ; Traverse the sorted array ; Move the index ahead while there are duplicates ; Driver program to test above function | #include <algorithm> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int countDistinct ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { while ( i < n - 1 && arr [ i ] == arr [ i + 1 ] ) i ++ ; res ++ ; } return res ; } int main ( ) { int arr [ ] = { 6 , 10 , 5 , 4 , 9 , 120 , 4 , 6 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countDistinct ( arr , n ) ; return 0 ; } |
Choose n elements such that their mean is maximum | C ++ implementation of the approach ; Utility function to print the contents of an array ; Function to print the array with maximum mean ; Sort the original array ; Construct new array ; Print the resultant array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; } void printMaxMean ( int arr [ ] , int n ) { int newArr [ n ] ; sort ( arr , arr + 2 * n ) ; for ( int i = 0 ; i < n ; i ++ ) newArr [ i ] = arr [ i + n ] ; printArray ( newArr , n ) ; } int main ( ) { int arr [ ] = { 4 , 8 , 3 , 1 , 3 , 7 , 0 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printMaxMean ( arr , n / 2 ) ; return 0 ; } |
Average of remaining elements after removing K largest and K smallest elements from array | C ++ implementation of the above approach ; Function to find average ; base case if 2 * k >= n means all element get removed ; first sort all elements ; sum of req number ; find average ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; double average ( int arr [ ] , int n , int k ) { double total = 0 ; if ( 2 * k >= n ) return 0 ; sort ( arr , arr + n ) ; int start = k , end = n - k - 1 ; for ( int i = start ; i <= end ; i ++ ) total += arr [ i ] ; return ( total / ( n - 2 * k ) ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 4 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 2 ; cout << average ( arr , n , k ) << endl ; return 0 ; } |
Minimum sum after subtracting multiples of k from the elements of the array | C ++ program of the above approach ; function to calculate minimum sum after transformation ; no element can be reduced further ; if all the elements of the array are identical ; check if a [ i ] can be reduced to a [ 0 ] ; one of the elements cannot be reduced to be equal to the other elements ; if k = 1 then all elements can be reduced to 1 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int min_sum ( int n , int k , int a [ ] ) { sort ( a , a + n ) ; if ( a [ 0 ] < 0 ) return -1 ; if ( k == 0 ) { if ( a [ 0 ] == a [ n - 1 ] ) return ( n * a [ 0 ] ) ; else return -1 ; } else { int f = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int p = a [ i ] - a [ 0 ] ; if ( p % k == 0 ) continue ; else { f = 1 ; break ; } } if ( f ) return -1 ; else { if ( k == 1 ) return n ; else return ( n * ( a [ 0 ] % k ) ) ; } } } int main ( ) { int arr [ ] = { 2 , 3 , 4 , 5 } ; int K = 1 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << min_sum ( N , K , arr ) ; return 0 ; } |
In | C ++ program in - place Merge Sort ; Merges two subarrays of arr [ ] . First subarray is arr [ l . . m ] Second subarray is arr [ m + 1. . r ] Inplace Implementation ; If the direct merge is already sorted ; Two pointers to maintain start of both arrays to merge ; If element 1 is in right place ; Shift all the elements between element 1 element 2 , right by 1. ; Update all the pointers ; l is for left index and r is right index of the sub - array of arr to be sorted ; Same as ( l + r ) / 2 , but avoids overflow for large l and r ; Sort first and second halves ; Function to print an array ; Driver program to test above functions | #include <iostream> NEW_LINE using namespace std ; void merge ( int arr [ ] , int start , int mid , int end ) { int start2 = mid + 1 ; if ( arr [ mid ] <= arr [ start2 ] ) { return ; } while ( start <= mid && start2 <= end ) { if ( arr [ start ] <= arr [ start2 ] ) { start ++ ; } else { int value = arr [ start2 ] ; int index = start2 ; while ( index != start ) { arr [ index ] = arr [ index - 1 ] ; index -- ; } arr [ start ] = value ; start ++ ; mid ++ ; start2 ++ ; } } } void mergeSort ( int arr [ ] , int l , int r ) { if ( l < r ) { int m = l + ( r - l ) / 2 ; mergeSort ( arr , l , m ) ; mergeSort ( arr , m + 1 , r ) ; merge ( arr , l , m , r ) ; } } void printArray ( int A [ ] , int size ) { int i ; for ( i = 0 ; i < size ; i ++ ) cout << " β " << A [ i ] ; cout << " STRNEWLINE " ; } int main ( ) { int arr [ ] = { 12 , 11 , 13 , 5 , 6 , 7 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; mergeSort ( arr , 0 , arr_size - 1 ) ; printArray ( arr , arr_size ) ; return 0 ; } |
Minimum Increment / decrement to make array elements equal | C ++ program to find minimum Increment or decrement to make array elements equal ; Function to return minimum operations need to be make each element of array equal ; Initialize cost to 0 ; Sort the array ; Middle element ; Find Cost ; If n , is even . Take minimum of the Cost obtained by considering both middle elements ; Find cost again ; Take minimum of two cost ; Return total cost ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minCost ( int A [ ] , int n ) { int cost = 0 ; sort ( A , A + n ) ; int K = A [ n / 2 ] ; for ( int i = 0 ; i < n ; ++ i ) cost += abs ( A [ i ] - K ) ; if ( n % 2 == 0 ) { int tempCost = 0 ; K = A [ ( n / 2 ) - 1 ] ; for ( int i = 0 ; i < n ; ++ i ) tempCost += abs ( A [ i ] - K ) ; cost = min ( cost , tempCost ) ; } return cost ; } int main ( ) { int A [ ] = { 1 , 6 , 7 , 10 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << minCost ( A , n ) ; return 0 ; } |
Print array elements in alternatively increasing and decreasing order | C ++ program to print array elements in alternative increasing and decreasing order ; Function to print array elements in alternative increasing and decreasing order ; First sort the array in increasing order ; start with 2 elements in increasing order ; till all the elements are not printed ; printing the elements in increasing order ; else printing the elements in decreasing order ; increasing the number of elements to printed in next iteration ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printArray ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int l = 0 , r = n - 1 , flag = 0 , i ; int k = 2 ; while ( l <= r ) { if ( flag == 0 ) { for ( i = l ; i < l + k && i <= r ; i ++ ) cout << arr [ i ] << " β " ; flag = 1 ; l = i ; } { for ( i = r ; i > r - k && i >= l ; i -- ) cout << arr [ i ] << " β " ; flag = 0 ; r = i ; } k ++ ; } } int main ( ) { int n = 6 ; int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; printArray ( arr , n ) ; 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 pairs whose product equal to given ' value ' ; The loop terminates when either of two pointers become NULL , or they cross each other ( second -> next == first ) , or they become same ( first == second ) ; pair found ; increment count ; move first in forward direction ; move second in backward direction ; if product is greater than ' value ' move second in backward direction ; else move first in forward direction ; required count of pairs ; function to count triplets in a sorted doubly linked list whose product is equal to a given value ' x ' ; if list is empty ; get pointer to the last node of the doubly linked list ; traversing the doubly linked list ; for each current node ; count pairs with product ( x / current -> data ) in the range first to last and add it to the ' count ' of triplets ; required count of triplets ; 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 ; 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 countPairs ( struct Node * first , struct Node * second , int value ) { int count = 0 ; while ( first != NULL && second != NULL && first != second && second -> next != first ) { if ( ( first -> data * second -> data ) == value ) { count ++ ; first = first -> next ; second = second -> prev ; } else if ( ( first -> data * second -> data ) > value ) second = second -> prev ; else first = first -> next ; } return count ; } int countTriplets ( struct Node * head , int x ) { if ( head == NULL ) return 0 ; struct Node * current , * first , * last ; int count = 0 ; last = head ; while ( last -> next != NULL ) last = last -> next ; for ( current = head ; current != NULL ; current = current -> next ) { first = current -> next ; count += countPairs ( first , last , x / current -> data ) ; } return count ; } 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 ; } |
Check if the characters of a given string are in alphabetical order | C ++ implementation of above approach ; Function that checks whether the string is in alphabetical order or not ; if element at index ' i ' is less than the element at index ' i - 1' then the string is not sorted ; Driver code ; check whether the string is in alphabetical order or not | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isAlphabaticOrder ( string s ) { int n = s . length ( ) ; for ( int i = 1 ; i < n ; i ++ ) { if ( s [ i ] < s [ i - 1 ] ) return false ; } return true ; } int main ( ) { string s = " aabbbcc " ; if ( isAlphabaticOrder ( s ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Product of non | C ++ program to find the product of all non - repeated elements in an array ; Function to find the product of all non - repeated elements in an array ; sort all elements of array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findProduct ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int prod = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] != arr [ i + 1 ] ) prod = prod * arr [ i ] ; } return prod ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 1 , 1 , 4 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << findProduct ( arr , n ) ; return 0 ; } |
Check if it is possible to rearrange rectangles in a non | C ++ implementation of above approach ; Function to check if it possible to form rectangles with heights as non - ascending ; set maximum ; replace the maximum with previous maximum ; replace the minimum with previous minimum ; print NO if the above two conditions fail at least once ; Driver code ; initialize the number of rectangles ; initialize n rectangles with length and breadth | #include <bits/stdc++.h> NEW_LINE using namespace std ; int rotateRec ( int n , int L [ ] , int B [ ] ) { int m = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { if ( max ( L [ i ] , B [ i ] ) <= m ) m = max ( L [ i ] , B [ i ] ) ; else if ( min ( L [ i ] , B [ i ] ) <= m ) m = min ( L [ i ] , B [ i ] ) ; else { return 0 ; } } return 1 ; } int main ( ) { int n = 3 ; int L [ ] = { 5 , 5 , 6 } ; int B [ ] = { 6 , 7 , 8 } ; rotateRec ( n , L , B ) == 1 ? cout << " YES " : cout << " NO " ; return 0 ; } |
Find a point such that sum of the Manhattan distances is minimized | C ++ implementation of above approach ; Function to print the required points which minimizes the sum of Manhattan distances ; Sorting points in all k dimension ; Output the required k points ; Driver code ; function call to print required points | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minDistance ( int n , int k , vector < vector < int > > & point ) { for ( int i = 0 ; i < k ; ++ i ) sort ( point [ i ] . begin ( ) , point [ i ] . end ( ) ) ; for ( int i = 0 ; i < k ; ++ i ) cout << point [ i ] [ ( ceil ( ( double ) n / 2 ) - 1 ) ] << " β " ; } int main ( ) { int n = 4 , k = 4 ; vector < vector < int > > point = { { 1 , 5 , 2 , 4 } , { 6 , 2 , 0 , 6 } , { 9 , 5 , 1 , 3 } , { 6 , 7 , 5 , 9 } } ; minDistance ( n , k , point ) ; return 0 ; } |
Sort first k values in ascending order and remaining n | C ++ program to sort first k elements in increasing order and remaining n - k elements in decreasing ; Function to sort the array ; Store the k elements in an array ; Store the remaining n - k elements in an array ; sorting the array from 0 to k - 1 places ; sorting the array from k to n places ; storing the values in the final array arr ; printing the array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printOrder ( int arr [ ] , int n , int k ) { int len1 = k , len2 = n - k ; int arr1 [ k ] , arr2 [ n - k ] ; for ( int i = 0 ; i < k ; i ++ ) arr1 [ i ] = arr [ i ] ; for ( int i = k ; i < n ; i ++ ) arr2 [ i - k ] = arr [ i ] ; sort ( arr1 , arr1 + len1 ) ; sort ( arr2 , arr2 + len2 ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i < k ) arr [ i ] = arr1 [ i ] ; else { arr [ i ] = arr2 [ len2 - 1 ] ; len2 -- ; } } for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; } int main ( ) { int arr [ ] = { 5 , 4 , 6 , 2 , 1 , 3 , 8 , 9 , -1 } ; int k = 4 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printOrder ( arr , n , k ) ; 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 ; Declare a hash array of size 10 and initialize all the elements to zero ; store the number of occurrences of the digits in the given array into the hash table ; Traverse the hash in descending order to print the required number ; Print the number of times a digits occurs ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findMaxNum ( int arr [ ] , int n ) { int hash [ 10 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { hash [ arr [ i ] ] ++ ; } for ( int i = 9 ; i >= 0 ; i -- ) { for ( int j = 0 ; j < hash [ i ] ; j ++ ) cout << i ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findMaxNum ( arr , n ) ; return 0 ; } |
Sort a nearly sorted array using STL | A STL based C ++ program to sort a nearly sorted array . ; Given an array of size n , where every element is k away from its target position , sorts the array in O ( n Log n ) time . ; Sort the array using inbuilt function ; An utility function to print array elements ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sortK ( int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; } void printArray ( int arr [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) cout << arr [ i ] << " β " ; cout << endl ; } int main ( ) { int k = 3 ; int arr [ ] = { 2 , 6 , 3 , 12 , 56 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortK ( arr , n , k ) ; cout << " Following β is β sorted β array STRNEWLINE " ; printArray ( arr , n ) ; return 0 ; } |
Equally divide into two sets such that one set has maximum distinct elements | C ++ program to equally divide n elements into two sets such that second set has maximum distinct elements . ; Driver code | #include <algorithm> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int distribution ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int count = 1 ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] > arr [ i - 1 ] ) count ++ ; return min ( count , n / 2 ) ; } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 1 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << distribution ( arr , n ) << endl ; return 0 ; } |
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 to print pairs of positive and negative values present in the array ; Store all the positive elements in the unordered_set ; Start traversing the array ; Check if the positive value of current element exists in the set or not ; { Print that pair ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printPairs ( int arr [ ] , int n ) { unordered_set < int > pairs ; bool pair_exists = false ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] > 0 ) pairs . insert ( arr [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < 0 ) if ( pairs . find ( - arr [ i ] ) != pairs . end ( ) ) cout << arr [ i ] << " , β " << - arr [ i ] << endl ; pair_exists = true ; } } 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 ; } |
Sort 3 numbers | C ++ program to sort an array of size 3 | #include <algorithm> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int main ( ) { int a [ ] = { 10 , 12 , 5 } ; sort ( a , a + 3 ) ; for ( int i = 0 ; i < 3 ; i ++ ) cout << a [ i ] << " β " ; return 0 ; } |
Print triplets with sum less than k | A Simple C ++ program to count triplets with sum smaller than a given value ; Fix the first element as A [ i ] ; Fix the second element as A [ j ] ; Now look for the third number ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int printTriplets ( int arr [ ] , int n , int sum ) { for ( int i = 0 ; i < n - 2 ; i ++ ) { for ( int j = i + 1 ; j < n - 1 ; j ++ ) { for ( int k = j + 1 ; k < n ; k ++ ) if ( arr [ i ] + arr [ j ] + arr [ k ] < sum ) cout << arr [ i ] << " , β " << arr [ j ] << " , β " << arr [ k ] << endl ; } } } int main ( ) { int arr [ ] = { 5 , 1 , 3 , 4 , 7 } ; int n = sizeof arr / sizeof arr [ 0 ] ; int sum = 12 ; printTriplets ( arr , n , sum ) ; return 0 ; } |
Count number of triplets in an array having sum in the range [ a , b ] | C ++ program to count triplets with sum that lies in given range [ a , b ] . ; Function to count triplets ; Initialize result ; Fix the first element as A [ i ] ; Fix the second element as A [ j ] ; Now look for the third number ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countTriplets ( int arr [ ] , int n , int a , int b ) { int ans = 0 ; for ( int i = 0 ; i < n - 2 ; i ++ ) { for ( int j = i + 1 ; j < n - 1 ; j ++ ) { for ( int k = j + 1 ; k < n ; k ++ ) if ( arr [ i ] + arr [ j ] + arr [ k ] >= a && arr [ i ] + arr [ j ] + arr [ k ] <= b ) ans ++ ; } } return ans ; } int main ( ) { int arr [ ] = { 2 , 7 , 5 , 3 , 8 , 4 , 1 , 9 } ; int n = sizeof arr / sizeof arr [ 0 ] ; int a = 8 , b = 16 ; cout << countTriplets ( arr , n , a , b ) << endl ; return 0 ; } |
Count number of triplets in an array having sum in the range [ a , b ] | C ++ program to count triplets with sum that lies in given range [ a , b ] . ; Function to find count of triplets having sum less than or equal to val . ; sort the input array . ; Initialize result ; to store sum ; Fix the first element ; Initialize other two elements as corner elements of subarray arr [ j + 1. . k ] ; Use Meet in the Middle concept . ; If sum of current triplet is greater , then to reduce it decrease k . ; If sum is less than or equal to given value , then add possible triplets ( k - j ) to result . ; Function to return count of triplets having sum in range [ a , b ] . ; to store count of triplets . ; Find count of triplets having sum less than or equal to b and subtract count of triplets having sum less than or equal to a - 1. ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countTripletsLessThan ( int arr [ ] , int n , int val ) { sort ( arr , arr + n ) ; int ans = 0 ; int j , k ; int sum ; for ( int i = 0 ; i < n - 2 ; i ++ ) { j = i + 1 ; k = n - 1 ; while ( j != k ) { sum = arr [ i ] + arr [ j ] + arr [ k ] ; if ( sum > val ) k -- ; else { ans += ( k - j ) ; j ++ ; } } } return ans ; } int countTriplets ( int arr [ ] , int n , int a , int b ) { int res ; res = countTripletsLessThan ( arr , n , b ) - countTripletsLessThan ( arr , n , a - 1 ) ; return res ; } int main ( ) { int arr [ ] = { 2 , 7 , 5 , 3 , 8 , 4 , 1 , 9 } ; int n = sizeof arr / sizeof arr [ 0 ] ; int a = 8 , b = 16 ; cout << countTriplets ( arr , n , a , b ) << endl ; return 0 ; } |
Multiset Equivalence Problem | C ++ program to check if two given multisets are equivalent ; Create two unordered maps m1 and m2 and insert values of both vectors . ; Now we check if both unordered_maps are same of not . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool areSame ( vector < int > & a , vector < int > & b ) { if ( a . size ( ) != b . size ( ) ) return false ; unordered_map < int , int > m1 , m2 ; for ( int i = 0 ; i < a . size ( ) ; i ++ ) { m1 [ a [ i ] ] ++ ; m2 [ b [ i ] ] ++ ; } for ( auto x : m1 ) { if ( m2 . find ( x . first ) == m2 . end ( ) m2 [ x . first ] != x . second ) return false ; } return true ; } int main ( ) { vector < int > a ( { 7 , 7 , 5 } ) , b ( { 7 , 7 , 5 } ) ; if ( areSame ( a , b ) ) cout << " Yes STRNEWLINE " ; else cout << " No STRNEWLINE " ; return 0 ; } |
Sum of Areas of Rectangles possible for an array | CPP code to find sum of all area rectangle possible ; Function to find area of rectangles ; sorting the array in descending order ; store the final sum of all the rectangles area possible ; temporary variable to store the length of rectangle ; Selecting the length of rectangle so that difference between any two number is 1 only . Here length is selected so flag is set ; flag is set means we have got length of rectangle ; length is set to a [ i + 1 ] so that if a [ i ] a [ i + 1 ] is less than by 1 then also we have the correct choice for length ; incrementing the counter one time more as we have considered a [ i + 1 ] element also so . ; Selecting the width of rectangle so that difference between any two number is 1 only . Here width is selected so now flag is again unset for next rectangle ; area is calculated for rectangle ; flag is set false for another rectangle which we can get from elements in array ; incrementing the counter one time more as we have considered a [ i + 1 ] element also so . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int MaxTotalRectangleArea ( int a [ ] , int n ) { sort ( a , a + n , greater < int > ( ) ) ; int sum = 0 ; bool flag = false ; int len ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( a [ i ] == a [ i + 1 ] a [ i ] - a [ i + 1 ] == 1 ) && ( ! flag ) ) { flag = true ; len = a [ i + 1 ] ; i ++ ; } else if ( ( a [ i ] == a [ i + 1 ] a [ i ] - a [ i + 1 ] == 1 ) && ( flag ) ) { sum = sum + a [ i + 1 ] * len ; flag = false ; i ++ ; } } return sum ; } int main ( ) { int a [ ] = { 10 , 10 , 10 , 10 , 11 , 10 , 11 , 10 , 9 , 9 , 8 , 8 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << MaxTotalRectangleArea ( a , n ) ; return 0 ; } |
Insertion sort to sort even and odd positioned elements in different orders | C ++ program to sort even positioned elements in ascending order and odd positioned elements in descending order . ; Function to calculate the given problem . ; checking for odd positioned . ; Inserting even positioned elements in ascending order . ; sorting the even positioned . ; Inserting odd positioned elements in descending order . ; A utility function to print an array of size n ; Driver program to test insertion sort | #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE void evenOddInsertionSort ( int arr [ ] , int n ) { for ( int i = 2 ; i < n ; i ++ ) { int j = i - 2 ; int temp = arr [ i ] ; if ( ( i + 1 ) & 1 == 1 ) { while ( temp >= arr [ j ] && j >= 0 ) { arr [ j + 2 ] = arr [ j ] ; j -= 2 ; } arr [ j + 2 ] = temp ; } else { while ( temp <= arr [ j ] && j >= 0 ) { arr [ j + 2 ] = arr [ j ] ; j -= 2 ; } arr [ j + 2 ] = temp ; } } } void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) printf ( " % d β " , arr [ i ] ) ; printf ( " STRNEWLINE " ) ; } int main ( ) { int arr [ ] = { 12 , 11 , 13 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; evenOddInsertionSort ( arr , n ) ; printArray ( arr , n ) ; return 0 ; } |
Stable sort for descending order | Bubble sort implementation to sort elements in descending order . ; Sorts a [ ] in descending order using bubble sort . ; Driver code | #include <iostream> NEW_LINE #include <vector> NEW_LINE using namespace std ; void print ( vector < int > a , int n ) { for ( int i = 0 ; i <= n ; i ++ ) cout << a [ i ] << " β " ; cout << endl ; } void sort ( vector < int > a , int n ) { for ( int i = n ; i >= 0 ; i -- ) for ( int j = n ; j > n - i ; j -- ) if ( a [ j ] > a [ j - 1 ] ) swap ( a [ j ] , a [ j - 1 ] ) ; print ( a , n ) ; } int main ( ) { int n = 7 ; vector < int > a ; a . push_back ( 2 ) ; a . push_back ( 4 ) ; a . push_back ( 3 ) ; a . push_back ( 2 ) ; a . push_back ( 4 ) ; a . push_back ( 5 ) ; a . push_back ( 3 ) ; sort ( a , n - 1 ) ; return 0 ; } |
Subtraction in the Array | C ++ implementation of the approach ; Function to perform the given operation on arr [ ] ; Skip elements which are 0 ; Pick smallest non - zero element ; If all the elements of arr [ ] are 0 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE void operations ( int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; ll i = 0 , sum = 0 ; while ( k -- ) { while ( i < n && arr [ i ] - sum == 0 ) i ++ ; if ( i < n && arr [ i ] - sum > 0 ) { cout << arr [ i ] - sum << " β " ; sum = arr [ i ] ; } else cout << 0 << endl ; } } int main ( ) { int k = 5 ; int arr [ ] = { 3 , 6 , 4 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; operations ( arr , n , k ) ; return 0 ; } |
Sort an array of 0 s , 1 s and 2 s ( Simple Counting ) | Simple C ++ program to sort an array of 0 s 1 s and 2 s . ; Variables to maintain the count of 0 ' s , β β 1' s and 2 's in the array ; Putting the 0 's in the array in starting. ; Putting the 1 ' s β in β the β array β after β the β 0' s . ; Putting the 2 ' s β in β the β array β after β the β 1' s ; Prints the array ; Driver code | #include <iostream> NEW_LINE using namespace std ; void sort012 ( int * arr , int n ) { int count0 = 0 , count1 = 0 , count2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == 0 ) count0 ++ ; if ( arr [ i ] == 1 ) count1 ++ ; if ( arr [ i ] == 2 ) count2 ++ ; } for ( int i = 0 ; i < count0 ; i ++ ) arr [ i ] = 0 ; for ( int i = count0 ; i < ( count0 + count1 ) ; i ++ ) arr [ i ] = 1 ; for ( int i = ( count0 + count1 ) ; i < n ; i ++ ) arr [ i ] = 2 ; return ; } void printArray ( int * arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; cout << endl ; } int main ( ) { int arr [ ] = { 0 , 1 , 1 , 0 , 1 , 2 , 1 , 2 , 0 , 0 , 0 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sort012 ( arr , n ) ; printArray ( arr , n ) ; return 0 ; } |
Alternate Lower Upper String Sort | C ++ program for unusul string sorting ; Function for alternate sorting of string ; Count occurrences of individual lower case and upper case characters ; Traverse through count arrays and one by one pick characters . Below loop takes O ( n ) time considering the MAX is constant . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 26 NEW_LINE void alternateSort ( string & s ) { int n = s . length ( ) ; int lCount [ MAX ] = { 0 } , uCount [ MAX ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { if ( isupper ( s [ i ] ) ) uCount [ s [ i ] - ' A ' ] ++ ; else lCount [ s [ i ] - ' a ' ] ++ ; } int i = 0 , j = 0 , k = 0 ; while ( k < n ) { while ( i < MAX && uCount [ i ] == 0 ) i ++ ; if ( i < MAX ) { s [ k ++ ] = ' A ' + i ; uCount [ i ] -- ; } while ( j < MAX && lCount [ j ] == 0 ) j ++ ; if ( j < MAX ) { s [ k ++ ] = ' a ' + j ; lCount [ j ] -- ; } } } int main ( ) { string str = " bAwutndekWEdkd " ; alternateSort ( str ) ; cout << str << " STRNEWLINE " ; } |
Job Selection Problem | C ++ implementation of the above approach ; Create a min - heap ( priority queue ) ; Add all goods to the Queue ; Pop Goods from Queue as long as it is not empty ; Print the good ; Add the Queue to the vector so that total voulme can be calculated ; Calclulating volume of goods left when all are produced . Move from right to left of sequence multiplying each volume by increasing powers of 1 - P starting from 0 ; Print result ; Driver code ; For implementation simplicity days are numbered from 1 to N . Hence 1 based indexing is used ; 10 % loss per day | #include <bits/stdc++.h> NEW_LINE using namespace std ; void optimum_sequence_jobs ( vector < int > & V , double P ) { int j = 1 , N = V . size ( ) - 1 ; double result = 0 ; priority_queue < int , vector < int > , greater < int > > Queue ; for ( int i = 1 ; i <= N ; i ++ ) Queue . push ( V [ i ] ) ; while ( ! Queue . empty ( ) ) { cout << Queue . top ( ) << " β " ; V [ j ++ ] = Queue . top ( ) ; Queue . pop ( ) ; } for ( int i = N ; i >= 1 ; i -- ) result += pow ( ( 1 - P ) , N - i ) * V [ i ] ; cout << endl << result << endl ; } int main ( ) { vector < int > V { -1 , 3 , 5 , 4 , 1 , 2 , 7 , 6 , 8 , 9 , 10 } ; double P = 0.10 ; optimum_sequence_jobs ( V , P ) ; return 0 ; } |
Sum of Manhattan distances between all pairs of points | CPP Program to find sum of Manhattan distance between all the pairs of given points ; Return the sum of distance between all the pair of points . ; for each point , finding distance to rest of the point ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int distancesum ( int x [ ] , int y [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) sum += ( abs ( x [ i ] - x [ j ] ) + abs ( y [ i ] - y [ j ] ) ) ; return sum ; } int main ( ) { int x [ ] = { -1 , 1 , 3 , 2 } ; int y [ ] = { 5 , 6 , 5 , 3 } ; int n = sizeof ( x ) / sizeof ( x [ 0 ] ) ; cout << distancesum ( x , y , n ) << endl ; return 0 ; } |
Sum of Manhattan distances between all pairs of points | CPP Program to find sum of Manhattan distances between all the pairs of given points ; Return the sum of distance of one axis . ; sorting the array . ; for each point , finding the distance . ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int distancesum ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int res = 0 , sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { res += ( arr [ i ] * i - sum ) ; sum += arr [ i ] ; } return res ; } int totaldistancesum ( int x [ ] , int y [ ] , int n ) { return distancesum ( x , n ) + distancesum ( y , n ) ; } int main ( ) { int x [ ] = { -1 , 1 , 3 , 2 } ; int y [ ] = { 5 , 6 , 5 , 3 } ; int n = sizeof ( x ) / sizeof ( x [ 0 ] ) ; cout << totaldistancesum ( x , y , n ) << endl ; return 0 ; } |
Sort an array with swapping only with a special element is allowed | CPP program to sort an array by moving one space around . ; n is total number of elements . index is index of 999 or space . k is number of elements yet to be sorted . ; print the sorted array when loop reaches the base case ; else if k > 0 and space is at 0 th index swap each number with space and store index at second last index ; if space is neither start of array nor last element of array and element before it greater than / the element next to space ; first swap space and element next to space in case of { 3 , 999 , 2 } make it { 3 , 2 , 999 } ; than swap space and greater element convert { 3 , 2 , 999 } to { 999 , 2 , 3 } ; Wrapper over sortRec . ; Find index of space ( or 999 ) ; Invalid input ; driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sortRec ( int arr [ ] , int index , int k , int n ) { if ( k == 0 ) { for ( int i = 1 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; cout << 999 ; return ; } else if ( k > 0 && index == 0 ) { index = n - 2 ; for ( int i = 1 ; i <= index ; i ++ ) { arr [ i - 1 ] = arr [ i ] ; } arr [ index ] = 999 ; } if ( index - 1 >= 0 && index + 1 < n && arr [ index - 1 ] > arr [ index + 1 ] ) { swap ( arr [ index ] , arr [ index + 1 ] ) ; swap ( arr [ index - 1 ] , arr [ index + 1 ] ) ; } else swap ( arr [ index ] , arr [ index - 1 ] ) ; sortRec ( arr , index - 1 , k - 1 , n ) ; } void sort ( int arr [ ] , int n ) { int index = -1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == 999 ) { index = i ; break ; } } if ( index == -1 ) return ; sortRec ( arr , index , n , n ) ; } int main ( ) { int arr [ ] = { 3 , 2 , 999 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sort ( arr , n ) ; return 0 ; } |
Find array with k number of merge sort calls | C ++ program to find an array that can be sorted with k merge sort calls . ; We make two recursive calls , so reduce k by 2. ; Create an array with values in [ 1 , n ] ; calling unsort function ; Driver code | #include <iostream> NEW_LINE using namespace std ; void unsort ( int l , int r , int a [ ] , int & k ) { if ( k < 1 l + 1 == r ) return ; k -= 2 ; int mid = ( l + r ) / 2 ; swap ( a [ mid - 1 ] , a [ mid ] ) ; unsort ( l , mid , a , k ) ; unsort ( mid , r , a , k ) ; } void arrayWithKCalls ( int n , int k ) { if ( k % 2 == 0 ) { cout << " β NO β SOLUTION β " ; return ; } int a [ n + 1 ] ; a [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) a [ i ] = i + 1 ; k -- ; unsort ( 0 , n , a , k ) ; for ( int i = 0 ; i < n ; ++ i ) cout << a [ i ] << ' β ' ; } int main ( ) { int n = 10 , k = 17 ; arrayWithKCalls ( n , k ) ; return 0 ; } |
Program to sort string in descending order | C ++ program to sort a string of characters in descending order ; function to print string in sorted order ; Hash array to keep count of characters . Initially count of all charters is initialized to zero . ; Traverse string and increment count of characters ; ' a ' - ' a ' will be 0 , ' b ' - ' a ' will be 1 , so for location of character in count array we wil do str [ i ] - ' a ' . ; Traverse the hash array and print characters ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; void sortString ( string & str ) { int charCount [ MAX_CHAR ] = { 0 } ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) charCount [ str [ i ] - ' a ' ] ++ ; for ( int i = MAX_CHAR - 1 ; i >= 0 ; i -- ) for ( int j = 0 ; j < charCount [ i ] ; j ++ ) cout << ( char ) ( ' a ' + i ) ; } int main ( ) { string s = " alkasingh " ; sortString ( s ) ; return 0 ; } |
Median after K additional integers | CPP program to find median of an array when we are allowed to add additional K integers to it . ; Find median of array after adding k elements ; sorting the array in increasing order . ; printing the median of array . Since n + K is always odd and K < n , so median of array always lies in the range of n . ; driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printMedian ( int arr [ ] , int n , int K ) { sort ( arr , arr + n ) ; cout << arr [ ( n + K ) / 2 ] ; } int main ( ) { int arr [ ] = { 5 , 3 , 2 , 8 } ; int k = 3 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printMedian ( arr , n , k ) ; return 0 ; } |
Dual pivot Quicksort | C ++ program to implement dual pivot QuickSort ; lp means left pivot , and rp means right pivot . ; p is the left pivot , and q is the right pivot . ; if elements are less than the left pivot ; if elements are greater than or equal to the right pivot ; bring pivots to their appropriate positions . ; returning the indices of the pivots . * lp = j ; because we cannot return two elements from a function . ; Driver code | #include <iostream> NEW_LINE using namespace std ; int partition ( int * arr , int low , int high , int * lp ) ; void swap ( int * a , int * b ) { int temp = * a ; * a = * b ; * b = temp ; } void DualPivotQuickSort ( int * arr , int low , int high ) { if ( low < high ) { int lp , rp ; rp = partition ( arr , low , high , & lp ) ; DualPivotQuickSort ( arr , low , lp - 1 ) ; DualPivotQuickSort ( arr , lp + 1 , rp - 1 ) ; DualPivotQuickSort ( arr , rp + 1 , high ) ; } } int partition ( int * arr , int low , int high , int * lp ) { if ( arr [ low ] > arr [ high ] ) swap ( & arr [ low ] , & arr [ high ] ) ; int j = low + 1 ; int g = high - 1 , k = low + 1 , p = arr [ low ] , q = arr [ high ] ; while ( k <= g ) { if ( arr [ k ] < p ) { swap ( & arr [ k ] , & arr [ j ] ) ; j ++ ; } else if ( arr [ k ] >= q ) { while ( arr [ g ] > q && k < g ) g -- ; swap ( & arr [ k ] , & arr [ g ] ) ; g -- ; if ( arr [ k ] < p ) { swap ( & arr [ k ] , & arr [ j ] ) ; j ++ ; } } k ++ ; } j -- ; g ++ ; swap ( & arr [ low ] , & arr [ j ] ) ; swap ( & arr [ high ] , & arr [ g ] ) ; return g ; } int main ( ) { int arr [ ] = { 24 , 8 , 42 , 75 , 29 , 77 , 38 , 57 } ; DualPivotQuickSort ( arr , 0 , 7 ) ; cout << " Sorted β array : β " ; for ( int i = 0 ; i < 8 ; i ++ ) cout << arr [ i ] << " β " ; cout << endl ; } |
A sorting algorithm that slightly improves on selection sort | C ++ program to implement min max selection sort . ; shifting the min . ; Shifting the max . The equal condition happens if we shifted the max to arr [ min_i ] in the previous swap . ; Driver code | #include <iostream> NEW_LINE using namespace std ; void minMaxSelectionSort ( int * arr , int n ) { for ( int i = 0 , j = n - 1 ; i < j ; i ++ , j -- ) { int min = arr [ i ] , max = arr [ i ] ; int min_i = i , max_i = i ; for ( int k = i ; k <= j ; k ++ ) { if ( arr [ k ] > max ) { max = arr [ k ] ; max_i = k ; } else if ( arr [ k ] < min ) { min = arr [ k ] ; min_i = k ; } } swap ( arr [ i ] , arr [ min_i ] ) ; if ( arr [ min_i ] == max ) swap ( arr [ j ] , arr [ min_i ] ) ; else swap ( arr [ j ] , arr [ max_i ] ) ; } } int main ( ) { int arr [ ] = { 23 , 78 , 45 , 8 , 32 , 56 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minMaxSelectionSort ( arr , n ) ; printf ( " Sorted β array : STRNEWLINE " ) ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; cout << endl ; return 0 ; } |
Efficiently merging two sorted arrays with O ( 1 ) extra space | ; Find maximum element of both array ; increment by one to avoid collision of 0 and maximum element of array in modulo operation ; recover back original element to compare ; update element by adding multiplication with new number ; update element by adding multiplication with new number ; process those elements which are left in array a ; process those elements which are left in array b ; finally update elements by dividing with maximum element ; finally update elements by dividing with maximum element ; Driver Code ; Length of a ; length of b ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void mergeArray ( int a [ ] , int b [ ] , int n , int m ) { int mx = 0 ; for ( int i = 0 ; i < n ; i ++ ) { mx = max ( mx , a [ i ] ) ; } for ( int i = 0 ; i < m ; i ++ ) { mx = max ( mx , b [ i ] ) ; } mx ++ ; int i = 0 , j = 0 , k = 0 ; while ( i < n && j < m && k < ( n + m ) ) { int e1 = a [ i ] % mx ; int e2 = b [ j ] % mx ; if ( e1 <= e2 ) { if ( k < n ) a [ k ] += ( e1 * mx ) ; else b [ k - n ] += ( e1 * mx ) ; i ++ ; k ++ ; } else { if ( k < n ) a [ k ] += ( e2 * mx ) ; else b [ k - n ] += ( e2 * mx ) ; j ++ ; k ++ ; } } while ( i < n ) { int el = a [ i ] % mx ; if ( k < n ) a [ k ] += ( el * mx ) ; else b [ k - n ] += ( el * mx ) ; i ++ ; k ++ ; } while ( j < m ) { int el = b [ j ] % mx ; if ( k < n ) a [ k ] += ( el * mx ) ; else b [ k - n ] += ( el * mx ) ; j ++ ; k ++ ; } for ( int i = 0 ; i < n ; i ++ ) a [ i ] = a [ i ] / mx ; for ( int i = 0 ; i < m ; i ++ ) b [ i ] = b [ i ] / mx ; return ; } int main ( ) { int a [ ] = { 3 , 5 , 6 , 8 , 12 } ; int b [ ] = { 1 , 4 , 9 , 13 } ; int n = sizeof ( a ) / sizeof ( int ) ; int m = sizeof ( b ) / sizeof ( int ) ; mergeArray ( a , b , n , m ) ; cout << " First β array β : β " ; for ( int i = 0 ; i < n ; i ++ ) cout << a [ i ] << " β " ; cout << endl ; cout << " Second β array β : β " ; for ( int i = 0 ; i < m ; i ++ ) cout << b [ i ] << " β " ; cout << endl ; return 0 ; } |
Sort an array according to absolute difference with a given value " using β constant β extra β space " | C ++ program to sort an array based on absolute difference with a given value x . ; Below lines are similar to insertion sort ; Insert arr [ i ] at correct place ; Function to print the array ; Main Function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void arrange ( int arr [ ] , int n , int x ) { for ( int i = 1 ; i < n ; i ++ ) { int diff = abs ( arr [ i ] - x ) ; int j = i - 1 ; if ( abs ( arr [ j ] - x ) > diff ) { int temp = arr [ i ] ; while ( abs ( arr [ j ] - x ) > diff && j >= 0 ) { arr [ j + 1 ] = arr [ j ] ; j -- ; } arr [ j + 1 ] = temp ; } } } void print ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; } int main ( ) { int arr [ ] = { 10 , 5 , 3 , 9 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 7 ; arrange ( arr , n , x ) ; print ( arr , n ) ; return 0 ; } |
Check if a grid can become row | C ++ program to check if we can make a grid of character sorted using adjacent swaps . ; v [ ] is vector of strings . len is length of strings in every row . ; Driver code ; int len = 5 ; Length of strings | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( vector < string > v , int len ) { int n = v . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) sort ( v [ i ] . begin ( ) , v [ i ] . end ( ) ) ; for ( int i = 0 ; i < len - 1 ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) if ( v [ i ] [ j ] > v [ i + 1 ] [ j ] ) return false ; return true ; } int main ( ) { vector < string > v = { " ebcda " , " ihgfj " , " klmno " , " pqrst " , " yvwxu " } ; check ( v , len ) ? cout << " Yes " : cout << " No " ; return 0 ; } |
Sort first half in ascending and second half in descending order | 1 | C ++ program to print first half in ascending order and the second half in descending order ; function to print half of the array in ascending order and the other half in descending order ; sorting the array ; printing first half in ascending order ; printing second half in descending order ; driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printOrder ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; for ( int i = 0 ; i < n / 2 ; i ++ ) cout << arr [ i ] << " β " ; for ( int j = n - 1 ; j >= n / 2 ; j -- ) cout << arr [ j ] << " β " ; } int main ( ) { int arr [ ] = { 5 , 4 , 6 , 2 , 1 , 3 , 8 , -1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printOrder ( arr , n ) ; return 0 ; } |
Find the Sub | C ++ program to find subarray with sum closest to 0 ; Function to find the subarray ; Pick a starting point ; Consider current starting point as a subarray and update minimum sum and subarray indexes ; Try all subarrays starting with i ; update minimum sum and subarray indexes ; Return starting and ending indexes ; Drivers code | #include <bits/stdc++.h> NEW_LINE using namespace std ; pair < int , int > findSubArray ( int arr [ ] , int n ) { int start , end , min_sum = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { int curr_sum = arr [ i ] ; if ( min_sum > abs ( curr_sum ) ) { min_sum = abs ( curr_sum ) ; start = i ; end = i ; } for ( int j = i + 1 ; j < n ; j ++ ) { curr_sum = curr_sum + arr [ j ] ; if ( min_sum > abs ( curr_sum ) ) { min_sum = abs ( curr_sum ) ; start = i ; end = j ; } } } pair < int , int > p = make_pair ( start , end ) ; return p ; } int main ( ) { int arr [ ] = { 2 , -5 , 4 , -6 , -3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; pair < int , int > point = findSubArray ( arr , n ) ; cout << " Subarray β starting β from β " ; cout << point . first << " β to β " << point . second ; return 0 ; } |
Find shortest unique prefix for every word in a given list | Set 2 ( Using Sorting ) | C ++ program to print shortest unique prefixes for every word . ; create an array to store the results ; sort the array of strings ; compare the first string with its only right neighbor ; Store the unique prefix of a [ 1 ] from its left neighbor ; compute common prefix of a [ i ] unique from its right neighbor ; compare the new prefix with previous prefix ; store the prefix of a [ i + 1 ] unique from its left neighbour ; compute the unique prefix for the last string in sorted array ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < string > uniquePrefix ( vector < string > & a ) { int size = a . size ( ) ; vector < string > res ( size ) ; sort ( a . begin ( ) , a . end ( ) ) ; int j = 0 ; while ( j < min ( a [ 0 ] . length ( ) - 1 , a [ 1 ] . length ( ) - 1 ) ) { if ( a [ 0 ] [ j ] == a [ 1 ] [ j ] ) j ++ ; else break ; } int ind = 0 ; res [ ind ++ ] = a [ 0 ] . substr ( 0 , j + 1 ) ; string temp_prefix = a [ 1 ] . substr ( 0 , j + 1 ) ; for ( int i = 1 ; i < size - 1 ; i ++ ) { j = 0 ; while ( j < min ( a [ i ] . length ( ) - 1 , a [ i + 1 ] . length ( ) - 1 ) ) { if ( a [ i ] [ j ] == a [ i + 1 ] [ j ] ) j ++ ; else break ; } string new_prefix = a [ i ] . substr ( 0 , j + 1 ) ; if ( temp_prefix . length ( ) > new_prefix . length ( ) ) res [ ind ++ ] = temp_prefix ; else res [ ind ++ ] = new_prefix ; temp_prefix = a [ i + 1 ] . substr ( 0 , j + 1 ) ; } j = 0 ; string sec_last = a [ size - 2 ] ; string last = a [ size - 1 ] ; while ( j < min ( sec_last . length ( ) - 1 , last . length ( ) - 1 ) ) { if ( sec_last [ j ] == last [ j ] ) j ++ ; else break ; } res [ ind ] = last . substr ( 0 , j + 1 ) ; return res ; } int main ( ) { vector < string > input = { " zebra " , " dog " , " duck " , " dove " } ; vector < string > output = uniquePrefix ( input ) ; cout << " The β shortest β unique β prefixes β in β sorted β order β are β : β STRNEWLINE " ; for ( auto i : output ) cout << i << ' β ' ; 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 minimum amount to buy all candies ; Buy current candy ; And take k candies for free from the last ; Function to find the maximum amount to buy all candies ; Buy candy with maximum amount ; And get k candies for free from the starting ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinimum ( int arr [ ] , int n , int k ) { int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { res += arr [ i ] ; n = n - k ; } return res ; } int findMaximum ( int arr [ ] , int n , int k ) { int res = 0 , index = 0 ; for ( int i = n - 1 ; i >= index ; i -- ) { res += arr [ i ] ; index += k ; } return res ; } int main ( ) { int arr [ ] = { 3 , 2 , 1 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 2 ; sort ( arr , arr + n ) ; cout << findMinimum ( arr , n , k ) << " β " << findMaximum ( arr , n , k ) << endl ; return 0 ; } |
Merge two sorted arrays | C ++ program to merge two sorted arrays using maps ; Function to merge arrays ; Declaring a map . using map as a inbuilt tool to store elements in sorted order . ; Inserting values to a map . ; Printing keys of the map . ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void mergeArrays ( int a [ ] , int b [ ] , int n , int m ) { map < int , bool > mp ; for ( int i = 0 ; i < n ; i ++ ) mp [ a [ i ] ] = true ; for ( int i = 0 ; i < m ; i ++ ) mp [ b [ i ] ] = true ; for ( auto i : mp ) cout << i . first << " β " ; } int main ( ) { int a [ ] = { 1 , 3 , 5 , 7 } , b [ ] = { 2 , 4 , 6 , 8 } ; int size = sizeof ( a ) / sizeof ( int ) ; int size1 = sizeof ( b ) / sizeof ( int ) ; mergeArrays ( a , b , size , size1 ) ; return 0 ; } |
Print array of strings in sorted order without copying one string into another | C ++ implementation to print array of strings in sorted order without copying one string into another ; function to print strings in sorted order ; Initially the index of the strings are assigned to the ' index [ ] ' ; selection sort technique is applied ; with the help of ' index [ ] ' strings are being compared ; index of the smallest string is placed at the ith index of ' index [ ] ' ; printing strings in sorted order ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printInSortedOrder ( string arr [ ] , int n ) { int index [ n ] ; int i , j , min ; for ( i = 0 ; i < n ; i ++ ) index [ i ] = i ; for ( i = 0 ; i < n - 1 ; i ++ ) { min = i ; for ( j = i + 1 ; j < n ; j ++ ) { if ( arr [ index [ min ] ] . compare ( arr [ index [ j ] ] ) > 0 ) min = j ; } if ( min != i ) { int temp = index [ min ] ; index [ min ] = index [ i ] ; index [ i ] = temp ; } } for ( i = 0 ; i < n ; i ++ ) cout << arr [ index [ i ] ] << " β " ; } int main ( ) { string arr [ ] = { " geeks " , " quiz " , " geeks " , " for " } ; int n = 4 ; printInSortedOrder ( arr , n ) ; return 0 ; } |
Find maximum height pyramid from the given array of objects | C ++ program to find maximum height pyramid from the given object width . ; Returns maximum number of pyramidcal levels n boxes of given widths . ; Sort objects in increasing order of widths ; Total width of previous level and total number of objects in previous level ; Number of object in current level . ; Width of current level . ; Picking the object . So increase current width and number of object . ; If current width and number of object are greater than previous . ; Update previous width , number of object on previous level . ; Reset width of current level , number of object on current level . ; Increment number of level . ; Driver Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxLevel ( int boxes [ ] , int n ) { sort ( boxes , boxes + n ) ; int prev_width = boxes [ 0 ] ; int prev_count = 1 ; int curr_count = 0 ; int curr_width = 0 ; for ( int i = 1 ; i < n ; i ++ ) { curr_width += boxes [ i ] ; curr_count += 1 ; if ( curr_width > prev_width && curr_count > prev_count ) { prev_width = curr_width ; prev_count = curr_count ; curr_count = 0 ; curr_width = 0 ; ans ++ ; } } return ans ; } int main ( ) { int boxes [ ] = { 10 , 20 , 30 , 50 , 60 , 70 } ; int n = sizeof ( boxes ) / sizeof ( boxes [ 0 ] ) ; cout << maxLevel ( boxes , n ) << endl ; return 0 ; } |
Find the largest multiple of 3 from array of digits | Set 2 ( In O ( n ) time and O ( 1 ) space ) | C ++ program to find the largest number that can be mode from elements of the array and is divisible by 3 ; Number of digits ; function to sort array of digits using counts ; Store count of all elements ; Store ; Remove elements from arr [ ] at indexes ind1 and ind2 ; Returns largest multiple of 3 that can be formed using arr [ ] elements . ; Sum of all array element ; Sum is divisible by 3 , no need to delete an element ; Sort array element in increasing order ; Find reminder ; If remainder is '1' , we have to delete either one element of remainder '1' or two elements of remainder '2' ; Traverse array elements ; Store first element of remainder '1' ; If this is first occurrence of remainder 2 ; If second occurrence ; If remainder is '2' , we have to delete either one element of remainder '2' or two elements of remainder '1' ; traverse array elements ; store first element of remainder '2' ; If this is first occurrence of remainder 1 ; If second occurrence ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX_SIZE 10 NEW_LINE void sortArrayUsingCounts ( int arr [ ] , int n ) { int count [ MAX_SIZE ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) count [ arr [ i ] ] ++ ; int index = 0 ; for ( int i = 0 ; i < MAX_SIZE ; i ++ ) while ( count [ i ] > 0 ) arr [ index ++ ] = i , count [ i ] -- ; } bool removeAndPrintResult ( int arr [ ] , int n , int ind1 , int ind2 = -1 ) { for ( int i = n - 1 ; i >= 0 ; i -- ) if ( i != ind1 && i != ind2 ) cout << arr [ i ] ; } bool largest3Multiple ( int arr [ ] , int n ) { int sum = accumulate ( arr , arr + n , 0 ) ; if ( sum % 3 == 0 ) return true ; sortArrayUsingCounts ( arr , n ) ; int remainder = sum % 3 ; if ( remainder == 1 ) { int rem_2 [ 2 ] ; rem_2 [ 0 ] = -1 , rem_2 [ 1 ] = -1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % 3 == 1 ) { removeAndPrintResult ( arr , n , i ) ; return true ; } if ( arr [ i ] % 3 == 2 ) { if ( rem_2 [ 0 ] == -1 ) rem_2 [ 0 ] = i ; else if ( rem_2 [ 1 ] == -1 ) rem_2 [ 1 ] = i ; } } if ( rem_2 [ 0 ] != -1 && rem_2 [ 1 ] != -1 ) { removeAndPrintResult ( arr , n , rem_2 [ 0 ] , rem_2 [ 1 ] ) ; return true ; } } else if ( remainder == 2 ) { int rem_1 [ 2 ] ; rem_1 [ 0 ] = -1 , rem_1 [ 1 ] = -1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % 3 == 2 ) { removeAndPrintResult ( arr , n , i ) ; return true ; } if ( arr [ i ] % 3 == 1 ) { if ( rem_1 [ 0 ] == -1 ) rem_1 [ 0 ] = i ; else if ( rem_1 [ 1 ] == -1 ) rem_1 [ 1 ] = i ; } } if ( rem_1 [ 0 ] != -1 && rem_1 [ 1 ] != -1 ) { removeAndPrintResult ( arr , n , rem_1 [ 0 ] , rem_1 [ 1 ] ) ; return true ; } } cout << " Not β possible " ; return false ; } int main ( ) { int arr [ ] = { 4 , 4 , 1 , 1 , 1 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; largest3Multiple ( arr , n ) ; return 0 ; } |
Minimum swaps to reach permuted array with at most 2 positions left swaps allowed | C ++ program to find minimum number of swaps to reach a permutation with at most 2 left swaps allowed for every element ; This funt merges two sorted arrays and returns inversion count in the arrays . ; i is index for left subarray ; j is index for right subarray ; k is index for resultant merged subarray ; Copy the remaining elements of left subarray ( if there are any ) to temp ; Copy the remaining elements of right subarray ( if there are any ) to temp ; Copy back the merged elements to original array ; An auxiliary recursive function that sorts the input array and returns the number of inversions in the array . ; Divide the array into two parts and call _mergeSortAndCountInv ( ) for each of the parts ; Inversion count will be sum of inversions in left - part , right - part and number of inversions in merging ; Merge the two parts ; This function sorts the input array and returns the number of inversions in the array ; method returns minimum number of swaps to reach permuted array ' arr ' ; loop over all elements to check Invalid permutation condition ; if an element is at distance more than 2 from its actual position then it is not possible to reach permuted array just by swapping with 2 positions left elements so returning - 1 ; If permuted array is not Invalid , then number of Inversion in array will be our final answer ; Driver code to test above methods ; change below example | #include <bits/stdc++.h> NEW_LINE using namespace std ; int merge ( int arr [ ] , int temp [ ] , int left , int mid , int right ) { int inv_count = 0 ; int i = left ; int j = mid ; int k = left ; while ( ( i <= mid - 1 ) && ( j <= right ) ) { if ( arr [ i ] <= arr [ j ] ) temp [ k ++ ] = arr [ i ++ ] ; else { temp [ k ++ ] = arr [ j ++ ] ; inv_count = inv_count + ( mid - i ) ; } } while ( i <= mid - 1 ) temp [ k ++ ] = arr [ i ++ ] ; while ( j <= right ) temp [ k ++ ] = arr [ j ++ ] ; for ( i = left ; i <= right ; i ++ ) arr [ i ] = temp [ i ] ; return inv_count ; } int _mergeSort ( int arr [ ] , int temp [ ] , int left , int right ) { int mid , inv_count = 0 ; if ( right > left ) { mid = ( right + left ) / 2 ; inv_count = _mergeSort ( arr , temp , left , mid ) ; inv_count += _mergeSort ( arr , temp , mid + 1 , right ) ; inv_count += merge ( arr , temp , left , mid + 1 , right ) ; } return inv_count ; } int mergeSort ( int arr [ ] , int array_size ) { int * temp = ( int * ) malloc ( sizeof ( int ) * array_size ) ; return _mergeSort ( arr , temp , 0 , array_size - 1 ) ; } int minSwapToReachArr ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { if ( ( arr [ i ] - 1 ) - i > 2 ) return -1 ; } int numOfInversion = mergeSort ( arr , N ) ; return numOfInversion ; } int main ( ) { int arr [ ] = { 1 , 2 , 5 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( int ) ; int res = minSwapToReachArr ( arr , N ) ; if ( res == -1 ) cout << " Not β Possible STRNEWLINE " ; else cout << res << endl ; return 0 ; } |
Sort all even numbers in ascending order and then sort all odd numbers in descending order | C ++ program sort array in even and odd manner . The odd numbers are to be sorted in descending order and the even numbers in ascending order ; To do two way sort . First sort even numbers in ascending order , then odd numbers in descending order . ; Make all odd numbers negative ; if ( arr [ i ] & 1 ) Check for odd ; Sort all numbers ; Retaining original array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void twoWaySort ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) arr [ i ] *= -1 ; sort ( arr , arr + n ) ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] & 1 ) arr [ i ] *= -1 ; } int main ( ) { int arr [ ] = { 1 , 3 , 2 , 7 , 5 , 4 } ; int n = sizeof ( arr ) / sizeof ( int ) ; twoWaySort ( arr , n ) ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; return 0 ; } |
Sort all even numbers in ascending order and then sort all odd numbers in descending order | C ++ implementation of the approach ; Utility function to print the contents of the array ; To do two way sort . Make comparator function for the inbuilt sort function of c ++ such that odd numbers are placed before even in descending and ascending order respectively ; If both numbers are even , smaller number should be placed at lower index ; If both numbers are odd larger number should be placed at lower index ; If a is odd and b is even , a should be placed before b ; If b is odd and a is even , b should be placed before a ; Driver code ; Sort the array ; Print the sorted array | #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 ] << " β " ; } bool compare ( int a , int b ) { if ( a % 2 == 0 && b % 2 == 0 ) return a < b ; if ( a % 2 != 0 && b % 2 != 0 ) return b < a ; if ( a % 2 != 0 ) return true ; return false ; } int main ( ) { int arr [ ] = { 1 , 3 , 2 , 7 , 5 , 4 } ; int n = sizeof ( arr ) / sizeof ( int ) ; sort ( arr , arr + n , compare ) ; printArr ( arr , n ) ; return 0 ; } |
Possible to form a triangle from array values | C ++ program to find if it is possible to form a triangle from array values ; Method prints possible triangle when array values are taken as sides ; If number of elements are less than 3 , then no triangle is possible ; first sort the array ; loop for all 3 consecutive triplets ; If triplet satisfies triangle condition , break ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPossibleTriangle ( int arr [ ] , int N ) { if ( N < 3 ) return false ; sort ( arr , arr + N ) ; for ( int i = 0 ; i < N - 2 ; i ++ ) if ( arr [ i ] + arr [ i + 1 ] > arr [ i + 2 ] ) return true ; return false ; } int main ( ) { int arr [ ] = { 5 , 4 , 3 , 1 , 2 } ; int N = sizeof ( arr ) / sizeof ( int ) ; isPossibleTriangle ( arr , N ) ? cout << " Yes " : cout << " No " ; return 0 ; } |
Bucket Sort To Sort an Array with Negative Numbers | C ++ program to sort an array of positive and negative numbers using bucket sort ; Function to sort arr [ ] of size n using bucket sort ; 1 ) Create n empty buckets ; 2 ) Put array elements in different buckets ; int bi = n * arr [ i ] ; Index in bucket ; 3 ) Sort individual buckets ; 4 ) Concatenate all buckets into arr [ ] ; This function mainly splits array into two and then calls bucketSort ( ) for two arrays . ; traverse array elements ; store - Ve elements by converting into + ve element ; store + ve elements ; First store elements of Neg [ ] array by converting into - ve ; store + ve element ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void bucketSort ( vector < float > & arr , int n ) { vector < float > b [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { b [ bi ] . push_back ( arr [ i ] ) ; } for ( int i = 0 ; i < n ; i ++ ) sort ( b [ i ] . begin ( ) , b [ i ] . end ( ) ) ; int index = 0 ; arr . clear ( ) ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < b [ i ] . size ( ) ; j ++ ) arr . push_back ( b [ i ] [ j ] ) ; } void sortMixed ( float arr [ ] , int n ) { vector < float > Neg ; vector < float > Pos ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < 0 ) Neg . push_back ( -1 * arr [ i ] ) ; else Pos . push_back ( arr [ i ] ) ; } bucketSort ( Neg , ( int ) Neg . size ( ) ) ; bucketSort ( Pos , ( int ) Pos . size ( ) ) ; for ( int i = 0 ; i < Neg . size ( ) ; i ++ ) arr [ i ] = -1 * Neg [ Neg . size ( ) - 1 - i ] ; for ( int j = Neg . size ( ) ; j < n ; j ++ ) arr [ j ] = Pos [ j - Neg . size ( ) ] ; } int main ( ) { float arr [ ] = { -0.897 , 0.565 , 0.656 , -0.1234 , 0 , 0.3434 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortMixed ( arr , n ) ; cout << " Sorted β array β is β STRNEWLINE " ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; return 0 ; } |
K | C ++ program to find the K - th smallest element after removing some integers from natural number . ; Return the K - th smallest element . ; Making an array , and mark all number as unmarked . ; Marking the number present in the given array . ; If j is unmarked , reduce k by 1. ; If k is 0 return j . ; Driven Program | #include <bits/stdc++.h> NEW_LINE #define MAX 1000000 NEW_LINE using namespace std ; int ksmallest ( int arr [ ] , int n , int k ) { int b [ MAX ] ; memset ( b , 0 , sizeof b ) ; for ( int i = 0 ; i < n ; i ++ ) b [ arr [ i ] ] = 1 ; for ( int j = 1 ; j < MAX ; j ++ ) { if ( b [ j ] != 1 ) k -- ; if ( ! k ) return j ; } } int main ( ) { int k = 1 ; int arr [ ] = { 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ksmallest ( arr , n , k ) ; return 0 ; } |
Sort an array when two halves are sorted | C ++ program to Merge two sorted halves of array Into Single Sorted Array ; Sort the given array using sort STL ; Driver code ; Print sorted Array | #include <bits/stdc++.h> NEW_LINE using namespace std ; void mergeTwoHalf ( int A [ ] , int n ) { sort ( A , A + n ) ; } int main ( ) { int A [ ] = { 2 , 3 , 8 , -1 , 7 , 10 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; mergeTwoHalf ( A , n ) ; for ( int i = 0 ; i < n ; i ++ ) cout << A [ i ] << " β " ; 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.