text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Minimize the maximum minimum difference after one removal from array | C ++ implementation of the approach ; Function to return the minimum required difference ; Sort the given array ; When minimum element is removed ; When maximum element is removed ; Return the minimum of diff1 and diff2 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinDifference ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int diff1 = arr [ n - 1 ] - arr [ 1 ] ; int diff2 = arr [ n - 2 ] - arr [ 0 ] ; return min ( diff1 , diff2 ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findMinDifference ( arr , n ) ; return 0 ; }
Minimize the maximum minimum difference after one removal from array | C ++ implementation of the approach ; Function to return the minimum required difference ; If current element is greater than max ; max will become secondMax ; Update the max ; If current element is greater than secondMax but smaller than max ; Update the secondMax ; If current element is smaller than min ; min will become secondMin ; Update the min ; If current element is smaller than secondMin but greater than min ; Update the secondMin ; Minimum of the two possible differences ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinDifference ( int arr [ ] , int n ) { int min__ , secondMin , max__ , secondMax ; min__ = secondMax = ( arr [ 0 ] < arr [ 1 ] ) ? arr [ 0 ] : arr [ 1 ] ; max__ = secondMin = ( arr [ 0 ] < arr [ 1 ] ) ? arr [ 1 ] : arr [ 0 ] ; for ( int i = 2 ; i < n ; i ++ ) { if ( arr [ i ] > max__ ) { secondMax = max__ ; max__ = arr [ i ] ; } else if ( arr [ i ] > secondMax ) { secondMax = arr [ i ] ; } else if ( arr [ i ] < min__ ) { secondMin = min__ ; min__ = arr [ i ] ; } else if ( arr [ i ] < secondMin ) { secondMin = arr [ i ] ; } } int diff = min ( max__ - secondMin , secondMax - min__ ) ; return diff ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ( findMinDifference ( arr , n ) ) ; }
Integers from the range that are composed of a single distinct digit | C ++ implementation of the approach ; Boolean function to check distinct digits of a number ; Take last digit ; Check if all other digits are same as last digit ; Remove last digit ; Function to return the count of integers that are composed of a single distinct digit only ; If i has single distinct digit ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkDistinct ( int x ) { int last = x % 10 ; while ( x ) { if ( x % 10 != last ) return false ; x = x / 10 ; } return true ; } int findCount ( int L , int R ) { int count = 0 ; for ( int i = L ; i <= R ; i ++ ) { if ( checkDistinct ( i ) ) count += 1 ; } return count ; } int main ( ) { int L = 10 , R = 50 ; cout << findCount ( L , R ) ; return 0 ; }
Smallest Pair Sum in an array | C ++ program to print the sum of the minimum pair ; Function to return the sum of the minimum pair from the array ; If found new minimum ; Minimum now becomes second minimum ; Update minimum ; If current element is > min and < secondMin ; Update secondMin ; Return the sum of the minimum pair ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int smallest_pair ( int a [ ] , int n ) { int min = INT_MAX , secondMin = INT_MAX ; for ( int j = 0 ; j < n ; j ++ ) { if ( a [ j ] < min ) { secondMin = min ; min = a [ j ] ; } else if ( ( a [ j ] < secondMin ) && a [ j ] != min ) secondMin = a [ j ] ; } return ( secondMin + min ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << smallest_pair ( arr , n ) ; return 0 ; }
Longest subarray with elements divisible by k | C ++ program of above approach ; function to find longest subarray ; this will contain length of longest subarray found ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longestsubarray ( int arr [ ] , int n , int k ) { int current_count = 0 ; int max_count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % k == 0 ) current_count ++ ; else current_count = 0 ; max_count = max ( current_count , max_count ) ; } return max_count ; } int main ( ) { int arr [ ] = { 2 , 5 , 11 , 32 , 64 , 88 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 8 ; cout << longestsubarray ( arr , n , k ) ; return 0 ; }
Remove elements that appear strictly less than k times | C ++ program to remove the elements which appear strictly less than k times from the array . ; Hash map which will store the frequency of the elements of the array . ; Incrementing the frequency of the element by 1. ; Print the element which appear more than or equal to k times . ; Driver code
#include " iostream " NEW_LINE #include " unordered _ map " NEW_LINE using namespace std ; void removeElements ( int arr [ ] , int n , int k ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < n ; ++ i ) { mp [ arr [ i ] ] ++ ; } for ( int i = 0 ; i < n ; ++ i ) { if ( mp [ arr [ i ] ] >= k ) { cout << arr [ i ] << " ▁ " ; } } } int main ( ) { int arr [ ] = { 1 , 2 , 2 , 3 , 2 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 2 ; removeElements ( arr , n , k ) ; return 0 ; }
Check if a string contains a palindromic sub | C ++ program to check if there is a substring palindrome of even length . ; function to check if two consecutive same characters are present ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( string s ) { for ( int i = 0 ; i < s . length ( ) - 1 ; i ++ ) if ( s [ i ] == s [ i + 1 ] ) return true ; return false ; } int main ( ) { string s = " xzyyz " ; if ( check ( s ) ) cout << " YES " << endl ; else cout << " NO " << endl ; return 0 ; }
Remove elements from the array which appear more than k times | C ++ program to remove the elements which appear more than k times from the array . ; Hash map which will store the frequency of the elements of the array . ; Incrementing the frequency of the element by 1. ; Print the element which appear less than or equal to k times . ; Driver code
#include " iostream " NEW_LINE #include " unordered _ map " NEW_LINE using namespace std ; void RemoveElements ( int arr [ ] , int n , int k ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < n ; ++ i ) { mp [ arr [ i ] ] ++ ; } for ( int i = 0 ; i < n ; ++ i ) { if ( mp [ arr [ i ] ] <= k ) { cout << arr [ i ] << " ▁ " ; } } } int main ( int argc , char const * argv [ ] ) { int arr [ ] = { 1 , 2 , 2 , 3 , 2 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 2 ; RemoveElements ( arr , n , k ) ; return 0 ; }
Find the smallest after deleting given elements | C ++ program to find the smallest number from the array after n deletions ; Returns minimum element from arr [ 0. . m - 1 ] after deleting elements from del [ 0. . n - 1 ] ; Hash Map of the numbers to be deleted ; Increment the count of del [ i ] ; Initializing the smallestElement ; Search if the element is present ; Decrement its frequency ; If the frequency becomes 0 , erase it from the map ; Else compare it smallestElement ; Driver Code
#include " climits " NEW_LINE #include " iostream " NEW_LINE #include " unordered _ map " NEW_LINE using namespace std ; int findSmallestAfterDel ( int arr [ ] , int m , int del [ ] , int n ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < n ; ++ i ) { mp [ del [ i ] ] ++ ; } int smallestElement = INT_MAX ; for ( int i = 0 ; i < m ; ++ i ) { if ( mp . find ( arr [ i ] ) != mp . end ( ) ) { mp [ arr [ i ] ] -- ; if ( mp [ arr [ i ] ] == 0 ) mp . erase ( arr [ i ] ) ; } else smallestElement = min ( smallestElement , arr [ i ] ) ; } return smallestElement ; } int main ( ) { int array [ ] = { 5 , 12 , 33 , 4 , 56 , 12 , 20 } ; int m = sizeof ( array ) / sizeof ( array [ 0 ] ) ; int del [ ] = { 12 , 4 , 56 , 5 } ; int n = sizeof ( del ) / sizeof ( del [ 0 ] ) ; cout << findSmallestAfterDel ( array , m , del , n ) ; return 0 ; }
Find the largest after deleting the given elements | C ++ program to find the largest number from the array after n deletions ; Returns maximum element from arr [ 0. . m - 1 ] after deleting elements from del [ 0. . n - 1 ] ; Hash Map of the numbers to be deleted ; Increment the count of del [ i ] ; Initializing the largestElement ; Search if the element is present ; Decrement its frequency ; If the frequency becomes 0 , erase it from the map ; Else compare it largestElement ; Driver Code
#include " climits " NEW_LINE #include " iostream " NEW_LINE #include " unordered _ map " NEW_LINE using namespace std ; int findlargestAfterDel ( int arr [ ] , int m , int del [ ] , int n ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < n ; ++ i ) { mp [ del [ i ] ] ++ ; } int largestElement = INT_MIN ; for ( int i = 0 ; i < m ; ++ i ) { if ( mp . find ( arr [ i ] ) != mp . end ( ) ) { mp [ arr [ i ] ] -- ; if ( mp [ arr [ i ] ] == 0 ) mp . erase ( arr [ i ] ) ; } else largestElement = max ( largestElement , arr [ i ] ) ; } return largestElement ; } int main ( ) { int array [ ] = { 5 , 12 , 33 , 4 , 56 , 12 , 20 } ; int m = sizeof ( array ) / sizeof ( array [ 0 ] ) ; int del [ ] = { 12 , 33 , 56 , 5 } ; int n = sizeof ( del ) / sizeof ( del [ 0 ] ) ; cout << findlargestAfterDel ( array , m , del , n ) ; return 0 ; }
Number of anomalies in an array | A simple C ++ solution to count anomalies in an array . ; Driver code
#include <iostream> NEW_LINE using namespace std ; int countAnomalies ( int arr [ ] , int n , int k ) { int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int j ; for ( j = 0 ; j < n ; j ++ ) if ( i != j && abs ( arr [ i ] - arr [ j ] ) <= k ) break ; if ( j == n ) res ++ ; } return res ; } int main ( ) { int arr [ ] = { 7 , 1 , 8 } , k = 5 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countAnomalies ( arr , n , k ) ; return 0 ; }
Count majority element in a matrix | C ++ program to find count of all majority elements in a Matrix ; Function to find count of all majority elements in a Matrix ; Store frequency of elements in matrix ; loop to iteratre through map ; check if frequency is greater than or equal to ( N * M ) / 2 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int majorityInMatrix ( int arr [ N ] [ M ] ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { mp [ arr [ i ] [ j ] ] ++ ; } } int countMajority = 0 ; for ( auto itr = mp . begin ( ) ; itr != mp . end ( ) ; itr ++ ) { if ( itr -> second >= ( ( N * M ) / 2 ) ) { countMajority ++ ; } } return countMajority ; } int main ( ) { int mat [ N ] [ M ] = { { 1 , 2 , 2 } , { 1 , 3 , 2 } , { 1 , 2 , 6 } } ; cout << majorityInMatrix ( mat ) << endl ; return 0 ; }
Find pair with maximum difference in any column of a Matrix | C ++ program to find column with max difference of any pair of elements ; Function to find the column with max difference ; Traverse matrix column wise ; Insert elements of column to vector ; calculating difference between maximum and minimum ; driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int colMaxDiff ( int mat [ N ] [ N ] ) { int max_diff = INT_MIN ; for ( int i = 0 ; i < N ; i ++ ) { int max_val = mat [ 0 ] [ i ] , min_val = mat [ 0 ] [ i ] ; for ( int j = 1 ; j < N ; j ++ ) { max_val = max ( max_val , mat [ j ] [ i ] ) ; min_val = min ( min_val , mat [ j ] [ i ] ) ; } max_diff = max ( max_diff , max_val - min_val ) ; } return max_diff ; } int main ( ) { int mat [ N ] [ N ] = { { 1 , 2 , 3 , 4 , 5 } , { 5 , 3 , 5 , 4 , 0 } , { 5 , 6 , 7 , 8 , 9 } , { 0 , 6 , 3 , 4 , 12 } , { 9 , 7 , 12 , 4 , 3 } , } ; cout << " Max ▁ difference ▁ : ▁ " << colMaxDiff ( mat ) << endl ; return 0 ; }
Find the Missing Number in a sorted array | A binary search based program to find the only missing number in a sorted array of distinct elements within limited range . ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int search ( int ar [ ] , int size ) { int a = 0 , b = size - 1 ; int mid ; while ( ( b - a ) > 1 ) { mid = ( a + b ) / 2 ; if ( ( ar [ a ] - a ) != ( ar [ mid ] - mid ) ) b = mid ; else if ( ( ar [ b ] - b ) != ( ar [ mid ] - mid ) ) a = mid ; } return ( ar [ a ] + 1 ) ; } int main ( ) { int ar [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 8 } ; int size = sizeof ( ar ) / sizeof ( ar [ 0 ] ) ; cout << " Missing ▁ number : " << search ( ar , size ) ; }
Delete array element in given index range [ L | C ++ code to delete element in given range ; Delete L to R elements ; Return size of Array after delete element ; main Driver
#include <bits/stdc++.h> NEW_LINE using namespace std ; int deleteElement ( int A [ ] , int L , int R , int N ) { int i , j = 0 ; for ( i = 0 ; i < N ; i ++ ) { if ( i <= L i >= R ) { A [ j ] = A [ i ] ; j ++ ; } } return j ; } int main ( ) { int A [ ] = { 5 , 8 , 11 , 15 , 26 , 14 , 19 , 17 , 10 , 14 } ; int L = 2 , R = 7 ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int res_size = deleteElement ( A , L , R , n ) ; for ( int i = 0 ; i < res_size ; i ++ ) cout << A [ i ] << " ▁ " ; return 0 ; }
Longest subarray having average greater than or equal to x | CPP program to find Longest subarray having average greater than or equal to x . ; Comparison function used to sort preSum vector . ; Function to find index in preSum vector upto which all prefix sum values are less than or equal to val . ; Starting and ending index of search space . ; To store required index value . ; If middle value is less than or equal to val then index can lie in mid + 1. . n else it lies in 0. . mid - 1. ; Function to find Longest subarray having average greater than or equal to x . ; Update array by subtracting x from each element . ; Length of Longest subarray . ; Vector to store pair of prefix sum and corresponding ending index value . ; To store current value of prefix sum . ; To store minimum index value in range 0. . i of preSum vector . ; Insert values in preSum vector . ; Update minInd array . ; If sum is greater than or equal to 0 , then answer is i + 1. ; If sum is less than 0 , then find if there is a prefix array having sum that needs to be added to current sum to make its value greater than or equal to 0. If yes , then compare length of updated subarray with maximum length found so far . ; Driver code .
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool compare ( const pair < int , int > & a , const pair < int , int > & b ) { if ( a . first == b . first ) return a . second < b . second ; return a . first < b . first ; } int findInd ( vector < pair < int , int > > & preSum , int n , int val ) { int l = 0 ; int h = n - 1 ; int mid ; int ans = -1 ; while ( l <= h ) { mid = ( l + h ) / 2 ; if ( preSum [ mid ] . first <= val ) { ans = mid ; l = mid + 1 ; } else h = mid - 1 ; } return ans ; } int LongestSub ( int arr [ ] , int n , int x ) { int i ; for ( i = 0 ; i < n ; i ++ ) arr [ i ] -= x ; int maxlen = 0 ; vector < pair < int , int > > preSum ; int sum = 0 ; int minInd [ n ] ; for ( i = 0 ; i < n ; i ++ ) { sum = sum + arr [ i ] ; preSum . push_back ( { sum , i } ) ; } sort ( preSum . begin ( ) , preSum . end ( ) , compare ) ; minInd [ 0 ] = preSum [ 0 ] . second ; for ( i = 1 ; i < n ; i ++ ) { minInd [ i ] = min ( minInd [ i - 1 ] , preSum [ i ] . second ) ; } sum = 0 ; for ( i = 0 ; i < n ; i ++ ) { sum = sum + arr [ i ] ; if ( sum >= 0 ) maxlen = i + 1 ; else { int ind = findInd ( preSum , n , sum ) ; if ( ind != -1 && minInd [ ind ] < i ) maxlen = max ( maxlen , i - minInd [ ind ] ) ; } } return maxlen ; } int main ( ) { int arr [ ] = { -2 , 1 , 6 , -3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 3 ; cout << LongestSub ( arr , n , x ) ; return 0 ; }
Find the only missing number in a sorted array | CPP program to find the only missing element . ; If this is the first element which is not index + 1 , then missing element is mid + 1 ; if this is not the first missing element search in left side ; if it follows index + 1 property then search in right side ; if no element is missing ; Driver code
#include <iostream> NEW_LINE using namespace std ; int findmissing ( int ar [ ] , int N ) { int l = 0 , r = N - 1 ; while ( l <= r ) { int mid = ( l + r ) / 2 ; if ( ar [ mid ] != mid + 1 && ar [ mid - 1 ] == mid ) return mid + 1 ; if ( ar [ mid ] != mid + 1 ) r = mid - 1 ; else l = mid + 1 ; } return -1 ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 7 , 8 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findmissing ( arr , N ) ; return 0 ; }
Find index of first occurrence when an unsorted array is sorted | C ++ program to find index of first occurrence of x when array is sorted . ; lower_bound returns iterator pointing to first element that does not compare less to x . ; If x is not present return - 1. ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findFirst ( int arr [ ] , int n , int x ) { sort ( arr , arr + n ) ; int * ptr = lower_bound ( arr , arr + n , x ) ; return ( * ptr != x ) ? -1 : ( ptr - arr ) ; } int main ( ) { int x = 20 , arr [ ] = { 10 , 30 , 20 , 50 , 20 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findFirst ( arr , n , x ) ; return 0 ; }
Find index of first occurrence when an unsorted array is sorted | C ++ program to find index of first occurrence of x when array is sorted . ; Driver main
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findFirst ( int arr [ ] , int n , int x ) { int count = 0 ; bool isX = false ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == x ) isX = true ; else if ( arr [ i ] < x ) count ++ ; } return ( isX == false ) ? -1 : count ; } int main ( ) { int x = 20 , arr [ ] = { 10 , 30 , 20 , 50 , 20 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findFirst ( arr , n , x ) ; return 0 ; }
Find duplicate in an array in O ( n ) and by using O ( 1 ) extra space | CPP code to find the repeated elements in the array where every other is present once ; Function to find duplicate ; Find the intersection point of the slow and fast . ; Find the " entrance " to the cycle . ; Driver code
#include <iostream> NEW_LINE using namespace std ; int findDuplicate ( int arr [ ] ) { int slow = arr [ 0 ] ; int fast = arr [ 0 ] ; do { slow = arr [ slow ] ; fast = arr [ arr [ fast ] ] ; } while ( slow != fast ) ; int ptr1 = arr [ 0 ] ; int ptr2 = slow ; while ( ptr1 != ptr2 ) { ptr1 = arr [ ptr1 ] ; ptr2 = arr [ ptr2 ] ; } return ptr1 ; } int main ( ) { int arr [ ] = { 1 , 3 , 2 , 1 } ; cout << findDuplicate ( arr ) << endl ; return 0 ; }
Number of Larger Elements on right side in a string | C ++ program to count greater characters on right side of every character . ; Arrays to store result and character counts . ; start from right side of string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX_CHAR 26 NEW_LINE void printGreaterCount ( string str ) { int len = str . length ( ) ; int ans [ len ] = { 0 } , count [ MAX_CHAR ] = { 0 } ; for ( int i = len - 1 ; i >= 0 ; i -- ) { count [ str [ i ] - ' a ' ] ++ ; for ( int j = str [ i ] - ' a ' + 1 ; j < MAX_CHAR ; j ++ ) ans [ i ] += count [ j ] ; } for ( int i = 0 ; i < len ; i ++ ) cout << ans [ i ] << " ▁ " ; } int main ( ) { string str = " abcd " ; printGreaterCount ( str ) ; return 0 ; }
Print all pairs with given sum | C ++ implementation of simple method to find count of pairs with given sum . ; Returns number of pairs in arr [ 0. . n - 1 ] with sum equal to ' sum ' ; Store counts of all elements in map m ; Traverse through all elements ; Search if a pair can be formed with arr [ i ] . ; Driver function to test the above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printPairs ( int arr [ ] , int n , int sum ) { unordered_map < int , int > m ; for ( int i = 0 ; i < n ; i ++ ) { int rem = sum - arr [ i ] ; if ( m . find ( rem ) != m . end ( ) ) { int count = m [ rem ] ; for ( int j = 0 ; j < count ; j ++ ) cout << " ( " << rem << " , ▁ " << arr [ i ] << " ) " << endl ; } m [ arr [ i ] ] ++ ; } } int main ( ) { int arr [ ] = { 1 , 5 , 7 , -1 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int sum = 6 ; printPairs ( arr , n , sum ) ; return 0 ; }
Maximum product quadruple ( sub | A O ( n ) C ++ program to find maximum quadruple in an array . ; Function to find a maximum product of a quadruple in array of integers of size n ; if size is less than 4 , no quadruple exists ; Initialize Maximum , second maximum , third maximum and fourth maximum element ; Initialize Minimum , second minimum , third minimum and fourth minimum element ; Update Maximum , second maximum , third maximum and fourth maximum element ; Update second maximum , third maximum and fourth maximum element ; Update third maximum and fourth maximum element ; Update fourth maximum element ; Update Minimum , second minimum third minimum and fourth minimum element ; Update second minimum , third minimum and fourth minimum element ; Update third minimum and fourth minimum element ; Update fourth minimum element ; Return the maximum of x , y and z ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxProduct ( int arr [ ] , int n ) { if ( n < 4 ) return -1 ; int maxA = INT_MIN , maxB = INT_MIN , maxC = INT_MIN , maxD = INT_MIN ; int minA = INT_MAX , minB = INT_MAX , minC = INT_MAX , minD = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > maxA ) { maxD = maxC ; maxC = maxB ; maxB = maxA ; maxA = arr [ i ] ; } else if ( arr [ i ] > maxB ) { maxD = maxC ; maxC = maxB ; maxB = arr [ i ] ; } else if ( arr [ i ] > maxC ) { maxD = maxC ; maxC = arr [ i ] ; } else if ( arr [ i ] > maxD ) maxD = arr [ i ] ; if ( arr [ i ] < minA ) { minD = minC ; minC = minB ; minB = minA ; minA = arr [ i ] ; } else if ( arr [ i ] < minB ) { minD = minC ; minC = minB ; minB = arr [ i ] ; } else if ( arr [ i ] < minC ) { minD = minC ; minC = arr [ i ] ; } else if ( arr [ i ] < minD ) minD = arr [ i ] ; } int x = maxA * maxB * maxC * maxD ; int y = minA * minB * minC * minD ; int z = minA * minB * maxA * maxB ; return max ( x , max ( y , z ) ) ; } int main ( ) { int arr [ ] = { 1 , -4 , 3 , -6 , 7 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int max = maxProduct ( arr , n ) ; if ( max == -1 ) cout << " No ▁ Quadruple ▁ Exists " ; else cout << " Maximum ▁ product ▁ is ▁ " << max ; return 0 ; }
Ways to choose three points with distance between the most distant points <= L | C ++ program to count ways to choose triplets such that the distance between the farthest points <= L ; Returns the number of triplets with distance between farthest points <= L ; sort to get ordered triplets so that we can find the distance between farthest points belonging to a triplet ; generate and check for all possible triplets : { arr [ i ] , arr [ j ] , arr [ k ] } ; Since the array is sorted the farthest points will be a [ i ] and a [ k ] ; ; Driver Code ; set of n points on the X axis
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countTripletsLessThanL ( int n , int L , int * arr ) { sort ( arr , arr + n ) ; int ways = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { for ( int k = j + 1 ; k < n ; k ++ ) { int mostDistantDistance = arr [ k ] - arr [ i ] ; if ( mostDistantDistance <= L ) { ways ++ ; } } } } return ways ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int L = 3 ; int ans = countTripletsLessThanL ( n , L , arr ) ; cout << " Total ▁ Number ▁ of ▁ ways ▁ = ▁ " << ans << " STRNEWLINE " ; return 0 ; }
Triplets in array with absolute difference less than k | CPP program to count triplets with difference less than k . ; Return the lower bound i . e smallest index of element having value greater or equal to value ; Return the number of triplet indices satisfies the three constraints ; sort the array ; for each element from index 2 to n - 1. ; finding the lower bound of arr [ i ] - k . ; If there are at least two elements between lower bound and current element . ; increment the count by lb - i C 2. ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int binary_lower ( int value , int arr [ ] , int n ) { int start = 0 ; int end = n - 1 ; int ans = -1 ; int mid ; while ( start <= end ) { mid = ( start + end ) / 2 ; if ( arr [ mid ] >= value ) { end = mid - 1 ; ans = mid ; } else { start = mid + 1 ; } } return ans ; } int countTriplet ( int arr [ ] , int n , int k ) { int count = 0 ; sort ( arr , arr + n ) ; for ( int i = 2 ; i < n ; i ++ ) { int cur = binary_lower ( arr [ i ] - k , arr , n ) ; if ( cur <= i - 2 ) { count += ( ( i - cur ) * ( i - cur - 1 ) ) / 2 ; } } return count ; } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 2 , 3 } ; int k = 1 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countTriplet ( arr , n , k ) << endl ; return 0 ; }
Minimize the sum of roots of a given polynomial | C ++ program to find minimum sum of roots of a given polynomial ; resultant vector ; a vector that store indices of the positive elements ; a vector that store indices of the negative elements ; Case - 1 : ; Case - 2 : ; Case - 3 : ; Case - 4 : ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void getMinimumSum ( int arr [ ] , int n ) { vector < int > res ; vector < int > pos ; vector < int > neg ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > 0 ) pos . push_back ( i ) ; else if ( arr [ i ] < 0 ) neg . push_back ( i ) ; } if ( pos . size ( ) >= 2 && neg . size ( ) >= 2 ) { int posMax = INT_MIN , posMaxIdx = -1 ; int posMin = INT_MAX , posMinIdx = -1 ; int negMax = INT_MIN , negMaxIdx = -1 ; int negMin = INT_MAX , negMinIdx = -1 ; for ( int i = 0 ; i < pos . size ( ) ; i ++ ) { if ( arr [ pos [ i ] ] > posMax ) { posMaxIdx = pos [ i ] ; posMax = arr [ posMaxIdx ] ; } } for ( int i = 0 ; i < pos . size ( ) ; i ++ ) { if ( arr [ pos [ i ] ] < posMin && pos [ i ] != posMaxIdx ) { posMinIdx = pos [ i ] ; posMin = arr [ posMinIdx ] ; } } for ( int i = 0 ; i < neg . size ( ) ; i ++ ) { if ( abs ( arr [ neg [ i ] ] ) > negMax ) { negMaxIdx = neg [ i ] ; negMax = abs ( arr [ negMaxIdx ] ) ; } } for ( int i = 0 ; i < neg . size ( ) ; i ++ ) { if ( abs ( arr [ neg [ i ] ] ) < negMin && neg [ i ] != negMaxIdx ) { negMinIdx = neg [ i ] ; negMin = abs ( arr [ negMinIdx ] ) ; } } double posVal = -1.0 * ( double ) posMax / ( double ) posMin ; double negVal = -1.0 * ( double ) negMax / ( double ) negMin ; if ( posVal < negVal ) { res . push_back ( arr [ posMinIdx ] ) ; res . push_back ( arr [ posMaxIdx ] ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i != posMinIdx && i != posMaxIdx ) { res . push_back ( arr [ i ] ) ; } } } else { res . push_back ( arr [ negMinIdx ] ) ; res . push_back ( arr [ negMaxIdx ] ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i != negMinIdx && i != negMaxIdx ) { res . push_back ( arr [ i ] ) ; } } } for ( int i = 0 ; i < res . size ( ) ; i ++ ) { cout << res [ i ] << " ▁ " ; } cout << " STRNEWLINE " ; } else if ( pos . size ( ) >= 2 ) { int posMax = INT_MIN , posMaxIdx = -1 ; int posMin = INT_MAX , posMinIdx = -1 ; for ( int i = 0 ; i < pos . size ( ) ; i ++ ) { if ( arr [ pos [ i ] ] > posMax ) { posMaxIdx = pos [ i ] ; posMax = arr [ posMaxIdx ] ; } } for ( int i = 0 ; i < pos . size ( ) ; i ++ ) { if ( arr [ pos [ i ] ] < posMin && pos [ i ] != posMaxIdx ) { posMinIdx = pos [ i ] ; posMin = arr [ posMinIdx ] ; } } res . push_back ( arr [ posMinIdx ] ) ; res . push_back ( arr [ posMaxIdx ] ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i != posMinIdx && i != posMaxIdx ) { res . push_back ( arr [ i ] ) ; } } for ( int i = 0 ; i < res . size ( ) ; i ++ ) { cout << res [ i ] << " ▁ " ; } cout << " STRNEWLINE " ; } else if ( neg . size ( ) >= 2 ) { int negMax = INT_MIN , negMaxIdx = -1 ; int negMin = INT_MAX , negMinIdx = -1 ; for ( int i = 0 ; i < neg . size ( ) ; i ++ ) { if ( abs ( arr [ neg [ i ] ] ) > negMax ) { negMaxIdx = neg [ i ] ; negMax = abs ( arr [ negMaxIdx ] ) ; } } for ( int i = 0 ; i < neg . size ( ) ; i ++ ) { if ( abs ( arr [ neg [ i ] ] ) < negMin && neg [ i ] != negMaxIdx ) { negMinIdx = neg [ i ] ; negMin = abs ( arr [ negMinIdx ] ) ; } } res . push_back ( arr [ negMinIdx ] ) ; res . push_back ( arr [ negMaxIdx ] ) ; for ( int i = 0 ; i < n ; i ++ ) if ( i != negMinIdx && i != negMaxIdx ) res . push_back ( arr [ i ] ) ; for ( int i = 0 ; i < res . size ( ) ; i ++ ) cout << res [ i ] << " ▁ " ; cout << " STRNEWLINE " ; } else { cout << " No ▁ swap ▁ required STRNEWLINE " ; } } int main ( ) { int arr [ ] = { -4 , 1 , 6 , -3 , -2 , -1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; getMinimumSum ( arr , n ) ; return 0 ; }
Longest Palindromic Substring using Palindromic Tree | Set 3 | CPP code for Longest Palindromic substring using Palindromic Tree data structure ; store start and end indexes of current Node inclusively ; stores length of substring ; stores insertion Node for all characters a - z ; stores the Maximum Palindromic Suffix Node for the current Node ; two special dummy Nodes as explained above ; stores Node information for constant time access ; Keeps track the current Node while insertion ; Function to insert edge in tree ; Finding X , such that s [ currIndex ] + X + s [ currIndex ] is palindrome . ; Check if s [ currIndex ] + X + s [ currIndex ] is already Present in tree . ; Else Create new node ; ; Setting suffix edge for newly Created Node . ; Longest Palindromic suffix for a string of length 1 is a Null string . ; Else ; Driver code ; Imaginary root 's suffix edge points to itself, since for an imaginary string of length = -1 has an imaginary suffix string. Imaginary root. ; NULL root 's suffix edge points to Imaginary root, since for a string of length = 0 has an imaginary suffix string. ; last will be the index of our last substring
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAXN 1000 NEW_LINE struct Node { int start , end ; int length ; int insertionEdge [ 26 ] ; int suffixEdge ; } ; Node root1 , root2 ; Node tree [ MAXN ] ; int currNode ; string s ; int ptr ; void insert ( int currIndex ) { int temp = currNode ; while ( true ) { int currLength = tree [ temp ] . length ; if ( currIndex - currLength >= 1 && ( s [ currIndex ] == s [ currIndex - currLength - 1 ] ) ) break ; temp = tree [ temp ] . suffixEdge ; } if ( tree [ temp ] . insertionEdge [ s [ currIndex ] - ' a ' ] != 0 ) { currNode = tree [ temp ] . insertionEdge [ s [ currIndex ] - ' a ' ] ; return ; } ptr ++ ; tree [ temp ] . insertionEdge [ s [ currIndex ] - ' a ' ] = ptr ; tree [ ptr ] . end = currIndex ; tree [ ptr ] . length = tree [ temp ] . length + 2 ; tree [ ptr ] . start = tree [ ptr ] . end - tree [ ptr ] . length + 1 ; currNode = ptr ; temp = tree [ temp ] . suffixEdge ; if ( tree [ currNode ] . length == 1 ) { tree [ currNode ] . suffixEdge = 2 ; return ; } while ( true ) { int currLength = tree [ temp ] . length ; if ( currIndex - currLength >= 1 && ( s [ currIndex ] == s [ currIndex - currLength - 1 ] ) ) break ; temp = tree [ temp ] . suffixEdge ; } tree [ currNode ] . suffixEdge = tree [ temp ] . insertionEdge [ s [ currIndex ] - ' a ' ] ; } int main ( ) { root1 . length = -1 ; root1 . suffixEdge = 1 ; root2 . length = 0 ; root2 . suffixEdge = 1 ; tree [ 1 ] = root1 ; tree [ 2 ] = root2 ; ptr = 2 ; currNode = 1 ; s = " forgeeksskeegfor " ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) insert ( i ) ; int last = ptr ; for ( int i = tree [ last ] . start ; i <= tree [ last ] . end ; i ++ ) cout << s [ i ] ; return 0 ; }
Maximum occurring character in a linked list | C ++ program to count the maximum occurring character in linked list ; Link list node ; counting the frequency of current element p -> data ; if current counting is greater than max ; Push a node to linked list . Note that this function changes the head ; Driver program to test above function ; Start with the empty list ; this will create a linked list of character " geeksforgeeks "
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { char data ; struct Node * next ; } ; char maxChar ( struct Node * head ) { struct Node * p = head ; int max = -1 ; char res ; while ( p != NULL ) { struct Node * q = p -> next ; int count = 1 ; while ( q != NULL ) { if ( p -> data == q -> data ) count ++ ; q = q -> next ; } if ( max < count ) { res = p -> data ; max = count ; } p = p -> next ; } return res ; } void push ( struct Node * * head_ref , char new_data ) { struct Node * new_node = new Node ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } int main ( ) { struct Node * head = NULL ; char str [ ] = " skeegforskeeg " ; int i ; for ( i = 0 ; str [ i ] != ' \0' ; i ++ ) push ( & head , str [ i ] ) ; cout << maxChar ( head ) ; return 0 ; }
Find the one missing number in range | CPP program to find missing number in a range . ; Find the missing number in a range ; here we xor of all the number ; xor last number ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int missingNum ( int arr [ ] , int n ) { int minvalue = * min_element ( arr , arr + n ) ; int xornum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { xornum ^= ( minvalue ) ^ arr [ i ] ; minvalue ++ ; } return xornum ^ minvalue ; } int main ( ) { int arr [ ] = { 13 , 12 , 11 , 15 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << missingNum ( arr , n ) ; return 0 ; }
Find last index of a character in a string | CPP program to find last index of character x in given string . ; Returns last index of x if it is present . Else returns - 1. ; Driver code ; String in which char is to be found ; char whose index is to be found
#include <iostream> NEW_LINE using namespace std ; int findLastIndex ( string & str , char x ) { int index = -1 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) if ( str [ i ] == x ) index = i ; return index ; } int main ( ) { string str = " geeksforgeeks " ; char x = ' e ' ; int index = findLastIndex ( str , x ) ; if ( index == -1 ) cout << " Character ▁ not ▁ found " ; else cout << " Last ▁ index ▁ is ▁ " << index ; return 0 ; }
Find last index of a character in a string | Simple CPP program to find last index of character x in given string . ; Returns last index of x if it is present . Else returns - 1. ; Traverse from right ; Driver code
#include <iostream> NEW_LINE using namespace std ; int findLastIndex ( string & str , char x ) { for ( int i = str . length ( ) - 1 ; i >= 0 ; i -- ) if ( str [ i ] == x ) return i ; return -1 ; } int main ( ) { string str = " geeksforgeeks " ; char x = ' e ' ; int index = findLastIndex ( str , x ) ; if ( index == -1 ) cout << " Character ▁ not ▁ found " ; else cout << " Last ▁ index ▁ is ▁ " << index ; return 0 ; }
Smallest number whose set bits are maximum in a given range | C ++ program to find number whose set bits are maximum among ' l ' and ' r ' ; Returns smallest number whose set bits are maximum in given range . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countMaxSetBits ( int left , int right ) { while ( ( left | ( left + 1 ) ) <= right ) left |= left + 1 ; return left ; } int main ( ) { int l = 1 , r = 5 ; cout << countMaxSetBits ( l , r ) << " STRNEWLINE " ; l = 1 , r = 10 ; cout << countMaxSetBits ( l , r ) ; return 0 ; }
Largest number less than or equal to N in BST ( Iterative Approach ) | C ++ code to find the largest value smaller than or equal to N ; To create new BST Node ; To insert a new node in BST ; if tree is empty return new node ; if key is less then or greater then node value then recur down the tree ; return the ( unchanged ) node pointer ; Returns largest value smaller than or equal to key . If key is smaller than the smallest , it returns - 1. ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; Node * left , * right ; } ; Node * newNode ( int item ) { Node * temp = new Node ; temp -> key = item ; temp -> left = temp -> right = NULL ; return temp ; } Node * insert ( Node * node , int key ) { if ( node == NULL ) return newNode ( key ) ; if ( key < node -> key ) node -> left = insert ( node -> left , key ) ; else if ( key > node -> key ) node -> right = insert ( node -> right , key ) ; return node ; } int findFloor ( Node * root , int key ) { Node * curr = root , * ans = NULL ; while ( curr ) { if ( curr -> key <= key ) { ans = curr ; curr = curr -> right ; } else curr = curr -> left ; } if ( ans ) return ans -> key ; return -1 ; } int main ( ) { int N = 25 ; Node * root = insert ( root , 19 ) ; insert ( root , 2 ) ; insert ( root , 1 ) ; insert ( root , 3 ) ; insert ( root , 12 ) ; insert ( root , 9 ) ; insert ( root , 21 ) ; insert ( root , 19 ) ; insert ( root , 25 ) ; printf ( " % d " , findFloor ( root , N ) ) ; return 0 ; }
Find if given number is sum of first n natural numbers | C ++ program for finding s such that sum from 1 to s equals to n ; Function to find no . of elements to be added to get s ; Apply Binary search ; Find mid ; find sum of 1 to mid natural numbers using formula ; If sum is equal to n return mid ; If greater than n do r = mid - 1 ; else do l = mid + 1 ; If not possible , return - 1 ; Drivers code
#include <iostream> NEW_LINE using namespace std ; int findS ( int s ) { int l = 1 , r = ( s / 2 ) + 1 ; while ( l <= r ) { int mid = ( l + r ) / 2 ; int sum = mid * ( mid + 1 ) / 2 ; if ( sum == s ) return mid ; else if ( sum > s ) r = mid - 1 ; else l = mid + 1 ; } return -1 ; } int main ( ) { int s = 15 ; int n = findS ( s ) ; n == -1 ? cout << " - 1" : cout << n ; return 0 ; }
Search in an array of strings where non | C ++ program to find location of a str in an array of strings which is sorted and has empty strings between strings . ; Compare two string equals are not ; Main function to find string location ; Move mid to the middle ; If mid is empty , find closest non - empty string ; If mid is empty , search in both sides of mid and find the closest non - empty string , and set mid accordingly . ; If str is found at mid ; If str is greater than mid ; If str is smaller than mid ; Driver Code ; Input arr of Strings . ; input Search String
#include <bits/stdc++.h> NEW_LINE using namespace std ; int compareStrings ( string str1 , string str2 ) { int i = 0 ; while ( str1 [ i ] == str2 [ i ] && str1 [ i ] != ' \0' ) i ++ ; if ( str1 [ i ] > str2 [ i ] ) return -1 ; return ( str1 [ i ] < str2 [ i ] ) ; } int searchStr ( string arr [ ] , string str , int first , int last ) { if ( first > last ) return -1 ; int mid = ( last + first ) / 2 ; if ( arr [ mid ] . empty ( ) ) { int left = mid - 1 ; int right = mid + 1 ; while ( true ) { if ( left < first && right > last ) return -1 ; if ( right <= last && ! arr [ right ] . empty ( ) ) { mid = right ; break ; } if ( left >= first && ! arr [ left ] . empty ( ) ) { mid = left ; break ; } right ++ ; left -- ; } } if ( compareStrings ( str , arr [ mid ] ) == 0 ) return mid ; if ( compareStrings ( str , arr [ mid ] ) < 0 ) return searchStr ( arr , str , mid + 1 , last ) ; return searchStr ( arr , str , first , mid - 1 ) ; } int main ( ) { string arr [ ] = { " for " , " " , " " , " " , " geeks " , " ide " , " " , " practice " , " " , " " , " quiz " , " " , " " } ; string str = " quiz " ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << searchStr ( arr , str , 0 , n - 1 ) ; return 0 ; }
Maximum number of plates that can be placed from top to bottom in increasing order of size | C ++ Program for the above approach ; Comparator function to sort plates in decreasing order of area ; Function to count and return the max number of plates that can be placed ; Stores the maximum number of plates ; For each i - th plate , traverse all the previous plates ; If i - th plate is smaller than j - th plate ; Include the j - th plate only if current count exceeds the previously stored count ; Update the maximum count ; Driver code ; Sorting plates in decreasing order of area
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool comp ( vector < int > v1 , vector < int > v2 ) { return v1 [ 0 ] * v1 [ 1 ] > v2 [ 0 ] * v2 [ 1 ] ; } int countPlates ( vector < vector < int > > & plates , int n ) { int maximum_plates = 1 ; vector < int > dp ( n , 1 ) ; for ( int i = 1 ; i < n ; i ++ ) { int cur = dp [ i ] ; for ( int j = i - 1 ; j >= 0 ; j -- ) { if ( plates [ i ] [ 0 ] < plates [ j ] [ 0 ] && plates [ i ] [ 1 ] < plates [ j ] [ 1 ] ) { if ( cur + dp [ j ] > dp [ i ] ) { dp [ i ] = cur + dp [ j ] ; maximum_plates = max ( maximum_plates , dp [ i ] ) ; } } } } return maximum_plates ; } int main ( ) { vector < vector < int > > plates = { { 6 , 4 } , { 5 , 7 } , { 1 , 2 } , { 3 , 3 } , { 7 , 9 } } ; int n = plates . size ( ) ; sort ( plates . begin ( ) , plates . end ( ) , comp ) ; cout << countPlates ( plates , n ) ; return 0 ; }
Sort an array in increasing order of their Multiplicative Persistence | C ++ program for the above approach ; Function to find the number of steps required to reduce a given number to a single - digit number ; Stores the required result ; Iterate until a single digit number is not obtained ; Store the number in a temporary variable ; Iterate over all digits and store their product in num ; Increment the answer by 1 ; Return the result ; Comparator function to sort the array ; Count number of steps required to reduce X and Y into single digits integer ; Return true ; Function to sort the array according to the number of steps required to reduce a given number into a single digit number ; Sort the array using the comparator function ; Print the array after sorting ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countReduction ( int num ) { int ans = 0 ; while ( num >= 10 ) { int temp = num ; num = 1 ; while ( temp > 0 ) { int digit = temp % 10 ; temp = temp / 10 ; num *= digit ; } ans ++ ; } return ans ; } bool compare ( int x , int y ) { int x1 = countReduction ( x ) ; int y1 = countReduction ( y ) ; if ( x1 < y1 ) return true ; return false ; } void sortArray ( int a [ ] , int n ) { sort ( a , a + n , compare ) ; for ( int i = 0 ; i < n ; i ++ ) { cout << a [ i ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 39 , 999 , 4 , 9876 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortArray ( arr , N ) ; return 0 ; }
Check if a Binary String can be sorted in decreasing order by removing non | C ++ program for the above approach ; Function to sort the given string in decreasing order by removing the non adjacent characters ; Keeps the track whether the string can be sorted or not ; Traverse the given string S ; Check if S [ i ] and S [ i + 1 ] are both '1' ; Traverse the string S from the indices i to 0 ; If S [ j ] and S [ j + 1 ] is equal to 0 ; Mark flag false ; If flag is 0 , then it is not possible to sort the string ; Otherwise ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string canSortString ( string S , int N ) { int flag = 1 ; int i , j ; for ( i = N - 2 ; i >= 0 ; i -- ) { if ( S [ i ] == '1' && S [ i + 1 ] == '1' ) { break ; } } for ( int j = i ; j >= 0 ; j -- ) { if ( S [ j ] == '0' && S [ j + 1 ] == '0' ) { flag = 0 ; break ; } } if ( flag == 0 ) { return " No " ; } else { return " Yes " ; } } int main ( ) { string S = "10101011011" ; int N = S . length ( ) ; cout << canSortString ( S , N ) ; return 0 ; }
Rearrange array elements to maximize the sum of MEX of all prefix arrays | C ++ program for the above approach ; Function to find the maximum sum of MEX of prefix arrays for any arrangement of the given array ; Stores the final arrangement ; Sort the array in increasing order ; Iterate over the array arr [ ] ; Iterate over the array , arr [ ] and push the remaining occurrences of the elements into ans [ ] ; Print the array , ans [ ] ; Driver Code ; Given array ; Store the size of the array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maximumMex ( int arr [ ] , int N ) { vector < int > ans ; sort ( arr , arr + N ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( i == 0 arr [ i ] != arr [ i - 1 ] ) ans . push_back ( arr [ i ] ) ; } for ( int i = 0 ; i < N ; i ++ ) { if ( i > 0 && arr [ i ] == arr [ i - 1 ] ) ans . push_back ( arr [ i ] ) ; } for ( int i = 0 ; i < N ; i ++ ) cout << ans [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 1 , 0 , 0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maximumMex ( arr , N ) ; return 0 ; }
Sort an array using Bubble Sort without using loops | C ++ program for the above approach ; Function to implement bubble sort without using loops ; Base Case : If array contains a single element ; Base Case : If array contains two elements ; Store the first two elements of the list in variables a and b ; Store remaining elements in the list bs ; Store the list after each recursive call ; If a < b ; Otherwise , if b >= a ; Recursively call for the list less than the last element and and return the newly formed list ; Driver Code ; Print the array
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > bubble_sort ( vector < int > ar ) { if ( ar . size ( ) <= 1 ) return ar ; if ( ar . size ( ) == 2 ) { if ( ar [ 0 ] < ar [ 1 ] ) return ar ; else return { ar [ 1 ] , ar [ 0 ] } ; } int a = ar [ 0 ] ; int b = ar [ 1 ] ; vector < int > bs ; for ( int i = 2 ; i < ar . size ( ) ; i ++ ) bs . push_back ( ar [ i ] ) ; vector < int > res ; if ( a < b ) { vector < int > temp1 ; temp1 . push_back ( b ) ; for ( int i = 0 ; i < bs . size ( ) ; i ++ ) temp1 . push_back ( bs [ i ] ) ; vector < int > v = bubble_sort ( temp1 ) ; v . insert ( v . begin ( ) , a ) ; res = v ; } else { vector < int > temp1 ; temp1 . push_back ( a ) ; for ( int i = 0 ; i < bs . size ( ) ; i ++ ) temp1 . push_back ( bs [ i ] ) ; vector < int > v = bubble_sort ( temp1 ) ; v . insert ( v . begin ( ) , b ) ; res = v ; } vector < int > pass ; for ( int i = 0 ; i < res . size ( ) - 1 ; i ++ ) pass . push_back ( res [ i ] ) ; vector < int > ans = bubble_sort ( pass ) ; ans . push_back ( res [ res . size ( ) - 1 ] ) ; return ans ; } int main ( ) { vector < int > arr { 1 , 3 , 4 , 5 , 6 , 2 } ; vector < int > res = bubble_sort ( arr ) ; for ( int i = 0 ; i < res . size ( ) ; i ++ ) cout << res [ i ] << " ▁ " ; }
Modify a given matrix by placing sorted boundary elements in clockwise manner | C ++ program for the above approach ; Function to print the elements of the matrix in row - wise manner ; Function to sort boundary elements of a matrix starting from the outermost to the innermost boundary and place them in a clockwise manner ; k - starting row index m - ending row index l - starting column index n - ending column index i - iterator ; Stores the current boundary elements ; Push the first row ; Push the last column ; Push the last row ; Push the first column ; Sort the boundary elements ; Update the first row ; Update the last column ; Update the last row ; Update the first column ; Print the resultant matrix ; Driver Code ; Given matrix
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printMatrix ( vector < vector < int > > a ) { for ( auto x : a ) { for ( auto y : x ) { cout << y << " ▁ " ; } cout << " STRNEWLINE " ; } } void sortBoundaryWise ( vector < vector < int > > a ) { int i , k = 0 , l = 0 ; int m = a . size ( ) , n = a [ 0 ] . size ( ) ; int n_i , n_k = 0 , n_l = 0 , n_m = m , n_n = n ; while ( k < m && l < n ) { vector < int > boundary ; for ( i = l ; i < n ; ++ i ) { boundary . push_back ( a [ k ] [ i ] ) ; } k ++ ; for ( i = k ; i < m ; ++ i ) { boundary . push_back ( a [ i ] [ n - 1 ] ) ; } n -- ; if ( k < m ) { for ( i = n - 1 ; i >= l ; -- i ) { boundary . push_back ( a [ m - 1 ] [ i ] ) ; } m -- ; } if ( l < n ) { for ( i = m - 1 ; i >= k ; -- i ) { boundary . push_back ( a [ i ] [ l ] ) ; } l ++ ; } sort ( boundary . begin ( ) , boundary . end ( ) ) ; int ind = 0 ; for ( i = n_l ; i < n_n ; ++ i ) { a [ n_k ] [ i ] = boundary [ ind ++ ] ; } n_k ++ ; for ( i = n_k ; i < n_m ; ++ i ) { a [ i ] [ n_n - 1 ] = boundary [ ind ++ ] ; } n_n -- ; if ( n_k < n_m ) { for ( i = n_n - 1 ; i >= n_l ; -- i ) { a [ n_m - 1 ] [ i ] = boundary [ ind ++ ] ; } n_m -- ; } if ( n_l < n_n ) { for ( i = n_m - 1 ; i >= n_k ; -- i ) { a [ i ] [ n_l ] = boundary [ ind ++ ] ; } n_l ++ ; } } printMatrix ( a ) ; } int main ( ) { vector < vector < int > > matrix = { { 9 , 7 , 4 , 5 } , { 1 , 6 , 2 , -6 } , { 12 , 20 , 2 , 0 } , { -5 , -6 , 7 , -2 } } ; sortBoundaryWise ( matrix ) ; return 0 ; }
Minimum sum of absolute differences between pairs of a triplet from an array | C ++ Program for the above approach ; Function to find minimum sum of absolute differences of pairs of a triplet ; Sort the array ; Stores the minimum sum ; Traverse the array ; Update the minimum sum ; Print the minimum sum ; Driver Code ; Input ; Function call to find minimum sum of absolute differences of pairs in a triplet
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimum_sum ( int A [ ] , int N ) { sort ( A , A + N ) ; int sum = INT_MAX ; for ( int i = 0 ; i <= N - 3 ; i ++ ) { sum = min ( sum , abs ( A [ i ] - A [ i + 1 ] ) + abs ( A [ i + 1 ] - A [ i + 2 ] ) ) ; } cout << sum ; } int main ( ) { int A [ ] = { 1 , 1 , 2 , 3 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; minimum_sum ( A , N ) ; return 0 ; }
Make all characters of a string same by minimum number of increments or decrements of ASCII values of characters | C ++ program for the above approach ; Function to check if all characters of the string can be made the same ; Sort the string ; Calculate ASCII value of the median character ; Stores the minimum number of operations required to make all characters equal ; Traverse the string ; Calculate absolute value of current character and median character ; Print the minimum number of operations required ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sameChar ( string S , int N ) { sort ( S . begin ( ) , S . end ( ) ) ; int mid = S [ N / 2 ] ; int total_operations = 0 ; for ( int i = 0 ; i < N ; i ++ ) { total_operations += abs ( int ( S [ i ] ) - mid ) ; } cout << total_operations ; } int main ( ) { string S = " geeks " ; int N = S . size ( ) ; sameChar ( S , N ) ; return 0 ; }
Maximum score possible from an array with jumps of at most length K | C ++ program for the above approach ; Function to count the maximum score of an index ; Base Case ; If the value for the current index is pre - calculated ; Calculate maximum score for all the steps in the range from i + 1 to i + k ; Score for index ( i + j ) ; Update dp [ i ] and return the maximum value ; Function to get maximum score possible from the array A [ ] ; Array to store memoization ; Initialize dp [ ] with - 1 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxScore ( int i , int A [ ] , int K , int N , int dp [ ] ) { if ( i >= N - 1 ) return A [ N - 1 ] ; if ( dp [ i ] != -1 ) return dp [ i ] ; int score = INT_MIN ; for ( int j = 1 ; j <= K ; j ++ ) { score = max ( score , maxScore ( i + j , A , K , N , dp ) ) ; } return dp [ i ] = score + A [ i ] ; } int getScore ( int A [ ] , int N , int K ) { int dp [ N ] ; for ( int i = 0 ; i < N ; i ++ ) dp [ i ] = -1 ; cout << maxScore ( 0 , A , K , N , dp ) ; } int main ( ) { int A [ ] = { 100 , -30 , -50 , -15 , -20 , -30 } ; int K = 3 ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; getScore ( A , N , K ) ; return 0 ; }
Maximum score possible from an array with jumps of at most length K | C ++ program for the above approach ; Structure to sort a priority queue on the basis of first element of the pair ; Function to calculate maximum score possible from the array A [ ] ; Stores the score of previous k indices ; Stores the maximum score for current index ; Maximum score at first index ; Traverse the array to calculate maximum score for all indices ; Remove maximum scores for indices less than i - K ; Calculate maximum score for current index ; Push maximum score of current index along with index in maxheap ; Return the maximum score ; Driver Code ; Function call to calculate maximum score from the array A [ ]
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct mycomp { bool operator() ( pair < int , int > p1 , pair < int , int > p2 ) { return p1 . first < p2 . first ; } } ; int maxScore ( int A [ ] , int K , int N ) { priority_queue < pair < int , int > , vector < pair < int , int > > , mycomp > maxheap ; int maxScore = 0 ; maxheap . push ( { A [ 0 ] , 0 } ) ; for ( int i = 1 ; i < N ; i ++ ) { while ( maxheap . top ( ) . second < ( i - K ) ) { maxheap . pop ( ) ; } maxScore = A [ i ] + maxheap . top ( ) . first ; maxheap . push ( { maxScore , i } ) ; } return maxScore ; } int main ( ) { int A [ ] = { -44 , -17 , -54 , 79 } ; int K = 2 ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << maxScore ( A , K , N ) ; return 0 ; }
Count triplets from an array which can form quadratic equations with real roots | C ++ program for the above approach ; Function to find count of triplets ( a , b , c ) such that the equations ax ^ 2 + bx + c = 0 has real roots ; Stores count of triplets ( a , b , c ) such that ax ^ 2 + bx + c = 0 has real roots ; Base case ; Generate all possible triplets ( a , b , c ) ; If the coefficient of X ^ 2 and X are equal ; If coefficient of X ^ 2 or x are equal to the constant ; Condition for having real roots ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getCount ( int arr [ ] , int N ) { int count = 0 ; if ( N < 3 ) return 0 ; for ( int b = 0 ; b < N ; b ++ ) { for ( int a = 0 ; a < N ; a ++ ) { if ( a == b ) continue ; for ( int c = 0 ; c < N ; c ++ ) { if ( c == a c == b ) continue ; int d = arr [ b ] * arr [ b ] / 4 ; if ( arr [ a ] * arr <= d ) count ++ ; } } } return count ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << getCount ( arr , N ) ; return 0 ; }
Check if all array elements can be reduced to less than X | C ++ program to implement the above approach ; Function to check if all array elements can be reduced to less than X or not ; Checks if all array elements are already a X or not ; Traverse every possible pair ; Calculate GCD of two array elements ; If gcd is a 1 ; If gcd is a X , then a pair is present to reduce all array elements to a X ; If no pair is present with gcd is a X ; Function to check if all array elements area X ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool findAns ( int A [ ] , int N , int X ) { if ( check ( A , X , N ) ) { return true ; } for ( int i = 0 ; i < N ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { int g = __gcd ( A [ i ] , A [ j ] ) ; if ( g != 1 ) { if ( g <= X ) { return true ; } } } } return false ; } bool check ( int A [ ] , int X , int N ) { for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] > X ) { return false ; } } return true ; } int main ( ) { int X = 4 ; int A [ ] = { 2 , 1 , 5 , 3 , 6 } ; int N = 5 ; if ( findAns ( A , N , X ) ) { cout << " true " ; } else { cout << " false " ; } }
Check if X and Y elements can be selected from two arrays respectively such that the maximum in X is less than the minimum in Y | C ++ program for the above approach ; Function to check if it is possible to choose X and Y elements from a [ ] and b [ ] such that maximum element among X element is less than minimum element among Y elements ; Check if there are atleast X elements in arr1 [ ] and atleast Y elements in arr2 [ ] ; Sort arrays in ascending order ; Check if ( X - 1 ) - th element in arr1 [ ] is less than from M - Yth element in arr2 [ ] ; Return false ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string check ( int a [ ] , int b [ ] , int Na , int Nb , int k , int m ) { if ( Na < k Nb < m ) return " No " ; sort ( a , a + Na ) ; sort ( b , b + Nb ) ; if ( a [ k - 1 ] < b [ Nb - m ] ) { return " Yes " ; } return " No " ; } int main ( ) { int arr1 [ ] = { 1 , 2 , 3 } ; int arr2 [ ] = { 3 , 4 , 5 } ; int N = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int M = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; int X = 2 , Y = 1 ; cout << check ( arr1 , arr2 , N , M , X , Y ) ; return 0 ; }
Partition array into two subsets with minimum Bitwise XOR between their maximum and minimum | C ++ program for the above approach ; Function to split the array into two subset such that the Bitwise XOR between the maximum of one subset and minimum of other is minimum ; Sort the array in increasing order ; Calculating the min Bitwise XOR between consecutive elements ; Return the final minimum Bitwise XOR ; Driver Code ; Given array arr [ ] ; Size of array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int splitArray ( int arr [ ] , int N ) { sort ( arr , arr + N ) ; int result = INT_MAX ; for ( int i = 1 ; i < N ; i ++ ) { result = min ( result , arr [ i ] - arr [ i - 1 ] ) ; } return result ; } int main ( ) { int arr [ ] = { 3 , 1 , 2 , 6 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << splitArray ( arr , N ) ; return 0 ; }
Sort an array by left shifting digits of array elements | C ++ program for the above approach ; Function to check if an array is sorted in increasing order or not ; Traverse the array ; Function to sort the array by left shifting digits of array elements ; Stores previous array element ; Traverse the array arr [ ] ; Stores current element ; Stores current element in string format ; Left - shift digits of current element in all possible ways ; Left - shift digits of current element by idx ; If temp greater than or equal to prev and temp less than optEle ; Update arr [ i ] ; Update prev ; If arr is in increasing order ; Otherwise ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isIncreasing ( vector < int > arr ) { for ( int i = 0 ; i < arr . size ( ) - 1 ; i ++ ) { if ( arr [ i ] > arr [ i + 1 ] ) return false ; } return true ; } vector < int > sortArr ( vector < int > arr ) { int prev = -1 ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { int optEle = arr [ i ] ; string strEle = to_string ( arr [ i ] ) ; for ( int idx = 0 ; idx < strEle . size ( ) ; idx ++ ) { string strEle2 = strEle . substr ( idx ) + strEle . substr ( 0 , idx ) ; int temp = stoi ( strEle2 ) ; if ( temp >= prev && temp < optEle ) optEle = temp ; } arr [ i ] = optEle ; prev = arr [ i ] ; } if ( isIncreasing ( arr ) ) return arr ; else { arr = { -1 } ; return arr ; } } int main ( ) { vector < int > arr = { 511 , 321 , 323 , 432 , 433 } ; vector < int > res = sortArr ( arr ) ; for ( int i = 0 ; i < res . size ( ) ; i ++ ) cout << res [ i ] << " ▁ " ; return 0 ; }
Activity selection problem with K persons | C ++ program for the above approach ; Comparator ; Function to find maximum shops that can be visited by K persons ; Store opening and closing time of shops ; Sort the pair of array ; Stores the result ; Stores current number of persons visiting some shop with their ending time ; Check if current shop can be assigned to a person who 's already visiting any other shop ; Checks if there is any person whose closing time <= current shop opening time ; Erase previous shop visited by the person satisfying the condition ; Insert new closing time of current shop for the person satisfying a1he condition ; Increment the count by one ; In case if no person have closing time <= current shop opening time but there are some persons left ; Finally print the ans ; Driver Code ; Given starting and ending time ; Given K and N ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool compareBy ( const pair < int , int > & a , const pair < int , int > & b ) { if ( a . second != b . second ) return a . second < b . second ; return a . first < b . first ; } int maximumShops ( int * opening , int * closing , int n , int k ) { pair < int , int > a [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { a [ i ] . first = opening [ i ] ; a [ i ] . second = closing [ i ] ; } sort ( a , a + n , compareBy ) ; int count = 0 ; multiset < int > st ; for ( int i = 0 ; i < n ; i ++ ) { bool flag = false ; if ( ! st . empty ( ) ) { auto it = st . upper_bound ( a [ i ] . first ) ; if ( it != st . begin ( ) ) { it -- ; if ( * it <= a [ i ] . first ) { st . erase ( it ) ; st . insert ( a [ i ] . second ) ; count ++ ; flag = true ; } } } if ( st . size ( ) < k && flag == false ) { st . insert ( a [ i ] . second ) ; count ++ ; } } return count ; } int main ( ) { int S [ ] = { 1 , 8 , 3 , 2 , 6 } ; int E [ ] = { 5 , 10 , 6 , 5 , 9 } ; int K = 2 , N = sizeof ( S ) / sizeof ( S [ 0 ] ) ; cout << maximumShops ( S , E , N , K ) << endl ; }
Maximize maximum possible subarray sum of an array by swapping with elements from another array | C ++ program for the above approach ; Function to find the maximum subarray sum possible by swapping elements from array arr [ ] with that from array brr [ ] ; Stores elements from the arrays arr [ ] and brr [ ] ; Store elements of array arr [ ] and brr [ ] in the vector crr ; Sort the vector crr in descending order ; Stores maximum sum ; Calculate the sum till the last index in crr [ ] which is less than N which contains a positive element ; Print the sum ; Driver code ; Given arrays and respective lengths ; Calculate maximum subarray sum
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxSum ( int * arr , int * brr , int N , int K ) { vector < int > crr ; for ( int i = 0 ; i < N ; i ++ ) { crr . push_back ( arr [ i ] ) ; } for ( int i = 0 ; i < K ; i ++ ) { crr . push_back ( brr [ i ] ) ; } sort ( crr . begin ( ) , crr . end ( ) , greater < int > ( ) ) ; int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( crr [ i ] > 0 ) { sum += crr [ i ] ; } else { break ; } } cout << sum << endl ; } int main ( ) { int arr [ ] = { 7 , 2 , -1 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int brr [ ] = { 1 , 2 , 3 , 2 } ; int K = sizeof ( brr ) / sizeof ( brr [ 0 ] ) ; maxSum ( arr , brr , N , K ) ; }
Count pairs with Bitwise XOR greater than both the elements of the pair | C ++ program for the above approach ; Function that counts the pairs whose Bitwise XOR is greater than both the elements of pair ; Stores the count of pairs ; Generate all possible pairs ; Find the Bitwise XOR ; Find the maximum of two ; If xo < mx , increment count ; Print the value of count ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countPairs ( int A [ ] , int N ) { int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { int xo = ( A [ i ] ^ A [ j ] ) ; int mx = max ( A [ i ] , A [ j ] ) ; if ( xo > mx ) { count ++ ; } } } cout << count ; } int main ( ) { int arr [ ] = { 2 , 4 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countPairs ( arr , N ) ; return 0 ; }
Possible arrangement of persons waiting to sit in a hall | C ++ program for the above approach ; Function to find the arrangement of seating ; Stores the row in which the ith person sits ; Stores the width of seats along with their index or row number ; Sort the array ; Store the seats and row for boy 's seat ; Stores the index of row upto which boys have taken seat ; Iterate the string ; Push the row number at index in vector and heap ; Increment the index to let the next boy in the next minimum width vacant row ; Otherwise ; If girl then take top of element of the max heap ; Pop from queue ; Print the values ; Driver Code ; Given N ; Given arr [ ] ; Given string ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findTheOrder ( int arr [ ] , string s , int N ) { vector < int > ans ; pair < int , int > A [ N ] ; for ( int i = 0 ; i < N ; i ++ ) A [ i ] = { arr [ i ] , i + 1 } ; sort ( A , A + N ) ; priority_queue < pair < int , int > > q ; int index = 0 ; for ( int i = 0 ; i < 2 * N ; i ++ ) { if ( s [ i ] == '0' ) { ans . push_back ( A [ index ] . second ) ; q . push ( A [ index ] ) ; index ++ ; } else { ans . push_back ( q . top ( ) . second ) ; q . pop ( ) ; } } for ( auto i : ans ) { cout << i << " ▁ " ; } } int main ( ) { int N = 3 ; int arr [ ] = { 2 , 1 , 3 } ; string s = "001011" ; findTheOrder ( arr , s , N ) ; return 0 ; }
Difference between sum of K maximum even and odd array elements | C ++ program for the above approach ; Function to find the absolute difference between sum of first K maximum even and odd numbers ; Stores index from where odd number starts ; Segregate even and odd number ; If current element is even ; Sort in decreasing order even part ; Sort in decreasing order odd part ; Calculate sum of k maximum even number ; Calculate sum of k maximum odd number ; Print the absolute difference ; Driver Code ; Given array arr [ ] ; Size of array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void evenOddDiff ( int a [ ] , int n , int k ) { int j = -1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] % 2 == 0 ) { j ++ ; swap ( a [ i ] , a [ j ] ) ; } } j ++ ; sort ( a , a + j , greater < int > ( ) ) ; sort ( a + j , a + n , greater < int > ( ) ) ; int evenSum = 0 , oddSum = 0 ; for ( int i = 0 ; i < k ; i ++ ) { evenSum += a [ i ] ; } for ( int i = j ; i < ( j + k ) ; i ++ ) { oddSum += a [ i ] ; } cout << abs ( evenSum - oddSum ) ; } int main ( ) { int arr [ ] = { 1 , 8 , 3 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 2 ; evenOddDiff ( arr , N , K ) ; return 0 ; }
Rearrange array to make product of prefix sum array non zero | C ++ program to implement the above approach ; Function to print array elements ; Function to rearrange array that satisfies the given condition ; Stores sum of elements of the given array ; Calculate totalSum ; If the totalSum is equal to 0 ; No possible way to rearrange array ; If totalSum exceeds 0 ; Rearrange the array in descending order ; Otherwise ; Rearrange the array in ascending order ; 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 rearrangeArr ( int arr [ ] , int N ) { int totalSum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { totalSum += arr [ i ] ; } if ( totalSum == 0 ) { cout << " - 1" << endl ; } else if ( totalSum > 0 ) { sort ( arr , arr + N , greater < int > ( ) ) ; printArr ( arr , N ) ; } else { sort ( arr , arr + N ) ; printArr ( arr , N ) ; } } int main ( ) { int arr [ ] = { 1 , -1 , -2 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; rearrangeArr ( arr , N ) ; }
Split array into two equal length subsets such that all repetitions of a number lies in a single subset | C ++ program for the above approach ; Function to create the frequency array of the given array arr [ ] ; Hashmap to store the frequencies ; Store freq for each element ; Get the total frequencies ; Store frequencies in subset [ ] array ; Return frequency array ; Function to check is sum N / 2 can be formed using some subset ; dp [ i ] [ j ] store the answer to form sum j using 1 st i elements ; Initialize dp [ ] [ ] with true ; Fill the subset table in the bottom up manner ; If current element is less than j ; Update current state ; Return the result ; Function to check if the given array can be split into required sets ; Store frequencies of arr [ ] ; If size of arr [ ] is odd then print " Yes " ; Check if answer is true or not ; Print the result ; Driver Code ; Given array arr [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > findSubsets ( vector < int > arr , int N ) { map < int , int > M ; for ( int i = 0 ; i < N ; i ++ ) { M [ arr [ i ] ] ++ ; } vector < int > subsets ; int I = 0 ; for ( auto playerEntry = M . begin ( ) ; playerEntry != M . end ( ) ; playerEntry ++ ) { subsets . push_back ( playerEntry -> second ) ; I ++ ; } return subsets ; } bool subsetSum ( vector < int > subsets , int N , int target ) { bool dp [ N + 1 ] [ target + 1 ] ; for ( int i = 0 ; i < N + 1 ; i ++ ) dp [ i ] [ 0 ] = true ; for ( int i = 1 ; i <= N ; i ++ ) { for ( int j = 1 ; j <= target ; j ++ ) { dp [ i ] [ j ] = dp [ i - 1 ] [ j ] ; if ( j >= subsets [ i - 1 ] ) { dp [ i ] [ j ] |= dp [ i - 1 ] [ j - subsets [ i - 1 ] ] ; } } } return dp [ N ] [ target ] ; } void divideInto2Subset ( vector < int > arr , int N ) { vector < int > subsets = findSubsets ( arr , N ) ; if ( ( N ) % 2 == 1 ) { cout << " No " << endl ; return ; } int subsets_size = subsets . size ( ) ; bool isPossible = subsetSum ( subsets , subsets_size , N / 2 ) ; if ( isPossible ) { cout << " Yes " << endl ; } else { cout << " No " << endl ; } } int main ( ) { vector < int > arr { 2 , 1 , 2 , 3 } ; int N = arr . size ( ) ; divideInto2Subset ( arr , N ) ; return 0 ; }
Count ways to distribute exactly one coin to each worker | C ++ program for the above approach ; Function to find number of way to distribute coins giving exactly one coin to each person ; Sort the given arrays ; Start from bigger salary ; Increment the amount ; Reduce amount of valid coins by one each time ; Return the result ; Driver code ; Given two arrays ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MOD = 1000000007 ; int solve ( vector < int > & values , vector < int > & salary ) { long long ret = 1 ; int amt = 0 ; sort ( values . begin ( ) , values . end ( ) ) ; sort ( salary . begin ( ) , salary . end ( ) ) ; while ( salary . size ( ) ) { while ( values . size ( ) && values . back ( ) >= salary . back ( ) ) { amt ++ ; values . pop_back ( ) ; } if ( amt == 0 ) return 0 ; ret *= amt -- ; ret %= MOD ; salary . pop_back ( ) ; } return ret ; } int main ( ) { vector < int > values { 1 , 2 } , salary { 2 } ; cout << solve ( values , salary ) ; return 0 ; }
Count of index pairs with equal elements in an array | Set 2 | C ++ program for the above approach ; Function that counts the pair in the array arr [ ] ; Sort the array ; Initialize two pointers ; Add all valid pairs to answer ; Return the answer ; Driver Code ; Given array arr [ ] ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int arr [ ] , int n ) { int ans = 0 ; sort ( arr , arr + n ) ; int left = 0 , right = 1 ; while ( right < n ) { if ( arr [ left ] == arr [ right ] ) ans += right - left ; else left = right ; right ++ ; } return ans ; } int main ( ) { int arr [ ] = { 2 , 2 , 3 , 2 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , N ) ; return 0 ; }
Maximize the Sum of the given array using given operations | C ++ Program to maximise the sum of the given array ; Comparator to sort the array in ascending order ; Function to maximise the sum of the given array ; Stores { A [ i ] , B [ i ] } pairs ; Sort in descending order of the values in the array A [ ] ; Stores the maximum sum ; If B [ i ] is equal to 0 ; Simply add A [ i ] to the sum ; Add the highest K numbers ; Subtract from the sum ; Return the sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool compare ( pair < int , int > p1 , pair < int , int > p2 ) { return p1 . first > p2 . first ; } int maximiseScore ( int A [ ] , int B [ ] , int K , int N ) { vector < pair < int , int > > pairs ( N ) ; for ( int i = 0 ; i < N ; i ++ ) { pairs [ i ] = make_pair ( A [ i ] , B [ i ] ) ; } sort ( pairs . begin ( ) , pairs . end ( ) , compare ) ; int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( pairs [ i ] . second == 0 ) { sum += pairs [ i ] . first ; } else if ( pairs [ i ] . second == 1 ) { if ( K > 0 ) { sum += pairs [ i ] . first ; K -- ; } else { sum -= pairs [ i ] . first ; } } } return sum ; } int main ( ) { int A [ ] = { 5 , 4 , 6 , 2 , 8 } ; int B [ ] = { 1 , 0 , 1 , 1 , 0 } ; int K = 2 ; int N = sizeof ( A ) / sizeof ( int ) ; cout << maximiseScore ( A , B , K , N ) ; return 0 ; }
Minimize Cost to sort a String in Increasing Order of Frequencies of Characters | C ++ program to implement above approach ; For a single character ; Stores count of repetitions of a character ; If repeating character ; Otherwise ; Store frequency ; Reset count ; Insert the last character block ; Sort the frequencies ; Stores the minimum cost of all operations ; Store the absolute difference of i - th frequencies of ordered and unordered sequences ; Return the minimum cost ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sortString ( string S ) { vector < int > sorted , original ; bool insert = false ; if ( S . length ( ) == 1 ) { cout << 0 << endl ; } int curr = 1 ; for ( int i = 0 ; i < ( S . length ( ) - 1 ) ; i ++ ) { if ( S [ i ] == S [ i + 1 ] ) { curr += 1 ; insert = false ; } else { sorted . push_back ( curr ) ; original . push_back ( curr ) ; curr = 1 ; insert = true ; } } if ( ( S [ ( S . length ( ) - 1 ) ] != S [ ( S . length ( ) - 2 ) ] ) insert == false ) { sorted . push_back ( curr ) ; original . push_back ( curr ) ; } sort ( sorted . begin ( ) , sorted . end ( ) ) ; int t_cost = 0 ; for ( int i = 0 ; i < sorted . size ( ) ; i ++ ) { t_cost += abs ( sorted [ i ] - original [ i ] ) ; } return ( t_cost / 2 ) ; } int main ( ) { string S = " aabbcccdeffffggghhhhhii " ; cout << sortString ( S ) ; return 0 ; }
Sort numbers based on count of letters required to represent them in words | C ++ program to sort the strings based on the numbers of letters required to represent them ; letters [ i ] stores the count of letters required to represent the digit i ; Function to return the sum of letters required to represent N ; Function to sort the array according to the sum of letters to represent n ; Vector to store the digit sum with respective elements ; Inserting digit sum with elements in the vector pair ; Making the vector pair ; Sort the vector , this will sort the pair according to the sum of letters to represent n ; Print the sorted vector content ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int letters [ ] = { 4 , 3 , 3 , 3 , 4 , 4 , 3 , 5 , 5 , 4 } ; int sumOfLetters ( int n ) { int sum = 0 ; while ( n > 0 ) { sum += letters [ n % 10 ] ; n = n / 10 ; } return sum ; } void sortArr ( int arr [ ] , int n ) { vector < pair < int , int > > vp ; for ( int i = 0 ; i < n ; i ++ ) { vp . push_back ( make_pair ( sumOfLetters ( arr [ i ] ) , arr [ i ] ) ) ; } sort ( vp . begin ( ) , vp . end ( ) ) ; for ( int i = 0 ; i < vp . size ( ) ; i ++ ) cout << vp [ i ] . second << " ▁ " ; } int main ( ) { int arr [ ] = { 12 , 10 , 31 , 18 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortArr ( arr , n ) ; return 0 ; }
Range Queries for count of Armstrong numbers in subarray using MO 's algorithm | C ++ implementation to count the number of Armstrong numbers in subarray using MOaTMs algorithm ; Variable to represent block size . This is made global so compare ( ) of sort can use it . ; Structure to represent a query range ; Count of Armstrong numbers ; To store the count of Armstrong numbers ; Function used to sort all queries so that all queries of the same block are arranged together and within a block , queries are sorted in increasing order of R values . ; Different blocks , sort by block . ; Same block , sort by R value ; Function used to sort all queries in order of their index value so that results of queries can be printed in same order as of input ; Function that return true if num is armstrong else return false ; Function to Add elements of current range ; If a [ currL ] is a Armstrong number then increment count_Armstrong ; Function to remove elements of previous range ; If a [ currL ] is a Armstrong number then decrement count_Armstrong ; Function to generate the result of queries ; Initialize count_Armstrong to 0 ; Find block size ; Sort all queries so that queries of same blocks are arranged together . ; Initialize current L , current R and current result ; L and R values of current range ; Add Elements of current range ; Remove element of previous range ; Function to display the results of queries in their initial order ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int block ; struct Query { int L , R , index ; int armstrong ; } ; int count_Armstrong ; bool compare ( Query x , Query y ) { if ( x . L / block != y . L / block ) return x . L / block < y . L / block ; return x . R < y . R ; } bool compare1 ( Query x , Query y ) { return x . index < y . index ; } bool isArmstrong ( int x ) { int n = to_string ( x ) . size ( ) ; int sum1 = 0 ; int temp = x ; while ( temp > 0 ) { int digit = temp % 10 ; sum1 += pow ( digit , n ) ; temp /= 10 ; } if ( sum1 == x ) return true ; return false ; } void add ( int currL , int a [ ] ) { if ( isArmstrong ( a [ currL ] ) ) count_Armstrong ++ ; } void remove ( int currR , int a [ ] ) { if ( isArmstrong ( a [ currR ] ) ) count_Armstrong -- ; } void queryResults ( int a [ ] , int n , Query q [ ] , int m ) { count_Armstrong = 0 ; block = ( int ) sqrt ( n ) ; sort ( q , q + m , compare ) ; int currL = 0 , currR = 0 ; for ( int i = 0 ; i < m ; i ++ ) { int L = q [ i ] . L , R = q [ i ] . R ; while ( currR <= R ) { add ( currR , a ) ; currR ++ ; } while ( currL > L ) { add ( currL - 1 , a ) ; currL -- ; } while ( currR > R + 1 ) { remove ( currR - 1 , a ) ; currR -- ; } while ( currL < L ) { remove ( currL , a ) ; currL ++ ; } q [ i ] . armstrong = count_Armstrong ; } } void printResults ( Query q [ ] , int m ) { sort ( q , q + m , compare1 ) ; for ( int i = 0 ; i < m ; i ++ ) { cout << q [ i ] . armstrong << endl ; } } int main ( ) { int arr [ ] = { 18 , 153 , 8 , 9 , 14 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; Query q [ ] = { { 0 , 5 , 0 , 0 } , { 3 , 5 , 1 , 0 } } ; int m = sizeof ( q ) / sizeof ( q [ 0 ] ) ; queryResults ( arr , n , q , m ) ; printResults ( q , m ) ; return 0 ; }
Check if the Left View of the given tree is sorted or not | C ++ implementation to Check if the Left View of the given tree is Sorted or not ; Binary Tree Node ; Utility function to create a new node ; Function to find left view and check if it is sorted ; queue to hold values ; variable to check whether level order is sorted or not ; Iterate until the queue is empty ; Traverse every level in tree ; variable for initial level ; checking values are sorted or not ; Push left value if it is not null ; Push right value if it is not null ; Pop out the values from queue ; Check if the value are not sorted then break the loop ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int val ; struct node * right , * left ; } ; struct node * newnode ( int key ) { struct node * temp = new node ; temp -> val = key ; temp -> right = NULL ; temp -> left = NULL ; return temp ; } void func ( node * root ) { queue < node * > q ; bool t = true ; q . push ( root ) ; int i = -1 , j = -1 , k = -1 ; while ( ! q . empty ( ) ) { int h = q . size ( ) ; while ( h > 0 ) { root = q . front ( ) ; if ( i == -1 ) { j = root -> val ; } if ( i == -2 ) { if ( j <= root -> val ) { j = root -> val ; i = -3 ; } else { t = false ; break ; } } if ( root -> left != NULL ) { q . push ( root -> left ) ; } if ( root -> right != NULL ) { q . push ( root -> right ) ; } h = h - 1 ; q . pop ( ) ; } i = -2 ; if ( t == false ) { break ; } } if ( t ) cout << " true " << endl ; else cout << " false " << endl ; } int main ( ) { struct node * root = newnode ( 10 ) ; root -> right = newnode ( 50 ) ; root -> right -> right = newnode ( 15 ) ; root -> left = newnode ( 20 ) ; root -> left -> left = newnode ( 50 ) ; root -> left -> right = newnode ( 23 ) ; root -> right -> left = newnode ( 10 ) ; func ( root ) ; return 0 ; }
Divide a sorted array in K parts with sum of difference of max and min minimized in each part | C ++ program to find the minimum sum of differences possible for the given array when the array is divided into K subarrays ; Function to find the minimum sum of differences possible for the given array when the array is divided into K subarrays ; Array to store the differences between two adjacent elements ; Iterating through the array ; Storing differences to p ; Sorting p in descending order ; Sum of the first k - 1 values of p ; Computing the result ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calculate_minimum_split ( int n , int a [ ] , int k ) { int p [ n - 1 ] ; for ( int i = 1 ; i < n ; i ++ ) p [ i - 1 ] = a [ i ] - a [ i - 1 ] ; sort ( p , p + n - 1 , greater < int > ( ) ) ; int min_sum = 0 ; for ( int i = 0 ; i < k - 1 ; i ++ ) min_sum += p [ i ] ; int res = a [ n - 1 ] - a [ 0 ] - min_sum ; return res ; } int main ( ) { int arr [ 6 ] = { 4 , 8 , 15 , 16 , 23 , 42 } ; int k = 3 ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << calculate_minimum_split ( n , arr , k ) ; }
Sort an Array of dates in ascending order using Custom Comparator | C ++ implementation to sort the array of dates in the form of " DD - MM - YYYY " using custom comparator ; Comparator to sort the array of dates ; Condition to check the year ; Condition to check the month ; Condition to check the day ; Function that prints the dates in ascensding order ; Sort the dates using library sort function with custom Comparator ; Loop to print the dates ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int myCompare ( string date1 , string date2 ) { string day1 = date1 . substr ( 0 , 2 ) ; string month1 = date1 . substr ( 3 , 2 ) ; string year1 = date1 . substr ( 6 , 4 ) ; string day2 = date2 . substr ( 0 , 2 ) ; string month2 = date2 . substr ( 3 , 2 ) ; string year2 = date2 . substr ( 6 , 4 ) ; if ( year1 < year2 ) return 1 ; if ( year1 > year2 ) return 0 ; if ( month1 < month2 ) return 1 ; if ( month1 > month2 ) return 0 ; if ( day1 < day2 ) return 1 ; if ( day1 > day2 ) return 0 ; } void printDatesAscending ( vector < string > arr ) { sort ( arr . begin ( ) , arr . end ( ) , myCompare ) ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) cout << arr [ i ] << " STRNEWLINE " ; } int main ( ) { vector < string > arr ; arr . push_back ( "25-08-1996" ) ; arr . push_back ( "03-08-1970" ) ; arr . push_back ( "09-04-1994" ) ; arr . push_back ( "29-08-1996" ) ; arr . push_back ( "14-02-1972" ) ; printDatesAscending ( arr ) ; return 0 ; }
Sort an Array of Strings according to the number of Vowels in them | C ++ implementation of the approach ; Function to check the Vowel ; Returns count of vowels in str ; if ( isVowel ( str [ i ] ) ) Check for vowel ; Function to sort the array according to the number of the vowels ; Vector to store the number of vowels with respective elements ; Inserting number of vowels with respective strings in the vector pair ; Sort the vector , this will sort the pair according to the number of vowels ; Print the sorted vector content ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isVowel ( char ch ) { ch = toupper ( ch ) ; return ( ch == ' A ' ch == ' E ' ch == ' I ' ch == ' O ' ch == ' U ' ) ; } int countVowels ( string str ) { int count = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) ++ count ; return count ; } void sortArr ( string arr [ ] , int n ) { vector < pair < int , string > > vp ; for ( int i = 0 ; i < n ; i ++ ) { vp . push_back ( make_pair ( countVowels ( arr [ i ] ) , arr [ i ] ) ) ; } sort ( vp . begin ( ) , vp . end ( ) ) ; for ( int i = 0 ; i < vp . size ( ) ; i ++ ) cout << vp [ i ] . second << " ▁ " ; } int main ( ) { string arr [ ] = { " lmno " , " pqrst " , " aeiou " , " xyz " } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortArr ( arr , n ) ; return 0 ; }
Find the minimum cost to cross the River | C ++ implementation of the approach ; Function to return the minimum cost ; Sort the price array ; Calculate minimum price of n - 2 most costly person ; Both the ways as discussed above ; Calculate the minimum price of the two cheapest person ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE int minimumCost ( ll price [ ] , int n ) { sort ( price , price + n ) ; ll totalCost = 0 ; for ( int i = n - 1 ; i > 1 ; i -= 2 ) { if ( i == 2 ) { totalCost += price [ 2 ] + price [ 0 ] ; } else { ll price_first = price [ i ] + price [ 0 ] + 2 * price [ 1 ] ; ll price_second = price [ i ] + price [ i - 1 ] + 2 * price [ 0 ] ; totalCost += min ( price_first , price_second ) ; } } if ( n == 1 ) { totalCost += price [ 0 ] ; } else { totalCost += price [ 1 ] ; } return totalCost ; } int main ( ) { ll price [ ] = { 30 , 40 , 60 , 70 } ; int n = sizeof ( price ) / sizeof ( price [ 0 ] ) ; cout << minimumCost ( price , n ) ; return 0 ; }
Minimize the sum of differences of consecutive elements after removing exactly K elements | C ++ implementation of the above approach . ; states of DP ; function to find minimum sum ; base - case ; if state is solved before , return ; marking the state as solved ; recurrence relation ; driver function ; input values ; callin the required function ;
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 100 NEW_LINE #define INF 1000000 NEW_LINE int dp [ N ] [ N ] ; bool vis [ N ] [ N ] ; int findSum ( int * arr , int n , int k , int l , int r ) { if ( ( l ) + ( n - 1 - r ) == k ) return arr [ r ] - arr [ l ] ; if ( vis [ l ] [ r ] ) return dp [ l ] [ r ] ; vis [ l ] [ r ] = 1 ; return dp [ l ] [ r ] = min ( findSum ( arr , n , k , l , r - 1 ) , findSum ( arr , n , k , l + 1 , r ) ) ; } int32_t main ( ) { int arr [ ] = { 1 , 2 , 100 , 120 , 140 } ; int k = 2 ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << findSum ( arr , n , k , 0 , n - 1 ) ; }
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 ; Finding the index from where the even numbers will be stored ; Return the kth element ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getNumber ( int n , int k ) { int pos ; if ( n % 2 == 0 ) { pos = n / 2 ; } else { pos = ( n / 2 ) + 1 ; } if ( k <= pos ) { return ( k * 2 - 1 ) ; } else return ( ( k - pos ) * 2 ) ; } int main ( ) { int n = 8 , k = 5 ; cout << getNumber ( n , k ) ; return 0 ; }
All unique combinations whose sum equals to K | C ++ implementation of the approach ; Function to find all unique combination of given elements such that their sum is K ; If a unique combination is found ; For all other combinations ; Check if the sum exceeds K ; Check if it is repeated or not ; Take the element into the combination ; Recursive call ; Remove element from the combination ; Function to find all combination of the given elements ; Sort the given elements ; To store combination ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void unique_combination ( int l , int sum , int K , vector < int > & local , vector < int > & A ) { if ( sum == K ) { cout << " { " ; for ( int i = 0 ; i < local . size ( ) ; i ++ ) { if ( i != 0 ) cout << " ▁ " ; cout << local [ i ] ; if ( i != local . size ( ) - 1 ) cout << " , ▁ " ; } cout << " } " << endl ; return ; } for ( int i = l ; i < A . size ( ) ; i ++ ) { if ( sum + A [ i ] > K ) continue ; if ( i > l and A [ i ] == A [ i - 1 ] ) continue ; local . push_back ( A [ i ] ) ; unique_combination ( i + 1 , sum + A [ i ] , K , local , A ) ; local . pop_back ( ) ; } } void Combination ( vector < int > A , int K ) { sort ( A . begin ( ) , A . end ( ) ) ; vector < int > local ; unique_combination ( 0 , 0 , K , local , A ) ; } int main ( ) { vector < int > A = { 10 , 1 , 2 , 7 , 6 , 1 , 5 } ; int K = 8 ; Combination ( A , K ) ; return 0 ; }
Find the longest string that can be made up of other strings from the array | C ++ implementation of the approach ; Comparator to sort the string by their lengths in decreasing order ; Function that returns true if string s can be made up of by other two string from the array after concatenating one after another ; If current string has been processed before ; If current string is found in the map and it is not the string under consideration ; Split the string into two contiguous sub - strings ; If left sub - string is found in the map and the right sub - string can be made from the strings from the given array ; If everything failed , we return false ; Function to return the longest string that can made be made up from the other string of the given array ; Put all the strings in the map ; Sort the string in decreasing order of their lengths ; Starting from the longest string ; If current string can be made up from other strings ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool compare ( string s1 , string s2 ) { return s1 . size ( ) > s2 . size ( ) ; } bool canbuildword ( string & s , bool isoriginalword , map < string , bool > & mp ) { if ( mp . find ( s ) != mp . end ( ) && mp [ s ] == 0 ) return false ; if ( mp . find ( s ) != mp . end ( ) && mp [ s ] == 1 && isoriginalword == 0 ) { return true ; } for ( int i = 1 ; i < s . length ( ) ; i ++ ) { string left = s . substr ( 0 , i ) ; string right = s . substr ( i ) ; if ( mp . find ( left ) != mp . end ( ) && mp [ left ] == 1 && canbuildword ( right , 0 , mp ) ) { return true ; } } mp [ s ] = 0 ; return false ; } string printlongestword ( vector < string > listofwords ) { map < string , bool > mp ; for ( string s : listofwords ) { mp [ s ] = 1 ; } sort ( listofwords . begin ( ) , listofwords . end ( ) , compare ) ; for ( string s : listofwords ) { if ( canbuildword ( s , 1 , mp ) ) return s ; } return " - 1" ; } int main ( ) { vector < string > listofwords = { " geeks " , " for " , " geeksfor " , " geeksforgeeks " } ; cout << printlongestword ( listofwords ) ; 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 ; To store the closest sum ; Run three nested loops each loop for each element of triplet ; update the closestSum ; Return the closest sum found ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solution ( vector < int > & arr , int x ) { int closestSum = INT_MAX ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { for ( int j = i + 1 ; j < arr . size ( ) ; j ++ ) { for ( int k = j + 1 ; k < arr . size ( ) ; k ++ ) { if ( abs ( x - closestSum ) > abs ( x - ( arr [ i ] + arr [ j ] + arr [ k ] ) ) ) closestSum = ( arr [ i ] + arr [ j ] + arr [ k ] ) ; } } } return closestSum ; } int main ( ) { vector < int > arr = { -1 , 2 , 1 , -4 } ; int x = 1 ; cout << solution ( arr , x ) ; return 0 ; }
Build original array from the given sub | C ++ implementation of the approach ; Function to add edge to graph ; Function to calculate indegrees of all the vertices ; If there is an edge from i to x then increment indegree of x ; Function to perform topological sort ; Push every node to the queue which has no incoming edge ; Since edge u is removed , update the indegrees of all the nodes which had an incoming edge from u ; Function to generate the array from the given sub - sequences ; Create the graph from the input sub - sequences ; Add edge between every two consecutive elements of the given sub - sequences ; Get the indegrees for all the vertices ; Get the topological order of the created graph ; Driver code ; Size of the required array ; Given sub - sequences of the array ; Get the resultant array as vector ; Printing the array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void addEdge ( vector < int > adj [ ] , int u , int v ) { adj [ u ] . push_back ( v ) ; } void getindeg ( vector < int > adj [ ] , int V , vector < int > & indeg ) { for ( int i = 0 ; i < V ; i ++ ) { for ( auto x : adj [ i ] ) { indeg [ x ] ++ ; } } } vector < int > topo ( vector < int > adj [ ] , int V , vector < int > & indeg ) { queue < int > q ; for ( int i = 0 ; i < V ; i ++ ) { if ( indeg [ i ] == 0 ) q . push ( i ) ; } vector < int > res ; while ( ! q . empty ( ) ) { int u = q . front ( ) ; q . pop ( ) ; res . push_back ( u ) ; for ( auto x : adj [ u ] ) { indeg [ x ] -- ; if ( indeg [ x ] == 0 ) q . push ( x ) ; } } return res ; } vector < int > makearray ( vector < vector < int > > v , int V ) { vector < int > adj [ V ] ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { for ( int j = 0 ; j < v [ i ] . size ( ) - 1 ; j ++ ) { addEdge ( adj , v [ i ] [ j ] , v [ i ] [ j + 1 ] ) ; } } vector < int > indeg ( V , 0 ) ; getindeg ( adj , V , indeg ) ; vector < int > res = topo ( adj , V , indeg ) ; return res ; } int main ( ) { int n = 10 ; vector < vector < int > > subseqs { { 9 , 1 , 2 , 8 , 3 } , { 6 , 1 , 2 } , { 9 , 6 , 3 , 4 } , { 5 , 2 , 7 } , { 0 , 9 , 5 , 4 } } ; vector < int > res = makearray ( subseqs , n ) ; for ( auto x : res ) { cout << x << " ▁ " ; } return 0 ; }
Sum of Semi | C ++ implementation of the approach ; Vector to store the primes ; Create a boolean array " prime [ 0 . . n ] " ; Initialize all prime values to be true ; If prime [ p ] is not changed then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked ; Print all prime numbers ; Function to return the semi - prime sum ; Variable to store the sum of semi - primes ; Iterate over the prime values ; Break the loop once the product exceeds N ; Add valid products which are less than or equal to N each product is a semi - prime number ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE vector < ll > pr ; bool prime [ 10000000 + 1 ] ; void sieve ( ll n ) { for ( int i = 2 ; i <= n ; i += 1 ) { prime [ i ] = 1 ; } for ( ll p = 2 ; ( ll ) p * ( ll ) p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( ll i = ( ll ) p * ( ll ) p ; i <= n ; i += p ) prime [ i ] = false ; } } for ( ll p = 2 ; p <= n ; p ++ ) if ( prime [ p ] ) pr . push_back ( p ) ; } ll SemiPrimeSum ( ll N ) { ll ans = 0 ; for ( int i = 0 ; i < pr . size ( ) ; i += 1 ) { for ( int j = i ; j < pr . size ( ) ; j += 1 ) { if ( ( ll ) pr [ i ] * ( ll ) pr [ j ] > N ) break ; ans += ( ll ) pr [ i ] * ( ll ) pr [ j ] ; } } return ans ; } int main ( ) { ll N = 6 ; sieve ( N ) ; cout << SemiPrimeSum ( N ) ; return 0 ; }
Compress the array into Ranges | C ++ program to compress the array ranges ; Function to compress the array ranges ; start iteration from the ith array element ; loop until arr [ i + 1 ] == arr [ i ] and increment j ; if the program do not enter into the above while loop this means that ( i + 1 ) th element is not consecutive to i th element ; increment i for next iteration ; print the consecutive range found ; move i jump directly to j + 1 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void compressArr ( int arr [ ] , int n ) { int i = 0 , j = 0 ; sort ( arr , arr + n ) ; while ( i < n ) { j = i ; while ( ( j + 1 < n ) && ( arr [ j + 1 ] == arr [ j ] + 1 ) ) { j ++ ; } if ( i == j ) { cout << arr [ i ] << " ▁ " ; i ++ ; } else { cout << arr [ i ] << " - " << arr [ j ] << " ▁ " ; i = j + 1 ; } } } int main ( ) { int n = 7 ; int arr [ n ] = { 1 , 3 , 4 , 5 , 6 , 9 , 10 } ; compressArr ( arr , n ) ; }
Remove elements to make array sorted | C ++ implementation of the approach ; Function to sort the array by removing misplaced elements ; brr [ ] is used to store the sorted array elements ; Print the sorted array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void removeElements ( int arr [ ] , int n ) { int brr [ n ] , l = 1 ; brr [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { if ( brr [ l - 1 ] <= arr [ i ] ) { brr [ l ] = arr [ i ] ; l ++ ; } } for ( int i = 0 ; i < l ; i ++ ) cout << brr [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 10 , 12 , 9 , 10 , 2 , 13 , 14 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; removeElements ( arr , n ) ; return 0 ; }
Remove elements to make array sorted | C ++ implementation of the approach ; Function to sort the array by removing misplaced elements ; l stores the index ; Print the sorted array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void removeElements ( int arr [ ] , int n ) { int l = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ l - 1 ] <= arr [ i ] ) { arr [ l ] = arr [ i ] ; l ++ ; } } for ( int i = 0 ; i < l ; i ++ ) cout << arr [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 10 , 12 , 9 , 10 , 2 , 13 , 14 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; removeElements ( arr , n ) ; return 0 ; }
Find number from its divisors | C ++ implementation of the approach ; Function that returns X ; Sort the given array ; Get the possible X ; Container to store divisors ; Find the divisors of x ; Check if divisor ; sort the vec because a is sorted and we have to compare all the elements ; if size of both vectors is not same then we are sure that both vectors can 't be equal ; Check if a and vec have same elements in them ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findX ( int a [ ] , int n ) { sort ( a , a + n ) ; int x = a [ 0 ] * a [ n - 1 ] ; vector < int > vec ; for ( int i = 2 ; i * i <= x ; i ++ ) { if ( x % i == 0 ) { vec . push_back ( i ) ; if ( ( x / i ) != i ) vec . push_back ( x / i ) ; } } sort ( vec . begin ( ) , vec . end ( ) ) ; if ( vec . size ( ) != n ) return -1 ; else { int i = 0 ; for ( auto it : vec ) { if ( a [ i ++ ] != it ) return -1 ; } } return x ; } int main ( ) { int a [ ] = { 2 , 5 , 4 , 10 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << findX ( a , n ) ; return 0 ; }
Program to print an array in Pendulum Arrangement with constant space | C ++ implementation of the approach ; Function to print the Pendulum arrangement of the given array ; Sort the array ; pos stores the index of the last element of the array ; odd stores the last odd index in the array ; Move all odd index positioned elements to the right ; Shift the elements by one position from odd to pos ; Reverse the element from 0 to ( n - 1 ) / 2 ; Printing the pendulum arrangement ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void pendulumArrangement ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int odd , temp , in , pos ; pos = n - 1 ; if ( n % 2 == 0 ) odd = n - 1 ; else odd = n - 2 ; while ( odd > 0 ) { temp = arr [ odd ] ; in = odd ; while ( in != pos ) { arr [ in ] = arr [ in + 1 ] ; in ++ ; } arr [ in ] = temp ; odd = odd - 2 ; pos = pos - 1 ; } int start = 0 , end = ( n - 1 ) / 2 ; for ( ; start < end ; start ++ , end -- ) { temp = arr [ start ] ; arr [ start ] = arr [ end ] ; arr [ end ] = temp ; } for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 11 , 2 , 4 , 55 , 6 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; pendulumArrangement ( arr , n ) ; return 0 ; }
Find all the pairs with given sum in a BST | Set 2 | C ++ implementation of the above approach ; A binary tree node ; Function to add a node to the BST ; If the tree is empty , return a new node ; Otherwise , recur down the tree ; Function to find the target pairs ; LeftList which stores the left side values ; RightList which stores the right side values ; curr_left pointer is used for left side execution and curr_right pointer is used for right side execution ; Storing the left side values into LeftList till leaf node not found ; Storing the right side values into RightList till leaf node not found ; Last node of LeftList ; Last node of RightList ; To prevent repetition like 2 , 6 and 6 , 2 ; Delete the last value of LeftList and make the execution to the right side ; Delete the last value of RightList and make the execution to the left side ; ( left value + right value ) = target then print the left value and right value Delete the last value of left and right list and make the left execution to right side and right side execution to left side ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right , * root ; Node ( int data ) { this -> data = data ; left = NULL ; right = NULL ; root = NULL ; } } ; Node * AddNode ( Node * root , int data ) { if ( root == NULL ) { root = new Node ( data ) ; return root ; } if ( root -> data < data ) root -> right = AddNode ( root -> right , data ) ; else if ( root -> data > data ) root -> left = AddNode ( root -> left , data ) ; return root ; } void TargetPair ( Node * node , int tar ) { vector < Node * > LeftList ; vector < Node * > RightList ; Node * curr_left = node ; Node * curr_right = node ; while ( curr_left != NULL || curr_right != NULL || LeftList . size ( ) > 0 && RightList . size ( ) > 0 ) { while ( curr_left != NULL ) { LeftList . push_back ( curr_left ) ; curr_left = curr_left -> left ; } while ( curr_right != NULL ) { RightList . push_back ( curr_right ) ; curr_right = curr_right -> right ; } Node * LeftNode = LeftList [ LeftList . size ( ) - 1 ] ; Node * RightNode = RightList [ RightList . size ( ) - 1 ] ; int leftVal = LeftNode -> data ; int rightVal = RightNode -> data ; if ( leftVal >= rightVal ) break ; if ( leftVal + rightVal < tar ) { LeftList . pop_back ( ) ; curr_left = LeftNode -> right ; } else if ( leftVal + rightVal > tar ) { RightList . pop_back ( ) ; curr_right = RightNode -> left ; } else { cout << LeftNode -> data << " ▁ " << RightNode -> data << endl ; RightList . pop_back ( ) ; LeftList . pop_back ( ) ; curr_left = LeftNode -> right ; curr_right = RightNode -> left ; } } } int main ( ) { Node * root = NULL ; root = AddNode ( root , 2 ) ; root = AddNode ( root , 6 ) ; root = AddNode ( root , 5 ) ; root = AddNode ( root , 3 ) ; root = AddNode ( root , 4 ) ; root = AddNode ( root , 1 ) ; root = AddNode ( root , 7 ) ; int sum = 8 ; TargetPair ( root , sum ) ; }
Minimum number greater than the maximum of array which cannot be formed using the numbers in the array | C ++ implementation of the approach ; Function that returns the minimum number greater than maximum of the array that cannot be formed using the elements of the array ; Sort the given array ; Maximum number in the array ; table [ i ] will store the minimum number of elements from the array to form i ; Calculate the minimum number of elements from the array required to form the numbers from 1 to ( 2 * max ) ; If there exists a number greater than the maximum element of the array that can be formed using the numbers of array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findNumber ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int max = arr [ n - 1 ] ; int table [ ( 2 * max ) + 1 ] ; table [ 0 ] = 0 ; for ( int i = 1 ; i < ( 2 * max ) + 1 ; i ++ ) table [ i ] = INT_MAX ; int ans = -1 ; for ( int i = 1 ; i < ( 2 * max ) + 1 ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ j ] <= i ) { int res = table [ i - arr [ j ] ] ; if ( res != INT_MAX && res + 1 < table [ i ] ) table [ i ] = res + 1 ; } } if ( i > arr [ n - 1 ] && table [ i ] == INT_MAX ) { ans = i ; break ; } } return ans ; } int main ( ) { int arr [ ] = { 6 , 7 , 15 } ; int n = ( sizeof ( arr ) / sizeof ( int ) ) ; cout << findNumber ( arr , n ) ; return 0 ; }
Product of all Subsequences of size K except the minimum and maximum Elements | C ++ program to find product of all Subsequences of size K except the minimum and maximum Elements ; 2D array to store value of combinations nCr ; Function to pre - calculate value of all combinations nCr ; Function to calculate product of all subsequences except the minimum and maximum elements ; Sorting array so that it becomes easy to calculate the number of times an element will come in first or last place ; An element will occur ' powa ' times in total of which ' powla ' times it will be last element and ' powfa ' times it will be first element ; In total it will come powe = powa - powla - powfa times ; Multiplying a [ i ] powe times using Fermat Little Theorem under MODulo MOD for fast exponentiation ; Driver Code ; pre - calculation of all combinations
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MOD 1000000007 NEW_LINE #define ll long long NEW_LINE #define max 101 NEW_LINE ll C [ max - 1 ] [ max - 1 ] ; ll power ( ll x , unsigned ll y ) { unsigned ll res = 1 ; x = x % MOD ; while ( y > 0 ) { if ( y & 1 ) { res = ( res * x ) % MOD ; } y = y >> 1 ; x = ( x * x ) % MOD ; } return res % MOD ; } void combi ( int n , int k ) { int i , j ; for ( i = 0 ; i <= n ; i ++ ) { for ( j = 0 ; j <= min ( i , k ) ; j ++ ) { if ( j == 0 j == i ) C [ i ] [ j ] = 1 ; else C [ i ] [ j ] = ( C [ i - 1 ] [ j - 1 ] % MOD + C [ i - 1 ] [ j ] % MOD ) % MOD ; } } } unsigned ll product ( ll a [ ] , int n , int k ) { unsigned ll ans = 1 ; sort ( a , a + n ) ; ll powa = C [ n - 1 ] [ k - 1 ] ; for ( int i = 0 ; i < n ; i ++ ) { ll powla = C [ i ] [ k - 1 ] ; ll powfa = C [ n - i - 1 ] [ k - 1 ] ; ll powe = ( ( powa % MOD ) - ( powla + powfa ) % MOD + MOD ) % MOD ; unsigned ll mul = power ( a [ i ] , powe ) % MOD ; ans = ( ( ans % MOD ) * ( mul % MOD ) ) % MOD ; } return ans % MOD ; } int main ( ) { combi ( 100 , 100 ) ; ll arr [ ] = { 1 , 2 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof arr [ 0 ] ; int k = 3 ; unsigned ll ans = product ( arr , n , k ) ; cout << ans << endl ; return 0 ; }
Bitwise AND of N binary strings | C ++ implementation of the above approach ; Helper method : given two unequal sized bit strings , converts them to same length by adding leading 0 s in the smaller string . Returns the the new length ; Return len_b which is highest . No need to proceed further ! ; Return len_a which is greater or equal to len_b ; The main function that performs AND operation of two - bit sequences and returns the resultant string ; Make both strings of same length with the maximum length of s1 & s2 . ; Initialize res as NULL string ; We start from left to right as we have made both strings of same length . ; Convert s1 [ i ] and s2 [ i ] to int and perform bitwise AND operation , append to " res " string ; Driver Code ; Check corner case : If there is just one binary string , then print it and return .
#include <bits/stdc++.h> NEW_LINE using namespace std ; int makeEqualLength ( string & a , string & b ) { int len_a = a . length ( ) ; int len_b = b . length ( ) ; int num_zeros = abs ( len_a - len_b ) ; if ( len_a < len_b ) { for ( int i = 0 ; i < num_zeros ; i ++ ) { a = '0' + a ; } return len_b ; } else { for ( int i = 0 ; i < num_zeros ; i ++ ) { b = '0' + b ; } } return len_a ; } string andOperationBitwise ( string s1 , string s2 ) { int length = makeEqualLength ( s1 , s2 ) ; string res = " " ; for ( int i = 0 ; i < length ; i ++ ) { res = res + ( char ) ( ( s1 [ i ] - '0' & s2 [ i ] - '0' ) + '0' ) ; } return res ; } int main ( ) { string arr [ ] = { "101" , "110110" , "111" } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; string result ; if ( n < 2 ) { cout << arr [ n - 1 ] << endl ; return 0 ; } result = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { result = andOperationBitwise ( result , arr [ i ] ) ; } cout << result << endl ; }
Maximum number of segments that can contain the given points | C ++ implementation of the approach ; Function to return the maximum number of segments ; Sort both the vectors ; Initially pointing to the first element of b [ ] ; Try to find a match in b [ ] ; The segment ends before b [ j ] ; The point lies within the segment ; The segment starts after b [ j ] ; Return the required count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPoints ( int n , int m , vector < int > a , vector < int > b , int x , int y ) { sort ( a . begin ( ) , a . end ( ) ) ; sort ( b . begin ( ) , b . end ( ) ) ; int j = 0 ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { while ( j < m ) { if ( a [ i ] + y < b [ j ] ) break ; if ( b [ j ] >= a [ i ] - x && b [ j ] <= a [ i ] + y ) { count ++ ; j ++ ; break ; } else j ++ ; } } return count ; } int main ( ) { int x = 1 , y = 4 ; vector < int > a = { 1 , 5 } ; int n = a . size ( ) ; vector < int > b = { 1 , 1 , 2 } ; int m = a . size ( ) ; cout << countPoints ( n , m , a , b , x , y ) ; return 0 ; }
Merge K sorted arrays | Set 3 ( Using Divide and Conquer Approach ) | C ++ program to merge K sorted arrays ; Merge and sort k arrays ; Put the elements in sorted array . ; Sort the output array ; Driver Function ; Input 2D - array ; Number of arrays ; Output array ; Print merged array
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 4 NEW_LINE void merge_and_sort ( int * output , int arr [ ] [ N ] , int n , int k ) { for ( int i = 0 ; i < k ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { output [ i * n + j ] = arr [ i ] [ j ] ; } } sort ( output , output + n * k ) ; } int main ( ) { int arr [ ] [ N ] = { { 5 , 7 , 15 , 18 } , { 1 , 8 , 9 , 17 } , { 1 , 4 , 7 , 7 } } ; int n = N ; int k = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int * output = new int [ n * k ] ; merge_and_sort ( output , arr , n , k ) ; for ( int i = 0 ; i < n * k ; i ++ ) cout << output [ i ] << " ▁ " ; 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 ; will not work for negative elements , so . . adding this ; adding this to handle negative elements too . ; 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 . ; changed here as in case of even elements there will be 2 medians ; 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 ; int mod ; if ( matrix [ 0 ] [ 0 ] < 0 ) { mod = k - ( abs ( matrix [ 0 ] [ 0 ] ) % k ) ; } else { mod = matrix [ 0 ] [ 0 ] % k ; } for ( int i = 0 ; i < n ; ++ i ) { for ( int j = 0 ; j < m ; ++ j ) { arr . push_back ( matrix [ i ] [ j ] ) ; int val = matrix [ i ] [ j ] ; if ( val < 0 ) { int res = k - ( abs ( val ) % k ) ; if ( res != mod ) { return -1 ; } } else { int foo = matrix [ i ] [ j ] ; if ( foo % 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 ; }
Smallest subarray containing minimum and maximum values | C ++ implementation of above approach ; Function to return length of smallest subarray containing both maximum and minimum value ; find maximum and minimum values in the array ; iterate over the array and set answer to smallest difference between position of maximum and position of minimum value ; last occurrence of minValue ; last occurrence of maxValue ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minSubarray ( int A [ ] , int n ) { int minValue = * min_element ( A , A + n ) ; int maxValue = * max_element ( A , A + n ) ; int pos_min = -1 , pos_max = -1 , ans = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { if ( A [ i ] == minValue ) pos_min = i ; if ( A [ i ] == maxValue ) pos_max = i ; if ( pos_max != -1 and pos_min != -1 ) ans = min ( ans , abs ( pos_min - pos_max ) + 1 ) ; } return ans ; } int main ( ) { int A [ ] = { 1 , 5 , 9 , 7 , 1 , 9 , 4 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << minSubarray ( A , n ) ; return 0 ; }
Minimum number of consecutive sequences that can be formed in an array | C ++ program find the minimum number of consecutive sequences in an array ; Driver program ; function call to print required answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSequences ( int arr [ ] , int n ) { int count = 1 ; sort ( arr , arr + n ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) if ( arr [ i ] + 1 != arr [ i + 1 ] ) count ++ ; return count ; } int main ( ) { int arr [ ] = { 1 , 7 , 3 , 5 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countSequences ( arr , n ) ; return 0 ; }
Minimum number of increment / decrement operations such that array contains all elements from 1 to N | C ++ implementation of the above approach ; Function to find the minimum operations ; Sort the given array ; Count operations by assigning a [ i ] = i + 1 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long minimumMoves ( int a [ ] , int n ) { long long operations = 0 ; sort ( a , a + n ) ; for ( int i = 0 ; i < n ; i ++ ) operations += abs ( a [ i ] - ( i + 1 ) ) ; return operations ; } int main ( ) { int arr [ ] = { 5 , 3 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minimumMoves ( arr , n ) ; return 0 ; }
Print a case where the given sorting algorithm fails | C ++ program to find a case where the given algorithm fails ; Function to print a case where the given sorting algorithm fails ; only case where it fails ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printCase ( int n ) { if ( n <= 2 ) { cout << -1 ; return ; } for ( int i = n ; i >= 1 ; i -- ) cout << i << " ▁ " ; } int main ( ) { int n = 3 ; printCase ( n ) ; return 0 ; }
Find the missing elements from 1 to M in given N ranges | C ++ program to find missing elements from given Ranges ; Function to find missing elements from given Ranges ; First of all sort all the given ranges ; store ans in a different vector ; prev is use to store end of last range ; j is used as a counter for ranges ; for last segment ; finally print all answer ; Driver code ; Store ranges in vector of pair
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMissingNumber ( vector < pair < int , int > > ranges , int m ) { sort ( ranges . begin ( ) , ranges . end ( ) ) ; vector < int > ans ; int prev = 0 ; for ( int j = 0 ; j < ranges . size ( ) ; j ++ ) { int start = ranges [ j ] . first ; int end = ranges [ j ] . second ; for ( int i = prev + 1 ; i < start ; i ++ ) ans . push_back ( i ) ; prev = end ; } for ( int i = prev + 1 ; i <= m ; i ++ ) ans . push_back ( i ) ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) { if ( ans [ i ] <= m ) cout << ans [ i ] << " ▁ " ; } } int main ( ) { int N = 2 , M = 6 ; vector < pair < int , int > > ranges ; ranges . push_back ( { 1 , 2 } ) ; ranges . push_back ( { 4 , 5 } ) ; findMissingNumber ( ranges , M ) ; return 0 ; }
Check whether it is possible to make both arrays equal by modifying a single element | C ++ implementation of the above approach ; Function to check if both sequences can be made equal ; Sorting both the arrays ; Flag to tell if there are more than one mismatch ; To stores the index of mismatched element ; If there is more than one mismatch then return False ; If there is no mismatch or the difference between the mismatching elements is <= k then return true ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; static bool check ( int n , int k , int * a , int * b ) { sort ( a , a + n ) ; sort ( b , b + n ) ; bool fl = false ; int ind = -1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] != b [ i ] ) { if ( fl == true ) { return false ; } fl = true ; ind = i ; } } if ( ind == -1 | abs ( a [ ind ] - b [ ind ] ) <= k ) { return true ; } return false ; } int main ( ) { int n = 2 , k = 4 ; int a [ ] = { 1 , 5 } ; int b [ ] = { 1 , 1 } ; if ( check ( n , k , a , b ) ) { printf ( " Yes " ) ; } else { printf ( " No " ) ; } return 0 ; }
Sum of width ( max and min diff ) of all Subsequences | CPP implementation of above approach ; Function to return sum of width of all subsets ; Sort the array ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MOD 1000000007 NEW_LINE int SubseqWidths ( int A [ ] , int n ) { sort ( A , A + n ) ; int pow2 [ n ] ; pow2 [ 0 ] = 1 ; for ( int i = 1 ; i < n ; ++ i ) pow2 [ i ] = ( pow2 [ i - 1 ] * 2 ) % MOD ; int ans = 0 ; for ( int i = 0 ; i < n ; ++ i ) ans = ( ans + ( pow2 [ i ] - pow2 [ n - 1 - i ] ) * A [ i ] ) % MOD ; return ans ; } int main ( ) { int A [ ] = { 5 , 6 , 4 , 3 , 8 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << SubseqWidths ( A , n ) ; return 0 ; }
Covering maximum array elements with given value | C ++ implementation of the approach ; Function to find value for covering maximum array elements ; sort the students in ascending based on the candies ; To store the number of happy students ; To store the running sum ; If the current student can 't be made happy ; increment the count if we can make the ith student happy ; If the sum = x then answer is n ; If the count is equal to n then the answer is n - 1 ; Driver function
# include <bits/stdc++.h> NEW_LINE using namespace std ; int maxArrayCover ( vector < int > a , int n , int x ) { sort ( a . begin ( ) , a . end ( ) ) ; int cc = 0 ; int s = 0 ; for ( int i = 0 ; i < n ; i ++ ) { s += a [ i ] ; if ( s > x ) { break ; } cc += 1 ; } if ( accumulate ( a . begin ( ) , a . end ( ) , 0 ) == x ) { return n ; } else { if ( cc == n ) { return n - 1 ; } else { return cc ; } } } int main ( ) { int n = 3 ; int x = 70 ; vector < int > a = { 10 , 20 , 30 } ; printf ( " % d STRNEWLINE " , maxArrayCover ( a , n , x ) ) ; return 0 ; }
Quotient | CPP program to implement Quotient - Remainder Sort ; max_element finds maximum element in an array ; min_element finds minimum element in an array ; Creating a ROW * COL matrix of all zeros ; Driver Code
#include <algorithm> NEW_LINE #include <iostream> NEW_LINE using namespace std ; void QRsort ( int arr [ ] , int size ) { int MAX = * max_element ( arr , arr + size ) ; int MIN = * min_element ( arr , arr + size ) ; cout << " Maximum ▁ Element ▁ found ▁ is ▁ : ▁ " << MAX << endl ; cout << " Minimum ▁ Element ▁ found ▁ is ▁ : ▁ " << MIN << endl ; int COL = MIN ; int ROW = MAX / MIN + 1 ; int matrix [ ROW ] [ COL ] = { 0 } ; for ( int i = 0 ; i < size ; i ++ ) { int quotient = arr [ i ] / MIN ; int remainder = arr [ i ] % MIN ; matrix [ quotient ] [ remainder + 1 ] = arr [ i ] ; } int k = 0 ; for ( int i = 0 ; i < ROW ; i ++ ) { for ( int j = 0 ; j < COL ; j ++ ) { if ( matrix [ i ] [ j ] != 0 ) { arr [ k ++ ] = matrix [ i ] [ j ] ; } } } } void printArray ( int arr [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) cout << arr [ i ] << " ▁ " ; cout << endl ; } int main ( ) { int arr [ ] = { 5 , 3 , 7 , 4 , 8 , 2 , 6 } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Initial ▁ Array ▁ : ▁ " << endl ; printArray ( arr , size ) ; QRsort ( arr , size ) ; cout << " Array ▁ after ▁ sorting ▁ : ▁ " << endl ; printArray ( arr , size ) ; }
Check if a Linked List is Pairwise Sorted | C ++ program to check if linked list is pairwise sorted ; A linked list node ; Function to check if linked list is pairwise sorted ; Traverse further only if there are at - least two nodes left ; Function to add a node at the beginning of Linked List ; allocate node ; put in the data ; link the old list off the new node ; move the head to point to the new node ; Driver program to test above function ; The constructed linked list is : 10 -> 15 -> 9 -> 9 -> 1 -> 5
#include <iostream> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; bool isPairWiseSorted ( struct Node * head ) { bool flag = true ; struct Node * temp = head ; while ( temp != NULL && temp -> next != NULL ) { if ( temp -> data > temp -> next -> data ) { flag = false ; break ; } temp = temp -> next -> next ; } return flag ; } void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } int main ( ) { struct Node * start = NULL ; push ( & start , 5 ) ; push ( & start , 1 ) ; push ( & start , 9 ) ; push ( & start , 9 ) ; push ( & start , 15 ) ; push ( & start , 10 ) ; if ( isPairWiseSorted ( start ) ) cout << " YES " ; else cout << " NO " ; return 0 ; }
Maximum Sum of Products of Two Arrays | CPP program to calculate maximum sum of products of two arrays ; Function that calculates maximum sum of products of two arrays ; Variable to store the sum of products of array elements ; length of the arrays ; Sorting both the arrays ; Traversing both the arrays and calculating sum of product ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumSOP ( int * a , int * b ) { int sop = 0 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; sort ( a , a + n + 1 ) ; sort ( b , b + n + 1 ) ; for ( int i = 0 ; i <= n ; i ++ ) { sop += a [ i ] * b [ i ] ; } return sop ; } int main ( ) { int A [ ] = { 1 , 2 , 3 } ; int B [ ] = { 4 , 5 , 1 } ; cout << maximumSOP ( A , B ) ; return 0 ; }
Count number of triplets with product equal to given number | Set 2 | C ++ implementation of above approach ; Function to count such triplets ; Sort the array ; three pointer technique ; Calculate the product of a triplet ; Check if that product is greater than m , decrement mid ; Check if that product is smaller than m , increment start ; Check if that product is equal to m , decrement mid , increment start and increment the count of pairs ; Drivers code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countTriplets ( int arr [ ] , int n , int m ) { int count = 0 ; sort ( arr , arr + n ) ; int end , start , mid ; for ( end = n - 1 ; end >= 2 ; end -- ) { int start = 0 , mid = end - 1 ; while ( start < mid ) { long int prod = arr [ end ] * arr [ start ] * arr [ mid ] ; if ( prod > m ) mid -- ; else if ( prod < m ) start ++ ; else if ( prod == m ) { count ++ ; mid -- ; start ++ ; } } } return count ; } int main ( ) { int arr [ ] = { 1 , 1 , 1 , 1 , 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int m = 1 ; cout << countTriplets ( arr , n , m ) ; 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 . ; Insert all the resources in the set There will be unique resources in the set ; return minimum of distinct resources and n / 2 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int distribution ( int arr [ ] , int n ) { set < int , greater < int > > resources ; for ( int i = 0 ; i < n ; i ++ ) resources . insert ( arr [ i ] ) ; int m = resources . size ( ) ; return min ( m , 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 ; }