text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Sum of first N natural numbers with all powers of 2 added twice | C ++ program to implement the above approach ; Function to raise N to the power P and return the value ; Function to calculate the log base 2 of an integer ; Calculate log2 ( N ) indirectly using log ( ) method ; Function to calculate and return the required sum ; Sum of first N natural numbers ; Sum of all powers of 2 up to N ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; double power ( int N , int P ) { return pow ( N , P ) ; } int Log2 ( int N ) { int result = ( int ) ( log ( N ) / log ( 2 ) ) ; return result ; } double specialSum ( int n ) { double sum = n * ( n + 1 ) / 2 ; int a = Log2 ( n ) ; sum = sum + power ( 2 , a + 1 ) - 1 ; return sum ; } int main ( ) { int n = 4 ; cout << ( specialSum ( n ) ) << endl ; return 0 ; }
Rearrange an array such that product of every two consecutive elements is a multiple of 4 | C ++ Program to rearray array elements such that the product of every two consecutive elements is a multiple of 4 ; Function to rearrange array elements such that the every two consecutive elements is a multiple of 4 ; If element is odd ; Odd ; If element is divisible by 4 ; Divisible by 4 ; If element is not divisible by 4 ; Even but not divisible by 4 ; Condition for rearrangement to be possible ; Print ODD [ i ] and FOUR [ i ] consecutively ; Print the remaining FOUR [ i ] , if any ; Condition for rearrangement to be possible ; Print ODD [ i ] and FOUR [ i ] consecutively ; Print the remaining FOUR [ i ] , if any ; Print the NON_FOUR [ i ] elements at the end ; No possible configuration ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void Permute ( vector < int > & arr , int n ) { int odd = 0 , four = 0 ; int non_four = 0 ; vector < int > ODD , FOUR , NON_FOUR ; for ( auto x : arr ) { if ( x & 1 ) { odd ++ ; ODD . push_back ( x ) ; } else if ( x % 4 == 0 ) { four ++ ; FOUR . push_back ( x ) ; } else { non_four ++ ; NON_FOUR . push_back ( x ) ; } } if ( non_four == 0 && four >= odd - 1 ) { int x = ODD . size ( ) ; int y = FOUR . size ( ) ; int i ; for ( i = 0 ; i < x ; i ++ ) { cout << ODD [ i ] << " ▁ " ; if ( i < y ) cout << FOUR [ i ] << " ▁ " ; } while ( i < y ) cout << FOUR [ i ] << " ▁ " ; cout << endl ; } else if ( non_four > 0 and four >= odd ) { int x = ODD . size ( ) ; int y = FOUR . size ( ) ; int i ; for ( i = 0 ; i < x ; i ++ ) { cout << ODD [ i ] << " ▁ " ; if ( i < y ) cout << FOUR [ i ] << " ▁ " ; } while ( i < y ) cout << FOUR [ i ] << " ▁ " ; for ( int j = 0 ; j < ( int ) NON_FOUR . size ( ) ; j ++ ) cout << NON_FOUR [ j ] << " ▁ " ; cout << endl ; } else cout << " Not ▁ Possible " << endl ; } signed main ( ) { vector < int > arr = { 2 , 7 , 1 , 8 , 2 , 8 } ; int N = sizeof ( arr ) / sizeof ( arr ) ; Permute ( arr , N ) ; return 0 ; }
Construct the smallest possible Array with given Sum and XOR | C ++ program for the above approach ; Function to find array ; array not possible ; Array possible with exactly 1 or no element ; Checking array with two elements possible or not . ; Driver Code ; Given sum and value of Bitwise XOR ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findArray ( int sum , int xorr ) { if ( xorr > sum sum % 2 != xorr % 2 ) { cout << " No ▁ Array ▁ Possible STRNEWLINE " ; return ; } if ( sum == xorr ) { if ( sum == 0 ) cout << " Array ▁ is ▁ empty " << " ▁ with ▁ size ▁ 0 STRNEWLINE " ; else cout << " Array ▁ size ▁ is ▁ " << 1 << " Array is " << sum << " STRNEWLINE " ; return ; } int mid = ( sum - xorr ) / 2 ; if ( xorr & mid == 1 ) { cout << " Array ▁ size ▁ is ▁ " << 3 << " STRNEWLINE " ; cout << " Array ▁ is ▁ " << xorr << " ▁ " << mid << " ▁ " << mid << " STRNEWLINE " ; } else { cout << " Array ▁ size ▁ is ▁ " << 2 << " STRNEWLINE " ; cout << " Array ▁ is ▁ " << ( xorr + mid ) << " ▁ " << mid << " STRNEWLINE " ; } } int main ( ) { int sum = 4 , xorr = 2 ; findArray ( sum , xorr ) ; cout << " STRNEWLINE " ; return 0 ; }
Smallest number greater than X which is K | C ++ Program to find the smallest K periodic integer greater than X ; Function to find the smallest K periodic integer greater than X ; Stores the number in a temporary string ; Set X [ i ] = X [ i - k ] for i > k ; Start from the current index ; Loop upto N change X [ j ] to X [ i ] ; Return X if current Value is greater than original value ; Find the first digit not equal to 9 ; Increment X [ i ] ; Set POS to current index ; Change X [ i ] to 0 for all indices from POS + 1 to K ; Set X [ i ] = X [ i - k ] for i > k ; Loop upto N change X [ j ] to X [ i ] ; Return the final string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string Kperiodicinteger ( string X , int N , int K ) { string temp = X ; for ( int i = 0 ; i < K ; i ++ ) { int j = i ; while ( j < N ) { X [ j ] = X [ i ] ; j += K ; } } if ( X >= temp ) { return X ; } int POS ; for ( int i = K - 1 ; i >= 0 ; i -- ) { if ( X [ i ] != '9' ) { X [ i ] ++ ; POS = i ; break ; } } for ( int i = POS + 1 ; i < K ; i ++ ) { X [ i ] = '0' ; } for ( int i = 0 ; i < K ; i ++ ) { int j = i ; while ( j < N ) { X [ j ] = X [ i ] ; j += K ; } } return X ; } int main ( ) { int N = 4 , K = 2 ; string X = "1215" ; cout << Kperiodicinteger ( X , N , K ) ; return 0 ; }
Maximum cost path in an Undirected Graph such that no edge is visited twice in a row | C ++ program for the above approach ; To store the resulting sum of the cost ; To store largest cost leaf vertex ; DFS Traversal to find the update the maximum cost of from any node to leaf ; Mark vertex as visited ; Store vertex initial cost ; Initially assuming edge not to be traversed ; Back edge found so , edge can be part of traversal ; New vertex is found ; Bitwise AND the current check with the returned check by the previous DFS Call ; Adds parent and its children cost ; Updates total cost of parent including child nodes ; Edge is part of the cycle ; Add cost of vertex to the answer ; Updates the largest cost leaf vertex ; Function to find the maximum cost from source vertex such that no two edges is traversed twice ; DFS Call ; Print the maximum cost ; Driver Code ; Cost Array ; Given Graph ; Given Source Node ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 100000 ; int canTake ; int best ; int dp [ N ] ; bool vis [ N ] ; int dfs ( vector < vector < int > > & g , int * cost , int u , int pre ) { vis [ u ] = true ; dp [ u ] = cost [ u ] ; bool check = 1 ; int cur = cost [ u ] ; for ( auto & x : g [ u ] ) { if ( vis [ x ] && x != pre ) { check = 0 ; } else if ( ! vis [ x ] ) { check &= dfs ( g , cost , x , u ) ; cur = max ( cur , cost [ u ] + dp [ x ] ) ; } } dp [ u ] = cur ; if ( ! check ) { canTake += cost [ u ] ; } else { best = max ( best , dp [ u ] ) ; } return check ; } int FindMaxCost ( vector < vector < int > > & g , int * cost , int source ) { dfs ( g , cost , source , -1 ) ; cout << canTake + best ; } int main ( ) { int n = 5 , m = 5 ; int cost [ ] = { 2 , 2 , 8 , 6 , 9 } ; vector < vector < int > > g ( n ) ; g [ 0 ] . push_back ( 1 ) ; g [ 1 ] . push_back ( 0 ) ; g [ 0 ] . push_back ( 2 ) ; g [ 2 ] . push_back ( 0 ) ; g [ 0 ] . push_back ( 3 ) ; g [ 3 ] . push_back ( 0 ) ; g [ 1 ] . push_back ( 2 ) ; g [ 2 ] . push_back ( 1 ) ; g [ 1 ] . push_back ( 4 ) ; g [ 4 ] . push_back ( 1 ) ; int source = 1 ; FindMaxCost ( g , cost , source ) ; return 0 ; }
Reverse a subarray of the given array to minimize the sum of elements at even position | C ++ implementation to reverse a subarray of the given array to minimize the sum of elements at even position ; Function that will give the max negative value ; Check for count greater than 0 as we require only negative solution ; Function to print the minimum sum ; Taking sum of only even index elements ; Initialize two vectors v1 , v2 ; v1 will keep account for change if 1 th index element goes to 0 ; v2 will keep account for change if 1 th index element goes to 2 ; Get the max negative value ; Driver code
#include <bits/stdc++.h> NEW_LINE #define N 5 NEW_LINE using namespace std ; int after_rev ( vector < int > v ) { int mini = 0 , count = 0 ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { count += v [ i ] ; if ( count > 0 ) count = 0 ; if ( mini > count ) mini = count ; } return mini ; } void print ( int arr [ N ] ) { int sum = 0 ; for ( int i = 0 ; i < N ; i += 2 ) sum += arr [ i ] ; vector < int > v1 , v2 ; for ( int i = 0 ; i + 1 < N ; i += 2 ) v1 . push_back ( arr [ i + 1 ] - arr [ i ] ) ; for ( int i = 1 ; i + 1 < N ; i += 2 ) v2 . push_back ( arr [ i ] - arr [ i + 1 ] ) ; int change = min ( after_rev ( v1 ) , after_rev ( v2 ) ) ; if ( change < 0 ) sum += change ; cout << sum << endl ; } int main ( ) { int arr [ N ] = { 0 , 1 , 4 , 3 } ; print ( arr ) ; return 0 ; }
Smallest number to be added in first Array modulo M to make frequencies of both Arrays equal | C ++ program for the above approach ; Utility function to find the answer ; Stores the frequencies of array elements ; Stores the possible values of X ; Generate possible positive values of X ; Initialize answer to MAX value ; Flag to check if the current element of the set can be considered ; If the frequency of an element in A [ ] is not equal to that in B [ ] after the operation ; Current set element cannot be considered ; Update minimum value of X ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int moduloEquality ( int A [ ] , int B [ ] , int n , int m ) { map < int , int > mapA , mapB ; for ( int i = 0 ; i < n ; i ++ ) { mapA [ A [ i ] ] ++ ; mapB [ B [ i ] ] ++ ; } set < int > possibleValues ; int FirstElement = B [ 0 ] ; for ( int i = 0 ; i < n ; i ++ ) { int cur = A [ i ] ; possibleValues . insert ( cur > FirstElement ? m - cur + FirstElement : FirstElement - cur ) ; } int ans = INT_MAX ; for ( auto it : possibleValues ) { bool possible = true ; for ( auto it2 : mapA ) { if ( it2 . second != mapB [ ( it2 . first + it ) % m ] ) { possible = false ; break ; } } if ( possible ) { ans = min ( ans , it ) ; } } return ans ; } int main ( ) { int n = 4 ; int m = 3 ; int A [ ] = { 0 , 0 , 2 , 1 } ; int B [ ] = { 2 , 0 , 1 , 1 } ; cout << moduloEquality ( A , B , n , m ) << endl ; return 0 ; }
Count all indices of cyclic regular parenthesis | C ++ program for the above approach ; Function to find all indices which cyclic shift leads to get balanced parenthesis ; Create auxiliary array ; Finding prefix sum and minimum element ; Update the minimum element ; ChecK if count of ' ( ' and ' ) ' are equal ; Find count of minimum element ; Find the frequency of mn ; Return the count ; Driver Code ; Given string S ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countCyclicShifts ( string & S , int n ) { int aux [ n ] = { 0 } ; for ( int i = 0 ; i < n ; ++ i ) { if ( S [ i ] == ' ( ' ) aux [ i ] = 1 ; else aux [ i ] = -1 ; } int mn = aux [ 0 ] ; for ( int i = 1 ; i < n ; ++ i ) { aux [ i ] += aux [ i - 1 ] ; mn = min ( mn , aux [ i ] ) ; } if ( aux [ n - 1 ] != 0 ) return 0 ; int count = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( aux [ i ] == mn ) count ++ ; } return count ; } int main ( ) { string S = " ) ( ) ( " ; int N = S . length ( ) ; cout << countCyclicShifts ( S , N ) ; return 0 ; }
Maximize Profit by trading stocks based on given rate per day | C ++ program for the above approach ; Function to find the maximum profit ; Start from the last day ; Traverse and keep adding the profit until a day with price of stock higher than currentDay is obtained ; Set this day as currentDay with maximum cost of stock currently ; Return the profit ; Driver Code ; Given array of prices ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxProfit ( int * prices , int n ) { int profit = 0 , currentDay = n - 1 ; while ( currentDay > 0 ) { int day = currentDay - 1 ; while ( day >= 0 && ( prices [ currentDay ] > prices [ day ] ) ) { profit += ( prices [ currentDay ] - prices [ day ] ) ; day -- ; } currentDay = day ; } return profit ; } int main ( ) { int prices [ ] = { 2 , 3 , 5 } ; int N = sizeof ( prices ) / sizeof ( prices [ 0 ] ) ; cout << maxProfit ( prices , N ) ; return 0 ; }
Check given string is oddly palindrome or not | Set 2 | C ++ program for the above approach ; Function to check if string formed by odd indices is palindromic or not ; Check if length of OddString odd , to consider edge case ; Push odd index character of first half of str in stack ; Middle element of odd length palindromic string is not compared ; If stack is empty then return true ; Driver Code ; Given string
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isOddStringPalindrome ( string str , int n ) { int oddStringSize = n / 2 ; bool lengthOdd = ( ( oddStringSize % 2 == 1 ) ? true : false ) ; stack < char > s ; int i = 1 ; int c = 0 ; while ( i < n && c < oddStringSize / 2 ) { s . push ( str [ i ] ) ; i += 2 ; c ++ ; } if ( lengthOdd ) i = i + 2 ; while ( i < n && s . size ( ) > 0 ) { if ( s . top ( ) == str [ i ] ) s . pop ( ) ; else break ; i = i + 2 ; } if ( s . size ( ) == 0 ) return true ; return false ; } int main ( ) { int N = 10 ; string s = " aeafacafae " ; if ( isOddStringPalindrome ( s , N ) ) cout << " Yes STRNEWLINE " ; else cout << " No STRNEWLINE " ; return 0 ; }
Check given string is oddly palindrome or not | Set 2 | C ++ program for the above approach ; Functions checks if characters at odd index of the string forms palindrome or not ; Initialise two pointers ; Iterate till left <= right ; If there is a mismatch occurs then return false ; Increment and decrement the left and right pointer by 2 ; Driver Code ; Given String ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isOddStringPalindrome ( string str , int n ) { int left , right ; if ( n % 2 == 0 ) { left = 1 ; right = n - 1 ; } else { left = 1 ; right = n - 2 ; } while ( left < n && right >= 0 && left < right ) { if ( str [ left ] != str [ right ] ) return false ; left += 2 ; right -= 2 ; } return true ; } int main ( ) { int n = 10 ; string s = " aeafacafae " ; if ( isOddStringPalindrome ( s , n ) ) cout << " Yes STRNEWLINE " ; else cout << " No STRNEWLINE " ; return 0 ; }
Remove minimum characters from string to split it into three substrings under given constraints | C ++ program for the above approach ; Function that counts minimum character that must be removed ; Length of string ; Create prefix array ; Initialize first position ; Fill prefix array ; Initialise maxi ; Check all the possibilities by putting i and j at different position & find maximum among them ; Print the characters to be removed ; Driver Code ; Given String ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void min_remove ( string str ) { int N = str . length ( ) ; int prefix_a [ N + 1 ] ; int prefix_b [ N + 1 ] ; int prefix_c [ N + 1 ] ; prefix_a [ 0 ] = 0 ; prefix_b [ 0 ] = 0 ; prefix_c [ 0 ] = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { prefix_a [ i ] = prefix_a [ i - 1 ] + ( str [ i - 1 ] == ' a ' ) ; prefix_b [ i ] = prefix_b [ i - 1 ] + ( str [ i - 1 ] == ' b ' ) ; prefix_c [ i ] = prefix_c [ i - 1 ] + ( str [ i - 1 ] == ' c ' ) ; } int maxi = INT_MIN ; for ( int i = 0 ; i <= N ; i ++ ) { for ( int j = i ; j <= N ; j ++ ) { maxi = max ( maxi , ( prefix_a [ i ] + ( prefix_b [ j ] - prefix_b [ i ] ) + ( prefix_c [ N ] - prefix_c [ j ] ) ) ) ; } } cout << ( N - maxi ) << endl ; } int main ( ) { string str = " aaaabaaxccac " ; min_remove ( str ) ; return 0 ; }
Create an array of size N with sum S such that no subarray exists with sum S or S | C ++ for the above approach ; Function to create an array with N elements with sum as S such that the given conditions satisfy ; Check if the solution exists ; Print the array as print ( n - 1 ) elements of array as 2 ; Print the last element of the array ; Print the value of k ; If solution doesnot exists ; Driver Code ; Given N and sum S ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void createArray ( int n , int s ) { if ( 2 * n <= s ) { for ( int i = 0 ; i < n - 1 ; i ++ ) { cout << "2" << " ▁ " ; s -= 2 ; } cout << s << endl ; cout << "1" << endl ; } else cout << " - 1" << endl ; } int main ( ) { int N = 1 ; int S = 4 ; createArray ( N , S ) ; }
Maximize partitions such that no two substrings have any common character | C ++ program to find the maximum number of partitions possible such that no two substrings have common character ; Function to calculate and return the maximum number of partitions ; r : Stores the maximum number of partitions k : Stores the ending index of the partition ; Stores the last index of every unique character of the string ; Traverse the string and store the last index of every character ; Store the last index of the first character from map ; Update K to find the end of partition ; Otherwise , the end of partition is found ; Increment r ; Update k for the next partition ; Add the last partition ; Driver Program
#include using namespace std ; int maximum_partition ( string str ) { int i = 0 , j = 0 , k = 0 ; int c = 0 , r = 0 ; unordered_map m ; for ( i = str . length ( ) - 1 ; i >= 0 ; i -- ) { if ( m [ str [ i ] ] == 0 ) { m [ str [ i ] ] = i ; } } i = 0 ; k = m [ str [ i ] ] ; for ( i = 0 ; i < str . length ( ) ; i ++ ) { if ( i <= k ) { c = c + 1 ; k = max ( k , m [ str [ i ] ] ) ; } else { r = r + 1 ; c = 1 ; k = max ( k , m [ str [ i ] ] ) ; } } if ( c != 0 ) { r = r + 1 ; } return r ; } int main ( ) { string str = " ababcbacadefegdehijhklij " ; cout << maximum_partition ( str ) ; }
Minimize steps required to move all 1 's in a matrix to a given index | C ++ program to calculate the minimum steps required to reach a given cell from all cells consisting of 1 's ; Function to calculate and return the minimum number of steps required to move all 1 s to ( X , Y ) ; Iterate the given matrix ; Update the answer with minimum moves required for the given element to reach the given index ; Return the number of steps ; Driver Code ; Given matrix ; Given position ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findAns ( vector < vector < int > > mat , int x , int y , int n , int m ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( mat [ i ] [ j ] == 1 ) { ans += abs ( x - i ) + abs ( y - j ) ; } } } return ans ; } int main ( ) { vector < vector < int > > mat = { { 1 , 0 , 0 , 0 } , { 0 , 1 , 0 , 1 } , { 1 , 0 , 1 , 1 } } ; int x = 0 , y = 2 ; cout << findAns ( mat , x , y , mat . size ( ) , mat [ 0 ] . size ( ) ) << endl ; return 0 ; }
Count of all possible reverse bitonic subarrays | C ++ program for the above approach ; Function that counts all the reverse bitonic subarray in arr [ ] ; To store the count of reverse bitonic subarray ; Iterate the array and select the starting element ; Iterate for selecting the ending element for subarray ; Subarray arr [ i to j ] ; For 1 length , increment the count and continue ; For Decreasing Subarray ; Check if only Decreasing ; For Increasing Subarray ; Print the total count of subarrays ; Driver Code ; Given array arr [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countReversebitonic ( int arr [ ] , int n ) { int c = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { int temp = arr [ i ] , f = 0 ; if ( j == i ) { c ++ ; continue ; } int k = i + 1 ; while ( temp > arr [ k ] && k <= j ) { temp = arr [ k ] ; k ++ ; } if ( k > j ) { c ++ ; f = 2 ; } while ( temp < arr [ k ] && k <= j && f != 2 ) { temp = arr [ k ] ; k ++ ; } if ( k > j && f != 2 ) { c ++ ; f = 0 ; } } } cout << c << endl ; } int main ( ) { int arr [ ] = { 2 , 3 , 1 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countReversebitonic ( arr , N ) ; }
Longest increasing sequence by the boundary elements of an Array | C ++ Program to print the longest increasing subsequence from the boundary elements of an array ; Function to return the length of Longest Increasing subsequence ; Set pointers at both ends ; Stores the recent value added to the subsequence ; Stores the length of the subsequence ; Check if both elements can be added to the subsequence ; Check if the element on the left can be added to the subsequence only ; Check if the element on the right can be added to the subsequence only ; If none of the values can be added to the subsequence ; Driver Code ; Length of array
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longestSequence ( int n , int arr [ ] ) { int l = 0 , r = n - 1 ; int prev = INT_MIN ; int ans = 0 ; while ( l <= r ) { if ( arr [ l ] > prev && arr [ r ] > prev ) { if ( arr [ l ] < arr [ r ] ) { ans += 1 ; prev = arr [ l ] ; l += 1 ; } else { ans += 1 ; prev = arr [ r ] ; r -= 1 ; } } else if ( arr [ l ] > prev ) { ans += 1 ; prev = arr [ l ] ; l += 1 ; } else if ( arr [ r ] > prev ) { ans += 1 ; prev = arr [ r ] ; r -= 1 ; } else { break ; } } return ans ; } int main ( ) { int arr [ ] = { 3 , 5 , 1 , 4 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << longestSequence ( n , arr ) ; return 0 ; }
Total number of cells covered in a matrix after D days | C ++ implementation to find the Total number of cells covered in a matrix after D days ; Function to return the total infected cells after d days ; Top extension ; Bottom extension ; Left extension ; Right extension ; Calculating the cells in each quadrilateral ; Sum all of them to get total cells in each quadrilateral ; Add the singleblocks along the lines of top , down , left , right ; Return the ans ; Driver code ; Dimensions of cell ; Starting Coordinates ; Number of Days ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( int n , int m , int x , int y , int d ) { int top = min ( d , x - 1 ) ; int down = min ( d , n - x ) ; int left = min ( d , y - 1 ) ; int right = min ( d , m - y ) ; int quad1 = top * left ; int quad2 = left * down ; int quad3 = down * right ; int quad4 = right * top ; int totalsq = quad1 + quad2 + quad3 + quad4 ; int singleBlocks = top + down + left + right + 1 ; return totalsq + singleBlocks ; } int main ( ) { int n , m , x , y , d ; n = 10 , m = 10 ; x = 7 , y = 8 ; d = 4 ; d -- ; cout << solve ( n , m , x , y , d ) ; }
Smallest subsequence with sum of absolute difference of consecutive elements maximized | C ++ program to find smallest subsequence with sum of absolute difference of consecutive elements maximized ; Function to print the smallest subsequence and its sum ; Final subsequence ; First element is a default endpoint ; Iterating through the array ; Check for monotonically increasing endpoint ; Check for monotonically decreasing endpoint ; Last element is a default endpoint ; Length of final subsequence ; Print the subsequence ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void getSubsequence ( vector < int > & arr , int n ) { vector < int > req ; req . push_back ( arr [ 0 ] ) ; for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( arr [ i ] > arr [ i + 1 ] && arr [ i ] > arr [ i - 1 ] ) req . push_back ( arr [ i ] ) ; else if ( arr [ i ] < arr [ i + 1 ] && arr [ i ] < arr [ i - 1 ] ) req . push_back ( arr [ i ] ) ; } req . push_back ( arr [ n - 1 ] ) ; cout << req . size ( ) << endl ; for ( auto x : req ) cout << x << " ▁ " ; } int main ( ) { vector < int > arr = { 1 , 2 , 5 , 3 , 6 , 7 , 4 } ; int n = arr . size ( ) ; getSubsequence ( arr , n ) ; return 0 ; }
Minimum steps to convert all paths in matrix from top left to bottom right as palindromic paths | C ++ implementation to find the minimum number of changes required such that every path from top left to the bottom right are palindromic paths ; Function to find the minimum number of the changes required for the every path to be palindromic ; count variable for maintaining total changes . ; left and right variables for keeping distance values from cell ( 0 , 0 ) and ( N - 1 , M - 1 ) respectively . ; Iterating over the matrix ; Finding minimum number of changes required . ; Minimum no . of changes will be the the minimum no . of different values and we will assume to make them equals to value with maximum frequency element ; Moving ahead with greater distance ; Drive Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define M 3 NEW_LINE #define N 3 NEW_LINE int minchanges ( int mat [ N ] [ M ] ) { int count = 0 ; int left = 0 , right = N + M - 2 ; while ( left < right ) { unordered_map < int , int > mp ; int totalsize = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( i + j == left ) { mp [ mat [ i ] [ j ] ] ++ ; totalsize ++ ; } else if ( i + j == right ) { mp [ mat [ i ] [ j ] ] ++ ; totalsize ++ ; } } } unordered_map < int , int > :: iterator itr = mp . begin ( ) ; int changes = 0 ; for ( ; itr != mp . end ( ) ; itr ++ ) changes = max ( changes , itr -> second ) ; count += totalsize - changes ; left ++ ; right -- ; } return count ; } int main ( ) { int mat [ ] [ M ] = { { 1 , 4 , 1 } , { 2 , 5 , 3 } , { 1 , 3 , 1 } } ; cout << minchanges ( mat ) ; return 0 ; }
Count of longest possible subarrays with sum not divisible by K | C ++ program for the above problem ; Function to find the count of longest subarrays with sum not divisible by K ; Sum of all elements in an array ; If overall sum is not divisible then return 1 , as only one subarray of size n is possible ; Index of the first number not divisible by K ; Index of the last number not divisible by K ; Subarray doesn 't exist ; Sum of the window ; Calculate the sum of rest of the windows of size len ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int CountLongestSubarrays ( int arr [ ] , int n , int k ) { int i , s = 0 ; for ( i = 0 ; i < n ; ++ i ) { s += arr [ i ] ; } if ( s % k ) { return 1 ; } else { int ini = 0 ; while ( ini < n && arr [ ini ] % k == 0 ) { ++ ini ; } int final = n - 1 ; while ( final >= 0 && arr [ final ] % k == 0 ) { -- final ; } int len , sum = 0 , count = 0 ; if ( ini == n ) { return -1 ; } else { len = max ( n - 1 - ini , final ) ; } for ( i = 0 ; i < len ; i ++ ) { sum += arr [ i ] ; } if ( sum % k != 0 ) { count ++ ; } for ( i = len ; i < n ; i ++ ) { sum = sum + arr [ i ] ; sum = sum - arr [ i - len ] ; if ( sum % k != 0 ) { count ++ ; } } return count ; } } int main ( ) { int arr [ ] = { 3 , 2 , 2 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; cout << CountLongestSubarrays ( arr , n , k ) ; return 0 ; }
Count of triplets in a given Array having GCD K | C ++ program to count the number of triplets in the array with GCD equal to K ; frequency array ; mul [ i ] stores the count of multiples of i ; cnt [ i ] stores the count of triplets with gcd = i ; Return nC3 ; Function to count and return the number of triplets in the array with GCD equal to K ; Store frequency of array elements ; Store the multiples of i present in the array ; Count triplets with gcd equal to any multiple of i ; Remove all triplets which have gcd equal to a multiple of i ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAXN = 1e6 + 1 ; int freq [ MAXN ] = { 0 } ; int mul [ MAXN ] = { 0 } ; int cnt [ MAXN ] = { 0 } ; int nC3 ( int n ) { if ( n < 3 ) return 0 ; return ( n * ( n - 1 ) * ( n - 2 ) ) / 6 ; } void count_triplet ( vector < int > arr , int N , int K ) { for ( int i = 0 ; i < N ; i ++ ) { freq [ arr [ i ] ] ++ ; } for ( int i = 1 ; i <= 1000000 ; i ++ ) { for ( int j = i ; j <= 1000000 ; j += i ) { mul [ i ] += freq [ j ] ; } cnt [ i ] = nC3 ( mul [ i ] ) ; } for ( int i = 1000000 ; i >= 1 ; i -- ) { for ( int j = 2 * i ; j <= 1000000 ; j += i ) { cnt [ i ] -= cnt [ j ] ; } } cout << " Number ▁ of ▁ triplets ▁ " << " with ▁ GCD ▁ " << K ; cout << " ▁ are ▁ " << cnt [ K ] ; } int main ( ) { vector < int > arr = { 1 , 7 , 12 , 6 , 15 , 9 } ; int N = 6 , K = 3 ; count_triplet ( arr , N , K ) ; return 0 ; }
Check if a subsequence of length K with odd sum exists | C ++ program to check if a subsequence of length K with odd sum exists in the given array ; Function to check if any required subsequence exists or not ; Store count of odd and even elements in the array ; Calculate the count of odd and even elements ; If no odd elements exists or no even elements exists when K is even ; Subsequence is not possible ; Possible otherwise ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isSubseqPossible ( int arr [ ] , int N , int K ) { int i ; int odd = 0 , even = 0 ; for ( i = 0 ; i < N ; i ++ ) { if ( arr [ i ] % 2 == 1 ) odd ++ ; else even ++ ; } if ( odd == 0 || ( even == 0 && K % 2 == 0 ) ) return false ; return true ; } int main ( ) { int arr [ ] = { 2 , 3 , 5 , 7 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; cout << ( isSubseqPossible ( arr , N , K ) ? " Yes " : " No " ) ; return 0 ; }
Path traversed using exactly M coins in K jumps | C ++ program to print the path using exactly K jumps and M coins ; Function that print the path using exactly K jumps and M coins ; If no path exists ; It decides which box to be jump ; It decides whether to jump on left side or to jump on right side ; Print the path ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void print_path ( int N , int jump , int coin ) { if ( jump > coin || jump * ( N - 1 ) < coin ) { cout << " - 1" << endl ; } else { int pos = 1 ; while ( jump > 0 ) { int tmp = min ( N - 1 , coin - ( jump - 1 ) ) ; if ( pos + tmp <= N ) { pos += tmp ; } else { pos -= tmp ; } cout << pos << " ▁ " ; coin -= tmp ; jump -= 1 ; } } } int main ( ) { int N = 5 , K = 4 , M = 12 ; print_path ( N , K , M ) ; return 0 ; }
Minimum salary hike for each employee such that no employee feels unfair | C ++ program for the above approach ; Function that print minimum hike ; Insert INF at begin and end of array ; To store hike of each employee ; for Type 1 employee ; for Type 2 employee ; for Type 3 employee ; for Type 4 employee ; Print the min hike for each employee ; Driver Code ; Given array of rating of employees ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define INF 1e9 NEW_LINE void findMinHike ( vector < int > arr , int n ) { arr . insert ( arr . begin ( ) , INF ) ; arr . push_back ( INF ) ; vector < int > hike ( n + 2 , 0 ) ; for ( int i = 1 ; i <= n ; i ++ ) { if ( arr [ i - 1 ] >= arr [ i ] && arr [ i ] <= arr [ i + 1 ] ) { hike [ i ] = 1 ; } } for ( int i = 1 ; i <= n ; i ++ ) { if ( arr [ i - 1 ] < arr [ i ] && arr [ i ] <= arr [ i + 1 ] ) { hike [ i ] = hike [ i - 1 ] + 1 ; } } for ( int i = 1 ; i <= n ; i ++ ) { if ( arr [ i - 1 ] >= arr [ i ] && arr [ i ] > arr [ i + 1 ] ) { hike [ i ] = hike [ i + 1 ] + 1 ; } } for ( int i = 1 ; i <= n ; i ++ ) { if ( arr [ i - 1 ] < arr [ i ] && arr [ i ] > arr [ i + 1 ] ) { hike [ i ] = max ( hike [ i - 1 ] , hike [ i + 1 ] ) + 1 ; } } for ( int i = 1 ; i <= n ; i ++ ) { cout << hike [ i ] << " ▁ " ; } } int main ( ) { vector < int > arr = { 5 , 3 , 4 , 2 , 1 , 6 } ; findMinHike ( arr , arr . size ( ) ) ; return 0 ; }
Minimize the cost to make all the adjacent elements distinct in an Array | C ++ program to find the minimum cost required to make all adjacent elements distinct ; Function that prints minimum cost required ; Dp - table ; Base case Not increasing the first element ; Increasing the first element by 1 ; Increasing the first element by 2 ; Condition if current element is not equal to previous non - increased element ; Condition if current element is not equal to previous element after being increased by 1 ; Condition if current element is not equal to previous element after being increased by 2 ; Take the minimum from all cases ; Finding the minimum cost ; Printing the minimum cost required to make all adjacent elements distinct ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumCost ( int arr [ ] , int cost [ ] , int N ) { vector < vector < int > > dp ( N , vector < int > ( 3 ) ) ; dp [ 0 ] [ 0 ] = 0 ; dp [ 0 ] [ 1 ] = cost [ 0 ] ; dp [ 0 ] [ 2 ] = cost [ 0 ] * 2 ; for ( int i = 1 ; i < N ; i ++ ) { for ( int j = 0 ; j < 3 ; j ++ ) { int minimum = 1e6 ; if ( j + arr [ i ] != arr [ i - 1 ] ) minimum = min ( minimum , dp [ i - 1 ] [ 0 ] ) ; if ( j + arr [ i ] != arr [ i - 1 ] + 1 ) minimum = min ( minimum , dp [ i - 1 ] [ 1 ] ) ; if ( j + arr [ i ] != arr [ i - 1 ] + 2 ) minimum = min ( minimum , dp [ i - 1 ] [ 2 ] ) ; dp [ i ] [ j ] = j * cost [ i ] + minimum ; } } int ans = 1e6 ; for ( int i = 0 ; i < 3 ; i ++ ) ans = min ( ans , dp [ N - 1 ] [ i ] ) ; cout << ans << " STRNEWLINE " ; } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 2 , 3 , 4 } ; int cost [ ] = { 3 , 2 , 5 , 4 , 2 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minimumCost ( arr , cost , N ) ; return 0 ; }
Subarray with largest sum after excluding its maximum element | C ++ implementation to find the maximum sum subarray such by excluding the maximum element from the subarray ; Function to find the maximum sum subarray by excluding the maximum element from the array ; Loop to store all the positive elements in the map ; Loop to iterating over the map and considering as the maximum element of the current including subarray ; Make the current element maximum ; Iterate through array and apply kadane 's algorithm ; Condition if current element is greater than mx then make the element - infinity ; Store the indices in some variable ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maximumSumSubarray ( int arr [ ] , int n ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] >= 0 && mp . find ( arr [ i ] ) == mp . end ( ) ) mp [ arr [ i ] ] = 1 ; } int first = 0 ; int last = 0 ; int ans = 0 ; int INF = 1e6 ; for ( auto i : mp ) { int mx = i . first ; int curr = 0 ; int curr_start ; for ( int j = 0 ; j < n ; j ++ ) { if ( curr == 0 ) curr_start = j ; int val = arr [ j ] > mx ? - INF : arr [ j ] ; curr += val ; if ( curr < 0 ) curr = 0 ; if ( curr > ans ) { ans = curr ; first = curr_start ; last = j ; } } } cout << first + 1 << " ▁ " << last + 1 ; } int main ( ) { int arr [ ] = { 5 , -2 , 10 , -1 , 4 } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maximumSumSubarray ( arr , size ) ; return 0 ; }
Extended Knapsack Problem | C ++ code for the extended Knapsack Approach ; To store the dp values ; for each element given ; For each possible weight value ; For each case where the total elements are less than the constraint ; To ensure that we dont go out of the array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 100 ] [ 100 ] [ 100 ] ; int maxProfit ( int profit [ ] , int weight [ ] , int n , int max_W , int max_E ) { for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= max_W ; j ++ ) { for ( int k = 1 ; k <= max_E ; k ++ ) { if ( j >= weight [ i - 1 ] ) { dp [ i ] [ j ] [ k ] = max ( dp [ i - 1 ] [ j ] [ k ] , dp [ i - 1 ] [ j - weight [ i - 1 ] ] [ k - 1 ] + profit [ i - 1 ] ) ; } else { dp [ i ] [ j ] [ k ] = dp [ i - 1 ] [ j ] [ k ] ; } } } } return dp [ n ] [ max_W ] [ max_E ] ; } int main ( ) { memset ( dp , 0 , sizeof ( dp ) ) ; int n = 5 ; int profit [ ] = { 2 , 7 , 1 , 5 , 3 } ; int weight [ ] = { 2 , 5 , 2 , 3 , 4 } ; int max_weight = 8 ; int max_element = 2 ; cout << maxProfit ( profit , weight , n , max_weight , max_element ) << " STRNEWLINE " ; return 0 ; }
Shortest Path with even number of Edges from Source to Destination | C ++ program for the above approach ; Adjacency List : to represent graph ; Distance Array : to store shortest distance to every node ; returns value which will represent even_x ; returns value which will represent odd_x ; converting edge ( a -> b ) to 2 different edges i . e . ( a -> b ) converts to ( 1 ) . even_a -> odd_b ( 2 ) . odd_a -> even_b since , graph is undirected , so we push them in reverse order too hence , 4 push_back operations are there . ; Function calculates shortest distance to all nodes from " source " using Dijkstra Shortest Path Algorithm and returns shortest distance to " destination " ; Priority Queue / min - heap to store and process ( distance , node ) ; pushing source node to priority queue and dist from source to source is set to 0 ; U is the node at top of the priority queue note that pq . top ( ) . first refers to the Distance and pq . top ( ) . second will refer to the Node ; exploring all neighbours of node u ; v is neighbour node of u and c is the cost / weight of edge ( u , v ) ; relaxation : checking if there is a shorter path to v via u ; updating distance of v ; returning shortest distance to " destination " ; Driver function ; n = number of Nodes , m = number of Edges ; if ans is INF : There is no even length path from source to destination else path exists and we print the shortest distance
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAXX = 10000 , INF = 1e9 ; vector < vector < pair < int , int > > > adj ( MAXX * 10 + 3 ) ; vector < int > dist ( MAXX * 10 + 3 , INF ) ; int even ( int x ) { return x * 10 + 2 ; } int odd ( int x ) { return x * 10 + 1 ; } void addEdge ( int a , int b , int cost ) { adj [ even ( a ) ] . push_back ( { odd ( b ) , cost } ) ; adj [ odd ( a ) ] . push_back ( { even ( b ) , cost } ) ; adj [ odd ( b ) ] . push_back ( { even ( a ) , cost } ) ; adj [ even ( b ) ] . push_back ( { odd ( a ) , cost } ) ; } int dijkstra ( int source , int destination ) { priority_queue < pair < int , int > , vector < pair < int , int > > , greater < pair < int , int > > > pq ; pq . push ( { 0 , even ( source ) } ) ; dist [ even ( source ) ] = 0 ; while ( ! pq . empty ( ) ) { int u = pq . top ( ) . second ; pq . pop ( ) ; for ( pair < int , int > p : adj [ u ] ) { int v = p . first ; int c = p . second ; if ( dist [ u ] + c < dist [ v ] ) { dist [ v ] = dist [ u ] + c ; pq . push ( { dist [ v ] , v } ) ; } } } return dist [ even ( destination ) ] ; } int main ( ) { int n = 5 , m = 6 ; addEdge ( 1 , 2 , 1 ) ; addEdge ( 2 , 3 , 2 ) ; addEdge ( 2 , 5 , 15 ) ; addEdge ( 3 , 5 , 1 ) ; addEdge ( 3 , 4 , 4 ) ; addEdge ( 5 , 4 , 3 ) ; int source = 1 ; int destination = n ; int ans = dijkstra ( source , destination ) ; if ( ans == INF ) cout << " - 1" << " STRNEWLINE " ; else cout << ans << " STRNEWLINE " ; return 0 ; }
Minimum insertions to make XOR of an Array equal to half of its sum | C ++ Program to make XOR of of all array elements equal to half of its sum by minimum insertions ; Function to make XOR of the array equal to half of its sum ; Calculate the sum and Xor of all the elements ; If the required condition satisfies already , return the original array ; If Xor is already zero , Insert sum ; Otherwise , insert xr and insert sum + xr ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int make_xor_half ( vector < int > & arr ) { int sum = 0 , xr = 0 ; for ( int a : arr ) { sum += a ; xr ^= a ; } if ( 2 * xr == sum ) return -1 ; if ( xr == 0 ) { arr . push_back ( sum ) ; return 1 ; } arr . push_back ( xr ) ; arr . push_back ( sum + xr ) ; return 2 ; } int main ( ) { int N = 7 ; vector < int > nums = { 3 , 4 , 7 , 1 , 2 , 5 , 6 } ; int count = make_xor_half ( nums ) ; if ( count == -1 ) cout << " - 1" << endl ; else if ( count == 1 ) cout << nums [ N ] << endl ; else cout << nums [ N ] << " ▁ " << nums [ N + 1 ] << endl ; return 0 ; }
Count number of triangles possible for the given sides range | C ++ implementation to count the number of possible triangles for the given sides ranges ; Function to count the number of possible triangles for the given sides ranges ; Iterate for every possible of x ; Range of y is [ b , c ] From this range First we will find the number of x + y greater than d ; For x + y greater than d we can choose all z from [ c , d ] Total permutation will be ; Now we will find the number of x + y in between the [ c , d ] ; [ l , r ] will be the range from total [ c , d ] x + y belongs For any r such that r = x + y We can choose z , in the range [ c , d ] only less than r , Thus total permutation be ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count_triangles ( int a , int b , int c , int d ) { int ans = 0 ; for ( int x = a ; x <= b ; ++ x ) { int num_greater_than_d = max ( d , c + x ) - max ( d , b + x - 1 ) ; ans += num_greater_than_d * ( d - c + 1 ) ; int r = min ( max ( c , c + x ) , d ) - c ; int l = min ( max ( c , b + x - 1 ) , d ) - c ; int x1 = ( r * ( r + 1 ) ) / 2 ; int x2 = ( l * ( l + 1 ) ) / 2 ; ans += x1 - x2 ; } return ans ; } int main ( ) { int a = 2 , b = 3 , c = 4 , d = 5 ; cout << count_triangles ( a , b , c , d ) << endl ; return 0 ; }
Minimum number of swaps required to make the string K periodic | C ++ code to find the minimum number of swaps required to make the string K periodic ; Mark all allowed characters as true ; Initialize the freq array to 0 ; Increase the frequency of each character ; Total number of periods of size K in the string ; Check if the current character is present in allowed and whether the current frequency is greater than all previous frequencies for this position ; update the answer by subtracting the maxfrequency from total positions if there exist extra character at the end of the string apart from the n / k characters then add 1. ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minFlip ( string s , int n , int k , char a [ ] , int p ) { bool allowed [ 26 ] = { 0 } ; for ( int i = 0 ; i < p ; i ++ ) { allowed [ a [ i ] - ' a ' ] = true ; } char freq [ k ] [ 26 ] ; for ( int i = 0 ; i < k ; i ++ ) for ( int j = 0 ; j < 26 ; j ++ ) freq [ i ] [ j ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) { freq [ i % k ] [ s [ i ] - ' a ' ] += 1 ; } int ans = 0 ; int totalpositions = n / k ; for ( int i = 0 ; i < k ; i ++ ) { int maxfrequency = 0 ; for ( int j = 0 ; j < 26 ; j ++ ) { if ( freq [ i ] [ j ] > maxfrequency and allowed [ j ] == true ) maxfrequency = freq [ i ] [ j ] ; } ans += ( totalpositions - maxfrequency + ( ( i % k < n % k ) ? 1 : 0 ) ) ; } cout << ans << endl ; } int main ( ) { string S = " nihsiakyt " ; int n = S . length ( ) ; int K = 3 ; char A [ 5 ] = { ' n ' , ' i ' , ' p ' , ' s ' , ' q ' } ; int p = sizeof ( A ) / sizeof ( A [ 0 ] ) ; minFlip ( S , n , K , A , p ) ; return 0 ; }
Minimum number of colors required to color a Circular Array | C ++ implementation of above approach ; Function that finds minimum number of colors required ; To check that if all the elements are same or not ; To check if only one adjacent exist ; Traverse the array ; If adjacent elements found different means all are not same ; If two adjacent elements found to be same then make one_adjacent_same true ; If all elements are same then print 1 ; If total number of elements are even or there exist two adjacent elements that are same then print 2 ; Else 3 type of colors are required ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void colorRequired ( int arr [ ] , int n ) { bool all_same = true ; bool one_adjacent_same = false ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( arr [ i ] != arr [ i + 1 ] ) { all_same = false ; } if ( arr [ i ] == arr [ i + 1 ] ) { one_adjacent_same = true ; } } if ( all_same == true ) { cout << 1 << endl ; return ; } if ( n % 2 == 0 one_adjacent_same == true ) { cout << 2 << endl ; return ; } cout << 3 << endl ; } int main ( ) { int arr [ ] = { 1 , 2 , 1 , 1 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; colorRequired ( arr , n ) ; return 0 ; }
Maximize the sum of sum of the Array by removing end elements | C ++ program to maximize the sum of sum of the Array by removing end elements ; Function to find the maximum sum of sum ; compute the sum of whole array ; Traverse and remove the minimum value from an end to maximum the sum value ; If the left end element is smaller than right end ; remove the left end element ; If the right end element is smaller than left end ; remove the right end element ; Add the remaining element sum in the result ; Return the maximum sum of sum ; Driver code
#include <iostream> NEW_LINE using namespace std ; int maxRemainingSum ( int arr [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; int i = 0 ; int j = n - 1 ; int result = 0 ; while ( i < j ) { if ( arr [ i ] < arr [ j ] ) { sum -= arr [ i ] ; i ++ ; } else { sum -= arr [ j ] ; j -- ; } result += sum ; } return result ; } int main ( ) { int arr [ ] = { 3 , 1 , 7 , 2 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxRemainingSum ( arr , N ) ; return 0 ; }
Split a number as sum of K numbers which are not divisible by K | C ++ program to split a number as sum of K numbers which are not divisible by K ; Function to split into K parts and print them ; Print 1 K - 1 times ; Print N - K + 1 ; Print 1 K - 2 times ; Print 2 and N - K ; Driver code
#include <iostream> NEW_LINE using namespace std ; void printKParts ( int N , int K ) { if ( N % K == 0 ) { for ( int i = 1 ; i < K ; i ++ ) cout << "1 , ▁ " ; cout << N - ( K - 1 ) << endl ; } else { if ( K == 2 ) { cout << " Not ▁ Possible " << endl ; return ; } for ( int i = 1 ; i < K - 1 ; i ++ ) cout << 1 << " , ▁ " ; cout << 2 << " , ▁ " << N - K << endl ; } } int main ( ) { int N = 18 , K = 5 ; printKParts ( N , K ) ; return 0 ; }
Make the intervals non | C ++ implementation for intervals scheduling to two processors such that there are no overlapping intervals ; Function to assign the intervals to two different processors ; Loop to pair the interval with their indices ; sorting the interval by their start times ; Loop to iterate over the intervals with their start time ; Condition to check if there is a possible solution ; form = ''.join(form) ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void assignIntervals ( vector < vector < int > > interval , int n ) { for ( int i = 0 ; i < n ; i ++ ) interval [ i ] . push_back ( i ) ; sort ( interval . begin ( ) , interval . end ( ) ) ; int firstEndTime = -1 ; int secondEndTime = -1 ; char fin = ' ▁ ' ; bool flag = false ; for ( int i = 0 ; i < n ; i ++ ) { if ( interval [ i ] [ 0 ] >= firstEndTime ) { firstEndTime = interval [ i ] [ 1 ] ; interval [ i ] . push_back ( ' S ' ) ; } else if ( interval [ i ] [ 0 ] >= secondEndTime ) { secondEndTime = interval [ i ] [ 1 ] ; interval [ i ] . push_back ( ' F ' ) ; } else { flag = true ; break ; } } if ( flag ) cout << ( -1 ) ; else { vector < char > form ( n , ' ▁ ' ) ; for ( int i = 0 ; i < n ; i ++ ) { int indi = interval [ i ] [ 2 ] ; form [ indi ] = interval [ i ] [ 3 ] ; } for ( int i = 0 ; i < form . size ( ) ; i ++ ) cout << form [ i ] << " , " ; } } int main ( ) { vector < vector < int > > intervals = { { 360 , 480 } , { 420 , 540 } , { 600 , 660 } } ; assignIntervals ( intervals , intervals . size ( ) ) ; return 0 ; }
Minimum operation required to make a balanced sequence | C ++ implementation of the approach ; Function to return the minimum operations required ; Condition where we got only one closing bracket instead of 2 , here we have to add one more closing bracket to make the sequence balanced ; Add closing bracket that costs us one operation ; Remove the top opening bracket because we got the 1 opening and 2 continuous closing brackets ; Inserting the opening bracket to stack ; After making the sequence balanced closing is now set to 0 ; Case when there is no opening bracket the sequence starts with a closing bracket and one opening bracket is required Now we have one opening and one closing bracket ; Add opening bracket that costs us one operation ; Assigning 1 to cntClosing because we have one closing bracket ; Case where we got two continuous closing brackets Need to pop one opening bracket from stack top ; Condition where stack is not empty This is the case where we have only opening brackets ( st . size ( ) * 2 ) will give us the total closing bracket needed cntClosing is the count of closing bracket that we already have ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperations ( string s , int len ) { int operationCnt = 0 ; stack < char > st ; int cntClosing = 0 ; for ( int i = 0 ; i < len ; i ++ ) { if ( s [ i ] == ' { ' ) { if ( cntClosing > 0 ) { operationCnt ++ ; st . pop ( ) ; } st . push ( s [ i ] ) ; cntClosing = 0 ; } else if ( st . empty ( ) ) { st . push ( ' { ' ) ; operationCnt ++ ; cntClosing = 1 ; } else { cntClosing = ( cntClosing + 1 ) % 2 ; if ( cntClosing == 0 ) { st . pop ( ) ; } } } operationCnt += st . size ( ) * 2 - cntClosing ; return operationCnt ; } int main ( ) { string str = " } } { " ; int len = str . length ( ) ; cout << minOperations ( str , len ) ; return 0 ; }
Longest subsequence with different adjacent characters | C ++ program for the above approach ; Function to find the longest Subsequence with different adjacent character ; Length of the string s ; Previously picked character ; If the current character is different from the previous then include this character and update previous character ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longestSubsequence ( string s ) { int n = s . length ( ) ; int answer = 0 ; char prev = ' - ' ; for ( int i = 0 ; i < n ; i ++ ) { if ( prev != s [ i ] ) { prev = s [ i ] ; answer ++ ; } } return answer ; } int main ( ) { string str = " ababa " ; cout << longestSubsequence ( str ) ; return 0 ; }
Length of longest subarray of length at least 2 with maximum GCD | C ++ program for the above approach ; Function to calculate GCD of two numbers ; Function to find maximum size subarray having maximum GCD ; Base Case ; Let the maximum GCD be 1 initially ; Loop thourgh array to find maximum GCD of subarray with size 2 ; Traverse the array ; Is a multiple of k , increase cnt ; Else update maximum length with consecutive element divisible by k Set cnt to 0 ; Update the maxLength ; Return the maxLength ; Driver Code ; Function Call
#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 maximumGcdSubarray ( int arr [ ] , int n ) { if ( n == 1 ) return 0 ; int k = 1 ; for ( int i = 1 ; i < n ; ++ i ) { k = max ( k , gcd ( arr [ i ] , arr [ i - 1 ] ) ) ; } int cnt = 0 ; int maxLength = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % k == 0 ) { cnt ++ ; } else { maxLength = max ( maxLength , cnt ) ; cnt = 0 ; } } maxLength = max ( maxLength , cnt ) ; return maxLength ; } int main ( ) { int arr [ ] = { 18 , 3 , 6 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maximumGcdSubarray ( arr , n ) ; return 0 ; }
Split N powers of 2 into two subsets such that their difference of sum is minimum | C ++ program to find the minimum difference possible by splitting all powers of 2 up to N into two sets of equal size ; Store the largest ; Form two separate groups ; Initialize the sum for two groups as 0 ; Insert 2 ^ n in the first group ; Calculate the sum of least n / 2 - 1 elements added to the first set ; Sum of remaining n / 2 - 1 elements ; Min Difference between the two groups ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void MinDiff ( int n ) { int val = pow ( 2 , n ) ; int sep = n / 2 ; int grp1 = 0 ; int grp2 = 0 ; grp1 = grp1 + val ; for ( int i = 1 ; i < sep ; i ++ ) grp1 = grp1 + pow ( 2 , i ) ; for ( int i = sep ; i < n ; i ++ ) grp2 = grp2 + pow ( 2 , i ) ; cout << ( abs ( grp1 - grp2 ) ) ; } int main ( ) { int n = 4 ; MinDiff ( n ) ; }
Count elements in first Array with absolute difference greater than K with an element in second Array | C ++ program to count elements in first Array with absolute difference greater than K with an element in second Array ; Function to count the such elements ; Store count of required elements in arr1 ; Initialise the smallest and the largest value from the second array arr2 [ ] ; Find the smallest and the largest element in arr2 ; Check if absolute difference of smallest and arr1 [ i ] or largest and arr1 [ i ] is > K then arr [ i ] is a required element ; Print the final result ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countDist ( int arr1 [ ] , int n , int arr2 [ ] , int m , int k ) { int count = 0 ; int smallest = arr2 [ 0 ] ; int largest = arr2 [ 0 ] ; for ( int i = 0 ; i < m ; i ++ ) { smallest = max ( smallest , arr2 [ i ] ) ; largest = min ( largest , arr1 [ i ] ) ; } for ( int i = 0 ; i < n ; i ++ ) { if ( abs ( arr1 [ i ] - smallest ) > k || abs ( arr1 [ i ] - largest ) > k ) count ++ ; } cout << count ; } int main ( ) { int arr1 [ ] = { 3 , 1 , 4 } ; int n = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int arr2 [ ] = { 5 , 1 , 2 } ; int m = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; int k = 2 ; countDist ( arr1 , n , arr2 , m , k ) ; return 0 ; }
Make sum of all subarrays of length K equal by only inserting elements | C ++ implementation of above approach ; Function that prints another array whose all subarray of length k have an equal sum ; Store all distinct elements in the unordered map ; Condition if the number of distinct elements is greater than k ; Push all distinct elements in a vector ; Push 1 while the size of vector not equal to k ; Print the vector 2 times ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void MakeArray ( int a [ ] , int n , int k ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp . find ( a [ i ] ) == mp . end ( ) ) mp [ a [ i ] ] = 1 ; } if ( mp . size ( ) > k ) { cout << " Not ▁ possible STRNEWLINE " ; return ; } vector < int > ans ; for ( auto i : mp ) { ans . push_back ( i . first ) ; } while ( ans . size ( ) < k ) { ans . push_back ( 1 ) ; } for ( int i = 0 ; i < 2 ; i ++ ) { for ( int j = 0 ; j < k ; j ++ ) cout << ans [ j ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 1 , 2 , 2 , 1 } ; int K = 2 ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; MakeArray ( arr , size , K ) ; return 0 ; }
Longest substring with atmost K characters from the given set of characters | C ++ implementation to find the longest substring in the string which contains atmost K characters from the given set of characters ; Function to find the longest substring in the string which contains atmost K characters from the given set of characters ; Base Condition ; Count for Characters from set in substring ; Two pointers ; Loop to iterate until right pointer is not equal to N ; Loop to increase the substring length until the characters from set are at most K ; Check if current pointer points a character from set ; If the count of the char is exceeding the limit ; update answer with substring length ; Increment the left pointer until the count is less than or equal to K ; If the character which comes out is normal character then decrement the count by 1 ; Driver Code ; Construction of set ; output result
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxNormalSubstring ( string & P , set < char > Q , int K , int N ) { if ( K == 0 ) return 0 ; int count = 0 ; int left = 0 , right = 0 ; int ans = 0 ; while ( right < N ) { while ( right < N && count <= K ) { if ( Q . find ( P [ right ] ) != Q . end ( ) ) { if ( count + 1 > K ) break ; else count ++ ; } right ++ ; if ( count <= K ) ans = max ( ans , right - left ) ; } while ( left < right ) { left ++ ; if ( Q . find ( P [ left - 1 ] ) != Q . end ( ) ) count -- ; if ( count < K ) break ; } } return ans ; } int main ( ) { string P = " giraffe " ; set < char > Q ; Q . insert ( ' a ' ) ; Q . insert ( ' f ' ) ; Q . insert ( ' g ' ) ; Q . insert ( ' r ' ) ; int K = 2 ; int N = P . length ( ) ; cout << maxNormalSubstring ( P , Q , K , N ) ; return 0 ; }
Find the minimum value of the given expression over all pairs of the array | C ++ program to find the minimum value of the given expression over all pairs of the array ; Function to find the minimum value of the expression ; Iterate over all the pairs and find the minimum value ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MinimumValue ( int a [ ] , int n ) { int answer = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { answer = min ( answer , ( ( a [ i ] & a [ j ] ) ^ ( a [ i ] a [ j ] ) ) ) ; } } return answer ; } int main ( ) { int N = 6 ; int A [ N ] = { 12 , 3 , 14 , 5 , 9 , 8 } ; cout << MinimumValue ( A , N ) ; return 0 ; }
Number of substrings with length divisible by the number of 1 's in it | C ++ program to count number of substring under given condition ; Function return count of such substring ; Mark 1 at those indices where '1' appears ; Take prefix sum ; Iterate through all the substrings ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countOfSubstrings ( string s ) { int n = s . length ( ) ; int prefix_sum [ n ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == '1' ) prefix_sum [ i ] = 1 ; } for ( int i = 1 ; i < n ; i ++ ) prefix_sum [ i ] += prefix_sum [ i - 1 ] ; int answer = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { int countOfOnes = prefix_sum [ j ] - ( i - 1 >= 0 ? prefix_sum [ i - 1 ] : 0 ) ; int length = j - i + 1 ; if ( countOfOnes > 0 && length % countOfOnes == 0 ) answer ++ ; } } return answer ; } int main ( ) { string S = "1111100000" ; cout << countOfSubstrings ( S ) ; return 0 ; }
Find the number of elements X such that X + K also exists in the array | C ++ implementation of find number of elements x in this array such x + k also present in this array . ; Function to return the count of element x such that x + k also lies in this array ; Key in map will store elements and value will store the frequency of the elements ; Find if i . first + K is present in this map or not ; If we find i . first or key + K in this map then we have to increase in answer the frequency of this element ; Driver code ; array initialisation ; size of array ; initialise k
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count_element ( int N , int K , int * arr ) { map < int , int > mp ; for ( int i = 0 ; i < N ; ++ i ) mp [ arr [ i ] ] ++ ; int answer = 0 ; for ( auto i : mp ) { if ( mp . find ( i . first + K ) != mp . end ( ) ) answer += i . second ; } return answer ; } int main ( ) { int arr [ ] = { 3 , 6 , 2 , 8 , 7 , 6 , 5 , 9 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 2 ; cout << count_element ( N , K , arr ) ; return 0 ; }
Find the size of largest group where groups are according to the xor of digits | c ++ implementation to Find the size of largest group , where groups are according to the xor of its digits . ; Function to find out xor of digit ; calculate xor digitwise ; return xor ; Function to find the size of largest group ; hash map for counting frequency ; counting freq of each element ; find the maximum ; Driver code ; initialise N
#include <bits/stdc++.h> NEW_LINE using namespace std ; int digit_xor ( int x ) { int xorr = 0 ; while ( x ) { xorr ^= x % 10 ; x = x / 10 ; } return xorr ; } int find_count ( int n ) { map < int , int > mpp ; for ( int i = 1 ; i <= n ; i ++ ) { mpp [ digit_xor ( i ) ] += 1 ; } int maxm = 0 ; for ( auto x : mpp ) { if ( x . second > maxm ) maxm = x . second ; } return maxm ; } int main ( ) { int N = 13 ; cout << find_count ( N ) ; return 0 ; }
Count of largest sized groups while grouping according to product of digits | C ++ implementation to Count the groups having largest size while grouping is according to the product of its digits ; Function to find out product of digit ; calculate product ; return the product of digits ; Function to find the count ; hash map for counting frequency ; counting freq of each element ; find the maximum ; count the number of groups having size of equal to largest group . ; Driver code ; initialise N
#include <bits/stdc++.h> NEW_LINE using namespace std ; int digit_prod ( int x ) { int prod = 1 ; while ( x ) { prod *= x % 10 ; x = x / 10 ; } return prod ; } int find_count ( int n ) { map < int , int > mpp ; for ( int i = 1 ; i <= n ; i ++ ) { mpp [ digit_prod ( i ) ] += 1 ; } int ans = 1 ; int maxm = 0 ; for ( auto x : mpp ) { if ( x . second > maxm ) { maxm = x . second ; ans = 1 ; } else if ( x . second == maxm ) { ans ++ ; } } return ans ; } int main ( ) { int N = 13 ; cout << find_count ( N ) ; return 0 ; }
Count of subarrays having exactly K prime numbers | C ++ program for the above approach ; A utility function to check if the number n is prime or not ; Base Cases ; Check to skip middle five numbers in below loop ; If n is divisible by i & i + 2 then it is not prime ; Function to find number of subarrays with sum exactly equal to k ; STL map to store number of subarrays starting from index zero having particular value of sum . ; To store the sum of element traverse so far ; Add current element to currsum ; If currsum = K , then a new subarray is found ; If currsum > K then find the no . of subarrays with sum currsum - K and exclude those subarrays ; Add currsum to count of different values of sum ; Return the final result ; Function to count the subarray with K primes ; Update the array element ; If current element is prime then update the arr [ i ] to 1 ; Else change arr [ i ] to 0 ; Function Call ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int n ) { int i ; if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) { return false ; } for ( i = 5 ; i * i <= n ; i += 6 ) { if ( n % i == 0 || n % ( i + 2 ) == 0 ) { return false ; } } return true ; } int findSubarraySum ( int arr [ ] , int n , int K ) { unordered_map < int , int > prevSum ; int res = 0 ; int currsum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { currsum += arr [ i ] ; if ( currsum == K ) { res ++ ; } if ( prevSum . find ( currsum - K ) != prevSum . end ( ) ) res += ( prevSum [ currsum - K ] ) ; prevSum [ currsum ] ++ ; } return res ; } void countSubarray ( int arr [ ] , int n , int K ) { for ( int i = 0 ; i < n ; i ++ ) { if ( isPrime ( arr [ i ] ) ) { arr [ i ] = 1 ; } else { arr [ i ] = 0 ; } } cout << findSubarraySum ( arr , n , K ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int K = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countSubarray ( arr , N , K ) ; return 0 ; }
Count the elements having frequency equals to its value | C ++ program to count the elements having frequency equals to its value ; Function to find the count ; Hash map for counting frequency ; Counting freq of each element ; Check if value equals to frequency and increment the count ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find_maxm ( int arr [ ] , int n ) { map < int , int > mpp ; for ( int i = 0 ; i < n ; i ++ ) { mpp [ arr [ i ] ] += 1 ; } int ans = 0 ; for ( auto x : mpp ) { int value = x . first ; int freq = x . second ; if ( value == freq ) { ans ++ ; } } return ans ; } int main ( ) { int arr [ ] = { 3 , 2 , 2 , 3 , 4 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << find_maxm ( arr , n ) ; return 0 ; }
Find the Number of Permutations that satisfy the given condition in an array | C ++ program to find the number of permutations that satisfy the given condition in an array ; Function to calculate x ^ y recursively ; Function to return the number of permutations that satisfy the given condition in an array ; If there is only one element then only one permutation is available ; Sort the array for calculating the number of elements occurring twice ; If the maximum element is occurring twice , then the number of permutations satisfying the condition is 0 ; This variable will store the number of element occurring twice ; Loop to check the number of elements occurring twice ; Check if this element is occurring twice ; If this element is occurring twice then check if this number is occurring more than twice ; If element occurring thrice then no permutation will satisfy the given condition ; Since we have checked the next element as well , then we can increment the loop variable ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int pow ( int x , int y ) { if ( y == 1 ) return x ; if ( y == 0 ) return 1 ; int temp = pow ( x , y / 2 ) ; temp *= temp ; if ( y & 1 ) temp *= x ; return temp ; } int noOfPermutations ( int * a , int n ) { if ( n == 1 ) { return 1 ; } sort ( a , a + n ) ; if ( a [ n - 1 ] == a [ n - 2 ] ) { return 0 ; } int x = 0 ; for ( int i = 0 ; i < n - 2 ; ++ i ) { if ( a [ i ] == a [ i + 1 ] ) { if ( a [ i ] == a [ i + 2 ] ) { return 0 ; } x ++ ; i ++ ; } } return pow ( 2 , n - 2 * x - 1 ) ; } int main ( ) { int a [ ] = { 1 , 2 , 2 , 3 , 4 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int num = noOfPermutations ( a , n ) ; cout << num ; return 0 ; }
Length of the Smallest Subarray that must be removed in order to Maximise the GCD | C ++ program to find the length of the smallest subarray that must be removed in order to maximise the GCD ; Function to find the length of the smallest subarray that must be removed in order to maximise the GCD ; Store the maximum possible GCD of the resulting subarray ; Two pointers initially pointing to the first and last element respectively ; Moving the left pointer to the right if the elements are divisible by the maximum GCD ; Moving the right pointer to the left if the elements are divisible by the maximum GCD ; Return the length of the subarray ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int GetMinSubarrayLength ( int a [ ] , int n ) { int ans = max ( a [ 0 ] , a [ n - 1 ] ) ; int lo = 0 , hi = n - 1 ; while ( lo < n and a [ lo ] % ans == 0 ) lo ++ ; while ( hi > lo and a [ hi ] % ans == 0 ) hi -- ; return ( hi - lo + 1 ) ; } int main ( ) { int arr [ ] = { 4 , 8 , 2 , 1 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int length = GetMinSubarrayLength ( arr , N ) ; cout << length << " STRNEWLINE " ; return 0 ; }
Maximize the number of indices such that element is greater than element to its left | C ++ program of the above approach ; Function to find the maximum pairs such that arr [ i + 1 ] > arr [ i ] ; To store the frequency of the element in arr [ ] ; Store the frequency in map M ; To find the maximum frequency store in map M ; Print the maximum number of possible pairs ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countPairs ( int arr [ ] , int N ) { unordered_map < int , int > M ; for ( int i = 0 ; i < N ; i ++ ) { M [ arr [ i ] ] ++ ; } int maxFreq = 0 ; for ( auto & it : M ) { maxFreq = max ( maxFreq , it . second ) ; } cout << N - maxFreq << endl ; } int main ( ) { int arr [ ] = { 1 , 8 , 5 , 9 , 8 , 8 , 7 , 7 , 5 , 7 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countPairs ( arr , N ) ; return 0 ; }
Find minimum value of the expression by choosing K elements from given array | CPP program to find the minimum possible of the expression by choosing exactly K ( ? N ) integers form given array arr ; Function to find the minimum possible of the expression by choosing exactly K ( ? N ) integers form given array arr ; Sorting the array for least k element selection ; Select first k elements from sorted array ; Return value of solved expression ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumValue ( int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; int answer = 0 ; for ( int i = 0 ; i < k ; i ++ ) answer += arr [ i ] * arr [ i ] ; return answer * ( 2 * k - 2 ) ; } int main ( ) { int arr [ ] = { 4 , 21 , 5 , 3 , 8 } , k = 3 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minimumValue ( arr , n , k ) ; return 0 ; }
Transform N to Minimum possible value | CPP program to transform N to the minimum value ; Initialising the answer ; Function to find the digitsum ; Iterate over all digits and add them ; Return the digit su , ; Function to transform N to the minimum value ; If the final value is lesser than least value ; If final value is equal to least value then check for lesser number of steps to reach this value ; The value will be obtained in less than 15 steps as proved so applying normal recursive operations ; Driver code ; Function call ; Print the answers
#include <bits/stdc++.h> NEW_LINE using namespace std ; int min_val = INT_MAX ; int min_steps = 0 ; int sumOfDigits ( int n ) { string s = to_string ( n ) ; int sum = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { sum += ( s [ i ] - '0' ) ; } return sum ; } void Transform ( int n , int d , int steps ) { if ( n < min_val ) { min_val = n ; min_steps = steps ; } else if ( n == min_val ) { min_steps = min ( min_steps , steps ) ; } if ( steps < 15 ) { Transform ( sumOfDigits ( n ) , d , steps + 1 ) ; Transform ( n + d , d , steps + 1 ) ; } } int main ( ) { int N = 9 , D = 3 ; Transform ( N , D , 0 ) ; cout << min_val << " ▁ " << min_steps ; return 0 ; }
Remove all 1 s from the adjacent left of 0 s in a Binary Array | C ++ implementation of the above approach ; Function to find the maximum number of 1 's before 0 ; Traverse the array ; If value is 1 ; If consecutive 1 followed by 0 , then update the maxCnt ; Print the maximum consecutive 1 's followed by 0 ; Driver Code ; Function Call ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void noOfMoves ( int arr [ ] , int n ) { int cnt = 0 ; int maxCnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == 1 ) { cnt ++ ; } else { if ( cnt != 0 ) { maxCnt = max ( maxCnt , cnt ) ; cnt = 0 ; } } } cout << maxCnt << endl ; } int main ( ) { int arr [ ] = { 0 , 1 , 1 , 1 , 1 , 0 , 0 , 1 , 1 , 0 , 0 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; noOfMoves ( arr , N ) ; int arr1 [ ] = { 1 , 0 , 1 , 0 , 1 , 0 , 1 , 0 } ; N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; noOfMoves ( arr1 , N ) ; return 0 ; }
Check if given coins can be used to pay a value of S | C ++ implementation to check if it is possible to pay a value ; Function to check if it is possible to pay a value ; Loop to add the value of coin A ; Condition to check if it is possible to pay a value of S ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void knowPair ( int a , int b , int n , int s , int m ) { int i = 0 , rem = 0 ; int count_b = 0 , flag = 0 ; while ( i <= a ) { rem = s - ( n * i ) ; count_b = rem / m ; if ( rem % m == 0 && count_b <= b ) { flag = 1 ; } i ++ ; } if ( flag == 1 ) { cout << " YES " << endl ; } else { cout << " NO " << endl ; } } int main ( ) { int A = 1 ; int B = 2 ; int n = 3 ; int S = 4 ; int m = 2 ; knowPair ( A , B , n , S , m ) ; return 0 ; }
Sum of all numbers in the given range which are divisible by M | C ++ program to find the sum of numbers divisible by M in the given range ; Function to find the sum of numbers divisible by M in the given range ; Variable to store the sum ; Running a loop from A to B and check if a number is divisible by i . ; If the number is divisible , then add it to sum ; Return the sum ; Driver code ; A and B define the range M is the dividend ; Printing the result
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumDivisibles ( int A , int B , int M ) { int sum = 0 ; for ( int i = A ; i <= B ; i ++ ) if ( i % M == 0 ) sum += i ; return sum ; } int main ( ) { int A = 6 , B = 15 , M = 3 ; cout << sumDivisibles ( A , B , M ) << endl ; return 0 ; }
Sum of all numbers in the given range which are divisible by M | C ++ program to find the sum of numbers divisible by M in the given range ; Function to find the largest number smaller than or equal to N that is divisible by K ; Finding the remainder when N is divided by K ; If the remainder is 0 , then the number itself is divisible by K ; Else , then the difference between N and remainder is the largest number which is divisible by K ; Function to find the smallest number greater than or equal to N that is divisible by K ; Finding the remainder when N is divided by K ; If the remainder is 0 , then the number itself is divisible by K ; Else , then the difference between N and remainder is the largest number which is divisible by K ; Function to find the sum of numbers divisible by M in the given range ; Variable to store the sum ; To bring the smallest and largest numbers in the range [ A , B ] ; To count the number of terms in the AP ; Sum of n terms of an AP ; Driver code ; A and B define the range , M is the dividend ; Printing the result
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findSmallNum ( int N , int K ) { int rem = N % K ; if ( rem == 0 ) return N ; else return N - rem ; } int findLargeNum ( int N , int K ) { int rem = ( N + K ) % K ; if ( rem == 0 ) return N ; else return N + K - rem ; } int sumDivisibles ( int A , int B , int M ) { int sum = 0 ; int first = findSmallNum ( A , M ) ; int last = findLargeNum ( B , M ) ; if ( first < A ) first += M ; if ( last > B ) first -= M ; int n = ( B / M ) - ( A - 1 ) / M ; return n * ( first + last ) / 2 ; } int main ( ) { int A = 6 , B = 15 , M = 3 ; cout << sumDivisibles ( A , B , M ) ; return 0 ; }
Count of all unique substrings with non | C ++ program to find the count of all unique sub - strings with non - repeating characters ; Function to count all unique distinct character substrings ; Hashmap to store all substrings ; Iterate over all the substrings ; Boolean array to maintain all characters encountered so far ; Variable to maintain the substring till current position ; Get the position of the character in the string ; Check if the character is encountred ; Add the current character to the substring ; Insert substring in Hashmap ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int distinctSubstring ( string & P , int N ) { unordered_set < string > S ; for ( int i = 0 ; i < N ; ++ i ) { vector < bool > freq ( 26 , false ) ; string s ; for ( int j = i ; j < N ; ++ j ) { int pos = P [ j ] - ' a ' ; if ( freq [ pos ] == true ) break ; freq [ pos ] = true ; s += P [ j ] ; S . insert ( s ) ; } } return S . size ( ) ; } int main ( ) { string S = " abba " ; int N = S . length ( ) ; cout << distinctSubstring ( S , N ) ; return 0 ; }
Sum of all subarrays of size K | C ++ implementation to find the sum of all subarrays of size K ; Function to find the sum of all subarrays of size K ; Loop to consider every subarray of size K ; Initialize sum = 0 ; Calculate sum of all elements of current subarray ; Print sum of each subarray ; Driver Code ; Function Call
#include <iostream> NEW_LINE using namespace std ; int calcSum ( int arr [ ] , int n , int k ) { for ( int i = 0 ; i <= n - k ; i ++ ) { int sum = 0 ; for ( int j = i ; j < k + i ; j ++ ) sum += arr [ j ] ; cout << sum << " ▁ " ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; calcSum ( arr , n , k ) ; return 0 ; }
Sum of all subarrays of size K | C ++ implementation to find the sum of all subarrays of size K ; Function to find the sum of all subarrays of size K ; Initialize sum = 0 ; Consider first subarray of size k Store the sum of elements ; Print the current sum ; Consider every subarray of size k Remove first element and add current element to the window ; Add the element which enters into the window and subtract the element which pops out from the window of the size K ; Print the sum of subarray ; Drivers Code ; Function Call
#include <iostream> NEW_LINE using namespace std ; int calcSum ( int arr [ ] , int n , int k ) { int sum = 0 ; for ( int i = 0 ; i < k ; i ++ ) sum += arr [ i ] ; cout << sum << " ▁ " ; for ( int i = k ; i < n ; i ++ ) { sum = ( sum - arr [ i - k ] ) + arr [ i ] ; cout << sum << " ▁ " ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; calcSum ( arr , n , k ) ; return 0 ; }
Number of indices pair such that element pair sum from first Array is greater than second Array | C ++ program to find the number of indices pair such that pair sum from first Array is greater than second Array ; Function to get the number of pairs of indices { i , j } in the given two arrays A and B such that A [ i ] + A [ j ] > B [ i ] + B [ j ] ; Intitializing the difference array D ; Computing the difference between the elements at every index and storing it in the array D ; Sort the array D ; Variable to store the total number of pairs that satisfy the given condition ; Loop to iterate through the difference array D and find the total number of pairs of indices that follow the given condition ; If the value at the index i is positive , then it remains positive for any pairs with j such that j > i . ; If the value at that index is negative then we need to find the index of the value just greater than - D [ i ] ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getPairs ( vector < int > A , vector < int > B , int n ) { vector < int > D ( n ) ; for ( int i = 0 ; i < n ; i ++ ) { D [ i ] = A [ i ] - B [ i ] ; } sort ( D . begin ( ) , D . end ( ) ) ; long long total = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( D [ i ] > 0 ) { total += n - i - 1 ; } else { int k = upper_bound ( D . begin ( ) , D . end ( ) , - D [ i ] ) - D . begin ( ) ; total += n - k ; } } return total ; } int main ( ) { int n = 5 ; vector < int > A ; vector < int > B ; A . push_back ( 4 ) ; A . push_back ( 8 ) ; A . push_back ( 2 ) ; A . push_back ( 6 ) ; A . push_back ( 2 ) ; B . push_back ( 4 ) ; B . push_back ( 5 ) ; B . push_back ( 4 ) ; B . push_back ( 1 ) ; B . push_back ( 3 ) ; cout << getPairs ( A , B , n ) ; }
Number of pairs such that their HCF and LCM is equal | Naive C ++ program to count number of pairs such that their hcf and lcm are equal ; Function to return HCF of two numbers ; Function to return LCM of two numbers ; Returns the number of valid pairs ; Traversing the array . For each array element , checking if it follow the condition ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } int lcm ( int a , int b ) { return ( a * b ) / gcd ( a , b ) ; } int countPairs ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( lcm ( arr [ i ] , arr [ j ] ) == gcd ( arr [ i ] , arr [ j ] ) ) ans ++ ; return ans ; } int main ( ) { int arr [ ] = { 1 , 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , n ) ; return 0 ; }
Number of pairs such that their HCF and LCM is equal | C ++ program to count number of pairs such that their hcf and lcm are equal ; Function to count number of pairs such that their hcf and lcm are equal ; Store frequencies of array elements ; Count of pairs ( arr [ i ] , arr [ j ] ) where arr [ i ] = arr [ j ] ; Count of pairs ( arr [ i ] , arr [ j ] ) where arr [ i ] = arr [ j ] , ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int a [ ] , int n ) { unordered_map < int , int > frequency ; for ( int i = 0 ; i < n ; i ++ ) { frequency [ a [ i ] ] ++ ; } int count = 0 ; for ( auto x : frequency ) { int f = x . second ; count += f * ( f - 1 ) / 2 ; } return count ; } int main ( ) { int arr [ ] = { 1 , 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , n ) ; return 0 ; }
Find the maximum possible value of last element of the Array | C ++ program to find the maximum possible value of last element of the array ; Function to find the maximum possible value of last element of the array ; Traverse for all element ; Find the distance ; If moves less than distance then we can not move this number to end ; How many number we can move to end ; Take the minimum of both of them ; Increment in the end ; Remove taken moves ; Return the last element ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxValue ( int arr [ ] , int n , int moves ) { for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] > 0 ) { int distance = n - 1 - i ; if ( moves < distance ) break ; int can_take = moves / distance ; int take = min ( arr [ i ] , can_take ) ; arr [ n - 1 ] += take ; moves -= take * distance ; } } return arr [ n - 1 ] ; } int main ( ) { int arr [ ] = { 2 , 3 , 0 , 1 } ; int M = 5 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxValue ( arr , N , M ) ; return 0 ; }
Minimum number of Factorials whose sum is equal to N | C ++ program to find minimum number of factorials ; Array to calculate all factorials less than or equal to N Since there can be only 14 factorials till 10 ^ 10 Hence the maximum size of fact [ ] is 14 ; Store the actual size of fact [ ] ; Function to precompute factorials till N ; Precomputing factorials ; Function to find the minimum number of factorials whose sum represents N ; Precompute factorials ; Initialize result ; Traverse through all factorials ; Find factorials ; Print min count ; Print result ; Driver program
#include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE using namespace std ; ll fact [ 14 ] ; int size = 1 ; void preCompute ( int N ) { fact [ 0 ] = 1 ; for ( int i = 1 ; fact [ i - 1 ] <= N ; i ++ ) { fact [ i ] = ( fact [ i - 1 ] * i ) ; size ++ ; } } void findMin ( int N ) { preCompute ( N ) ; int originalN = N ; vector < int > ans ; for ( int i = size - 1 ; i >= 0 ; i -- ) { while ( N >= fact [ i ] ) { N -= fact [ i ] ; ans . push_back ( fact [ i ] ) ; } } cout << ans . size ( ) << " STRNEWLINE " ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) cout << ans [ i ] << " ▁ " ; } int main ( ) { int n = 27 ; findMin ( n ) ; return 0 ; }
Longest increasing sub | C ++ implementation to find the longest increasing subsequence in repeating element of array ; Function to find the LCS ; Loop to create frequency array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findLCS ( int arr [ ] , int n ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) { mp [ arr [ i ] ] ++ ; } return mp . size ( ) ; } int main ( ) { int n = 3 ; int arr [ ] = { 3 , 2 , 1 } ; cout << findLCS ( arr , n ) ; return 0 ; }
Path with maximum product in 2 | C ++ Program to find maximum product path from ( 0 , 0 ) to ( N - 1 , M - 1 ) ; Function to find maximum product ; It will store the maximum product till a given cell . ; It will store the minimum product till a given cell ( for - ve elements ) ; If we are at topmost or leftmost , just copy the elements . ; If we 're not at the above, we can consider the above value. ; If we 're not on the leftmost, we can consider the left value. ; Store max & min product till i , j . ; Return the max product path from 0 , 0 -> N - 1 , M - 1. ; Driver Code ; Print maximum product from ( 0 , 0 ) to ( N - 1 , M - 1 )
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 3 NEW_LINE #define M 3 NEW_LINE int maxProductPath ( int arr [ N ] [ M ] ) { vector < vector < int > > maxPath ( N , vector < int > ( M , INT_MIN ) ) ; vector < vector < int > > minPath ( N , vector < int > ( M , INT_MAX ) ) ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { int minVal = INT_MAX ; int maxVal = INT_MIN ; if ( i == 0 && j == 0 ) { maxVal = arr [ i ] [ j ] ; minVal = arr [ i ] [ j ] ; } if ( i > 0 ) { int tempMax = max ( maxPath [ i - 1 ] [ j ] * arr [ i ] [ j ] , minPath [ i - 1 ] [ j ] * arr [ i ] [ j ] ) ; maxVal = max ( maxVal , tempMax ) ; int tempMin = min ( maxPath [ i - 1 ] [ j ] * arr [ i ] [ j ] , minPath [ i - 1 ] [ j ] * arr [ i ] [ j ] ) ; minVal = min ( minVal , tempMin ) ; } if ( j > 0 ) { int tempMax = max ( maxPath [ i ] [ j - 1 ] * arr [ i ] [ j ] , minPath [ i ] [ j - 1 ] * arr [ i ] [ j ] ) ; maxVal = max ( maxVal , tempMax ) ; int tempMin = min ( maxPath [ i ] [ j - 1 ] * arr [ i ] [ j ] , minPath [ i ] [ j - 1 ] * arr [ i ] [ j ] ) ; minVal = min ( minVal , tempMin ) ; } maxPath [ i ] [ j ] = maxVal ; minPath [ i ] [ j ] = minVal ; } } return maxPath [ N - 1 ] [ M - 1 ] ; } int main ( ) { int arr [ N ] [ M ] = { { 1 , -2 , 3 } , { 4 , -5 , 6 } , { -7 , -8 , 9 } } ; cout << maxProductPath ( arr ) << endl ; return 0 ; }
Shortest Job First ( or SJF ) CPU Scheduling Non | C ++ implementation of shortest job first using the concept of segment tree ; Process ID ; Arrival time ; Burst time ; Completion time ; Turnaround time ; Waiting time ; Array to store all the process information by implementing the above struct util ; Process id ; burst time ; Segment tree array to process the queries in nlogn ; To keep an account of where a particular process_id is in the segment tree base array ; Comparator function to sort the struct array according to arrival time ; Function to update the burst time and process id in the segment tree ; Function to return the range minimum of the burst time of all the arrived processes using segment tree ; Function to perform non_preemptive shortest job first and return the completion time , turn around time and waiting time for the given processes ; To store the number of processes that have been completed ; To keep an account of the number of processes that have been arrived ; Current running time ; To find the list of processes whose arrival time is less than or equal to the current time ; To find the minimum of all the running times from the set of processes whose arrival time is less than or equal to the current time ; Checking if the process has already been executed ; Calculating and updating the array with the current time , turn around time and waiting time ; Update the process burst time with infinity when the process is executed ; Function to call the functions and perform shortest job first operation ; Sort the array based on the arrival times ; Calling the function to perform non - premptive - sjf ; Function to print the required values after performing shortest job first ; Driver code ; Number of processes ; Initializing the process id and burst time ; Arrival time , Burst time and ID of the processes on which SJF needs to be performed ; Print the calculated time
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long NEW_LINE #define z 1000000007 NEW_LINE #define sh 100000 NEW_LINE #define pb push_back NEW_LINE #define pr ( x ) printf("%d ", x) NEW_LINE struct util { int id ; int at ; int bt ; int ct ; int tat ; int wt ; } ar [ sh + 1 ] ; struct util1 { int p_id ; int bt1 ; } ; util1 range ; util1 tr [ 4 * sh + 5 ] ; int mp [ sh + 1 ] ; bool cmp ( util a , util b ) { if ( a . at == b . at ) return a . id < b . id ; return a . at < b . at ; } void update ( int node , int st , int end , int ind , int id1 , int b_t ) { if ( st == end ) { tr [ node ] . p_id = id1 ; tr [ node ] . bt1 = b_t ; return ; } int mid = ( st + end ) / 2 ; if ( ind <= mid ) update ( 2 * node , st , mid , ind , id1 , b_t ) ; else update ( 2 * node + 1 , mid + 1 , end , ind , id1 , b_t ) ; if ( tr [ 2 * node ] . bt1 < tr [ 2 * node + 1 ] . bt1 ) { tr [ node ] . bt1 = tr [ 2 * node ] . bt1 ; tr [ node ] . p_id = tr [ 2 * node ] . p_id ; } else { tr [ node ] . bt1 = tr [ 2 * node + 1 ] . bt1 ; tr [ node ] . p_id = tr [ 2 * node + 1 ] . p_id ; } } util1 query ( int node , int st , int end , int lt , int rt ) { if ( end < lt st > rt ) return range ; if ( st >= lt && end <= rt ) return tr [ node ] ; int mid = ( st + end ) / 2 ; util1 lm = query ( 2 * node , st , mid , lt , rt ) ; util1 rm = query ( 2 * node + 1 , mid + 1 , end , lt , rt ) ; if ( lm . bt1 < rm . bt1 ) return lm ; return rm ; } void non_preemptive_sjf ( int n ) { int counter = n ; int upper_range = 0 ; int tm = min ( INT_MAX , ar [ upper_range + 1 ] . at ) ; while ( counter ) { for ( ; upper_range <= n ; ) { upper_range ++ ; if ( ar [ upper_range ] . at > tm upper_range > n ) { upper_range -- ; break ; } update ( 1 , 1 , n , upper_range , ar [ upper_range ] . id , ar [ upper_range ] . bt ) ; } util1 res = query ( 1 , 1 , n , 1 , upper_range ) ; if ( res . bt1 != INT_MAX ) { counter -- ; int index = mp [ res . p_id ] ; tm += ( res . bt1 ) ; ar [ index ] . ct = tm ; ar [ index ] . tat = ar [ index ] . ct - ar [ index ] . at ; ar [ index ] . wt = ar [ index ] . tat - ar [ index ] . bt ; update ( 1 , 1 , n , index , INT_MAX , INT_MAX ) ; } else { tm = ar [ upper_range + 1 ] . at ; } } } void execute ( int n ) { sort ( ar + 1 , ar + n + 1 , cmp ) ; for ( int i = 1 ; i <= n ; i ++ ) mp [ ar [ i ] . id ] = i ; non_premptive_sjf ( n ) ; } void print ( int n ) { cout << " ProcessId ▁ " << " Arrival ▁ Time ▁ " << " Burst ▁ Time ▁ " << " Completion ▁ Time ▁ " << " Turn ▁ Around ▁ Time ▁ " << " Waiting ▁ Time STRNEWLINE " ; for ( int i = 1 ; i <= n ; i ++ ) { cout << ar [ i ] . id << " ▁ TABSYMBOL TABSYMBOL ▁ " << ar [ i ] . at << " ▁ TABSYMBOL TABSYMBOL ▁ " << ar [ i ] . bt << " ▁ TABSYMBOL TABSYMBOL ▁ " << ar [ i ] . ct << " ▁ TABSYMBOL TABSYMBOL ▁ " << ar [ i ] . tat << " ▁ TABSYMBOL TABSYMBOL ▁ " << ar [ i ] . wt << " ▁ STRNEWLINE " ; } } int main ( ) { int n = 5 ; range . p_id = INT_MAX ; range . bt1 = INT_MAX ; for ( int i = 1 ; i <= 4 * sh + 1 ; i ++ ) { tr [ i ] . p_id = INT_MAX ; tr [ i ] . bt1 = INT_MAX ; } ar [ 1 ] . at = 1 ; ar [ 1 ] . bt = 7 ; ar [ 1 ] . id = 1 ; ar [ 2 ] . at = 2 ; ar [ 2 ] . bt = 5 ; ar [ 2 ] . id = 2 ; ar [ 3 ] . at = 3 ; ar [ 3 ] . bt = 1 ; ar [ 3 ] . id = 3 ; ar [ 4 ] . at = 4 ; ar [ 4 ] . bt = 2 ; ar [ 4 ] . id = 4 ; ar [ 5 ] . at = 5 ; ar [ 5 ] . bt = 8 ; ar [ 5 ] . id = 5 ; execute ( n ) ; print ( n ) ; }
Vertical and Horizontal retrieval ( MRT ) on Tapes | C ++ program to print Vertical filling ; 2D matrix for vertical insertion on tapes ; It is used for checking whether tape is full or not ; It is used for calculating total retrieval time ; It is used for calculating mean retrieval time ; It is used for calculating mean retrieval time ; vertical insertion on tape ; initialize variables to 0 for each iteration ; Used for getting ' sum ' sizes of records in tape to determine whether tape is full or not ; if tape is not full ; check for ability of tapes to hold value ; initialize variables to 0 for each iteration ; display elements of tape ; calculating total retrieval time ; MRT formula ; calculating mean retrieval time using formula ; v . size ( ) is function of vector is used to get size of vector ; Driver Code ; store the size of records [ ] ; store the size of tapes [ ] ; sorting of an array is required to attain greedy approach of algorithm
#include <bits/stdc++.h> NEW_LINE using namespace std ; void vertical_Fill ( int records [ ] , int tape [ ] , int m , int n ) { int v [ m ] [ n ] = { 0 } ; int sum = 0 ; int Retrieval_Time = 0 ; double Mrt ; int z = 0 , j = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { sum = 0 ; for ( int k = 0 ; k < i ; k ++ ) { sum += v [ j ] [ k ] ; } if ( sum + records [ z ] <= tape [ j ] ) { v [ j ] [ i ] = records [ z ] ; z ++ ; } } if ( v [ 2 ] [ i ] == 0 ) { break ; } } for ( int i = 0 ; i < m ; i ++ ) { Retrieval_Time = 0 ; cout << " tape ▁ " << i + 1 << " ▁ : ▁ [ ▁ " ; for ( j = 0 ; j < n ; j ++ ) { if ( v [ i ] [ j ] != 0 ) { cout << v [ i ] [ j ] << " ▁ " ; } else { break ; } } cout << " ] " ; for ( int k = 0 ; v [ i ] [ k ] != 0 ; k ++ ) { Retrieval_Time += v [ i ] [ k ] * ( j - k ) ; } Mrt = ( double ) Retrieval_Time / j ; cout << " TABSYMBOL MRT ▁ : ▁ " << Mrt << endl ; } } int main ( ) { int records [ ] = { 15 , 2 , 8 , 23 , 45 , 50 , 60 , 120 } ; int tape [ ] = { 25 , 80 , 160 } ; int n = sizeof ( records ) / sizeof ( records [ 0 ] ) ; int m = sizeof ( tape ) / sizeof ( tape [ 0 ] ) ; sort ( records , records + n ) ; vertical_Fill ( records , tape , m , n ) ; return 0 ; }
Minimum number of subsequences required to convert one string to another | C ++ program to find the Minimum number of subsequences required to convert one string to another ; Function to find the no of subsequences ; Push the values of indexes of each character ; Find the next index available in the array ; If Character is not in string A ; Check if the next index is not equal to the size of array which means there is no index greater than minIndex in the array ; Update value of minIndex with this index ; Update the value of counter and minIndex for next operation ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minSubsequnces ( string A , string B ) { vector < int > v [ 26 ] ; int minIndex = -1 , cnt = 1 , j = 0 ; int flag = 0 ; for ( int i = 0 ; i < A . length ( ) ; i ++ ) { int p = ( int ) A [ i ] - 97 ; v [ p ] . push_back ( i ) ; } while ( j < B . length ( ) ) { int p = ( int ) B [ j ] - 97 ; int k = upper_bound ( v [ p ] . begin ( ) , v [ p ] . end ( ) , minIndex ) - v [ p ] . begin ( ) ; if ( v [ p ] . size ( ) == 0 ) { flag = 1 ; break ; } if ( k != v [ p ] . size ( ) ) { minIndex = v [ p ] [ k ] ; j = j + 1 ; } else { cnt = cnt + 1 ; minIndex = -1 ; } } if ( flag == 1 ) { return -1 ; } return cnt ; } int main ( ) { string A1 = " abbace " ; string B1 = " acebbaae " ; cout << minSubsequnces ( A1 , B1 ) << endl ; return 0 ; }
Find two equal subsequences of maximum length with at least one different index | C ++ implementation of the approach ; Function to return the required length of the subsequences ; To store the result ; To store the last visited position of lowercase letters ; Initialisation of frequency array to - 1 to indicate no character has previously occured ; For every character of the string ; Get the index of the current character ; If the current character has appeared before in the string ; Update the result ; Update the last position of the current character ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 26 ; int maxLength ( string str , int len ) { int res = 0 ; int lastPos [ MAX ] ; for ( int i = 0 ; i < MAX ; i ++ ) { lastPos [ i ] = -1 ; } for ( int i = 0 ; i < len ; i ++ ) { int C = str [ i ] - ' a ' ; if ( lastPos [ C ] != -1 ) { res = max ( len - ( i - lastPos [ C ] - 1 ) - 1 , res ) ; } lastPos [ C ] = i ; } return res ; } int main ( ) { string str = " geeksforgeeks " ; int len = str . length ( ) ; cout << maxLength ( str , len ) ; return 0 ; }
Maximum profit by selling N items at two markets | C ++ implementation of the approach ; Max profit will be saved here ; loop to check all possible combinations of sales ; the sum of the profit after the sale for products 0 to i in market A ; the sum of the profit after the sale for products i to n in market B ; Replace the value of Max Profit with a bigger value among maxP and sumA + sumB ; Return the value of Max Profit ; Driver Program11111111111111111111111
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxProfit ( vector < int > a , vector < int > b , int n ) { int maxP = -1 ; for ( int i = 0 ; i < n + 1 ; i ++ ) { int sumA = 0 ; for ( int j = 0 ; j < min ( i , ( int ) a . size ( ) ) ; j ++ ) sumA += a [ j ] ; int sumB = 0 ; for ( int j = i ; j < b . size ( ) ; j ++ ) sumB += b [ j ] ; maxP = max ( maxP , sumA + sumB ) ; } return maxP ; } int main ( ) { vector < int > a = { 2 , 3 , 2 } ; vector < int > b = { 10 , 30 , 40 } ; cout << maxProfit ( a , b , 4 ) ; return 0 ; }
Partitions possible such that the minimum element divides all the other elements of the partition | C ++ implementation of the approach ; Function to return the count partitions possible from the given array such that the minimum element of any partition divides all the other elements of that partition ; Initialize the count variable ; Find the minimum element ; Break if no minimum element present ; Increment the count if minimum element present ; Replace all the element divisible by min_elem ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPartitions ( int A [ ] , int N ) { int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int min_elem = * min_element ( A , A + N ) ; if ( min_elem == INT_MAX ) break ; count ++ ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] % min_elem == 0 ) A [ i ] = INT_MAX ; } } return count ; } int main ( ) { int arr [ ] = { 7 , 6 , 5 , 4 , 3 , 2 , 2 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPartitions ( arr , N ) ; return 0 ; }
Minimum number of swaps to make two binary string equal | C ++ program for the above approach ; Function to calculate min swaps to make binary strings equal ; Count of zero 's ; Count of one 's ; As discussed above ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minSwaps ( string & s1 , string & s2 ) { int c0 = 0 , c1 = 0 ; for ( int i = 0 ; i < s1 . size ( ) ; i ++ ) { if ( s1 [ i ] == '0' && s2 [ i ] == '1' ) { c0 ++ ; } else if ( s1 [ i ] == '1' && s2 [ i ] == '0' ) { c1 ++ ; } } int ans = c0 / 2 + c1 / 2 ; if ( c0 % 2 == 0 && c1 % 2 == 0 ) { return ans ; } else if ( ( c0 + c1 ) % 2 == 0 ) { return ans + 2 ; } else { return -1 ; } } int main ( ) { string s1 = "0011" , s2 = "1111" ; int ans = minSwaps ( s1 , s2 ) ; cout << ans << ' ' ; return 0 ; }
Minimum changes required to make all element in an array equal | C ++ program to find minimum changes required to make all elements of the array equal ; Function to count of minimum changes required to make all elements equal ; Store the count of each element as key value pair in unordered map ; Find the count of maximum occurring element ; Return count of all element minus count of maximum occurring element ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minChanges ( int arr [ ] , int n ) { unordered_map < int , int > umap ; for ( int i = 0 ; i < n ; i ++ ) { umap [ arr [ i ] ] ++ ; } int maxFreq = 0 ; for ( auto p : umap ) { maxFreq = max ( maxFreq , p . second ) ; } return n - maxFreq ; } int main ( ) { int arr [ ] = { 2 , 3 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minChanges ( arr , n ) << ' ' ; return 0 ; }
Minimum operations to make two numbers equal | C ++ implementation of the above approach ; Function to find the minimum no of operations ; find the maximum of two and store it in p ; increase it until it is achievable from given n and m ; Here value added to n and m will be S ( n ) = p - n + p - m ; check whether integer value of n exist by the formula n = ( - 1 + sqrt ( 1 + 8 * S ( n ) ) ) / 2 ; Driver code ; Function calling
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperations ( int n , int m ) { int a = 0 , k = 1 ; int p = max ( n , m ) ; while ( n != m ) { float s = ( float ) ( p - n + p - m ) ; float q = ( -1 + sqrt ( 8 * s + 1 ) ) / 2 ; if ( q - floor ( q ) == 0 ) { a = q ; n = m ; } p = p + 1 ; } return a ; } int main ( ) { int n = 1 , m = 3 ; cout << minOperations ( n , m ) ; return 0 ; }
Count of subarrays with sum at least K | C ++ implementation of the approach ; Function to return the number of subarrays with sum atleast k ; To store the right index and the current sum ; To store the number of sub - arrays ; For all left indexes ; Get elements till current sum is less than k ; No such subarray is possible ; Add all possible subarrays ; Remove the left most element ; Return the required answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int k_sum ( int a [ ] , int n , int k ) { int r = 0 , sum = 0 ; int ans = 0 ; for ( int l = 0 ; l < n ; l ++ ) { while ( sum < k ) { if ( r == n ) break ; else { sum += a [ r ] ; r ++ ; } } if ( sum < k ) break ; ans += n - r + 1 ; sum -= a [ l ] ; } return ans ; } int main ( ) { int a [ ] = { 6 , 1 , 2 , 7 } , k = 10 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << k_sum ( a , n , k ) ; return 0 ; }
Find if a crest is present in the index range [ L , R ] of the given array | C ++ implementation of the approach ; Function that returns true if the array contains a crest in the index range [ L , R ] ; To keep track of elements which satisfy the Property ; Property is satisfied for the current element ; Cumulative Sum ; If a crest is present in the given index range ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool hasCrest ( int arr [ ] , int n , int L , int R ) { int present [ n ] = { 0 } ; for ( int i = 1 ; i <= n - 2 ; i ++ ) { if ( ( arr [ i ] <= arr [ i + 1 ] ) && ( arr [ i ] <= arr [ i - 1 ] ) ) { present [ i ] = 1 ; } } for ( int i = 1 ; i < n ; i ++ ) { present [ i ] += present [ i - 1 ] ; } if ( present [ L ] == present [ R - 1 ] ) return true ; return false ; } int main ( ) { int arr [ ] = { 2 , 1 , 3 , 5 , 12 , 11 , 7 , 9 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int L = 2 ; int R = 6 ; if ( hasCrest ( arr , N , L , R ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Maximum Sum of Products of two arrays by toggling adjacent bits | C ++ program to find the maximum SoP of two arrays by toggling adjacent bits in the second array ; Function to return Max Sum ; intialParity and finalParity are 0 if total no . of 1 's is even else 1 ; minPositive and maxNegative will store smallest positive and smallest negative integer respectively . ; Count of Initial Parity ; if arr1 [ i ] is positive then add 1 in finalParity to get 1 at arr2 [ i ] ; if both parity are odd or even then return sum ; else add one more 1 or remove 1 ; if minPositive > maxNegative , put 1 at maxNegative and add it to our sum ; else remove minPositive no . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSum ( int arr1 [ ] , int arr2 [ ] , int n ) { int initialParity = 0 , finalParity = 0 ; int sum = 0 , minPositive = INT_MAX , maxNegative = INT_MIN ; for ( int i = 0 ; i < n ; i ++ ) { initialParity += arr2 [ i ] ; if ( arr1 [ i ] >= 0 ) { finalParity += 1 ; sum += arr1 [ i ] ; minPositive = min ( minPositive , arr1 [ i ] ) ; } else { maxNegative = max ( maxNegative , arr1 [ i ] ) ; } } if ( initialParity % 2 == finalParity % 2 ) { return sum ; } else { if ( minPositive + maxNegative >= 0 ) { return sum + maxNegative ; } else { return sum - minPositive ; } } } int main ( ) { int arr1 [ ] = { 2 , -4 , 5 , 3 } ; int arr2 [ ] = { 0 , 1 , 0 , 1 } ; int n = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; cout << maxSum ( arr1 , arr2 , n ) << endl ; return 0 ; }
Minimum number to be added to all digits of X to make X > Y | C ++ program to find Minimum number to be added to all digits of X to make X > Y ; Function to check if X is lexicographically larger Y ; It is lexicographically larger ; Utility function to check minimum value of d ; If X is already larger do not need to add anything ; Adding d to all elements of X ; If X is larger now print d ; else print d + 1 ; Driver Code ; Taking the numbers as sequences
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool IsLarger ( int X [ ] , int Y [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { if ( X [ i ] < Y [ i ] ) { return false ; } } return true ; } int solve ( int X [ ] , int Y [ ] , int n ) { int ans = 0 ; if ( IsLarger ( X , Y , n ) ) { ans = 0 ; } else { int d = Y [ 0 ] - X [ 0 ] ; for ( int i = 0 ; i < n ; i ++ ) { X [ i ] += d ; } if ( IsLarger ( X , Y , n ) ) { ans = d ; } else { ans = d + 1 ; } } return ans ; } int main ( ) { int X [ ] = { 2 , 3 , 6 , 9 } ; int Y [ ] = { 3 , 4 , 8 , 1 } ; int n = sizeof ( X ) / sizeof ( X [ 0 ] ) ; cout << solve ( X , Y , n ) ; return 0 ; }
Maximum possible Bitwise OR of the two numbers from the range [ L , R ] | C ++ implementation of the approach ; Function to return the maximum bitwise OR of any pair from the given range ; Converting L to its binary representation ; Converting R to its binary representation ; In order to make the number of bits of L and R same ; Push 0 to the MSB ; When ith bit of R is 1 and ith bit of L is 0 ; From MSB side set all bits of L to be 1 ; From ( i + 1 ) th bit , all bits of L changed to be 1 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long int max_bitwise_or ( long long int L , long long int R ) { vector < long long int > v1 , v2 , v3 ; long long int z = 0 , i , ans = 0 , cnt = 1 ; while ( L > 0 ) { v1 . push_back ( L % 2 ) ; L = L / 2 ; } while ( R > 0 ) { v2 . push_back ( R % 2 ) ; R = R / 2 ; } while ( v1 . size ( ) != v2 . size ( ) ) { v1 . push_back ( 0 ) ; } for ( i = v2 . size ( ) - 1 ; i >= 0 ; i -- ) { if ( v2 [ i ] == 1 && v1 [ i ] == 0 && z == 0 ) { z = 1 ; continue ; } if ( z == 1 ) { v1 [ i ] = 1 ; } } for ( i = 0 ; i < v2 . size ( ) ; i ++ ) { v3 . push_back ( v2 [ i ] v1 [ i ] ) ; } for ( i = 0 ; i < v2 . size ( ) ; i ++ ) { if ( v3 [ i ] == 1 ) { ans += cnt ; } cnt *= 2 ; } return ans ; } int main ( ) { long long int L = 10 , R = 20 ; cout << max_bitwise_or ( L , R ) ; return 0 ; }
Find the minimum value of X for an expression | C ++ implementation of above approach ; Function to calculate value of X ; Check for both possibilities ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int valueofX ( int ar [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum = sum + ar [ i ] ; } if ( sum % n == 0 ) { return sum / n ; } else { int A = sum / n , B = sum / n + 1 ; int ValueA = 0 , ValueB = 0 ; for ( int i = 0 ; i < n ; i ++ ) { ValueA += ( ar [ i ] - A ) * ( ar [ i ] - A ) ; ValueB += ( ar [ i ] - B ) * ( ar [ i ] - B ) ; } if ( ValueA < ValueB ) { return A ; } else { return B ; } } } int main ( ) { int n = 7 ; int arr [ 7 ] = { 6 , 9 , 1 , 6 , 1 , 3 , 7 } ; cout << valueofX ( arr , n ) << ' ' ; return 0 ; }
Minimum length String with Sum of the alphabetical values of the characters equal to N | C ++ program to find the Minimum length String with Sum of the alphabetical values of the characters equal to N ; Function to find the minimum length ; Function to find the minimum length String ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minLength ( int n ) { int ans = n / 26 ; if ( n % 26 != 0 ) ans ++ ; return ans ; } string minString ( int n ) { int ans = n / 26 ; string res = " " ; while ( ans -- ) { res = res + " z " ; } if ( n % 26 != 0 ) { res = res + ( char ) ( ( n % 26 ) + 96 ) ; } return res ; } int main ( ) { int n = 50 ; cout << minLength ( n ) << endl << minString ( n ) ; return 0 ; }
Minimum halls required for class scheduling | C ++ implementation of the approach ; Function to return the minimum number of halls required ; Array to store the number of lectures ongoing at time t ; For every lecture increment start point s decrement ( end point + 1 ) ; Perform prefix sum and update the ans to maximum ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100001 NEW_LINE int minHalls ( int lectures [ ] [ 2 ] , int n ) { int prefix_sum [ MAX ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { prefix_sum [ lectures [ i ] [ 0 ] ] ++ ; prefix_sum [ lectures [ i ] [ 1 ] + 1 ] -- ; } int ans = prefix_sum [ 0 ] ; for ( int i = 1 ; i < MAX ; i ++ ) { prefix_sum [ i ] += prefix_sum [ i - 1 ] ; ans = max ( ans , prefix_sum [ i ] ) ; } return ans ; } int main ( ) { int lectures [ ] [ 2 ] = { { 0 , 5 } , { 1 , 2 } , { 1 , 10 } } ; int n = sizeof ( lectures ) / sizeof ( lectures [ 0 ] ) ; cout << minHalls ( lectures , n ) ; return 0 ; }
Find the minimum capacity of the train required to hold the passengers | C ++ implementation of the approach ; Function to return the minimum capacity required ; To store the minimum capacity ; To store the current capacity of the train ; For every station ; Add the number of people entering the train and subtract the number of people exiting the train to get the current capacity of the train ; Update the minimum capacity ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minCapacity ( int enter [ ] , int exit [ ] , int n ) { int minCap = 0 ; int currCap = 0 ; for ( int i = 0 ; i < n ; i ++ ) { currCap = currCap + enter [ i ] - exit [ i ] ; minCap = max ( minCap , currCap ) ; } return minCap ; } int main ( ) { int enter [ ] = { 3 , 5 , 2 , 0 } ; int exit [ ] = { 0 , 2 , 4 , 4 } ; int n = sizeof ( enter ) / sizeof ( enter [ 0 ] ) ; cout << minCapacity ( enter , exit , n ) ; return 0 ; }
Count of numbers in the range [ L , R ] which satisfy the given conditions | C ++ implementation of the approach ; Maximum possible valid number ; To store all the required number from the range [ 1 , MAX ] ; Function that returns true if x satisfies the given conditions ; To store the digits of x ; If current digit appears more than once ; If current digit is greater than 5 ; Put the digit in the map ; Function to generate all the required numbers in the range [ 1 , MAX ] ; Insert first 5 valid numbers ; Inserting 0 externally because 0 cannot be the leading digit in any number ; If x satisfies the given conditions ; Cannot append anymore digit as adding a digit will repeat one of the already present digits ; Append all the valid digits one by one and push the new generated number to the queue ; Append the digit ; Push the newly generated number to the queue ; Function to copmpare two strings which represent a numerical value ; Function to return the count of valid numbers in the range [ l , r ] ; Generate all the valid numbers in the range [ 1 , MAX ] ; To store the count of numbers in the range [ l , r ] ; For every valid number in the range [ 1 , MAX ] ; If current number is within the required range ; If number is equal to either l or r ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 543210 NEW_LINE vector < string > ans ; bool isValidNum ( string x ) { map < int , int > mp ; for ( int i = 0 ; i < x . length ( ) ; i ++ ) { if ( mp . find ( x [ i ] - '0' ) != mp . end ( ) ) { return false ; } else if ( x [ i ] - '0' > 5 ) { return false ; } else { mp [ x [ i ] - '0' ] = 1 ; } } return true ; } void generate ( ) { queue < string > q ; q . push ( "1" ) ; q . push ( "2" ) ; q . push ( "3" ) ; q . push ( "4" ) ; q . push ( "5" ) ; bool flag = true ; ans . push_back ( "0" ) ; while ( ! q . empty ( ) ) { string x = q . front ( ) ; q . pop ( ) ; if ( isValidNum ( x ) ) { ans . push_back ( x ) ; } if ( x . length ( ) == 6 ) continue ; for ( int i = 0 ; i <= 5 ; i ++ ) { string z = to_string ( i ) ; string temp = x + z ; q . push ( temp ) ; } } } bool comp ( string a , string b ) { if ( a . size ( ) == b . size ( ) ) return a < b ; else return a . size ( ) < b . size ( ) ; } int findcount ( string l , string r ) { generate ( ) ; int count = 0 ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) { string a = ans [ i ] ; if ( comp ( l , a ) && comp ( a , r ) ) { count ++ ; } else if ( a == l a == r ) { count ++ ; } } return count ; } int main ( ) { string l = "1" , r = "1000" ; cout << findcount ( l , r ) ; return 0 ; }
Find permutation with maximum remainder Sum | C ++ implementation of the approach ; Function to find the permutation ; Put n at the first index 1 ; Put all the numbers from 2 to n sequentially ; Driver code ; Display the permutation
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > Findpermutation ( int n ) { vector < int > a ( n + 1 ) ; a [ 1 ] = n ; for ( int i = 2 ; i <= n ; i ++ ) a [ i ] = i - 1 ; return a ; } int main ( ) { int n = 8 ; vector < int > v = Findpermutation ( n ) ; for ( int i = 1 ; i <= n ; i ++ ) cout << v [ i ] << ' ▁ ' ; return 0 ; }
Lexicographically smallest string of length N and sum K | C ++ implementation of the approach ; Function to return the lexicographically smallest string of length n that satisfies the given condition ; Iteration from the last position in the array ; If k is a positive integer ; ' z ' needs to be inserted ; Add the required character ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string lexo_small ( int n , int k ) { string arr = " " ; for ( int i = 0 ; i < n ; i ++ ) arr += ' a ' ; for ( int i = n - 1 ; i >= 0 ; i -- ) { k -= i ; if ( k >= 0 ) { if ( k >= 26 ) { arr [ i ] = ' z ' ; k -= 26 ; } else { char c = ( char ) ( k + 97 - 1 ) ; arr [ i ] = c ; k -= arr [ i ] - ' a ' + 1 ; } } else break ; k += i ; } return arr ; } int main ( ) { int n = 5 , k = 42 ; string arr = lexo_small ( n , k ) ; cout << arr ; }
Check if string can be rearranged so that every Odd length Substring is Palindrome | C ++ implementation of the above approach ; Function to check is it possible to rearrange the string such that every odd length substring is palindrome ; Length of the string ; To count number of distinct character in string ; To count frequency of each character ; Inserting into set ; Incrementing the frequency ; All characters in the string are same ; There are more than 2 different character in string ; Currently there is 2 different character in string ; Get the frequencies of the characters that present in string ; Difference between their count is less than or equal to 1 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool IsPossible ( string s ) { int n = s . length ( ) ; set < char > count ; map < char , int > map ; for ( int i = 0 ; i < n ; i ++ ) { count . insert ( s [ i ] ) ; map [ s [ i ] ] += 1 ; } if ( count . size ( ) == 1 ) { return true ; } if ( count . size ( ) > 2 ) { return false ; } auto it = count . begin ( ) ; int x = 0 , y = 0 ; x = map [ * it ] ; it ++ ; y = map [ * it ] ; if ( abs ( x - y ) <= 1 ) { return true ; } return false ; } int main ( ) { string s = " aaaddad " ; if ( IsPossible ( s ) ) cout << " YES STRNEWLINE " ; else cout << " NO STRNEWLINE " ; return 0 ; }
Minimum element left from the array after performing given operations | C ++ implementation of the approach ; Function to return the minimum possible value of the last element left after performing the given operations ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMin ( int arr [ ] , int n ) { int minVal = * min_element ( arr , arr + n ) ; return minVal ; } int main ( ) { int arr [ ] = { 5 , 3 , 1 , 6 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << getMin ( arr , n ) ; return 0 ; }
Largest substring with same Characters | CPP program to find largest sub string with same characters ; Function to find largest sub string with same characters ; Traverse the string ; If character is same as previous increment temp value ; Return the required answer ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Substring ( string s ) { int ans = 1 , temp = 1 ; for ( int i = 1 ; i < s . size ( ) ; i ++ ) { if ( s [ i ] == s [ i - 1 ] ) { ++ temp ; } else { ans = max ( ans , temp ) ; temp = 1 ; } } ans = max ( ans , temp ) ; return ans ; } int main ( ) { string s = " abcdddddeff " ; cout << Substring ( s ) ; return 0 ; }
Number of balanced parenthesis substrings | CPP program to find number of balanced parenthesis sub strings ; Function to find number of balanced parenthesis sub strings ; To store required answer ; Vector to stores the number of balanced brackets at each depth . ; d stores checks the depth of our sequence For example level of ( ) is 1 and that of ( ( ) ) is 2. ; If open bracket increase depth ; If closing bracket ; Return the required answer ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Balanced_Substring ( string str , int n ) { int ans = 0 ; vector < int > arr ( n / 2 + 1 , 0 ) ; int d = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == ' ( ' ) d ++ ; else { if ( d == 1 ) { for ( int j = 2 ; j <= n / 2 + 1 && arr [ j ] != 0 ; j ++ ) arr [ j ] = 0 ; } ++ ans ; ans += arr [ d ] ; arr [ d ] ++ ; d -- ; } } return ans ; } int main ( ) { string str = " ( ) ( ) ( ) " ; int n = str . size ( ) ; cout << Balanced_Substring ( str , n ) ; return 0 ; }
Count ways to divide circle using N non | C ++ implementation of the above approach ; Function to calculate x ^ y % mod efficiently ; Initialize the answer ; If power is odd ; Update the answer ; Square the base and half the exponent ; Return the value ; Function to calculate ncr % mod efficiently ; Initialize the answer ; Calculate ncr in O ( r ) ; Multiply with the numerator factor ; Calculate the inverse of factor of denominator ; Multiply with inverse value ; Return answer value ; Function to return the number of non intersecting chords ; define mod value ; Value of C ( 2 n , n ) ; Modulo inverse of ( n + 1 ) ; Multiply with modulo inverse ; Return the answer ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int power ( long long x , int y , int mod ) { long long res = 1 ; while ( y ) { if ( y & 1 ) res = ( res * x ) % mod ; x = ( x * x ) % mod ; y = ( y >> 1 ) ; } return ( int ) ( res % mod ) ; } int ncr ( int n , int r , int mod ) { long long res = 1 ; for ( int i = 1 ; i <= r ; i += 1 ) { res = ( res * ( n - i + 1 ) ) % mod ; int inv = power ( i , mod - 2 , mod ) ; res = ( res * inv ) % mod ; } return ( int ) ( res % mod ) ; } int NoOfChords ( int A ) { int mod = 1e9 + 7 ; long long ans = ncr ( 2 * A , A , mod ) ; int inv = power ( A + 1 , mod - 2 , mod ) ; ans = ( ans * inv ) % mod ; return ( int ) ( ans % mod ) ; } int main ( ) { int N = 2 ; cout << NoOfChords ( N ) ; return 0 ; }
Longest Subarray having strictly positive XOR | C ++ implementation of the approach ; Function to return the length of the longest sub - array having positive XOR ; To store the XOR of all the elements ; To check if all the elements of the array are 0 s ; Take XOR of all the elements ; If any positive value is found the make the checkallzero false ; If complete array is the answer ; If all elements are equal to zero ; Initialize l and r ; First positive value of the array ; Last positive value of the array ; Maximum length among these two subarrays ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int StrictlyPositiveXor ( int A [ ] , int N ) { int allxor = 0 ; bool checkallzero = true ; for ( int i = 0 ; i < N ; i += 1 ) { allxor ^= A [ i ] ; if ( A [ i ] > 0 ) checkallzero = false ; } if ( allxor != 0 ) return N ; if ( checkallzero ) return -1 ; int l = N , r = -1 ; for ( int i = 0 ; i < N ; i += 1 ) { if ( A [ i ] > 0 ) { l = i + 1 ; break ; } } for ( int i = N - 1 ; i >= 0 ; i -= 1 ) { if ( A [ i ] > 0 ) { r = i + 1 ; break ; } } return max ( N - l , r - 1 ) ; } int main ( ) { int A [ ] = { 1 , 0 , 0 , 1 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << StrictlyPositiveXor ( A , N ) ; return 0 ; }
Find minimum length sub | C ++ implementation of the approach ; Function to return the minimum length of a sub - array which contains { 0 , 1 , 2 , 3 , 4 } as a sub - sequence ; To store the indices where 0 , 1 , 2 , 3 and 4 are present ; To store if there exist a valid prefix of sequence in array ; Base Case ; If current element is 0 ; Update the count of 0 s till now ; Push the index of the new 0 ; To check if previous element of the given sequence is found till now ; If it is the end of sequence ; Iterate for other elements of the sequence ; Binary Search to find closest occurrence less than equal to starting point ; Update the starting point ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX_INT 1000000 NEW_LINE int solve ( int Array [ ] , int N ) { vector < int > pos [ 5 ] ; int pref [ 5 ] = { 0 } ; if ( Array [ 0 ] == 0 ) { pref [ 0 ] = 1 ; pos [ 0 ] . push_back ( 0 ) ; } int ans = MAX_INT ; for ( int i = 1 ; i < N ; i ++ ) { if ( Array [ i ] == 0 ) { pref [ 0 ] ++ ; pos [ 0 ] . push_back ( i ) ; } else { if ( pref [ Array [ i ] - 1 ] > 0 ) { pref [ Array [ i ] ] ++ ; pos [ Array [ i ] ] . push_back ( i ) ; if ( Array [ i ] == 4 ) { int end = i ; int start = i ; for ( int j = 3 ; j >= 0 ; j -- ) { int s = 0 ; int e = pos [ j ] . size ( ) - 1 ; int temp = -1 ; while ( s <= e ) { int m = ( s + e ) / 2 ; if ( pos [ j ] [ m ] <= start ) { temp = pos [ j ] [ m ] ; s = m + 1 ; } else { e = m - 1 ; } } start = temp ; } ans = min ( ans , end - start + 1 ) ; } } } } return ans ; } int main ( ) { int Array [ ] = { 0 , 1 , 2 , 3 , 4 , 2 , 0 , 3 , 4 } ; int N = sizeof ( Array ) / sizeof ( Array [ 0 ] ) ; cout << solve ( Array , N ) ; return 0 ; }
Find optimal weights which can be used to weigh all the weights in the range [ 1 , X ] | C ++ implementation of the approach ; Function to find the optimal weights ; Number of weights required ; Finding the value of required powers of 3 ; Optimal Weights are powers of 3 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findWeights ( int X ) { int sum = 0 ; int power = 0 ; while ( sum < X ) { sum = pow ( 3 , power + 1 ) - 1 ; sum /= 2 ; power ++ ; } int ans = 1 ; for ( int i = 1 ; i <= power ; i ++ ) { cout << ans << " ▁ " ; ans = ans * 3 ; } } int main ( ) { int X = 2 ; findWeights ( X ) ; return 0 ; }
Order of indices which is lexicographically smallest and sum of elements is <= X | C ++ implementation of the approach ; Function to return the chosen indices ; Maximum indices chosen ; Try to replace the first element in ans by i , making the order lexicographically smaller ; If no further replacement possible return ; If found an index smaller than ind and sum not exceeding X then remove index of smallest value from ans and then add index i to ans ; Driver code ; Print the chosen indices
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > solve ( int X , vector < int > & A ) { int min = INT_MAX ; int ind = -1 ; for ( int i = 0 ; i < A . size ( ) ; i ++ ) { if ( A [ i ] < min ) { min = A [ i ] ; ind = i ; } } int maxIndChosen = X / min ; vector < int > ans ; if ( maxIndChosen == 0 ) { return ans ; } for ( int i = 0 ; i < maxIndChosen ; i ++ ) { ans . push_back ( ind ) ; } int temp = maxIndChosen ; int sum = maxIndChosen * A [ ind ] ; for ( int i = 0 ; i < ind ; i ++ ) { if ( sum - X == 0 temp == 0 ) break ; while ( ( sum - A [ ind ] + A [ i ] ) <= X && temp != 0 ) { ans . erase ( ans . begin ( ) ) ; ans . push_back ( i ) ; temp -- ; sum += ( A [ i ] - A [ ind ] ) ; } } sort ( ans . begin ( ) , ans . end ( ) ) ; return ans ; } int main ( ) { vector < int > A = { 5 , 6 , 4 , 8 } ; int X = 18 ; vector < int > ans = solve ( X , A ) ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) cout << ans [ i ] << " ▁ " ; return 0 ; }
Find if a binary matrix exists with given row and column sums | C ++ implementation of the above approach ; Function to check if matrix exists ; Store sum of rowsums , max of row sum number of non zero row sums ; Store sum of column sums , max of column sum number of non zero column sums ; Check condition 1 , 2 , 3 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool matrix_exist ( int row [ ] , int column [ ] , int r , int c ) { int row_sum = 0 ; int column_sum = 0 ; int row_max = -1 ; int column_max = -1 ; int row_non_zero = 0 ; int column_non_zero = 0 ; for ( int i = 0 ; i < r ; i ++ ) { row_sum += row [ i ] ; row_max = max ( row_max , row [ i ] ) ; if ( row [ i ] ) row_non_zero ++ ; } for ( int i = 0 ; i < c ; i ++ ) { column_sum += column [ i ] ; column_max = max ( column_max , column [ i ] ) ; if ( column [ i ] ) column_non_zero ++ ; } if ( ( row_sum != column_sum ) || ( row_max > column_non_zero ) || ( column_max > row_non_zero ) ) return false ; return true ; } int main ( ) { int row [ ] = { 2 , 2 , 2 , 2 , 2 } ; int column [ ] = { 5 , 5 , 0 , 0 } ; int r = sizeof ( row ) / sizeof ( row [ 0 ] ) ; int c = sizeof ( column ) / sizeof ( column [ 0 ] ) ; if ( matrix_exist ( row , column , r , c ) ) cout << " YES STRNEWLINE " ; else cout << " NO STRNEWLINE " ; }