text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Minimum Number of Bullets required to penetrate all bricks | C ++ program for the above approach ; Custom comparator function ; Function to find the minimum number of bullets required to penetrate all bricks ; Sort the points in ascending order ; Check if there are no points ; Iterate through all the points ; Increase the count ; Return the count ; Driver Code ; Given coordinates of bricks ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool compare ( vector < int > & a , vector < int > & b ) { return a [ 1 ] < b [ 1 ] ; } int findMinBulletShots ( vector < vector < int > > & points ) { sort ( points . begin ( ) , points . end ( ) , compare ) ; if ( points . size ( ) == 0 ) return 0 ; int cnt = 1 ; int curr = points [ 0 ] [ 1 ] ; for ( int j = 1 ; j < points . size ( ) ; j ++ ) { if ( curr < points [ j ] [ 0 ] ) { cnt ++ ; curr = points [ j ] [ 1 ] ; } } return cnt ; } int main ( ) { vector < vector < int > > bricks { { 5000 , 900000 } , { 1 , 100 } , { 150 , 499 } } ; cout << findMinBulletShots ( bricks ) ; return 0 ; } |
Count array elements that can be maximized by adding any permutation of first N natural numbers | C ++ program for the above approach ; Comparator function to sort the given array ; Function to get the count of values that can have the maximum value ; Sort array in decreasing order ; Stores the answer ; mark stores the maximum value till each index i ; Check if arr [ i ] can be maximum ; Update the mark ; Print the total count ; Driver Code ; Given array arr [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool cmp ( int x , int y ) { return x > y ; } void countMaximum ( int * a , int n ) { sort ( a , a + n , cmp ) ; int count = 0 ; int mark = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( ( a [ i ] + n >= mark ) ) { count += 1 ; } mark = max ( mark , a [ i ] + i + 1 ) ; } cout << count ; } int main ( ) { int arr [ ] = { 8 , 9 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countMaximum ( arr , N ) ; } |
Kth character from the Nth string obtained by the given operations | C ++ program for the above approach ; Function to return Kth character from recursive string ; If N is 1 then return A ; Iterate a loop and generate the recursive string ; Update current string ; Change A to B and B to A ; Reverse the previous string ; Return the kth character ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; char findKthChar ( int n , int k ) { string prev = " A " ; string cur = " " ; if ( n == 1 ) { return ' A ' ; } for ( int i = 2 ; i <= n ; i ++ ) { cur = prev + " B " ; for ( int i = 0 ; i < prev . length ( ) ; i ++ ) { if ( prev [ i ] == ' A ' ) { prev [ i ] = ' B ' ; } else { prev [ i ] = ' A ' ; } } reverse ( prev . begin ( ) , prev . end ( ) ) ; cur += prev ; prev = cur ; } return cur [ k - 1 ] ; } int main ( ) { int N = 4 ; int K = 3 ; cout << findKthChar ( N , K ) ; return 0 ; } |
Maximize length of subarray of equal elements by performing at most K increment operations | C ++ 14 program for above approach ; Function to find the maximum length of subarray of equal elements after performing at most K increments ; Stores the size of required subarray ; Starting point of a window ; Stores the sum of window ; Iterate over array ; Current element ; Remove index of minimum elements from deque which are less than the current element ; Insert current index in deque ; Update current window sum ; Calculate required operation to make current window elements equal ; If cost is less than k ; Shift window start pointer towards right and update current window sum ; Return answer ; Driver Code ; Length of array | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define newl " NEW_LINE " int maxSubarray ( int a [ ] , int k , int n ) { int answer = 0 ; int start = 0 ; long int s = 0 ; deque < int > dq ; for ( int i = 0 ; i < n ; i ++ ) { int x = a [ i ] ; while ( ! dq . empty ( ) && a [ dq . front ( ) ] <= x ) dq . pop_front ( ) ; dq . push_back ( i ) ; s += x ; long int cost = ( long int ) a [ dq . front ( ) ] * ( answer + 1 ) - s ; if ( cost <= ( long int ) k ) answer ++ ; else { if ( dq . front ( ) == start ) dq . pop_front ( ) ; s -= a [ start ++ ] ; } } return answer ; } int main ( ) { int a [ ] = { 2 , 2 , 4 } ; int k = 10 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << ( maxSubarray ( a , k , n ) ) ; return 0 ; } |
Find depth of the deepest odd level leaf node | C ++ program to find depth of the deepest odd level leaf node ; A utility function to find maximum of two integers ; A Binary Tree node ; A utility function to allocate a new tree node ; A recursive function to find depth of the deepest odd level leaf ; Base Case ; If this node is a leaf and its level is odd , return its level ; If not leaf , return the maximum value from left and right subtrees ; Main function which calculates the depth of deepest odd level leaf . This function mainly uses depthOfOddLeafUtil ( ) ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int max ( int x , int y ) { return ( x > y ) ? x : y ; } struct Node { int data ; struct Node * left , * right ; } ; struct Node * newNode ( int data ) { struct Node * node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; node -> data = data ; node -> left = node -> right = NULL ; return node ; } int depthOfOddLeafUtil ( struct Node * root , int level ) { if ( root == NULL ) return 0 ; if ( root -> left == NULL && root -> right == NULL && level & 1 ) return level ; return max ( depthOfOddLeafUtil ( root -> left , level + 1 ) , depthOfOddLeafUtil ( root -> right , level + 1 ) ) ; } int depthOfOddLeaf ( struct Node * root ) { int level = 1 , depth = 0 ; return depthOfOddLeafUtil ( root , level ) ; } int main ( ) { struct Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> right -> left = newNode ( 5 ) ; root -> right -> right = newNode ( 6 ) ; root -> right -> left -> right = newNode ( 7 ) ; root -> right -> right -> right = newNode ( 8 ) ; root -> right -> left -> right -> left = newNode ( 9 ) ; root -> right -> right -> right -> right = newNode ( 10 ) ; root -> right -> right -> right -> right -> left = newNode ( 11 ) ; cout << depthOfOddLeaf ( root ) << " β is β the β required β depth " ; getchar ( ) ; return 0 ; } |
Check if an array can be split into subarrays with GCD exceeding K | C ++ program for the above approach ; Function to check if it is possible to split an array into subarrays having GCD at least K ; Iterate over the array arr [ ] ; If the current element is less than or equal to k ; If no array element is found to be less than or equal to k ; Driver Code ; Given array arr [ ] ; Length of the array ; Given K ; Function Call | #include <iostream> NEW_LINE using namespace std ; string canSplitArray ( int arr [ ] , int n , int k ) { for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] <= k ) { return " No " ; } } return " Yes " ; } int main ( ) { int arr [ ] = { 2 , 4 , 6 , 1 , 8 , 16 } ; int N = sizeof arr / sizeof arr [ 0 ] ; int N = sizeof arr / sizeof arr [ 0 ] ; int K = 3 ; cout << canSplitArray ( arr , N , K ) ; } |
Smallest subarray from a given Array with sum greater than or equal to K | Set 2 | C ++ 14 program for the above approach ; Function to find the smallest subarray sum greater than or equal to target ; Base Case ; If sum of the array is less than target ; If target is equal to the sum of the array ; Required condition ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int smallSumSubset ( vector < int > data , int target , int maxVal ) { int sum = 0 ; for ( int i : data ) sum += i ; if ( target <= 0 ) return 0 ; else if ( sum < target ) return maxVal ; else if ( sum == target ) return data . size ( ) ; else if ( data [ 0 ] >= target ) return 1 ; else if ( data [ 0 ] < target ) { vector < int > temp ; for ( int i = 1 ; i < data . size ( ) ; i ++ ) temp . push_back ( data [ i ] ) ; return min ( smallSumSubset ( temp , target , maxVal ) , 1 + smallSumSubset ( temp , target - data [ 0 ] , maxVal ) ) ; } } int main ( ) { vector < int > data = { 3 , 1 , 7 , 1 , 2 } ; int target = 11 ; int val = smallSumSubset ( data , target , data . size ( ) + 1 ) ; if ( val > data . size ( ) ) cout << -1 ; else cout << val ; } |
Maximize cost obtained by removal of substrings " pr " or " rp " from a given String | C ++ Program to implement the above approach ; Function to maintain the case , X >= Y ; To maintain X >= Y ; Replace ' p ' to ' r ' ; Replace ' r ' to ' p ' . ; Function to return the maximum cost ; Stores the length of the string ; To maintain X >= Y . ; Stores the maximum cost ; Stores the count of ' p ' after removal of all " pr " substrings up to str [ i ] ; Stores the count of ' r ' after removal of all " pr " substrings up to str [ i ] ; Stack to maintain the order of characters after removal of substrings ; If substring " pr " is removed ; Increase cost by X ; If any substring " rp " left in the Stack ; If any substring " rp " left in the Stack ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool swapXandY ( string & str , int X , int Y ) { int N = str . length ( ) ; swap ( X , Y ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( str [ i ] == ' p ' ) { str [ i ] = ' r ' ; } else if ( str [ i ] == ' r ' ) { str [ i ] = ' p ' ; } } } int maxCost ( string str , int X , int Y ) { int N = str . length ( ) ; if ( Y > X ) { swapXandY ( str , X , Y ) ; } int res = 0 ; int countP = 0 ; int countR = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( str [ i ] == ' p ' ) { countP ++ ; } else if ( str [ i ] == ' r ' ) { if ( countP > 0 ) { countP -- ; res += X ; } else countR ++ ; } else { res += min ( countP , countR ) * Y ; countP = 0 ; countR = 0 ; } } res += min ( countP , countR ) * Y ; return res ; } int main ( ) { string str = " abppprrr " ; int X = 5 , Y = 4 ; cout << maxCost ( str , X , Y ) ; } |
Check if an array contains only one distinct element | C ++ program for the above approach ; Function to find if the array contains only one distinct element ; Assume first element to be the unique element ; Traversing the array ; If current element is not equal to X then break the loop and print No ; Compare and print the result ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void uniqueElement ( int arr [ ] , int n ) { int x = arr [ 0 ] ; int flag = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] != x ) { flag = 0 ; break ; } } if ( flag == 1 ) cout << " Yes " ; else cout << " No " ; } int main ( ) { int arr [ ] = { 9 , 9 , 9 , 9 , 9 , 9 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; uniqueElement ( arr , n ) ; } |
Maximum Count of pairs having equal Sum based on the given conditions | C ++ Program to implement the above approach ; Function to find the maximum count of pairs having equal sum ; Size of the array ; Iterate through evey sum of pairs possible from the given array ; Count of pairs with given sum ; Check for a possible pair ; Update count of possible pair ; Update the answer by taking the pair which is maximum for every possible sum ; Return the max possible pair ; Function to return the count of pairs ; Size of the array ; Stores the frequencies ; Count the frequency ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxCount ( vector < int > & freq , int mini , int maxi ) { int n = freq . size ( ) - 1 ; int ans = 0 ; for ( int sum = 2 * mini ; sum <= 2 * maxi ; ++ sum ) { int possiblePair = 0 ; for ( int firElement = 1 ; firElement < ( sum + 1 ) / 2 ; firElement ++ ) { if ( sum - firElement <= maxi ) { possiblePair += min ( freq [ firElement ] , freq [ sum - firElement ] ) ; } } if ( sum % 2 == 0 ) { possiblePair += freq [ sum / 2 ] / 2 ; } ans = max ( ans , possiblePair ) ; } return ans ; } int countofPairs ( vector < int > & a ) { int n = a . size ( ) ; int mini = * min_element ( a . begin ( ) , a . end ( ) ) , maxi = * max_element ( a . begin ( ) , a . end ( ) ) ; vector < int > freq ( n + 1 , 0 ) ; for ( int i = 0 ; i < n ; ++ i ) freq [ a [ i ] ] ++ ; return maxCount ( freq , mini , maxi ) ; } int main ( ) { vector < int > a = { 1 , 2 , 4 , 3 , 3 , 5 , 6 } ; cout << countofPairs ( a ) << endl ; } |
Maximum Subarray Sum possible by replacing an Array element by its Square | C ++ program to implement the above approach ; Function to find the maximum subarray sum possible ; Stores sum without squaring ; Stores sum squaring ; Stores the maximum subarray sum ; Either extend the subarray or start a new subarray ; Either extend previous squared subarray or start a new subarray by squaring the current element ; Update maximum subarray sum ; Return answer ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getMaxSum ( int a [ ] , int n ) { int dp [ n ] [ 2 ] ; dp [ 0 ] [ 0 ] = a [ 0 ] ; dp [ 0 ] [ 1 ] = a [ 0 ] * a [ 0 ] ; int max_sum = max ( dp [ 0 ] [ 0 ] , dp [ 0 ] [ 1 ] ) ; for ( int i = 1 ; i < n ; i ++ ) { dp [ i ] [ 0 ] = max ( a [ i ] , dp [ i - 1 ] [ 0 ] + a [ i ] ) ; dp [ i ] [ 1 ] = max ( dp [ i - 1 ] [ 1 ] + a [ i ] , a [ i ] * a [ i ] ) ; dp [ i ] [ 1 ] = max ( dp [ i ] [ 1 ] , dp [ i - 1 ] [ 0 ] + a [ i ] * a [ i ] ) ; max_sum = max ( max_sum , dp [ i ] [ 1 ] ) ; max_sum = max ( max_sum , dp [ i ] [ 0 ] ) ; } return max_sum ; } int32_t main ( ) { int n = 5 ; int a [ ] = { 1 , -5 , 8 , 12 , -8 } ; cout << getMaxSum ( a , n ) << endl ; return 0 ; } |
Smallest Subarray with Sum K from an Array | C ++ Program to implement the above approach ; Function to find the length of the smallest subarray with sum K ; Stores the frequency of prefix sums in the array ; Initialize len as INT_MAX ; If sum of array till i - th index is less than K ; No possible subarray exists till i - th index ; Find the exceeded value ; If exceeded value is zero ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int subArraylen ( int arr [ ] , int n , int K ) { unordered_map < int , int > mp ; mp [ arr [ 0 ] ] = 0 ; for ( int i = 1 ; i < n ; i ++ ) { arr [ i ] = arr [ i ] + arr [ i - 1 ] ; mp [ arr [ i ] ] = i ; } int len = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < K ) continue ; else { int x = arr [ i ] - K ; if ( x == 0 ) len = min ( len , i ) ; if ( mp . find ( x ) == mp . end ( ) ) continue ; else { len = min ( len , i - mp [ x ] ) ; } } } return len ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 3 , 2 , 4 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 7 ; int len = subArraylen ( arr , n , K ) ; if ( len == INT_MAX ) { cout << " - 1" ; } else { cout << len << endl ; } return 0 ; } |
Find depth of the deepest odd level leaf node | CPP program to find depth of the deepest odd level leaf node of binary tree ; tree node ; returns a new tree Node ; return max odd number depth of leaf node ; create a queue for level order traversal ; traverse until the queue is empty ; traverse for complete level ; check if the node is leaf node and level is odd if level is odd , then update result ; check for left child ; check for right child ; driver program ; construct a tree | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int data ) { Node * temp = new Node ( ) ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } int maxOddLevelDepth ( Node * root ) { if ( ! root ) return 0 ; queue < Node * > q ; q . push ( root ) ; int result = INT_MAX ; int level = 0 ; while ( ! q . empty ( ) ) { int size = q . size ( ) ; level += 1 ; while ( size > 0 ) { Node * temp = q . front ( ) ; q . pop ( ) ; if ( ! temp -> left && ! temp -> right && ( level % 2 != 0 ) ) { result = level ; } if ( temp -> left ) { q . push ( temp -> left ) ; } if ( temp -> right ) { q . push ( temp -> right ) ; } size -= 1 ; } } return result ; } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> right -> left = newNode ( 5 ) ; root -> right -> right = newNode ( 6 ) ; root -> right -> left -> right = newNode ( 7 ) ; root -> right -> right -> right = newNode ( 8 ) ; root -> right -> left -> right -> left = newNode ( 9 ) ; root -> right -> right -> right -> right = newNode ( 10 ) ; root -> right -> right -> right -> right -> left = newNode ( 11 ) ; int result = maxOddLevelDepth ( root ) ; if ( result == INT_MAX ) cout << " No β leaf β node β at β odd β level STRNEWLINE " ; else cout << result ; cout << " β is β the β required β depth β " << endl ; return 0 ; } |
Nth Term of a Fibonacci Series of Primes formed by concatenating pairs of Primes in a given range | C ++ program to implement the above approach ; Stores at each index if it 's a prime or not ; Sieve of Eratosthenes to generate all possible primes ; If p is a prime ; Set all multiples of p as non - prime ; Function to generate the required Fibonacci Series ; Stores all primes between n1 and n2 ; Generate all primes between n1 and n2 ; Stores all concatenations of each pair of primes ; Generate all concatenations of each pair of primes ; Stores the primes out of the numbers generated above ; Store the unique primes ; Find the minimum ; Find the minimum ; Find N ; Print the N - th term of the Fibonacci Series ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define int long long int NEW_LINE int prime [ 100001 ] ; void SieveOfEratosthenes ( ) { for ( int i = 0 ; i < 100001 ; i ++ ) prime [ i ] = 1 ; int p = 2 ; while ( p * p <= 100000 ) { if ( prime [ p ] == 1 ) { for ( int i = p * p ; i < 100001 ; i += p ) prime [ i ] = 0 ; } p += 1 ; } } int join ( int a , int b ) { int mul = 1 ; int bb = b ; while ( b != 0 ) { mul *= 10 ; b /= 10 ; } a *= mul ; a += bb ; return a ; } void fibonacciOfPrime ( int n1 , int n2 ) { SieveOfEratosthenes ( ) ; vector < int > initial ; for ( int i = n1 ; i <= n2 ; i ++ ) if ( prime [ i ] ) initial . push_back ( i ) ; vector < int > now ; for ( auto a : initial ) for ( auto b : initial ) if ( a != b ) { int c = join ( a , b ) ; now . push_back ( c ) ; } vector < int > current ; for ( auto x : now ) if ( prime [ x ] ) current . push_back ( x ) ; set < int > current_set ; for ( auto i : current ) current_set . insert ( i ) ; int first = * min_element ( current_set . begin ( ) , current_set . end ( ) ) ; int second = * max_element ( current_set . begin ( ) , current_set . end ( ) ) ; int count = current_set . size ( ) - 1 ; int curr = 1 ; int c ; while ( curr < count ) { c = first + second ; first = second ; second = c ; curr += 1 ; } cout << ( c ) << endl ; } int32_t main ( ) { int x = 2 ; int y = 40 ; fibonacciOfPrime ( x , y ) ; } |
Count of Array elements greater than all elements on its left and next K elements on its right | C ++ Program to implement the above approach ; Function to print the count of Array elements greater than all elements on its left and next K elements on its right ; Iterate over the array ; If the stack is not empty and the element at the top of the stack is smaller than arr [ i ] ; Store the index of next greater element ; Pop the top element ; Insert the current index ; Stores the count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countElements ( int arr [ ] , int n , int k ) { stack < int > s ; vector < int > next_greater ( n , n + 1 ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . empty ( ) ) { s . push ( i ) ; continue ; } while ( ! s . empty ( ) && arr [ s . top ( ) ] < arr [ i ] ) { next_greater [ s . top ( ) ] = i ; s . pop ( ) ; } s . push ( i ) ; } int count = 0 ; int maxi = INT_MIN ; for ( int i = 0 ; i < n ; i ++ ) { if ( next_greater [ i ] - i > k && maxi < arr [ i ] ) { maxi = max ( maxi , arr [ i ] ) ; count ++ ; } } return count ; } int main ( ) { int arr [ ] = { 4 , 2 , 3 , 6 , 4 , 3 , 2 } ; int K = 2 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countElements ( arr , n , K ) ; return 0 ; } |
Maximize length of Subarray of 1 's after removal of a pair of consecutive Array elements | C ++ program to find the maximum count of 1 s ; If arr [ i - 2 ] = = 1 then we increment the count of occurences of 1 's ; else we initialise the count with 0 ; If arr [ i + 2 ] = = 1 then we increment the count of occurences of 1 's ; else we initialise the count with 0 ; We get the maximum count by skipping the current and the next element . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void maxLengthOf1s ( vector < int > arr , int n ) { vector < int > prefix ( n , 0 ) ; for ( int i = 2 ; i < n ; i ++ ) { if ( arr [ i - 2 ] == 1 ) prefix [ i ] = prefix [ i - 1 ] + 1 ; else prefix [ i ] = 0 ; } vector < int > suffix ( n , 0 ) ; for ( int i = n - 3 ; i >= 0 ; i -- ) { if ( arr [ i + 2 ] == 1 ) suffix [ i ] = suffix [ i + 1 ] + 1 ; else suffix [ i ] = 0 ; } int ans = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { ans = max ( ans , prefix [ i + 1 ] + suffix [ i ] ) ; } cout << ans << " STRNEWLINE " ; } int main ( ) { int n = 6 ; vector < int > arr = { 1 , 1 , 1 , 0 , 1 , 1 } ; maxLengthOf1s ( arr , n ) ; return 0 ; } |
Minimum number of operations required to obtain a given Binary String | C ++ Program to implement the above approach ; Function to find the minimum number of operations required to obtain the string s ; Iterate the string s ; If first occurrence of 1 is found ; Mark the index ; Base case : If no 1 occurred ; No operations required ; Stores the character for which last operation was performed ; Stores minimum number of operations ; Iterate from pos to n ; Check if s [ i ] is 0 ; Check if last operation was performed because of 1 ; Set last to 0 ; Check if last operation was performed because of 0 ; Set last to 1 ; Return the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperations ( string s ) { int n = s . size ( ) ; int pos = -1 ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { if ( s [ i ] == '1' ) { pos = i ; break ; } } if ( pos == -1 ) { return 0 ; } int last = 1 ; int ans = 1 ; for ( int i = pos + 1 ; i < n ; i ++ ) { if ( s [ i ] == '0' ) { if ( last == 1 ) { ans ++ ; last = 0 ; } } else { if ( last == 0 ) { ans ++ ; last = 1 ; } } } return ans ; } int main ( ) { string s = "10111" ; cout << minOperations ( s ) ; return 0 ; } |
Find the Deepest Node in a Binary Tree | A C ++ program to find value of the deepest node in a given binary tree ; A tree node ; Utility function to create a new node ; maxLevel : keeps track of maximum level seen so far . res : Value of deepest node so far . level : Level of root ; Update level and resue ; Returns value of deepest node ; Initialze result and max level ; Updates value " res " and " maxLevel " Note that res and maxLen are passed by reference . ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } void find ( Node * root , int level , int & maxLevel , int & res ) { if ( root != NULL ) { find ( root -> left , ++ level , maxLevel , res ) ; if ( level > maxLevel ) { res = root -> data ; maxLevel = level ; } find ( root -> right , level , maxLevel , res ) ; } } int deepestNode ( Node * root ) { int res = -1 ; int maxLevel = -1 ; find ( root , 0 , maxLevel , res ) ; return res ; } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> right -> left = newNode ( 5 ) ; root -> right -> right = newNode ( 6 ) ; root -> right -> left -> right = newNode ( 7 ) ; root -> right -> right -> right = newNode ( 8 ) ; root -> right -> left -> right -> left = newNode ( 9 ) ; cout << deepestNode ( root ) ; return 0 ; } |
Count the number of clumps in the given Array | C ++ program to calculate the number of clumps in an array ; Function to count the number of clumps in the given array arr [ ] ; Initialise count of clumps as 0 ; Traverse the arr [ ] ; Whenever a sequence of same value is encountered ; Return the count of clumps ; Driver Code ; length of the given array arr [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countClumps ( int arr [ ] , int N ) { int clumps = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { int flag = 0 ; while ( arr [ i ] == arr [ i + 1 ] ) { flag = 1 ; i ++ ; } if ( flag ) clumps ++ ; } return clumps ; } int main ( ) { int arr [ ] = { 13 , 15 , 66 , 66 , 66 , 37 , 37 , 8 , 8 , 11 , 11 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countClumps ( arr , N ) << ' ' ; return 0 ; } |
Find if string is K | C ++ program to find if string is K - Palindrome or not using all characters exactly once ; when size of string is less than k ; when size of string is equal to k ; when size of string is greater than k to store the frequencies of the characters ; to store the count of characters whose number of occurrences is odd . ; iterating over the map ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void iskPalindromesPossible ( string s , int k ) { if ( s . size ( ) < k ) { cout << " Not β Possible " << endl ; return ; } if ( s . size ( ) == k ) { cout << " Possible " << endl ; return ; } map < char , int > freq ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) freq [ s [ i ] ] ++ ; int count = 0 ; for ( auto it : freq ) { if ( it . second % 2 == 1 ) count ++ ; } if ( count > k ) cout << " No " << endl ; else cout << " Yes " << endl ; } int main ( ) { string str = " poor " ; int K = 3 ; iskPalindromesPossible ( str , K ) ; str = " geeksforgeeks " ; K = 10 ; iskPalindromesPossible ( str , K ) ; return 0 ; } |
Find the Deepest Node in a Binary Tree | A C ++ program to find value of the deepest node in a given binary tree ; A tree node with constructor ; Utility function to find height of a tree , rooted at ' root ' . ; levels : current Level Utility function to print all nodes at a given level . ; Driver program ; Calculating height of tree ; Printing the deepest node | #include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * left , * right ; Node ( int key ) { data = key ; left = NULL ; right = NULL ; } } ; int height ( Node * root ) { if ( ! root ) return 0 ; int leftHt = height ( root -> left ) ; int rightHt = height ( root -> right ) ; return max ( leftHt , rightHt ) + 1 ; } void deepestNode ( Node * root , int levels ) { if ( ! root ) return ; if ( levels == 1 ) cout << root -> data ; else if ( levels > 1 ) { deepestNode ( root -> left , levels - 1 ) ; deepestNode ( root -> right , levels - 1 ) ; } } int main ( ) { Node * root = new Node ( 1 ) ; root -> left = new Node ( 2 ) ; root -> right = new Node ( 3 ) ; root -> left -> left = new Node ( 4 ) ; root -> right -> left = new Node ( 5 ) ; root -> right -> right = new Node ( 6 ) ; root -> right -> left -> right = new Node ( 7 ) ; root -> right -> right -> right = new Node ( 8 ) ; root -> right -> left -> right -> left = new Node ( 9 ) ; int levels = height ( root ) ; deepestNode ( root , levels ) ; return 0 ; } |
Check if an array is sorted and rotated using Binary Search | ; Function to return the index of the pivot ; Base cases ; Check if element at ( mid - 1 ) is pivot Consider the cases like { 4 , 5 , 1 , 2 , 3 } ; Decide whether we need to go to the left half or the right half ; Function to check if a given array is sorted rotated or not ; To check if the elements to the left of the pivot are in descending or not ; To check if the elements to the right of the pivot are in ascending or not ; If both of the above if is true Then the array is sorted rotated ; Else the array is not sorted rotated ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findPivot ( int arr [ ] , int low , int high ) { if ( high < low ) return -1 ; if ( high == low ) return low ; int mid = ( low + high ) / 2 ; if ( mid < high && arr [ mid + 1 ] < arr [ mid ] ) { return mid ; } if ( mid > low && arr [ mid ] < arr [ mid - 1 ] ) { return mid - 1 ; } if ( arr [ low ] > arr [ mid ] ) { return findPivot ( arr , low , mid - 1 ) ; } else { return findPivot ( arr , mid + 1 , high ) ; } } bool isRotated ( int arr [ ] , int n ) { int l = 0 ; int r = n - 1 ; int pivot = -1 ; if ( arr [ l ] > arr [ r ] ) { pivot = findPivot ( arr , l , r ) ; int temp = pivot ; if ( l < pivot ) { while ( pivot > l ) { if ( arr [ pivot ] < arr [ pivot - 1 ] ) { return false ; } pivot -- ; } } pivot = temp ; if ( pivot < r ) { pivot ++ ; while ( pivot < r ) { if ( arr [ pivot ] > arr [ pivot + 1 ] ) { return false ; } pivot ++ ; } } return true ; } else { return false ; } } int main ( ) { int arr [ ] = { 4 , 5 , 1 , 3 , 2 } ; if ( isRotated ( arr , 5 ) ) cout << " true " ; else cout << " false " ; return 0 ; } |
Find a distinct pair ( x , y ) in given range such that x divides y | C ++ implementation of the approach ; Function to return the possible pair ; ans1 , ans2 store value of x and y respectively ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findpair ( int l , int r ) { int ans1 = l ; int ans2 = 2 * l ; cout << ans1 << " , β " << ans2 << endl ; } int main ( ) { int l = 1 , r = 10 ; findpair ( l , r ) ; } |
Jump in rank of a student after updating marks | C ++ implementation of the approach ; Function to print the name of student who stood first after updation in rank ; Array of students ; Store the name of the student ; Update the marks of the student ; Store the current rank of the student ; Print the name and jump in rank ; Driver code ; Names of the students ; Marks of the students ; Updates that are to be done ; Number of students | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Student { string name ; int marks = 0 ; int prev_rank = 0 ; } ; void nameRank ( string names [ ] , int marks [ ] , int updates [ ] , int n ) { Student x [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { x [ i ] . name = names [ i ] ; x [ i ] . marks = marks [ i ] + updates [ i ] ; x [ i ] . prev_rank = i + 1 ; } Student highest = x [ 0 ] ; for ( int j = 1 ; j < n ; j ++ ) { if ( x [ j ] . marks >= highest . marks ) highest = x [ j ] ; } cout << " Name : β " << highest . name << " , β Jump : β " << abs ( highest . prev_rank - 1 ) << endl ; } int main ( ) { string names [ ] = { " sam " , " ram " , " geek " } ; int marks [ ] = { 80 , 79 , 75 } ; int updates [ ] = { 0 , 5 , -9 } ; int n = sizeof ( marks ) / sizeof ( marks [ 0 ] ) ; nameRank ( names , marks , updates , n ) ; } |
Integers from the range that are composed of a single distinct digit | C ++ implementation of the approach ; Function to return the count of digits of a number ; Function to return a number that contains only digit ' d ' repeated exactly count times ; Function to return the count of integers that are composed of a single distinct digit only ; Count of digits in L and R ; First digits of L and R ; If L has lesser number of digits than R ; If the number that starts with firstDigitL and has number of digits = countDigitsL is within the range include the number ; Exclude the number ; If the number that starts with firstDigitR and has number of digits = countDigitsR is within the range include the number ; Exclude the number ; If both L and R have equal number of digits ; Include the number greater than L upto the maximum number whose digit = coutDigitsL ; Exclude the numbers which are greater than R ; Return the count ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countDigits ( int n ) { int count = 0 ; while ( n > 0 ) { count += 1 ; n /= 10 ; } return count ; } int getDistinct ( int d , int count ) { int num = 0 ; count = pow ( 10 , count - 1 ) ; while ( count > 0 ) { num += ( count * d ) ; count /= 10 ; } return num ; } int findCount ( int L , int R ) { int count = 0 ; int countDigitsL = countDigits ( L ) ; int countDigitsR = countDigits ( R ) ; int firstDigitL = ( L / pow ( 10 , countDigitsL - 1 ) ) ; int firstDigitR = ( R / pow ( 10 , countDigitsR - 1 ) ) ; if ( countDigitsL < countDigitsR ) { count += ( 9 * ( countDigitsR - countDigitsL - 1 ) ) ; if ( getDistinct ( firstDigitL , countDigitsL ) >= L ) count += ( 9 - firstDigitL + 1 ) ; else count += ( 9 - firstDigitL ) ; if ( getDistinct ( firstDigitR , countDigitsR ) <= R ) count += firstDigitR ; else count += ( firstDigitR - 1 ) ; } else { if ( getDistinct ( firstDigitL , countDigitsL ) >= L ) count += ( 9 - firstDigitL + 1 ) ; else count += ( 9 - firstDigitL ) ; if ( getDistinct ( firstDigitR , countDigitsR ) <= R ) count -= ( 9 - firstDigitR ) ; else count -= ( 9 - firstDigitR + 1 ) ; } return count ; } int main ( ) { int L = 10 , R = 50 ; cout << findCount ( L , R ) ; return 0 ; } |
Check if a pair with given absolute difference exists in a Matrix | CPP code to check for pair with given difference exists in the matrix or not ; Function to check if a pair with given difference exists in the matrix ; Store elements in a hash ; Loop to iterate over the elements of the matrix ; Driver Code ; Input matrix ; Given difference | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 4 NEW_LINE #define M 4 NEW_LINE bool isPairWithDiff ( int mat [ N ] [ M ] , int k ) { unordered_set < int > ump ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( mat [ i ] [ j ] > k ) { int m = mat [ i ] [ j ] - k ; if ( ump . find ( m ) != ump . end ( ) ) { return true ; } } else { int m = k - mat [ i ] [ j ] ; if ( ump . find ( m ) != ump . end ( ) ) { return true ; } } ump . insert ( mat [ i ] [ j ] ) ; } } return false ; } int main ( ) { int mat [ N ] [ M ] = { { 5 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 100 } } ; int k = 85 ; if ( isPairWithDiff ( mat , k ) ) cout << " YES " << endl ; else cout << " NO " << endl ; return 0 ; } |
Next Smaller Element | A Stack based C ++ program to find next smaller element for all array elements ; prints NSE for elements of array arr [ ] of size n ; iterate for rest of the elementse ; if stack is not empty , then pop an element from stack . If the popped element is greater than next , then a ) print the pair b ) keep popping while elements are greater and stack is not empty ; push next to stack so that we can find NSE for it ; After iterating over the loop , the remaining elements in stack do not have any NSE , so set - 1 for them ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printNSE ( int arr [ ] , int n ) { stack < pair < int , int > > s ; vector < int > ans ( n ) ; for ( int i = 0 ; i < n ; i ++ ) { int next = arr [ i ] ; if ( s . empty ( ) ) { s . push ( { next , i } ) ; continue ; } while ( ! s . empty ( ) && s . top ( ) . first > next ) { ans [ s . top ( ) . second ] = next ; s . pop ( ) ; } s . push ( { next , i } ) ; } while ( ! s . empty ( ) ) { ans [ s . top ( ) . second ] = -1 ; s . pop ( ) ; } for ( int i = 0 ; i < n ; i ++ ) { cout << arr [ i ] << " β - - - > β " << ans [ i ] << endl ; } } int main ( ) { int arr [ ] = { 11 , 13 , 21 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printNSE ( arr , n ) ; return 0 ; } |
Deepest left leaf node in a binary tree | iterative approach | CPP program to find deepest left leaf node of binary tree ; tree node ; returns a new tree Node ; return the deepest left leaf node of binary tree ; create a queue for level order traversal ; traverse until the queue is empty ; Since we go level by level , the last stored left leaf node is deepest one , ; driver program ; construct a tree | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int data ) { Node * temp = new Node ( ) ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } Node * getDeepestLeftLeafNode ( Node * root ) { if ( ! root ) return NULL ; queue < Node * > q ; q . push ( root ) ; Node * result = NULL ; while ( ! q . empty ( ) ) { Node * temp = q . front ( ) ; q . pop ( ) ; if ( temp -> left ) { q . push ( temp -> left ) ; if ( ! temp -> left -> left && ! temp -> left -> right ) result = temp -> left ; } if ( temp -> right ) q . push ( temp -> right ) ; } return result ; } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> right -> left = newNode ( 5 ) ; root -> right -> right = newNode ( 6 ) ; root -> right -> left -> right = newNode ( 7 ) ; root -> right -> right -> right = newNode ( 8 ) ; root -> right -> left -> right -> left = newNode ( 9 ) ; root -> right -> right -> right -> right = newNode ( 10 ) ; Node * result = getDeepestLeftLeafNode ( root ) ; if ( result ) cout << " Deepest β Left β Leaf β Node β : : β " << result -> data << endl ; else cout << " No β result , β left β leaf β not β found STRNEWLINE " ; return 0 ; } |
Find all possible binary trees with given Inorder Traversal | C ++ program to find binary tree with given inorder traversal ; Node structure ; A utility function to create a new tree Node ; A utility function to do preorder traversal of BST ; Function for constructing all possible trees with given inorder traversal stored in an array from arr [ start ] to arr [ end ] . This function returns a vector of trees . ; List to store all possible trees ; if start > end then subtree will be empty so returning NULL in the list ; Iterating through all values from start to end for constructing left and right subtree recursively ; Constructing left subtree ; Constructing right subtree ; Now looping through all left and right subtrees and connecting them to ith root below ; Making arr [ i ] as root ; Connecting left subtree ; Connecting right subtree ; Adding this tree to list ; Driver Program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * left , * right ; } ; struct Node * newNode ( int item ) { struct Node * temp = new Node ; temp -> key = item ; temp -> left = temp -> right = NULL ; return temp ; } void preorder ( Node * root ) { if ( root != NULL ) { printf ( " % d β " , root -> key ) ; preorder ( root -> left ) ; preorder ( root -> right ) ; } } vector < Node * > getTrees ( int arr [ ] , int start , int end ) { vector < Node * > trees ; if ( start > end ) { trees . push_back ( NULL ) ; return trees ; } for ( int i = start ; i <= end ; i ++ ) { vector < Node * > ltrees = getTrees ( arr , start , i - 1 ) ; vector < Node * > rtrees = getTrees ( arr , i + 1 , end ) ; for ( int j = 0 ; j < ltrees . size ( ) ; j ++ ) { for ( int k = 0 ; k < rtrees . size ( ) ; k ++ ) { Node * node = newNode ( arr [ i ] ) ; node -> left = ltrees [ j ] ; node -> right = rtrees [ k ] ; trees . push_back ( node ) ; } } } return trees ; } int main ( ) { int in [ ] = { 4 , 5 , 7 } ; int n = sizeof ( in ) / sizeof ( in [ 0 ] ) ; vector < Node * > trees = getTrees ( in , 0 , n - 1 ) ; cout << " Preorder β traversals β of β different β " << " possible β Binary β Trees β are β STRNEWLINE " ; for ( int i = 0 ; i < trees . size ( ) ; i ++ ) { preorder ( trees [ i ] ) ; printf ( " STRNEWLINE " ) ; } return 0 ; } |
Check if a string is suffix of another | CPP program to find if a string is suffix of another ; Test case - sensitive implementation of endsWith function | #include <boost/algorithm/string.hpp> NEW_LINE #include <iostream> NEW_LINE #include <string> NEW_LINE using namespace std ; int main ( ) { string s1 = " geeks " , s2 = " geeksforgeeks " ; bool result = boost :: algorithm :: ends_with ( s2 , s1 ) ; if ( result ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Maximum elements that can be made equal with k updates | C ++ program to find maximum elements that can be made equal with k updates ; Function to calculate the maximum number of equal elements possible with atmost K increment of values . Here we have done sliding window to determine that whether there are x number of elements present which on increment will become equal . The loop here will run in fashion like 0. . . x - 1 , 1. . . x , 2. . . x + 1 , ... . , n - x - 1. . . n - 1 ; It can be explained with the reasoning that if for some x number of elements we can update the values then the increment to the segment ( i to j having length -> x ) so that all will be equal is ( x * maxx [ j ] ) this is the total sum of segment and ( pre [ j ] - pre [ i ] ) is present sum So difference of them should be less than k if yes , then that segment length ( x ) can be possible return true ; sort the array in ascending order ; Initializing the prefix array and maximum array ; Calculating prefix sum of the array ; Calculating max value upto that position in the array ; Binary search applied for computation here ; printing result ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool ElementsCalculationFunc ( int pre [ ] , int maxx [ ] , int x , int k , int n ) { for ( int i = 0 , j = x ; j <= n ; j ++ , i ++ ) { if ( x * maxx [ j ] - ( pre [ j ] - pre [ i ] ) <= k ) return true ; } return false ; } void MaxNumberOfElements ( int a [ ] , int n , int k ) { sort ( a , a + n ) ; for ( int i = 0 ; i <= n ; ++ i ) { pre [ i ] = 0 ; maxx [ i ] = 0 ; } for ( int i = 1 ; i <= n ; i ++ ) { pre [ i ] = pre [ i - 1 ] + a [ i - 1 ] ; maxx [ i ] = max ( maxx [ i - 1 ] , a [ i - 1 ] ) ; } int l = 1 , r = n , ans ; while ( l < r ) { int mid = ( l + r ) / 2 ; if ( ElementsCalculationFunc ( pre , maxx , mid - 1 , k , n ) ) { ans = mid ; l = mid + 1 ; } else r = mid - 1 ; } cout << ans << " STRNEWLINE " ; } int main ( ) { int arr [ ] = { 2 , 4 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; MaxNumberOfElements ( arr , n , k ) ; return 0 ; } |
Count palindromic characteristics of a String | C ++ program which counts different palindromic characteristics of a string . ; function which checks whether a substring str [ i . . j ] of a given string is a palindrome or not . ; P [ i ] [ j ] = true if substring str [ i . . j ] is palindrome , else false ; palindrome of single length ; palindrome of length 2 ; Palindromes of length more then 2. This loop is similar to Matrix Chain Multiplication . We start with a gap of length 2 and fill P table in a way that gap between starting and ending indexes increases one by one by outer loop . ; Pick starting point for current gap ; Set ending point ; If current string is palindrome ; function which recursively counts if a string str [ i . . j ] is a k - palindromic string or not . ; terminating condition for a string which is a k - palindrome . ; terminating condition for a string which is not a k - palindrome . ; increases the counter for the string if it is a k - palindrome . ; mid is middle pointer of the string str [ i ... j ] . ; if length of string which is ( j - i + 1 ) is odd than we have to subtract one from mid . else if even then no change . ; if the string is k - palindrome then we check if it is a ( k + 1 ) - palindrome or not by just sending any of one half of the string to the Count_k_Palindrome function . ; Finding all palindromic substrings of given string ; counting k - palindromes for each and every substring of given string . . ; Output the number of K - palindromic substrings of a given string . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_STR_LEN = 1000 ; bool P [ MAX_STR_LEN ] [ MAX_STR_LEN ] ; int Kpal [ MAX_STR_LEN ] ; void checkSubStrPal ( string str , int n ) { memset ( P , false , sizeof ( P ) ) ; for ( int i = 0 ; i < n ; i ++ ) P [ i ] [ i ] = true ; for ( int i = 0 ; i < n - 1 ; i ++ ) if ( str [ i ] == str [ i + 1 ] ) P [ i ] [ i + 1 ] = true ; for ( int gap = 2 ; gap < n ; gap ++ ) { for ( int i = 0 ; i < n - gap ; i ++ ) { int j = gap + i ; if ( str [ i ] == str [ j ] && P [ i + 1 ] [ j - 1 ] ) P [ i ] [ j ] = true ; } } } void countKPalindromes ( int i , int j , int k ) { if ( i == j ) { Kpal [ k ] ++ ; return ; } if ( P [ i ] [ j ] == false ) return ; Kpal [ k ] ++ ; int mid = ( i + j ) / 2 ; if ( ( j - i + 1 ) % 2 == 1 ) mid -- ; countKPalindromes ( i , mid , k + 1 ) ; } void printKPalindromes ( string s ) { memset ( Kpal , 0 , sizeof ( Kpal ) ) ; int n = s . length ( ) ; checkSubStrPal ( s , n ) ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n - i ; j ++ ) countKPalindromes ( j , j + i , 1 ) ; for ( int i = 1 ; i <= n ; i ++ ) cout << Kpal [ i ] << " β " ; cout << " STRNEWLINE " ; } int main ( ) { string s = " abacaba " ; printKPalindromes ( s ) ; return 0 ; } |
Print number in ascending order which contains 1 , 2 and 3 in their digits . | CPP program to print all number containing 1 , 2 and 3 in any order . ; prints all the number containing 1 , 2 , 3 ; check if the number contains 1 , 2 & 3 in any order ; sort all the numbers ; convert the number to string and find if it contains 1 , 2 & 3. ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string printNumbers ( int numbers [ ] , int n ) { vector < int > oneTwoThree ; for ( int i = 0 ; i < n ; i ++ ) { if ( findContainsOneTwoThree ( numbers [ i ] ) ) oneTwoThree . push_back ( numbers [ i ] ) ; } sort ( oneTwoThree . begin ( ) , oneTwoThree . end ( ) ) ; string result = " " ; for ( auto number : oneTwoThree ) { int value = number ; if ( result . length ( ) > 0 ) result += " , β " ; result += to_string ( value ) ; } return ( result . length ( ) > 0 ) ? result : " - 1" ; } bool findContainsOneTwoThree ( int number ) { string str = to_string ( number ) ; int countOnes = 0 , countTwo = 0 , countThree = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] == '1' ) countOnes ++ ; else if ( str [ i ] == '2' ) countTwo ++ ; else if ( str [ i ] == '3' ) countThree ++ ; } return ( countOnes && countTwo && countThree ) ; } int main ( ) { int numbers [ ] = { 123 , 1232 , 456 , 234 , 32145 } ; int n = sizeof ( numbers ) / sizeof ( numbers [ 0 ] ) ; string result = printNumbers ( numbers , n ) ; cout << result ; return 0 ; } |
Find k | C ++ implementation to solve k queries for given n ranges ; Structure to store the start and end point ; Comparison function for sorting ; Function to find Kth smallest number in a vector of merged intervals ; Traverse merged [ ] to find Kth smallest element using Linear search . ; To combined both type of ranges , overlapping as well as non - overlapping . ; Sorting intervals according to start time ; Merging all intervals into merged ; To check if starting point of next range is lying between the previous range and ending point of next range is greater than the Ending point of previous range then update ending point of previous range by ending point of next range . ; If starting point of next range is greater than the ending point of previous range then store next range in merged [ ] . ; Driver \'s Function ; Merge all intervals into merged [ ] ; Processing all queries on merged intervals | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Interval { int s ; int e ; } ; bool comp ( Interval a , Interval b ) { return a . s < b . s ; } int kthSmallestNum ( vector < Interval > merged , int k ) { int n = merged . size ( ) ; for ( int j = 0 ; j < n ; j ++ ) { if ( k <= abs ( merged [ j ] . e - merged [ j ] . s + 1 ) ) return ( merged [ j ] . s + k - 1 ) ; k = k - abs ( merged [ j ] . e - merged [ j ] . s + 1 ) ; } if ( k ) return -1 ; } void mergeIntervals ( vector < Interval > & merged , Interval arr [ ] , int n ) { sort ( arr , arr + n , comp ) ; merged . push_back ( arr [ 0 ] ) ; for ( int i = 1 ; i < n ; i ++ ) { Interval prev = merged . back ( ) ; Interval curr = arr [ i ] ; if ( ( curr . s >= prev . s && curr . s <= prev . e ) && ( curr . e > prev . e ) ) merged . back ( ) . e = curr . e ; else { if ( curr . s > prev . e ) merged . push_back ( curr ) ; } } } int main ( ) { Interval arr [ ] = { { 2 , 6 } , { 4 , 7 } } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int query [ ] = { 5 , 8 } ; int q = sizeof ( query ) / sizeof ( query [ 0 ] ) ; vector < Interval > merged ; mergeIntervals ( merged , arr , n ) ; for ( int i = 0 ; i < q ; i ++ ) cout << kthSmallestNum ( merged , query [ i ] ) << endl ; return 0 ; } |
Grouping Countries | CPP program to count no of distinct countries from a given group of people ; Answer is valid if adjacent sitting num people give same answer ; someone gives different answer ; check next person ; one valid country group has been found ; driver program to test above function | #include <iostream> NEW_LINE using namespace std ; void countCountries ( int ans [ ] , int N ) { int total_countries = 0 , i = 0 ; bool invalid = false ; while ( i < N ) { int curr_size = ans [ i ] ; int num = ans [ i ] ; while ( num > 0 ) { if ( ans [ i ] != curr_size ) { cout << " Invalid β Answer STRNEWLINE " ; return ; } else num -- ; i ++ ; } total_countries ++ ; } cout << " There β are β " << total_countries << " β distinct β companies β in β the β group . STRNEWLINE " ; } int main ( ) { int ans [ ] = { 1 , 1 , 2 , 2 , 4 , 4 , 4 , 4 } ; int n = sizeof ( ans ) / sizeof ( ans [ 0 ] ) ; countCountries ( ans , n ) ; return 0 ; } |
Deepest left leaf node in a binary tree | A C ++ program to find the deepest left leaf in a given binary tree ; A Binary Tree node ; New node ; A utility function to find deepest leaf node . lvl : level of current node . maxlvl : pointer to the deepest left leaf node found so far isLeft : A bool indicate that this node is left child of its parent resPtr : Pointer to the result ; Base case ; Update result if this node is left leaf and its level is more than the maxl level of the current result ; Recur for left and right subtrees ; A wrapper over deepestLeftLeafUtil ( ) . ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int val ; struct Node * left , * right ; } ; Node * newNode ( int data ) { Node * temp = new Node ; temp -> val = data ; temp -> left = temp -> right = NULL ; return temp ; } void deepestLeftLeafUtil ( Node * root , int lvl , int * maxlvl , bool isLeft , Node * * resPtr ) { if ( root == NULL ) return ; if ( isLeft && ! root -> left && ! root -> right && lvl > * maxlvl ) { * resPtr = root ; * maxlvl = lvl ; return ; } deepestLeftLeafUtil ( root -> left , lvl + 1 , maxlvl , true , resPtr ) ; deepestLeftLeafUtil ( root -> right , lvl + 1 , maxlvl , false , resPtr ) ; } Node * deepestLeftLeaf ( Node * root ) { int maxlevel = 0 ; Node * result = NULL ; deepestLeftLeafUtil ( root , 0 , & maxlevel , false , & result ) ; return result ; } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> right -> left = newNode ( 5 ) ; root -> right -> right = newNode ( 6 ) ; root -> right -> left -> right = newNode ( 7 ) ; root -> right -> right -> right = newNode ( 8 ) ; root -> right -> left -> right -> left = newNode ( 9 ) ; root -> right -> right -> right -> right = newNode ( 10 ) ; Node * result = deepestLeftLeaf ( root ) ; if ( result ) cout << " The β deepest β left β child β is β " << result -> val ; else cout << " There β is β no β left β leaf β in β the β given β tree " ; return 0 ; } |
Check if an array contains all elements of a given range | C ++ Code for Check if an array contains all elements of a given range ; Function to check the array for elements in given range ; Range is the no . of elements that are to be checked ; Traversing the array ; If an element is in range ; Checking whether elements in range 0 - range are negative ; Element from range is missing from array ; All range elements are present ; Driver code ; Defining Array and size ; A is lower limit and B is the upper limit of range ; True denotes all elements were present ; False denotes any element was not present | #include <iostream> NEW_LINE using namespace std ; bool check_elements ( int arr [ ] , int n , int A , int B ) { int range = B - A ; for ( int i = 0 ; i < n ; i ++ ) { if ( abs ( arr [ i ] ) >= A && abs ( arr [ i ] ) <= B ) { int z = abs ( arr [ i ] ) - A ; if ( arr [ z ] > 0 ) { arr [ z ] = arr [ z ] * -1 ; } } } int count = 0 ; for ( int i = 0 ; i <= range && i < n ; i ++ ) { if ( arr [ i ] > 0 ) return false ; else count ++ ; } if ( count != ( range + 1 ) ) return false ; return true ; } int main ( ) { int arr [ ] = { 1 , 4 , 5 , 2 , 7 , 8 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int A = 2 , B = 5 ; if ( check_elements ( arr , n , A , B ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Recursive Programs to find Minimum and Maximum elements of array | Recursive C ++ program to find minimum ; function to print Minimum element using recursion ; if size = 0 means whole array has been traversed ; driver code to test above function | #include <iostream> NEW_LINE using namespace std ; int findMinRec ( int A [ ] , int n ) { if ( n == 1 ) return A [ 0 ] ; return min ( A [ n - 1 ] , findMinRec ( A , n - 1 ) ) ; } int main ( ) { int A [ ] = { 1 , 4 , 45 , 6 , -50 , 10 , 2 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << findMinRec ( A , n ) ; return 0 ; } |
Allocate minimum number of pages | C ++ program for optimal allocation of pages ; Utility function to check if current minimum value is feasible or not . ; iterate over all books ; check if current number of pages are greater than curr_min that means we will get the result after mid no . of pages ; count how many students are required to distribute curr_min pages ; increment student count ; update curr_sum ; if students required becomes greater than given no . of students , return false ; else update curr_sum ; function to find minimum pages ; return - 1 if no . of books is less than no . of students ; Count total number of pages ; initialize start as 0 pages and end as total pages ; traverse until start <= end ; check if it is possible to distribute books by using mid as current minimum ; update result to current distribution as it 's the best we have found till now. ; as we are finding minimum and books are sorted so reduce end = mid - 1 that means ; if not possible means pages should be increased so update start = mid + 1 ; at - last return minimum no . of pages ; Drivers code ; Number of pages in books ; int m = 2 ; No . of students | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPossible ( int arr [ ] , int n , int m , int curr_min ) { int studentsRequired = 1 ; int curr_sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > curr_min ) return false ; if ( curr_sum + arr [ i ] > curr_min ) { studentsRequired ++ ; curr_sum = arr [ i ] ; if ( studentsRequired > m ) return false ; } else curr_sum += arr [ i ] ; } return true ; } int findPages ( int arr [ ] , int n , int m ) { long long sum = 0 ; if ( n < m ) return -1 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; int start = 0 , end = sum ; int result = INT_MAX ; while ( start <= end ) { int mid = ( start + end ) / 2 ; if ( isPossible ( arr , n , m , mid ) ) { result = mid ; end = mid - 1 ; } else start = mid + 1 ; } return result ; } int main ( ) { int arr [ ] = { 12 , 34 , 67 , 90 } ; int n = sizeof arr / sizeof arr [ 0 ] ; cout << " Minimum β number β of β pages β = β " << findPages ( arr , n , m ) << endl ; 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 ; Recursive function to count and return the max number of plates that can be placed ; If no plate remains ; If length and width of previous plate exceeds that of the current plate ; Calculate including the plate ; Calculate excluding the plate ; Otherwise ; Calculate only excluding the plate ; Driver code ; Sorting plates in decreasing order of area ; Assuming first plate to be of maximum size | #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 lastLength , int lastWidth , int i , int n ) { if ( i == n ) return 0 ; int taken = 0 , notTaken = 0 ; if ( lastLength > plates [ i ] [ 0 ] && lastWidth > plates [ i ] [ 1 ] ) { taken = 1 + countPlates ( plates , plates [ i ] [ 0 ] , plates [ i ] [ 1 ] , i + 1 , n ) ; notTaken = countPlates ( plates , lastLength , lastWidth , i + 1 , n ) ; } else notTaken = countPlates ( plates , lastLength , lastWidth , i + 1 , n ) ; return max ( taken , notTaken ) ; } 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 ) ; int lastLength = INT_MAX ; int lastWidth = INT_MAX ; cout << countPlates ( plates , lastLength , lastWidth , 0 , n ) ; return 0 ; } |
Smallest element with K set bits such that sum of Bitwise AND of each array element with K is maximum | C ++ program for the above approach ; Comparator function to sort the vector of pairs ; Function to find the value of X such that Bitwise AND of all array elements with X is maximum ; Stores the count of set bit at each position ; Stores the resultant value of X ; Calculate the count of set bits at each position ; If the jth bit is set ; Stores the contribution of each set bit ; Store all bit and amount of contribution ; Find the total contribution ; Sort V [ ] in decreasing order of second parameter ; Choose exactly K set bits ; Print the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool comp ( pair < int , int > & a , pair < int , int > & b ) { if ( a . second != b . second ) return a . second > b . second ; return a . first < b . first ; } int maximizeSum ( int arr [ ] , int n , int k ) { vector < int > cnt ( 30 , 0 ) ; int X = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < 30 ; j ++ ) { if ( arr [ i ] & ( 1 << j ) ) cnt [ j ] ++ ; } } vector < pair < int , int > > v ; for ( int i = 0 ; i < 30 ; i ++ ) { int gain = cnt [ i ] * ( 1 << i ) ; v . push_back ( { i , gain } ) ; } sort ( v . begin ( ) , v . end ( ) , comp ) ; for ( int i = 0 ; i < k ; i ++ ) { X |= ( 1 << v [ i ] . first ) ; } cout << X ; } int main ( ) { int arr [ ] = { 3 , 4 , 5 , 1 } ; int K = 1 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maximizeSum ( arr , N , K ) ; return 0 ; } |
Largest Roman Numeral possible by rearranging characters of a given string | C ++ implementation of the above approach ; Function to find decimal value of a roman character ; Function to convert string representing roman number to equivalent decimal value ; Stores the decimal value of the string S ; Stores the size of the S ; Update res ; Traverse the string ; Return res ; Function to convert decimal to equivalent roman numeral ; Stores the string ; Stores all the digit values of a roman digit ; Iterate while number is greater than 0 ; Return res ; Function to sort the string in descending order of values assigned to characters ; Function to find largest roman value possible by rearranging the characters of the string ; Stores all roman characters ; Traverse the string ; If X is not found ; Stores the decimal value of the roman number ; Find the roman value equivalent to the decimal value of N ; Return result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int charVal ( char c ) { if ( c == ' I ' ) return 1 ; if ( c == ' V ' ) return 5 ; if ( c == ' X ' ) return 10 ; if ( c == ' L ' ) return 50 ; if ( c == ' C ' ) return 100 ; if ( c == ' D ' ) return 500 ; if ( c == ' M ' ) return 1000 ; return -1 ; } int romanToDec ( string S ) { int res = 0 ; int n = S . size ( ) ; res = charVal ( S [ n - 1 ] ) ; for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( charVal ( S [ i ] ) < charVal ( S [ i + 1 ] ) ) res -= charVal ( S [ i ] ) ; else res += charVal ( S [ i ] ) ; } return res ; } string DecToRoman ( int number ) { string res = " " ; int num [ ] = { 1 , 4 , 5 , 9 , 10 , 40 , 50 , 90 , 100 , 400 , 500 , 900 , 1000 } ; string sym [ ] = { " I " , " IV " , " V " , " IX " , " X " , " XL " , " L " , " XC " , " C " , " CD " , " D " , " CM " , " M " } ; int i = 12 ; while ( number > 0 ) { int div = number / num [ i ] ; number = number % num [ i ] ; while ( div -- ) { res += sym [ i ] ; } i -- ; } return res ; } bool compare ( char x , char y ) { int val_x = charVal ( x ) ; int val_y = charVal ( y ) ; return ( val_x > val_y ) ; } string findLargest ( string S ) { set < char > st = { ' I ' , ' V ' , ' X ' , ' L ' , ' C ' , ' D ' , ' M ' } ; for ( auto x : S ) { if ( st . find ( x ) == st . end ( ) ) return " Invalid " ; } sort ( S . begin ( ) , S . end ( ) , compare ) ; int N = romanToDec ( S ) ; string R = DecToRoman ( N ) ; if ( S != R ) return " Invalid " ; return S ; } int main ( ) { string S = " MCMIV " ; cout << findLargest ( S ) ; } |
Find Minimum Depth of a Binary Tree | C ++ program to find minimum depth of a given Binary Tree ; A BT Node ; Function to calculate the minimum depth of the tree ; Corner case . Should never be hit unless the code is called on root = NULL ; Base case : Leaf Node . This accounts for height = 1. ; If left subtree is not NULL , recur for left subtree ; If right subtree is not NULL , recur for right subtree ; Utility function to create new Node ; Driver program ; Let us construct the Tree shown in the above figure | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; int minDepth ( Node * root ) { if ( root == NULL ) return 0 ; if ( root -> left == NULL && root -> right == NULL ) return 1 ; int l = INT_MAX , r = INT_MAX ; if ( root -> left ) l = minDepth ( root -> left ) ; if ( root -> right ) r = minDepth ( root -> right ) ; return min ( l , r ) + 1 ; } Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return ( temp ) ; } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; cout << " The β minimum β depth β of β binary β tree β is β : β " << minDepth ( root ) ; return 0 ; } |
Remove an occurrence of most frequent array element exactly K times | C ++ program for the above approach ; Function to print the most frequent array element exactly K times ; Stores frequency array element ; Count frequency of array element ; Maximum array element ; Traverse the Map ; Find the element with maximum frequency ; If the frequency is maximum , store that number in element ; Print element as it contains the element having highest frequency ; Decrease the frequency of the maximum array element ; Reduce the number of operations ; Driver Code ; Given array ; Size of the array ; Given K | #include <bits/stdc++.h> NEW_LINE using namespace std ; void maxFreqElements ( int arr [ ] , int N , int K ) { map < int , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { mp [ arr [ i ] ] ++ ; } while ( K > 0 ) { int max = 0 ; int element ; for ( auto i : mp ) { if ( i . second > max ) { max = i . second ; element = i . first ; } } cout << element << " β " ; mp [ element ] -- ; K -- ; } } int main ( ) { int arr [ ] = { 1 , 3 , 2 , 1 , 4 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 2 ; maxFreqElements ( arr , N , K ) ; return 0 ; } |
Maximize difference between maximum and minimum array elements after K operations | C ++ program to implement the above approach ; Function to find the maximum difference between the maximum and minimum in the array after K operations ; Stores maximum difference between largest and smallest array element ; Sort the array in descending order ; Traverse the array arr [ ] ; Update maxDiff ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxDiffLargSmallOper ( int arr [ ] , int N , int K ) { int maxDiff = 0 ; sort ( arr , arr + N , greater < int > ( ) ) ; for ( int i = 0 ; i <= min ( K , N - 1 ) ; i ++ ) { maxDiff += arr [ i ] ; } return maxDiff ; } int main ( ) { int arr [ ] = { 7 , 7 , 7 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 1 ; cout << maxDiffLargSmallOper ( arr , N , K ) ; return 0 ; } |
Minimize cost to convert all characters of a binary string to 0 s | C ++ program to implement the above approach ; Function to get the minimum Cost to convert all characters of given string to 0 s ; Stores the range of indexes of characters that need to be flipped ; Stores the number of times current character is flipped ; Stores minimum cost to get the required string ; Traverse the given string ; Remove all value from pq whose value is less than i ; Update flip ; If current character is flipped odd times ; If current character contains non - zero value ; Update flip ; Update cost ; Append R [ i ] into pq ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minCost ( string str , int N , int R [ ] , int C [ ] ) { priority_queue < int , vector < int > , greater < int > > pq ; int flip = 0 ; int cost = 0 ; for ( int i = 0 ; i < N ; i ++ ) { while ( pq . size ( ) > 0 and pq . top ( ) < i ) { pq . pop ( ) ; flip -- ; } if ( flip % 2 == 1 ) { str [ i ] = '1' - str [ i ] + '0' ; } if ( str [ i ] == '1' ) { flip ++ ; cost += C [ i ] ; pq . push ( R [ i ] ) ; } } return cost ; } int main ( ) { string str = "1010" ; int R [ ] = { 1 , 2 , 2 , 3 } ; int C [ ] = { 3 , 1 , 2 , 3 } ; int N = str . length ( ) ; cout << minCost ( str , N , R , C ) ; } |
Find Minimum Depth of a Binary Tree | C ++ program to find minimum depth of a given Binary Tree ; A Binary Tree Node ; A queue item ( Stores pointer to node and an integer ) ; Iterative method to find minimum depth of Binary Tree ; Corner Case ; Create an empty queue for level order traversal ; Enqueue Root and initialize depth as 1 ; Do level order traversal ; Remove the front queue item ; Get details of the remove item ; If this is the first leaf node seen so far Then return its depth as answer ; If left subtree is not NULL , add it to queue ; If right subtree is not NULL , add it to queue ; Utility function to create a new tree Node ; Driver program to test above functions ; Let us create binary tree shown in above diagram | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; struct qItem { Node * node ; int depth ; } ; int minDepth ( Node * root ) { if ( root == NULL ) return 0 ; queue < qItem > q ; qItem qi = { root , 1 } ; q . push ( qi ) ; while ( q . empty ( ) == false ) { qi = q . front ( ) ; q . pop ( ) ; Node * node = qi . node ; int depth = qi . depth ; if ( node -> left == NULL && node -> right == NULL ) return depth ; if ( node -> left != NULL ) { qi . node = node -> left ; qi . depth = depth + 1 ; q . push ( qi ) ; } if ( node -> right != NULL ) { qi . node = node -> right ; qi . depth = depth + 1 ; q . push ( qi ) ; } } return 0 ; } Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; cout << minDepth ( root ) ; return 0 ; } |
Maximum Manhattan distance between a distinct pair from N coordinates | C ++ program for the above approach ; Function to calculate the maximum Manhattan distance ; Vectors to store maximum and minimum of all the four forms ; Sorting both the vectors ; Driver Code ; Given Co - ordinates ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void MaxDist ( vector < pair < int , int > > & A , int N ) { vector < int > V ( N ) , V1 ( N ) ; for ( int i = 0 ; i < N ; i ++ ) { V [ i ] = A [ i ] . first + A [ i ] . second ; V1 [ i ] = A [ i ] . first - A [ i ] . second ; } sort ( V . begin ( ) , V . end ( ) ) ; sort ( V1 . begin ( ) , V1 . end ( ) ) ; int maximum = max ( V . back ( ) - V . front ( ) , V1 . back ( ) - V1 . front ( ) ) ; cout << maximum << endl ; } int main ( ) { int N = 3 ; vector < pair < int , int > > A = { { 1 , 2 } , { 2 , 3 } , { 3 , 4 } } ; MaxDist ( A , N ) ; return 0 ; } |
Maximum distance between two points in coordinate plane using Rotating Caliper 's Method | ; Function calculates distance between two points ; Function to find the maximum distance between any two points ; Iterate over all possible pairs ; Update max ; Return actual distance ; Driver code ; Number of points ; Given points ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; long dist ( pair < long , long > p1 , pair < long , long > p2 ) { long x0 = p1 . first - p2 . first ; long y0 = p1 . second - p2 . second ; return x0 * x0 + y0 * y0 ; } double maxDist ( pair < long , long > p [ ] , int n ) { double Max = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { Max = max ( Max , ( double ) dist ( p [ i ] , p [ j ] ) ) ; } } return sqrt ( Max ) ; } int main ( ) { int n = 5 ; pair < long , long > p [ n ] ; p [ 0 ] . first = 4 , p [ 0 ] . second = 0 ; p [ 1 ] . first = 0 , p [ 1 ] . second = 2 ; p [ 2 ] . first = -1 , p [ 2 ] . second = -7 ; p [ 3 ] . first = 1 , p [ 3 ] . second = 10 ; p [ 4 ] . first = 2 , p [ 4 ] . second = -3 ; cout << fixed << setprecision ( 14 ) << maxDist ( p , n ) << endl ; return 0 ; } |
Reorder an array such that sum of left half is not equal to sum of right half | C ++ program for the above approach ; Function to print the required reordering of array if possible ; Sort the array in increasing order ; If all elements are equal , then it is not possible ; Else print the sorted array arr [ ] ; Driver Code ; Given array ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printArr ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; if ( arr [ 0 ] == arr [ n - 1 ] ) { cout << " No " << endl ; } else { cout << " Yes " << endl ; for ( int i = 0 ; i < n ; i ++ ) { cout << arr [ i ] << " β " ; } } } int main ( ) { int arr [ ] = { 1 , 2 , 2 , 1 , 3 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printArr ( arr , N ) ; return 0 ; } |
Find Minimum Depth of a Binary Tree | C ++ implementation to find minimum depth of a given Binary tree ; Class containing left and right child of current Node and key value ; Function to calculate the minimum depth of the tree ; Driver program to test above functions | #include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left ; struct Node * right ; Node ( int k ) { data = k ; left = right = NULL ; } } ; int minimumDepth ( Node * root , int level ) { if ( root == NULL ) return level ; level ++ ; return min ( minimumDepth ( root -> left , level ) , minimumDepth ( root -> right , level ) ) ; } int main ( ) { Node * root = new Node ( 1 ) ; root -> left = new Node ( 2 ) ; root -> right = new Node ( 3 ) ; root -> left -> left = new Node ( 4 ) ; root -> left -> right = new Node ( 5 ) ; cout << minimumDepth ( root , 0 ) ; return 0 ; } |
Maximize Array sum by swapping at most K elements with another array | C ++ implementation to find maximum sum of array A by swapping at most K elements with array B ; Function to find the maximum sum ; If element of array a is smaller than that of array b , swap them . ; Find sum of resultant array ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void maximumSum ( int a [ ] , int b [ ] , int k , int n ) { int i , j ; sort ( a , a + n ) ; sort ( b , b + n ) ; for ( i = 0 , j = n - 1 ; i < k ; i ++ , j -- ) { if ( a [ i ] < b [ j ] ) swap ( a [ i ] , b [ j ] ) ; else break ; } int sum = 0 ; for ( i = 0 ; i < n ; i ++ ) sum += a [ i ] ; cout << sum << endl ; } int main ( ) { int K = 1 ; int A [ ] = { 2 , 3 , 4 } ; int B [ ] = { 6 , 8 , 5 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; maximumSum ( A , B , K , N ) ; return 0 ; } |
Maximize distinct elements by incrementing / decrementing an element or keeping it same | C ++ program to Maximize distinct elements by incrementing / decrementing an element or keeping it same ; Function that Maximize the count of distinct element ; sort thr array ; keeping track of previous change ; check the decremented value ; check the current value ; check the incremented value ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int max_dist_ele ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int ans = 0 ; int prev = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( prev < ( arr [ i ] - 1 ) ) { ans ++ ; prev = arr [ i ] - 1 ; } else if ( prev < ( arr [ i ] ) ) { ans ++ ; prev = arr [ i ] ; } else if ( prev < ( arr [ i ] + 1 ) ) { ans ++ ; prev = arr [ i ] + 1 ; } } return ans ; } int main ( ) { int arr [ ] = { 1 , 1 , 1 , 8 , 8 , 8 , 9 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << max_dist_ele ( arr , n ) << endl ; return 0 ; } |
Find if array can be sorted by swaps limited to multiples of k | ; CheckSort function To check if array can be sorted ; sortarr is sorted array of arr ; if k = 1 then ( always possible to sort ) swapping can easily give sorted array ; comparing sortarray with array ; element at index j must be in j = i + l * k form where i = 0 , 1 , 2 , 3. . . where l = 0 , 1 , 2 , 3 , . . n - 1 ; if element is present then swapped ; if element of sorted array does not found in its sequence then flag remain zero that means arr can not be sort after swapping ; if flag is 0 Not possible else Possible ; Driver code ; size of step ; array initialized ; length of arr ; calling function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void CheckSort ( vector < int > arr , int k , int n ) { vector < int > sortarr ( arr . begin ( ) , arr . end ( ) ) ; sort ( sortarr . begin ( ) , sortarr . end ( ) ) ; if ( k == 1 ) printf ( " yes " ) ; else { int flag = 0 ; for ( int i = 0 ; i < n ; i ++ ) { flag = 0 ; for ( int j = i ; j < n ; j += k ) { if ( sortarr [ i ] == arr [ j ] ) { swap ( arr [ i ] , arr [ j ] ) ; flag = 1 ; break ; } if ( j + k >= n ) break ; } if ( flag == 0 ) break ; } if ( flag == 0 ) printf ( " Not β possible β to β sort " ) ; else printf ( " Possible β to β sort " ) ; } } int main ( ) { int k = 3 ; vector < int > arr = { 1 , 5 , 6 , 9 , 2 , 3 , 5 , 9 } ; int n = arr . size ( ) ; CheckSort ( arr , k , n ) ; return 0 ; } |
Replace node with depth in a binary tree | CPP program to replace every key value with its depth . ; A tree node structure ; Utility function to create a new Binary Tree node ; Helper function replaces the data with depth Note : Default value of level is 0 for root . ; Base Case ; Replace data with current depth ; A utility function to print inorder traversal of a Binary Tree ; Driver function to test above functions ; Constructing tree given in the above figure | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; struct Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } void replaceNode ( struct Node * node , int level = 0 ) { if ( node == NULL ) return ; node -> data = level ; replaceNode ( node -> left , level + 1 ) ; replaceNode ( node -> right , level + 1 ) ; } void printInorder ( struct Node * node ) { if ( node == NULL ) return ; printInorder ( node -> left ) ; cout << node -> data << " β " ; printInorder ( node -> right ) ; } int main ( ) { struct Node * root = new struct Node ; root = newNode ( 3 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 5 ) ; root -> left -> left = newNode ( 1 ) ; root -> left -> right = newNode ( 4 ) ; cout << " Before β Replacing β Nodes STRNEWLINE " ; printInorder ( root ) ; replaceNode ( root ) ; cout << endl ; cout << " After β Replacing β Nodes STRNEWLINE " ; printInorder ( root ) ; return 0 ; } |
Product of minimum edge weight between all pairs of a Tree | C ++ Implementation of above approach ; Function to return ( x ^ y ) mod p ; Declaring size array globally ; Initializing DSU data structure ; Function to find the root of ith node in the disjoint set ; Weighted union using Path Compression ; size of set A is small than size of set B ; size of set B is small than size of set A ; Function to add an edge in the tree ; Build the tree ; Function to return the required product ; Sorting the edges with respect to its weight ; Start iterating in decreasing order of weight ; Determine Current edge values ; Calculate root of each node and size of each set ; Using the formula ; Calculating final result ; Weighted union using Path Compression ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define mod 1000000007 NEW_LINE int power ( int x , unsigned int y , int p ) { int res = 1 ; x = x % p ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % p ; y = y >> 1 ; x = ( x * x ) % p ; } return res ; } int size [ 300005 ] ; int freq [ 300004 ] ; vector < pair < int , pair < int , int > > > edges ; void initialize ( int Arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { Arr [ i ] = i ; size [ i ] = 1 ; } } int root ( int Arr [ ] , int i ) { while ( Arr [ i ] != i ) { i = Arr [ i ] ; } return i ; } void weighted_union ( int Arr [ ] , int size [ ] , int A , int B ) { int root_A = root ( Arr , A ) ; int root_B = root ( Arr , B ) ; if ( size [ root_A ] < size [ root_B ] ) { Arr [ root_A ] = Arr [ root_B ] ; size [ root_B ] += size [ root_A ] ; } else { Arr [ root_B ] = Arr [ root_A ] ; size [ root_A ] += size [ root_B ] ; } } void AddEdge ( int a , int b , int w ) { edges . push_back ( { w , { a , b } } ) ; } void MakeTree ( ) { AddEdge ( 1 , 2 , 1 ) ; AddEdge ( 1 , 3 , 3 ) ; AddEdge ( 3 , 4 , 2 ) ; } int MinProduct ( ) { int result = 1 ; sort ( edges . begin ( ) , edges . end ( ) ) ; for ( int i = edges . size ( ) - 1 ; i >= 0 ; i -- ) { int curr_weight = edges [ i ] . first ; int Node1 = edges [ i ] . second . first ; int Node2 = edges [ i ] . second . second ; int Root1 = root ( freq , Node1 ) ; int Set1_size = size [ Root1 ] ; int Root2 = root ( freq , Node2 ) ; int Set2_size = size [ Root2 ] ; int prod = Set1_size * Set2_size ; int Product = power ( curr_weight , prod , mod ) ; result = ( ( result % mod ) * ( Product % mod ) ) % mod ; weighted_union ( freq , size , Node1 , Node2 ) ; } return result % mod ; } int main ( ) { int n = 4 ; initialize ( freq , n ) ; MakeTree ( ) ; cout << MinProduct ( ) ; } |
Check whether an array can be made strictly decreasing by modifying at most one element | C ++ implementation of the approach ; Function that returns true if the array can be made strictly decreasing with at most one change ; To store the number of modifications required to make the array strictly decreasing ; Check whether the last element needs to be modify or not ; Check whether the first element needs to be modify or not ; Loop from 2 nd element to the 2 nd last element ; Check whether arr [ i ] needs to be modified ; Modifying arr [ i ] ; Check if arr [ i ] is equal to any of arr [ i - 1 ] or arr [ i + 1 ] ; If more than 1 modification is required ; Driver code | #include <iostream> NEW_LINE using namespace std ; bool check ( int * arr , int n ) { int modify = 0 ; if ( arr [ n - 1 ] >= arr [ n - 2 ] ) { arr [ n - 1 ] = arr [ n - 2 ] - 1 ; modify ++ ; } if ( arr [ 0 ] <= arr [ 1 ] ) { arr [ 0 ] = arr [ 1 ] + 1 ; modify ++ ; } for ( int i = n - 2 ; i > 0 ; i -- ) { if ( ( arr [ i - 1 ] <= arr [ i ] && arr [ i + 1 ] <= arr [ i ] ) || ( arr [ i - 1 ] >= arr [ i ] && arr [ i + 1 ] >= arr [ i ] ) ) { arr [ i ] = ( arr [ i - 1 ] + arr [ i + 1 ] ) / 2 ; modify ++ ; if ( arr [ i ] == arr [ i - 1 ] arr [ i ] == arr [ i + 1 ] ) return false ; } } if ( modify > 1 ) return false ; return true ; } int main ( ) { int arr [ ] = { 10 , 5 , 11 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( check ( arr , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Maximal Disjoint Intervals | C ++ implementation of the approach ; Function to sort the vector elements by second element of pairs ; Function to find maximal disjoint set ; Sort the list of intervals ; First Interval will always be included in set ; End point of first interval ; Check if given interval overlap with previously included interval , if not then include this interval and update the end point of last added interval ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE bool sortbysec ( const pair < int , int > & a , const pair < int , int > & b ) { return ( a . second < b . second ) ; } void maxDisjointIntervals ( vector < pair < int , int > > list ) { sort ( list . begin ( ) , list . end ( ) , sortbysec ) ; cout << " [ " << list [ 0 ] . first << " , β " << list [ 0 ] . second << " ] " << endl ; int r1 = list [ 0 ] . second ; for ( int i = 1 ; i < list . size ( ) ; i ++ ) { int l1 = list [ i ] . first ; int r2 = list [ i ] . second ; if ( l1 > r1 ) { cout << " [ " << l1 << " , β " << r2 << " ] " << endl ; r1 = r2 ; } } } int main ( ) { int N = 4 ; vector < pair < int , int > > intervals = { { 1 , 4 } , { 2 , 3 } , { 4 , 6 } , { 8 , 9 } } ; maxDisjointIntervals ( intervals ) ; return 0 ; } |
Print k different sorted permutations of a given array | C ++ implementation of the approach ; Utility function to print the original indices of the elements of the array ; Function to print the required permutations ; To keep track of original indices ; Sort the array ; Count the number of swaps that can be made ; Cannot generate 3 permutations ; Print the first permutation ; Find an index to swap and create second permutation ; Print the last permutation ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int next_pos = 1 ; void printIndices ( int n , pair < int , int > a [ ] ) { for ( int i = 0 ; i < n ; i ++ ) cout << a [ i ] . second << " β " ; cout << endl ; } void printPermutations ( int n , int a [ ] , int k ) { pair < int , int > arr [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { arr [ i ] . first = a [ i ] ; arr [ i ] . second = i ; } sort ( arr , arr + n ) ; int count = 1 ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] . first == arr [ i - 1 ] . first ) count ++ ; if ( count < k ) { cout << " - 1" ; return ; } for ( int i = 0 ; i < k - 1 ; i ++ ) { printIndices ( n , arr ) ; for ( int j = next_pos ; j < n ; j ++ ) { if ( arr [ j ] . first == arr [ j - 1 ] . first ) { swap ( arr [ j ] , arr [ j - 1 ] ) ; next_pos = j + 1 ; break ; } } } printIndices ( n , arr ) ; } int main ( ) { int a [ ] = { 1 , 3 , 3 , 1 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int k = 3 ; printPermutations ( n , a , k ) ; return 0 ; } |
Maximum width of a binary tree | C ++ program to calculate width of binary tree ; A binary tree node has data , pointer to left child and a pointer to right child ; Function protoypes ; Function to get the maximum width of a binary tree ; Get width of each level and compare the width with maximum width so far ; Get width of a given level ; Compute the " height " of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node . ; compute the height of each subtree ; use the larger one ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver code ; Constructed binary tree is : 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int data ; node * left ; node * right ; } ; int getWidth ( node * root , int level ) ; int height ( node * node ) ; node * newNode ( int data ) ; int getMaxWidth ( node * root ) { int maxWidth = 0 ; int width ; int h = height ( root ) ; int i ; for ( i = 1 ; i <= h ; i ++ ) { width = getWidth ( root , i ) ; if ( width > maxWidth ) maxWidth = width ; } return maxWidth ; } int getWidth ( node * root , int level ) { if ( root == NULL ) return 0 ; if ( level == 1 ) return 1 ; else if ( level > 1 ) return getWidth ( root -> left , level - 1 ) + getWidth ( root -> right , level - 1 ) ; } int height ( node * node ) { if ( node == NULL ) return 0 ; else { int lHeight = height ( node -> left ) ; int rHeight = height ( node -> right ) ; return ( lHeight > rHeight ) ? ( lHeight + 1 ) : ( rHeight + 1 ) ; } } node * newNode ( int data ) { node * Node = new node ( ) ; Node -> data = data ; Node -> left = NULL ; Node -> right = NULL ; return ( Node ) ; } int main ( ) { node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> right = newNode ( 8 ) ; root -> right -> right -> left = newNode ( 6 ) ; root -> right -> right -> right = newNode ( 7 ) ; cout << " Maximum β width β is β " << getMaxWidth ( root ) << endl ; return 0 ; } |
Divide N segments into two non | C ++ Program to divide N segments into two non empty groups such that given condition is satisfied ; Function to print the answer if it exists using the concept of merge overlapping segments ; Sort the indices based on their corresponding value in V ; Resultant array Initialise all the values in resultant array with '2' except the position at the first index of sorted vec which is initialised as '1' Initialise maxR to store the maximum of all right values encountered so far ; If the i - th index has any any point in common with the ( i - 1 ) th index classify it as '1' in resultant array and update maxR if necessary else we have found the breakpoint and we can exit the loop ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printAnswer ( vector < pair < int , int > > v , int n ) { vector < pair < int , pair < int , int > > > vec ; for ( int i = 0 ; i < n ; i ++ ) { vec . push_back ( { v [ i ] . first , { v [ i ] . second , i } } ) ; } sort ( vec . begin ( ) , vec . end ( ) ) ; vector < int > res ( n , 2 ) ; int maxR = vec [ 0 ] . second . first ; res [ vec [ 0 ] . second . second ] = 1 ; bool ok = false ; for ( int i = 1 ; i < n ; i ++ ) { if ( maxR >= vec [ i ] . first ) { res [ vec [ i ] . second . second ] = res [ vec [ i - 1 ] . second . second ] ; maxR = max ( maxR , vec [ i ] . second . first ) ; } else { ok = true ; break ; } } if ( ok ) { for ( auto x : res ) cout << x << " β " ; cout << ' ' ; } else cout << " Not β possible STRNEWLINE " ; } int main ( ) { vector < pair < int , int > > v = { { 2 , 8 } , { 3 , 4 } , { 5 , 8 } , { 9 , 10 } } ; int n = ( int ) v . size ( ) ; printAnswer ( v , n ) ; } |
Count distinct elements in an array | CPP program to print all distinct elements of a given array ; This function prints all distinct elements ; Creates an empty hashset ; Traverse the input array ; If not present , then put it in hashtable and increment result ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countDistinct ( int arr [ ] , int n ) { unordered_set < int > s ; int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . find ( arr [ i ] ) == s . end ( ) ) { s . insert ( arr [ i ] ) ; res ++ ; } } return res ; } int main ( ) { int arr [ ] = { 6 , 10 , 5 , 4 , 9 , 120 , 4 , 6 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countDistinct ( arr , n ) ; return 0 ; } |
In | C ++ program for the above approach ; Calculating next gap ; Function for swapping ; Merging the subarrays using shell sorting Time Complexity : O ( nlog n ) Space Complexity : O ( 1 ) ; merge sort makes log n recursive calls and each time calls merge ( ) which takes nlog n steps Time Complexity : O ( n * log n + 2 ( ( n / 2 ) * log ( n / 2 ) ) + 4 ( ( n / 4 ) * log ( n / 4 ) ) + ... . . + 1 ) Time Complexity : O ( logn * ( n * log n ) ) i . e . O ( n * ( logn ) ^ 2 ) Space Complexity : O ( 1 ) ; Calculating mid to slice the array in two halves ; Recursive calls to sort left and right subarrays ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int nextGap ( int gap ) { if ( gap <= 1 ) return 0 ; return ( int ) ceil ( gap / 2.0 ) ; } void swap ( int nums [ ] , int i , int j ) { int temp = nums [ i ] ; nums [ i ] = nums [ j ] ; nums [ j ] = temp ; } void inPlaceMerge ( int nums [ ] , int start , int end ) { int gap = end - start + 1 ; for ( gap = nextGap ( gap ) ; gap > 0 ; gap = nextGap ( gap ) ) { for ( int i = start ; i + gap <= end ; i ++ ) { int j = i + gap ; if ( nums [ i ] > nums [ j ] ) swap ( nums , i , j ) ; } } } void mergeSort ( int nums [ ] , int s , int e ) { if ( s == e ) return ; int mid = ( s + e ) / 2 ; mergeSort ( nums , s , mid ) ; mergeSort ( nums , mid + 1 , e ) ; inPlaceMerge ( nums , s , e ) ; } int main ( ) { int nums [ ] = { 12 , 11 , 13 , 5 , 6 , 7 } ; int nums_size = sizeof ( nums ) / sizeof ( nums [ 0 ] ) ; mergeSort ( nums , 0 , nums_size - 1 ) ; for ( int i = 0 ; i < nums_size ; i ++ ) { cout << nums [ i ] << " β " ; } return 0 ; } |
Rearrange an array to maximize i * arr [ i ] | C ++ program for the Optimal Solution ; Function to calculate the maximum points earned by making an optimal selection on the given array ; Sorting the array ; Variable to store the total points earned ; Driver code | #include <bits/stdc++.h> NEW_LINE #include <iostream> NEW_LINE using namespace std ; static int findOptimalSolution ( int a [ ] , int N ) { sort ( a , a + N ) ; int points = 0 ; for ( int i = 0 ; i < N ; i ++ ) { points += a [ i ] * i ; } return points ; } int main ( ) { int a [ ] = { 1 , 4 , 2 , 3 , 9 } ; int N = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << ( findOptimalSolution ( a , N ) ) ; return 0 ; } |
Minimum number of towers required such that every house is in the range of at least one tower | C ++ implementation of above approach ; Function to count the number of tower ; first we sort the house numbers ; for count number of towers ; for iterate all houses ; count number of towers ; find find the middle location ; traverse till middle location ; this is point to middle house where we insert the tower ; now find the last location ; traverse till last house of the range ; return the number of tower ; Driver code ; given elements ; print number of towers | #include <bits/stdc++.h> NEW_LINE using namespace std ; int number_of_tower ( int house [ ] , int range , int n ) { sort ( house , house + n ) ; int numOfTower = 0 ; int i = 0 ; while ( i < n ) { numOfTower ++ ; int loc = house [ i ] + range ; while ( i < n && house [ i ] <= loc ) i ++ ; -- i ; loc = house [ i ] + range ; while ( i < n && house [ i ] <= loc ) i ++ ; } return numOfTower ; } int main ( ) { int house [ ] = { 7 , 2 , 4 , 6 , 5 , 9 , 12 , 11 } ; int range = 2 ; int n = sizeof ( house ) / sizeof ( house [ 0 ] ) ; cout << number_of_tower ( house , range , n ) ; } |
Check if the characters of a given string are in alphabetical order | C ++ implementation of above approach ; Function that checks whether the string is in alphabetical order or not ; length of the string ; create a character array of the length of the string ; assign the string to character array ; sort the character array ; check if the character array is equal to the string or not ; Driver code ; check whether the string is in alphabetical order or not | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isAlphabaticOrder ( string s ) { int n = s . length ( ) ; char c [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { c [ i ] = s [ i ] ; } sort ( c , c + n ) ; for ( int i = 0 ; i < n ; i ++ ) if ( c [ i ] != s [ i ] ) return false ; return true ; } int main ( ) { string s = " aabbbcc " ; if ( isAlphabaticOrder ( s ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Sort first k values in ascending order and remaining n | C ++ program to sort first k elements in increasing order and remaining n - k elements in decreasing ; function to sort the array ; Sort first k elements in ascending order ; Sort remaining n - k elements in descending order ; Driver code ; Our arr contains 8 elements | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printOrder ( int arr [ ] , int n , int k ) { sort ( arr , arr + k ) ; sort ( arr + k , arr + n , greater < int > ( ) ) ; } int main ( ) { int arr [ ] = { 5 , 4 , 6 , 2 , 1 , 3 , 8 , 9 , -1 } ; int k = 4 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printOrder ( arr , n , k ) ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; return 0 ; } |
Maximum width of a binary tree | A queue based C ++ program to find maximum width of a Binary Tree ; A binary tree node has data , pointer to left child and a pointer to right child ; Function to find the maximum width of the tree using level order traversal ; Base case ; Initialize result ; Do Level order traversal keeping track of number of nodes at every level . ; Get the size of queue when the level order traversal for one level finishes ; Update the maximum node count value ; Iterate for all the nodes in the queue currently ; Dequeue an node from queue ; Enqueue left and right children of dequeued node ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left ; struct Node * right ; } ; int maxWidth ( struct Node * root ) { if ( root == NULL ) return 0 ; int result = 0 ; queue < Node * > q ; q . push ( root ) ; while ( ! q . empty ( ) ) { int count = q . size ( ) ; result = max ( count , result ) ; while ( count -- ) { Node * temp = q . front ( ) ; q . pop ( ) ; if ( temp -> left != NULL ) q . push ( temp -> left ) ; if ( temp -> right != NULL ) q . push ( temp -> right ) ; } } return result ; } struct Node * newNode ( int data ) { struct Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } int main ( ) { struct Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> right = newNode ( 8 ) ; root -> right -> right -> left = newNode ( 6 ) ; root -> right -> right -> right = newNode ( 7 ) ; cout << " Maximum β width β is β " << maxWidth ( root ) << endl ; return 0 ; } |
Merging and Sorting Two Unsorted Stacks | C ++ program to merge to unsorted stacks into a third stack in sorted way . ; Sorts input stack and returns sorted stack . ; pop out the first element ; while temporary stack is not empty and top of stack is greater than temp ; pop from temporary stack and push it to the input stack ; push temp in temporary of stack ; Push contents of both stacks in result ; Sort the result stack . ; main function ; This is the temporary stack | #include <bits/stdc++.h> NEW_LINE using namespace std ; stack < int > sortStack ( stack < int > & input ) { stack < int > tmpStack ; while ( ! input . empty ( ) ) { int tmp = input . top ( ) ; input . pop ( ) ; while ( ! tmpStack . empty ( ) && tmpStack . top ( ) > tmp ) { input . push ( tmpStack . top ( ) ) ; tmpStack . pop ( ) ; } tmpStack . push ( tmp ) ; } return tmpStack ; } stack < int > sortedMerge ( stack < int > & s1 , stack < int > & s2 ) { stack < int > res ; while ( ! s1 . empty ( ) ) { res . push ( s1 . top ( ) ) ; s1 . pop ( ) ; } while ( ! s2 . empty ( ) ) { res . push ( s2 . top ( ) ) ; s2 . pop ( ) ; } return sortStack ( res ) ; } int main ( ) { stack < int > s1 , s2 ; s1 . push ( 34 ) ; s1 . push ( 3 ) ; s1 . push ( 31 ) ; s2 . push ( 1 ) ; s2 . push ( 12 ) ; s2 . push ( 23 ) ; stack < int > tmpStack = sortedMerge ( s1 , s2 ) ; cout << " Sorted β and β merged β stack β : STRNEWLINE " ; while ( ! tmpStack . empty ( ) ) { cout << tmpStack . top ( ) << " β " ; tmpStack . pop ( ) ; } } |
Lexicographical concatenation of all substrings of a string | CPP Program to create concatenation of all substrings in lexicographic order . ; Creating an array to store substrings ; finding all substrings of string ; Sort all substrings in lexicographic order ; Concatenating all substrings ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string lexicographicSubConcat ( string s ) { int n = s . length ( ) ; int sub_count = n * ( n + 1 ) / 2 ; string arr [ sub_count ] ; int index = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int len = 1 ; len <= n - i ; len ++ ) arr [ index ++ ] = s . substr ( i , len ) ; sort ( arr , arr + sub_count ) ; string res = " " ; for ( int i = 0 ; i < sub_count ; i ++ ) res += arr [ i ] ; return res ; } int main ( ) { string s = " abc " ; cout << lexicographicSubConcat ( s ) ; return 0 ; } |
Insertion Sort by Swapping Elements | Iterative CPP program to sort an array by swapping elements ; Utility function to print a Vector ; Function performs insertion sort on vector V ; Insert V [ i ] into list 0. . i - 1 ; Swap V [ j ] and V [ j - 1 ] ; Decrement j by 1 ; Driver Code | #include <iostream> NEW_LINE #include <vector> NEW_LINE using namespace std ; using Vector = vector < int > ; void printVector ( const Vector & V ) { for ( auto e : V ) { cout << e << " β " ; } cout << endl ; } void insertionSort ( Vector & V ) { int N = V . size ( ) ; int i , j , key ; for ( i = 1 ; i < N ; i ++ ) { j = i ; while ( j > 0 and V [ j ] < V [ j - 1 ] ) { swap ( V [ j ] , V [ j - 1 ] ) ; j -= 1 ; } } } int main ( ) { Vector A = { 9 , 8 , 7 , 5 , 2 , 1 , 2 , 3 } ; cout << " Array : β " << endl ; printVector ( A ) ; cout << " After β Sorting β : " << endl ; insertionSort ( A ) ; printVector ( A ) ; return 0 ; } |
Program to sort string in descending order | CPP program to sort a string in descending order using library function ; Driver code ; descOrder ( s ) ; function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void descOrder ( string s ) { sort ( s . begin ( ) , s . end ( ) , greater < char > ( ) ) ; } int main ( ) { string s = " geeksforgeeks " ; return 0 ; } |
Sort string of characters | C ++ program to sort a string of characters ; function to print string in sorted order ; Hash array to keep count of characters . Initially count of all charters is initialized to zero . ; Traverse string and increment count of characters ; ' a ' - ' a ' will be 0 , ' b ' - ' a ' will be 1 , so for location of character in count array we wil do str [ i ] - ' a ' . ; Traverse the hash array and print characters ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; void sortString ( string & str ) { int charCount [ MAX_CHAR ] = { 0 } ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) charCount [ str [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) for ( int j = 0 ; j < charCount [ i ] ; j ++ ) cout << ( char ) ( ' a ' + i ) ; } int main ( ) { string s = " geeksforgeeks " ; sortString ( s ) ; return 0 ; } |
Smallest element in an array that is repeated exactly ' k ' times . | C ++ program to find smallest number in array that is repeated exactly ' k ' times . ; finds the smallest number in arr [ ] that is repeated k times ; Computing frequencies of all elements ; Finding the smallest element with frequency as k ; If frequency of any of the number is equal to k starting from 0 then return the number ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 1000 ; int findDuplicate ( int arr [ ] , int n , int k ) { int freq [ MAX ] ; memset ( freq , 0 , sizeof ( freq ) ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < 1 && arr [ i ] > MAX ) { cout << " Out β of β range " ; return -1 ; } freq [ arr [ i ] ] += 1 ; } for ( int i = 0 ; i < MAX ; i ++ ) { if ( freq [ i ] == k ) return i ; } return -1 ; } int main ( ) { int arr [ ] = { 2 , 2 , 1 , 3 , 1 } ; int k = 2 ; int n = sizeof ( arr ) / ( sizeof ( arr [ 0 ] ) ) ; cout << findDuplicate ( arr , n , k ) ; return 0 ; } |
Find the Sub | C ++ program to find subarray with sum closest to 0 ; Sort on the basis of sum ; Returns subarray with sum closest to 0. ; To consider the case of subarray starting from beginning of the array ; Store prefix sum with index ; Sort on the basis of sum ; Find two consecutive elements with minimum difference ; Update minimum difference and starting and ending indexes ; Return starting and ending indexes ; Drivers code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct prefix { int sum ; int index ; } ; bool comparison ( prefix a , prefix b ) { return a . sum < b . sum ; } pair < int , int > findSubArray ( int arr [ ] , int n ) { int start , end , min_diff = INT_MAX ; prefix pre_sum [ n + 1 ] ; pre_sum [ 0 ] . sum = 0 ; pre_sum [ 0 ] . index = -1 ; for ( int i = 1 ; i <= n ; i ++ ) { pre_sum [ i ] . sum = pre_sum [ i - 1 ] . sum + arr [ i - 1 ] ; pre_sum [ i ] . index = i - 1 ; } sort ( pre_sum , pre_sum + ( n + 1 ) , comparison ) ; for ( int i = 1 ; i <= n ; i ++ ) { int diff = pre_sum [ i ] . sum - pre_sum [ i - 1 ] . sum ; if ( min_diff > diff ) { min_diff = diff ; start = pre_sum [ i - 1 ] . index ; end = pre_sum [ i ] . index ; } } pair < int , int > p = make_pair ( start + 1 , end ) ; return p ; } int main ( ) { int arr [ ] = { 2 , 3 , -4 , -1 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; pair < int , int > point = findSubArray ( arr , n ) ; cout << " Subarray β starting β from β " ; cout << point . first << " β to β " << point . second ; return 0 ; } |
Check whether a given array is a k sorted array or not | C ++ implementation to check whether the given array is a k sorted array or not ; function to find index of element ' x ' in sorted ' arr ' uses binary search technique ; function to check whether the given array is a ' k ' sorted array or not ; auxiliary array ' aux ' ; copy elements of ' arr ' to ' aux ' ; sort ' aux ' ; for every element of ' arr ' at index ' i ' , find its index ' j ' in ' aux ' ; index of arr [ i ] in sorted array ' aux ' ; if abs ( i - j ) > k , then that element is not at - most k distance away from its target position . Thus , ' arr ' is not a k sorted array ; ' arr ' is a k sorted array ; Driver program to test above | #include <bits / stdc++.h> NEW_LINE using namespace std ; int binarySearch ( int arr [ ] , int low , int high , int x ) { while ( low <= high ) { int mid = ( low + high ) / 2 ; if ( arr [ mid ] == x ) return mid ; else if ( arr [ mid ] > x ) high = mid - 1 ; else low = mid + 1 ; } } string isKSortedArray ( int arr [ ] , int n , int k ) { int aux [ n ] ; for ( int i = 0 ; i < n ; i ++ ) aux [ i ] = arr [ i ] ; sort ( aux , aux + n ) ; for ( int i = 0 ; i < n ; i ++ ) { int j = binarySearch ( aux , 0 , n - 1 , arr [ i ] ) ; if ( abs ( i - j ) > k ) return " No " ; } return " Yes " ; } int main ( ) { int arr [ ] = { 3 , 2 , 1 , 5 , 6 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 2 ; cout << " Is β it β a β k β sorted β array ? : β " << isKSortedArray ( arr , n , k ) ; return 0 ; } |
TimSort | C ++ program to perform TimSort . ; This function sorts array from left index to to right index which is of size atmost RUN ; Merge function merges the sorted runs ; Original array is broken in two parts left and right array ; After comparing , we merge those two array in larger sub array ; Copy remaining elements of left , if any ; Copy remaining element of right , if any ; Iterative Timsort function to sort the array [ 0. . . n - 1 ] ( similar to merge sort ) ; Sort individual subarrays of size RUN ; Start merging from size RUN ( or 32 ) . It will merge to form size 64 , then 128 , 256 and so on ... . ; pick starting point of left sub array . We are going to merge arr [ left . . left + size - 1 ] and arr [ left + size , left + 2 * size - 1 ] After every merge , we increase left by 2 * size ; find ending point of left sub array mid + 1 is starting point of right sub array ; merge sub array arr [ left ... . . mid ] & arr [ mid + 1. ... right ] ; Utility function to print the Array ; Driver program to test above function ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int RUN = 32 ; void insertionSort ( int arr [ ] , int left , int right ) { for ( int i = left + 1 ; i <= right ; i ++ ) { int temp = arr [ i ] ; int j = i - 1 ; while ( j >= left && arr [ j ] > temp ) { arr [ j + 1 ] = arr [ j ] ; j -- ; } arr [ j + 1 ] = temp ; } } void merge ( int arr [ ] , int l , int m , int r ) { int len1 = m - l + 1 , len2 = r - m ; int left [ len1 ] , right [ len2 ] ; for ( int i = 0 ; i < len1 ; i ++ ) left [ i ] = arr [ l + i ] ; for ( int i = 0 ; i < len2 ; i ++ ) right [ i ] = arr [ m + 1 + i ] ; int i = 0 ; int j = 0 ; int k = l ; while ( i < len1 && j < len2 ) { if ( left [ i ] <= right [ j ] ) { arr [ k ] = left [ i ] ; i ++ ; } else { arr [ k ] = right [ j ] ; j ++ ; } k ++ ; } while ( i < len1 ) { arr [ k ] = left [ i ] ; k ++ ; i ++ ; } while ( j < len2 ) { arr [ k ] = right [ j ] ; k ++ ; j ++ ; } } void timSort ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i += RUN ) insertionSort ( arr , i , min ( ( i + RUN - 1 ) , ( n - 1 ) ) ) ; for ( int size = RUN ; size < n ; size = 2 * size ) { for ( int left = 0 ; left < n ; left += 2 * size ) { int mid = left + size - 1 ; int right = min ( ( left + 2 * size - 1 ) , ( n - 1 ) ) ; if ( mid < right ) merge ( arr , left , mid , right ) ; } } } void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) printf ( " % d β " , arr [ i ] ) ; printf ( " STRNEWLINE " ) ; } int main ( ) { int arr [ ] = { -2 , 7 , 15 , -14 , 0 , 15 , 0 , 7 , -7 , -4 , -13 , 5 , 8 , -14 , 12 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Given β Array β is STRNEWLINE " ) ; printArray ( arr , n ) ; timSort ( arr , n ) ; printf ( " After β Sorting β Array β is STRNEWLINE " ) ; printArray ( arr , n ) ; return 0 ; } |
Program to print an array in Pendulum Arrangement | C ++ program for pendulum arrangement of numbers ; Prints pendulum arrangement of arr [ ] ; sorting the elements ; Auxiliary array to store output ; calculating the middle index ; storing the minimum element in the middle i is index for output array and j is for input array . ; adjustment for when no . of elements is even ; Printing the pendulum arrangement ; Driver function ; input Array ; calling pendulum function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void pendulumArrangement ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int op [ n ] ; int mid = ( n - 1 ) / 2 ; int j = 1 , i = 1 ; op [ mid ] = arr [ 0 ] ; for ( i = 1 ; i <= mid ; i ++ ) { op [ mid + i ] = arr [ j ++ ] ; op [ mid - i ] = arr [ j ++ ] ; } if ( n % 2 == 0 ) op [ mid + i ] = arr [ j ] ; cout << " Pendulum β arrangement : " << endl ; for ( i = 0 ; i < n ; i ++ ) cout << op [ i ] << " β " ; cout << endl ; } int main ( ) { int arr [ ] = { 14 , 6 , 19 , 21 , 12 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; pendulumArrangement ( arr , n ) ; return 0 ; } |
Maximum width of a binary tree | C ++ program to calculate width of binary tree ; A binary tree node has data , pointer to left child and a pointer to right child ; A utility function to get height of a binary tree ; Function to get the maximum width of a binary tree ; Create an array that will store count of nodes at each level ; Fill the count array using preorder traversal ; Return the maximum value from count array ; A function that fills count array with count of nodes at every level of given binary tree ; Compute the " height " of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node . ; compute the height of each subtree ; use the larger one ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Return the maximum value from count array ; Driver code ; Constructed bunary tree is : 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 | #include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int data ; node * left ; node * right ; } ; int height ( node * node ) ; node * newNode ( int data ) ; void getMaxWidthRecur ( node * root , int count [ ] , int level ) ; int getMax ( int arr [ ] , int n ) ; int getMaxWidth ( node * root ) { int width ; int h = height ( root ) ; int * count = new int [ h ] ; int level = 0 ; getMaxWidthRecur ( root , count , level ) ; return getMax ( count , h ) ; } void getMaxWidthRecur ( node * root , int count [ ] , int level ) { if ( root ) { count [ level ] ++ ; getMaxWidthRecur ( root -> left , count , level + 1 ) ; getMaxWidthRecur ( root -> right , count , level + 1 ) ; } } int height ( node * node ) { if ( node == NULL ) return 0 ; else { int lHeight = height ( node -> left ) ; int rHeight = height ( node -> right ) ; return ( lHeight > rHeight ) ? ( lHeight + 1 ) : ( rHeight + 1 ) ; } } node * newNode ( int data ) { node * Node = new node ( ) ; Node -> data = data ; Node -> left = NULL ; Node -> right = NULL ; return ( Node ) ; } int getMax ( int arr [ ] , int n ) { int max = arr [ 0 ] ; int i ; for ( i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > max ) max = arr [ i ] ; } return max ; } int main ( ) { node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> right = newNode ( 8 ) ; root -> right -> right -> left = newNode ( 6 ) ; root -> right -> right -> right = newNode ( 7 ) ; cout << " Maximum β width β is β " << getMaxWidth ( root ) << endl ; return 0 ; } |
Minimize the sum of product of two arrays with permutations allowed | C ++ program to calculate minimum sum of product of two arrays . ; Returns minimum sum of product of two arrays with permutations allowed ; Sort A and B so that minimum and maximum value can easily be fetched . ; Multiplying minimum value of A and maximum value of B ; Driven Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long int minValue ( int A [ ] , int B [ ] , int n ) { sort ( A , A + n ) ; sort ( B , B + n ) ; long long int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) result += ( A [ i ] * B [ n - i - 1 ] ) ; return result ; } int main ( ) { int A [ ] = { 3 , 1 , 1 } ; int B [ ] = { 6 , 5 , 4 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << minValue ( A , B , n ) << endl ; return 0 ; } |
Count of numbers in range [ L , R ] which can be represented as sum of two perfect powers | C ++ program for the above approach ; Function to find the number of numbers that can be expressed in the form of the sum of two perfect powers ; Stores all possible powers ; Push 1 and 0 in it ; Iterate over all the exponents ; Iterate over all possible numbers ; This loop will run for a maximum of sqrt ( R ) times ; Push this power in the array pows [ ] ; Increase the number ; Stores if i can be expressed as the sum of perfect power or not ; Iterate over all possible pairs of the array pows [ ] ; The number is valid ; Find the prefix sum of the array ok [ ] ; Return the count of required number ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int TotalPerfectPowerSum ( long long L , long long R ) { vector < long long > pows ; pows . push_back ( 0 ) ; pows . push_back ( 1 ) ; for ( int p = 2 ; p < 25 ; p ++ ) { long long int num = 2 ; while ( ( long long int ) ( pow ( num , p ) + 0.5 ) <= R ) { pows . push_back ( ( long long int ) ( pow ( num , p ) + 0.5 ) ) ; num ++ ; } } int ok [ R + 1 ] ; memset ( ok , 0 , sizeof ( ok ) ) ; for ( int i = 0 ; i < pows . size ( ) ; i ++ ) { for ( int j = 0 ; j < pows . size ( ) ; j ++ ) { if ( pows [ i ] + pows [ j ] <= R and pows [ i ] + pows [ j ] >= L ) { ok [ pows [ i ] + pows [ j ] ] = 1 ; } } } for ( int i = 0 ; i <= R ; i ++ ) { ok [ i ] += ok [ i - 1 ] ; } return ok [ R ] - ok [ L - 1 ] ; } signed main ( ) { int L = 5 , R = 8 ; cout << TotalPerfectPowerSum ( L , R ) ; return 0 ; } |
Vertical width of Binary tree | Set 1 | CPP program to print vertical width of a tree ; A Binary Tree Node ; get vertical width ; traverse left ; if curr is decrease then get value in minimum ; if curr is increase then get value in maximum ; traverse right ; 1 is added to include root in the width ; Utility function to create a new tree node ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; void lengthUtil ( Node * root , int & maximum , int & minimum , int curr = 0 ) { if ( root == NULL ) return ; lengthUtil ( root -> left , maximum , minimum , curr - 1 ) ; if ( minimum > curr ) minimum = curr ; if ( maximum < curr ) maximum = curr ; lengthUtil ( root -> right , maximum , minimum , curr + 1 ) ; } int getLength ( Node * root ) { int maximum = 0 , minimum = 0 ; lengthUtil ( root , maximum , minimum , 0 ) ; return ( abs ( minimum ) + maximum ) + 1 ; } Node * newNode ( int data ) { Node * curr = new Node ; curr -> data = data ; curr -> left = curr -> right = NULL ; return curr ; } int main ( ) { Node * root = newNode ( 7 ) ; root -> left = newNode ( 6 ) ; root -> right = newNode ( 5 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 3 ) ; root -> right -> left = newNode ( 2 ) ; root -> right -> right = newNode ( 1 ) ; cout << getLength ( root ) << " STRNEWLINE " ; return 0 ; } |
Maximize Array sum after changing sign of any elements for exactly M times | C ++ program for the above approach ; Function to find the maximum sum with M flips ; Declare a priority queue i . e . min heap ; Declare the sum as zero ; Push all elements of the array in it ; Iterate for M times ; Get the top element ; Flip the sign of the top element ; Remove the top element ; Update the sum ; Push the temp into the queue ; Driver program ; Given input | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findMaximumSumWithMflips ( int arr [ ] , int N , int M ) { priority_queue < int , vector < int > , greater < int > > pq ; int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { pq . push ( arr [ i ] ) ; sum += arr [ i ] ; } while ( M -- ) { sum -= pq . top ( ) ; int temp = -1 * pq . top ( ) ; pq . pop ( ) ; sum += temp ; pq . push ( temp ) ; } cout << sum ; } int main ( ) { int arr [ ] = { -3 , 7 , -1 , -5 , -3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int M = 4 ; findMaximumSumWithMflips ( arr , N , M ) ; return 0 ; } |
Minimum operations to make Array equal by repeatedly adding K from an element and subtracting K from other | C ++ program for the above approach ; Function to find the minimum number of operations to make all the elements of the array equal ; Store the sum of the array arr [ ] ; Traverse through the array ; If it is not possible to make all array element equal ; Store the minimum number of operations needed ; Traverse through the array ; Finally , print the minimum number operation to make array elements equal ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void miniOperToMakeAllEleEqual ( int arr [ ] , int n , int k ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; } if ( sum % n ) { cout << -1 ; return ; } int valueAfterDivision = sum / n ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( abs ( valueAfterDivision - arr [ i ] ) % k != 0 ) { cout << -1 ; return ; } count += abs ( valueAfterDivision - arr [ i ] ) / k ; } cout << count / 2 << endl ; } int main ( ) { int n = 3 , k = 3 ; int arr [ 3 ] = { 5 , 8 , 11 } ; miniOperToMakeAllEleEqual ( arr , n , k ) ; return 0 ; } |
Minimum operations to make product of adjacent element pair of prefix sum negative | C ++ code for the above approach ; Function to find minimum operations needed to make the product of any two adjacent elements in prefix sum array negative ; Stores the minimum operations ; Stores the prefix sum and number of operations ; Traverse the array ; Update the value of sum ; Check if i + r is odd ; Check if prefix sum is not positive ; Update the value of ans and sum ; Check if prefix sum is not negative ; Update the value of ans and sum ; Update the value of res ; Print the value of res ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minOperations ( vector < int > a ) { int res = INT_MAX ; int N = a . size ( ) ; for ( int r = 0 ; r < 2 ; r ++ ) { int sum = 0 , ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += a [ i ] ; if ( ( i + r ) % 2 ) { if ( sum <= 0 ) { ans += - sum + 1 ; sum = 1 ; } } else { if ( sum >= 0 ) { ans += sum + 1 ; sum = -1 ; } } } res = min ( res , ans ) ; } cout << res ; } int main ( ) { vector < int > a { 1 , -3 , 1 , 0 } ; minOperations ( a ) ; return 0 ; } |
Minimize sum of product of same | C ++ program to implement the above approach ; Function to print1 the arrays ; Function to reverse1 the subarray ; Function to calculate the minimum product of same - indexed elements of two given arrays ; Calculate initial product ; Traverse all odd length subarrays ; Remove the previous product ; Add the current product ; Check if current product is minimum or not ; Traverse all even length subarrays ; Remove the previous product ; Add to the current product ; Check if current product is minimum or not ; Update the pointers ; reverse1 the subarray ; print1 the subarray ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void print1 ( vector < int > & a , vector < int > & b ) { int minProd = 0 ; for ( int i = 0 ; i < a . size ( ) ; ++ i ) { cout << a [ i ] << " β " ; } cout << endl ; for ( int i = 0 ; i < b . size ( ) ; ++ i ) { cout << b [ i ] << " β " ; minProd += a [ i ] * b [ i ] ; } cout << endl ; cout << minProd ; } void reverse1 ( int left , int right , vector < int > & arr ) { while ( left < right ) { int temp = arr [ left ] ; arr [ left ] = arr [ right ] ; arr [ right ] = temp ; ++ left ; -- right ; } } void minimumProdArray ( vector < int > & a , vector < int > & b , int l ) { int total = 0 ; for ( int i = 0 ; i < a . size ( ) ; ++ i ) { total += a [ i ] * b [ i ] ; } int min = INT_MAX ; int first = 0 ; int second = 0 ; for ( int i = 0 ; i < a . size ( ) ; ++ i ) { int left = i - 1 ; int right = i + 1 ; int total1 = total ; while ( left >= 0 && right < a . size ( ) ) { total1 -= a [ left ] * b [ left ] + a [ right ] * b [ right ] ; total1 += a [ left ] * b [ right ] + a [ right ] * b [ left ] ; if ( min >= total1 ) { min = total1 ; first = left ; second = right ; } -- left ; ++ right ; } } for ( int i = 0 ; i < a . size ( ) ; ++ i ) { int left = i ; int right = i + 1 ; int total1 = total ; while ( left >= 0 && right < a . size ( ) ) { total1 -= a [ left ] * b [ left ] + a [ right ] * b [ right ] ; total1 += a [ left ] * b [ right ] + a [ right ] * b [ left ] ; if ( min >= total1 ) { min = total1 ; first = left ; second = right ; } -- left ; ++ right ; } } if ( min < total ) { reverse1 ( first , second , a ) ; print1 ( a , b ) ; } else { print1 ( a , b ) ; } } int main ( ) { int n = 4 ; vector < int > a { 2 , 3 , 1 , 5 } ; vector < int > b { 8 , 2 , 4 , 3 } ; minimumProdArray ( a , b , n ) ; } |
Maximize cost of removing all occurrences of substrings " ab " and " ba " | C ++ program for the above approach : ; Function to find the maximum cost of removing substrings " ab " and " ba " from S ; MaxStr is the substring char array with larger cost ; MinStr is the substring char array with smaller cost ; ; Denotes larger point ; Denotes smaller point ; Stores cost scored ; Stack to keep track of characters ; Traverse the string ; If the substring is maxstr ; Pop from the stack ; Add maxp to cost ; Push the character to the stack ; Remaining string after removing maxstr ; Find remaining string ; Reversing the string retrieved from the stack ; Removing all occurences of minstr ; If the substring is minstr ; Pop from the stack ; Add minp to the cost ; Otherwise ; Return the maximum cost ; Driver Code ; Input String ; Costs | #include <bits/stdc++.h> NEW_LINE using namespace std ; int MaxCollection ( string S , int P , int Q ) { char maxstr [ 2 ] ; string x = ( P >= Q ? " ab " : " ba " ) ; strcpy ( maxstr , x . c_str ( ) ) ; char minstr [ 2 ] ; x = ( P >= Q ? " ba " : " ab " ) ; strcpy ( minstr , x . c_str ( ) ) ; int maxp = max ( P , Q ) ; int minp = min ( P , Q ) ; int cost = 0 ; stack < char > stack1 ; char s [ S . length ( ) ] ; strcpy ( s , S . c_str ( ) ) ; for ( auto & ch : s ) { if ( ! stack1 . empty ( ) && ( stack1 . top ( ) == maxstr [ 0 ] && ch == maxstr [ 1 ] ) ) { stack1 . pop ( ) ; cost += maxp ; } else { stack1 . push ( ch ) ; } } string sb = " " ; while ( stack1 . size ( ) > 0 ) { sb = sb + stack1 . top ( ) ; stack1 . pop ( ) ; } reverse ( sb . begin ( ) , sb . end ( ) ) ; for ( auto & ch : sb ) { if ( ! stack1 . empty ( ) && ( stack1 . top ( ) == minstr [ 0 ] && ch == minstr [ 1 ] ) ) { stack1 . pop ( ) ; cost += minp ; } else { stack1 . push ( ch ) ; } } return cost ; } int main ( ) { string S = " cbbaabbaab " ; int P = 6 ; int Q = 4 ; cout << MaxCollection ( S , P , Q ) ; return 0 ; } |
Vertical width of Binary tree | Set 2 | CPP code to find vertical width of a binary tree ; Tree class ; Function to fill hd in set . ; Third parameter is horizontal distance ; Driver Code ; Creating the above tree | #include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * left , * right ; Node ( int data_new ) { data = data_new ; left = right = NULL ; } } ; void fillSet ( Node * root , unordered_set < int > & s , int hd ) { if ( ! root ) return ; fillSet ( root -> left , s , hd - 1 ) ; s . insert ( hd ) ; fillSet ( root -> right , s , hd + 1 ) ; } int verticalWidth ( Node * root ) { unordered_set < int > s ; fillSet ( root , s , 0 ) ; return s . size ( ) ; } int main ( ) { Node * root = NULL ; root = new Node ( 1 ) ; root -> left = new Node ( 2 ) ; root -> right = new Node ( 3 ) ; root -> left -> left = new Node ( 4 ) ; root -> left -> right = new Node ( 5 ) ; root -> right -> left = new Node ( 6 ) ; root -> right -> right = new Node ( 7 ) ; root -> right -> left -> right = new Node ( 8 ) ; root -> right -> right -> right = new Node ( 9 ) ; cout << verticalWidth ( root ) << " STRNEWLINE " ; return 0 ; } |
Maximum value of ( arr [ i ] * arr [ j ] ) + ( arr [ j ] | C ++ program for the above approach ; Function to find the value of the expression a * b + ( b - a ) ; Function to find the maximum value of the expression a * b + ( b - a ) possible for any pair ( a , b ) ; Sort the vector in ascending order ; Stores the maximum value ; Update ans by choosing the pair of the minimum and 2 nd minimum ; Update ans by choosing the pair of maximum and 2 nd maximum ; Return the value of ans ; Driver Code ; Given inputs | #include <bits/stdc++.h> NEW_LINE using namespace std ; int calc ( int a , int b ) { return a * b + ( b - a ) ; } int findMaximum ( vector < int > arr , int N ) { sort ( arr . begin ( ) , arr . end ( ) ) ; int ans = -1e9 ; ans = max ( ans , calc ( arr [ 0 ] , arr [ 1 ] ) ) ; ans = max ( ans , calc ( arr [ N - 2 ] , arr [ N - 1 ] ) ) ; return ans ; } int main ( ) { vector < int > arr = { 0 , -47 , 12 } ; int N = ( int ) arr . size ( ) ; cout << findMaximum ( arr , N ) ; return 0 ; } |
Minimize flips on K | ; store previous flip events ; remove an item which is out range of window . ; In a window , if A [ i ] is a even number with even times fliped , it need to be fliped again . On other hand , if A [ i ] is a odd number with odd times fliped , it need to be fliped again . ; flip . push ( i ) ; insert ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minKBitFlips ( int A [ ] , int K , int N ) { queue < int > flip ; int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( flip . size ( ) > 0 && ( i - flip . front ( ) >= K ) ) { flip . pop ( ) ; } if ( A [ i ] % 2 == flip . size ( ) % 2 ) { if ( i + K - 1 >= N ) { return -1 ; } count ++ ; } } return count ; } int main ( ) { int A [ ] = { 0 , 1 , 0 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int K = 1 ; int ans = minKBitFlips ( A , K , 3 ) ; cout << ans ; return 0 ; } |
Minimize flips on K | ; We 're flipping the subarray from A[i] to A[i+K-1] ; If not flip entire array , impossible ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minKBitFlips ( int A [ ] , int K , int N ) { int temp [ N ] ; memset ( temp , 0 , N ) ; int count = 0 ; int flip = 0 ; count ++ ; for ( int i = 0 ; i < N ; ++ i ) { flip ^= temp [ i ] ; if ( A [ i ] == flip ) { count ++ ; if ( i + K > N ) { return -1 ; } flip ^= 1 ; if ( i + K < N ) { temp [ i + K ] ^= 1 ; } } } return count ; } int main ( ) { int A [ ] = { 0 , 1 , 0 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int K = 1 ; int ans = minKBitFlips ( A , K , N ) ; cout << ans ; return 0 ; } |
Generate an N | C ++ program for the above approach ; Function to calculate GCD of given array ; Utility function to check for all the combinations ; If a sequence of size N is obtained ; If gcd of current combination is K ; If current element from first array is divisible by K ; Recursively proceed further ; If current combination satisfies given condition ; Remove the element from the combination ; If current element from second array is divisible by K ; Recursively proceed further ; If current combination satisfies given condition ; Remove the element from the combination ; Function to check for all possible combinations ; Stores the subsequence ; If GCD of any sequence is not equal to K ; Driver Code ; Given arrays ; size of the array ; Given value of K ; Function call to generate a subsequence whose GCD is K | #include <bits/stdc++.h> NEW_LINE using namespace std ; int GCD ( int a , int b ) { if ( b == 0 ) return a ; return GCD ( b , a % b ) ; } int GCDArr ( vector < int > a ) { int ans = a [ 0 ] ; for ( auto val : a ) { ans = GCD ( ans , val ) ; } return ans ; } bool findSubseqUtil ( int a [ ] , int b [ ] , vector < int > ans , int k , int i , int N ) { if ( ans . size ( ) == N ) { if ( GCDArr ( ans ) == k ) { for ( auto val : ans ) cout << val << " β " ; return true ; } else { return false ; } } if ( a [ i ] % k == 0 ) { ans . push_back ( a [ i ] ) ; bool temp = findSubseqUtil ( a , b , ans , k , i + 1 , N ) ; if ( temp == true ) return true ; ans . pop_back ( ) ; } if ( b [ i ] % k == 0 ) { ans . push_back ( b [ i ] ) ; bool temp = findSubseqUtil ( a , b , ans , k , i + 1 , N ) ; if ( temp == true ) return true ; ans . pop_back ( ) ; } return false ; } void findSubseq ( int A [ ] , int B [ ] , int K , int i , int N ) { vector < int > ans ; bool ret = findSubseqUtil ( A , B , ans , K , i , N ) ; if ( ret == false ) cout << -1 << " STRNEWLINE " ; } int main ( ) { int A [ ] = { 5 , 3 , 6 , 2 , 9 } ; int B [ ] = { 21 , 7 , 14 , 12 , 28 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int K = 3 ; findSubseq ( A , B , K , 0 , N ) ; return 0 ; } |
Kth element in permutation of first N natural numbers having all even numbers placed before odd numbers in increasing order | C ++ program for the above approach ; Function to find the K - th element in the required permutation ; Stores the required permutation ; Insert all the even numbers less than or equal to N ; Now , insert all odd numbers less than or equal to N ; Print the Kth element ; Driver Code ; functions call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findKthElement ( int N , int K ) { vector < int > v ; for ( int i = 1 ; i <= N ; i ++ ) { if ( i % 2 == 0 ) { v . push_back ( i ) ; } } for ( int i = 1 ; i <= N ; i ++ ) { if ( i % 2 != 0 ) { v . push_back ( i ) ; } } cout << v [ K - 1 ] ; } int main ( ) { int N = 10 , K = 3 ; findKthElement ( N , K ) ; return 0 ; } |
Minimum subsequences of a string A required to be appended to obtain the string B | C ++ program for the above approach ; Function to count the minimum subsequences of a string A required to be appended to obtain the string B ; Size of the string ; Maps characters to their respective indices ; Insert indices of characters into the sets ; Stores the position of the last visited index in the string A . Initially set it to - 1. ; Stores the required count ; Iterate over the characters of B ; If the character in B is not present in A , return - 1 ; Fetch the next index from B [ i ] 's set ; If the iterator points to the end of that set ; If it doesn 't point to the end, update previous ; Print the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void countminOpsToConstructAString ( string A , string B ) { int N = A . length ( ) ; int i = 0 ; map < char , set < int > > mp ; for ( i = 0 ; i < N ; i ++ ) { mp [ A [ i ] ] . insert ( i ) ; } int previous = -1 ; int ans = 1 ; for ( i = 0 ; i < B . length ( ) ; i ++ ) { char ch = B [ i ] ; if ( mp [ ch ] . size ( ) == 0 ) { cout << -1 ; return ; } auto it = mp [ ch ] . upper_bound ( previous ) ; if ( it == mp [ ch ] . end ( ) ) { previous = -1 ; ans ++ ; -- i ; continue ; } previous = * it ; } cout << ans ; } int main ( ) { string A = " abc " , B = " abac " ; countminOpsToConstructAString ( A , B ) ; return 0 ; } |
Maximize difference between odd and even indexed array elements by shift operations | C ++ program for the above approach ; Function to minimize array elements by shift operations ; For checking all the left shift operations ; Left shift ; Consider the minimum possible value ; Function to maximize array elements by shift operations ; For checking all the left shift operations ; Left shift ; Consider the maximum possible value ; Function to maximize the absolute difference between even and odd indexed array elements ; To calculate the difference of odd indexed elements and even indexed elements ; To calculate the difference between odd and even indexed array elements ; Print the maximum value ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimize ( int n ) { int optEle = n ; string strEle = to_string ( n ) ; for ( int idx = 0 ; idx < strEle . length ( ) ; idx ++ ) { int temp = stoi ( strEle . substr ( idx ) + strEle . substr ( 0 , idx ) ) ; optEle = min ( optEle , temp ) ; } return optEle ; } int maximize ( int n ) { int optEle = n ; string strEle = to_string ( n ) ; for ( int idx = 0 ; idx < strEle . length ( ) ; idx ++ ) { int temp = stoi ( strEle . substr ( idx ) + strEle . substr ( 0 , idx ) ) ; optEle = max ( optEle , temp ) ; } return optEle ; } void minimumDifference ( int arr [ ] , int N ) { int caseOne = 0 ; int minVal = 0 ; int maxVal = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( i % 2 == 0 ) minVal += minimize ( arr [ i ] ) ; else maxVal += maximize ( arr [ i ] ) ; } caseOne = abs ( maxVal - minVal ) ; int caseTwo = 0 ; minVal = 0 ; maxVal = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( i % 2 == 0 ) maxVal += maximize ( arr [ i ] ) ; else minVal += minimize ( arr [ i ] ) ; caseTwo = abs ( maxVal - minVal ) ; } cout << max ( caseOne , caseTwo ) << endl ; } int main ( ) { int arr [ ] = { 332 , 421 , 215 , 584 , 232 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minimumDifference ( arr , N ) ; return 0 ; } |
Find if given vertical level of binary tree is sorted or not | CPP program to determine whether vertical level l of binary tree is sorted or not . ; Structure of a tree node . ; Function to create new tree node . ; Helper function to determine if vertical level l of given binary tree is sorted or not . ; If root is null , then the answer is an empty subset and an empty subset is always considered to be sorted . ; Variable to store previous value in vertical level l . ; Variable to store current level while traversing tree vertically . ; Variable to store current node while traversing tree vertically . ; Declare queue to do vertical order traversal . A pair is used as element of queue . The first element in pair represents the node and the second element represents vertical level of that node . ; Insert root in queue . Vertical level of root is 0. ; Do vertical order traversal until all the nodes are not visited . ; Check if level of node extracted from queue is required level or not . If it is the required level then check if previous value in that level is less than or equal to value of node . ; If left child is not NULL then push it in queue with level reduced by 1. ; If right child is not NULL then push it in queue with level increased by 1. ; If the level asked is not present in the given binary tree , that means that level will contain an empty subset . Therefore answer will be true . ; Driver program ; 1 / \ 2 5 / \ 7 4 / 6 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; Node * left , * right ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return temp ; } bool isSorted ( Node * root , int level ) { if ( root == NULL ) return true ; int prevVal = INT_MIN ; int currLevel ; Node * currNode ; queue < pair < Node * , int > > q ; q . push ( make_pair ( root , 0 ) ) ; while ( ! q . empty ( ) ) { currNode = q . front ( ) . first ; currLevel = q . front ( ) . second ; q . pop ( ) ; if ( currLevel == level ) { if ( prevVal <= currNode -> key ) prevVal = currNode -> key ; else return false ; } if ( currNode -> left ) q . push ( make_pair ( currNode -> left , currLevel - 1 ) ) ; if ( currNode -> right ) q . push ( make_pair ( currNode -> right , currLevel + 1 ) ) ; } return true ; } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 5 ) ; root -> left -> left = newNode ( 7 ) ; root -> left -> right = newNode ( 4 ) ; root -> left -> right -> left = newNode ( 6 ) ; int level = -1 ; if ( isSorted ( root , level ) == true ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Minimize operations of removing 2 i | C ++ program to implement the above approach ; Function to find minimum count of steps required to remove all the array elements ; Stores minimum count of steps required to remove all the array elements ; Update N ; Traverse each bit of N ; If current bit is set ; Update cntStep ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumStepReqArr ( int arr [ ] , int N ) { int cntStep = 0 ; N += 1 ; for ( int i = 31 ; i >= 0 ; i -- ) { if ( N & ( 1 << i ) ) { cntStep += 1 ; } } return cntStep ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minimumStepReqArr ( arr , N ) ; return 0 ; } |
Minimize removal of alternating subsequences to empty given Binary String | ; Function to find the minimum number of operations required to empty the string ; Initialize variables ; Traverse the string ; If current character is 0 ; Update maximum consecutive 0 s and 1 s ; Print the minimum operation ; Driver code + ; input string ; length of string ; Function Call | #include <iostream> NEW_LINE using namespace std ; void minOpsToEmptyString ( string S , int N ) { int one = 0 , zero = 0 ; int x0 = 0 , x1 = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] == '0' ) { x0 ++ ; x1 = 0 ; } else { x1 ++ ; x0 = 0 ; } zero = max ( x0 , zero ) ; one = max ( x1 , one ) ; } cout << max ( one , zero ) << endl ; } int main ( ) { string S = "0100100111" ; int N = S . length ( ) ; minOpsToEmptyString ( S , N ) ; } |
Swap upper and lower triangular halves of a given Matrix | C ++ program for the above approach ; Function to swap laterally inverted images of upper and lower triangular halves of a given matrix ; Store the matrix elements from upper & lower triangular halves ; Traverse the matrix mat [ ] [ ] ; Find the index ; If current element lies on the principal diagonal ; If current element lies below the principal diagonal ; If current element lies above the principal diagonal ; Traverse again to swap values ; Find the index ; Principal diagonal ; Below main diagonal ; Above main diagonal ; Traverse the matrix and print ; Driver Code ; Given Matrix mat [ ] [ ] ; Swap the upper and lower triangular halves | #include <bits/stdc++.h> NEW_LINE using namespace std ; void ReverseSwap ( vector < vector < int > > & mat , int n ) { vector < int > lowerEle [ n ] ; vector < int > upperEle [ n ] ; int index ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { index = abs ( i - j ) ; if ( i == j ) { continue ; } else if ( j < i ) { lowerEle [ index ] . push_back ( mat [ i ] [ j ] ) ; } else { upperEle [ index ] . push_back ( mat [ i ] [ j ] ) ; } } } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { index = abs ( i - j ) ; if ( i == j ) { continue ; } else if ( j < i ) { mat [ i ] [ j ] = upperEle [ index ] . back ( ) ; upperEle [ index ] . pop_back ( ) ; } else { mat [ i ] [ j ] = lowerEle [ index ] . back ( ) ; lowerEle [ index ] . pop_back ( ) ; } } } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { cout << mat [ i ] [ j ] << " β " ; } cout << endl ; } } int main ( ) { vector < vector < int > > mat = { { 1 , 2 } , { 4 , 5 } } ; int N = mat . size ( ) ; ReverseSwap ( mat , N ) ; return 0 ; } |
Minimize sum of K positive integers with given LCM | C ++ program to implement the above approach ; Function to find the prime power of X ; Stores prime powers of X ; Iterate over the range [ 2 , sqrt ( X ) ] ; If X is divisible by i ; Stores prime power ; Calculate prime power of X ; Update X ; Update p ; Insert prime powers into primePow [ ] ; If X exceeds 1 ; Function to calculate the sum of array elements ; Stores sum of array elements ; Traverse the array ; Update sum ; Function to partition array into K groups such that sum of elements of the K groups is minimum ; If count of prime powers is equal to pos ; Stores minimum sum of of each partition of arr [ ] into K groups ; Traverse the array arr [ ] ; Include primePow [ pos ] into i - th groups ; Update res ; Remove factors [ pos ] from i - th groups ; Utility function to calculate minimum sum of K positive integers whose LCM is X ; Stores all prime powers of X ; Stores count of prime powers ; Stores minimum sum of K positive integers whose LCM is X ; If n is less than or equal to k ; Traverse primePow [ ] array ; Update sum ; Update sum ; arr [ i ] : Stores element in i - th group by partitioning the primePow [ ] array ; Update sum ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > primePower ( int X ) { vector < int > primePow ; for ( int i = 2 ; i * i <= X ; i ++ ) { if ( X % i == 0 ) { int p = 1 ; while ( X % i == 0 ) { X /= i ; p *= i ; } primePow . push_back ( p ) ; } } if ( X > 1 ) { primePow . push_back ( X ) ; } return primePow ; } int getSum ( vector < int > & ar ) { int sum = 0 ; for ( int i : ar ) { sum += i ; } return sum ; } int getMinSum ( int pos , vector < int > & arr , vector < int > & primePow ) { if ( pos == primePow . size ( ) ) { return getSum ( arr ) ; } int res = INT_MAX ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { arr [ i ] *= primePow [ pos ] ; res = min ( res , getMinSum ( pos + 1 , arr , primePow ) ) ; arr [ i ] /= primePow [ pos ] ; } return res ; } int minimumSumWithGivenLCM ( int k , int x ) { vector < int > primePow = primePower ( x ) ; int n = primePow . size ( ) ; int sum = 0 ; if ( n <= k ) { for ( int i : primePow ) { sum += i ; } sum += k - n ; } else { vector < int > arr ( k , 1 ) ; sum = getMinSum ( 0 , arr , primePow ) ; } return sum ; } int main ( ) { int k = 3 , x = 210 ; cout << minimumSumWithGivenLCM ( k , x ) ; return 0 ; } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.