text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Maximum number of uncrossed lines between two given arrays | C ++ program for the above approach ; Function to count maximum number of uncrossed lines between the two given arrays ; Stores the length of lcs obtained upto every index ; Iterate over first array ; Iterate over second array ; Update value in dp table ; If both characters are equal ; Update the length of lcs ; If both characters are not equal ; Update the table ; Return the answer ; Driver Code ; Given array A [ ] and B [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int uncrossedLines ( int * a , int * b , int n , int m ) { int dp [ n + 1 ] [ m + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) { for ( int j = 0 ; j <= m ; j ++ ) { if ( i == 0 j == 0 ) dp [ i ] [ j ] = 0 ; else if ( a [ i - 1 ] == b [ j - 1 ] ) dp [ i ] [ j ] = 1 + dp [ i - 1 ] [ j - 1 ] ; else dp [ i ] [ j ] = max ( dp [ i - 1 ] [ j ] , dp [ i ] [ j - 1 ] ) ; } } return dp [ n ] [ m ] ; } int main ( ) { int A [ ] = { 3 , 9 , 2 } ; int B [ ] = { 3 , 2 , 9 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int M = sizeof ( B ) / sizeof ( B [ 0 ] ) ; cout << uncrossedLines ( A , B , N , M ) ; return 0 ; } |
Minimize flips required to make all shortest paths from top | C ++ program for the above approach ; Function to count the minimum number of flips required ; Dimensions of matrix ; Stores the count the flips ; Check if element is same or not ; Return the final count ; Driver Code ; Given Matrix ; Given path as a string ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minFlips ( vector < vector < int > > & mat , string s ) { int N = mat . size ( ) ; int M = mat [ 0 ] . size ( ) ; int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( mat [ i ] [ j ] != s [ i + j ] - '0' ) { count ++ ; } } } return count ; } int main ( ) { vector < vector < int > > mat = { { 1 , 0 , 1 } , { 0 , 1 , 1 } , { 0 , 0 , 0 } } ; string s = "10001" ; cout << minFlips ( mat , s ) ; return 0 ; } |
Generate a pair of integers from a range [ L , R ] whose LCM also lies within the range | C ++ implementation of the above approach ; Checking if any pair is possible or not in range ( l , r ) ; If not possible print ( - 1 ) ; Print LCM pair ; Driver code ; Function call | #include <iostream> NEW_LINE using namespace std ; void lcmpair ( int l , int r ) { int x , y ; x = l ; y = 2 * l ; if ( y > r ) { cout << " - 1 STRNEWLINE " ; } else { cout << " X β = β " << x << " β Y β = β " << y << " STRNEWLINE " ; } } int main ( ) { int l = 13 , r = 69 ; lcmpair ( l , r ) ; return 0 ; } |
Print all possible shortest chains to reach a target word | C ++ Program to implement the above approach ; Function to print all possible shortest sequences starting from start to target . ; Find words differing by a single character with word ; Find next word in dict by changing each element from ' a ' to ' z ' ; Function to get all the shortest possible sequences starting from ' start ' to ' target ' ; Store all the shortest path . ; Store visited words in list ; Queue used to find the shortest path ; Stores the distinct words from given list ; Stores whether the shortest path is found or not ; Explore the next level ; Find words differing by a single character ; Add words to the path . ; Found the target ; If already reached target ; Erase all visited words . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void displaypath ( vector < vector < string > > & res ) { for ( int i = 0 ; i < res . size ( ) ; i ++ ) { cout << " [ β " ; for ( int j = 0 ; j < res [ 0 ] . size ( ) ; j ++ ) { cout << res [ i ] [ j ] << " , β " ; } cout << " β ] STRNEWLINE " ; } } vector < string > addWord ( string word , unordered_set < string > & dict ) { vector < string > res ; for ( int i = 0 ; i < word . size ( ) ; i ++ ) { char s = word [ i ] ; for ( char c = ' a ' ; c <= ' z ' ; c ++ ) { word [ i ] = c ; if ( dict . count ( word ) ) res . push_back ( word ) ; } word [ i ] = s ; } return res ; } vector < vector < string > > findLadders ( vector < string > & Dict , string beginWord , string endWord ) { vector < vector < string > > res ; unordered_set < string > visit ; queue < vector < string > > q ; unordered_set < string > dict ( Dict . begin ( ) , Dict . end ( ) ) ; q . push ( { beginWord } ) ; bool flag = false ; while ( ! q . empty ( ) ) { int size = q . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { vector < string > cur = q . front ( ) ; q . pop ( ) ; vector < string > newadd ; newadd = addWord ( cur . back ( ) , dict ) ; for ( int j = 0 ; j < newadd . size ( ) ; j ++ ) { vector < string > newline ( cur . begin ( ) , cur . end ( ) ) ; newline . push_back ( newadd [ j ] ) ; if ( newadd [ j ] == endWord ) { flag = true ; res . push_back ( newline ) ; } visit . insert ( newadd [ j ] ) ; q . push ( newline ) ; } } if ( flag ) { break ; } for ( auto it : visit ) { dict . erase ( it ) ; } visit . clear ( ) ; } return res ; } int main ( ) { vector < string > str { " ted " , " tex " , " red " , " tax " , " tad " , " den " , " rex " , " pee " } ; string beginWord = " red " ; string endWord = " tax " ; vector < vector < string > > res = findLadders ( str , beginWord , endWord ) ; displaypath ( res ) ; } |
Count non | C ++ Program to implement the above approach ; Function to reverse a number ; Store the reverse of N ; Return reverse of N ; Function to get the count of non - palindromic numbers having same first and last digit ; Store the required count ; Traverse the array ; Store reverse of arr [ i ] ; Check for palindrome ; IF non - palindromic ; Check if first and last digits are equal ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int revNum ( int N ) { int x = 0 ; while ( N ) { x = x * 10 + N % 10 ; N = N / 10 ; } return x ; } int ctNonPalin ( int arr [ ] , int N ) { int Res = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int x = revNum ( arr [ i ] ) ; if ( x == arr [ i ] ) { continue ; } else { Res += ( arr [ i ] % 10 == N % 10 ) ; } } return Res ; } int main ( ) { int arr [ ] = { 121 , 134 , 2342 , 4514 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ctNonPalin ( arr , N ) ; } |
Smallest subarray from a given Array with sum greater than or equal to K | Set 2 | C ++ program for the above approach ; Function to find the smallest subarray with sum greater than or equal target ; DP table to store the computed subproblems ; Initialize first column with 0 ; Initialize first row with 0 ; Check for invalid condition ; Fill up the dp table ; Print the minimum length ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minlt ( vector < int > arr , int target , int n ) { vector < vector < int > > dp ( arr . size ( ) + 1 , vector < int > ( target + 1 , -1 ) ) ; for ( int i = 0 ; i < arr . size ( ) + 1 ; i ++ ) dp [ i ] [ 0 ] = 0 ; for ( int j = 0 ; j < target + 1 ; j ++ ) dp [ 0 ] [ j ] = INT_MAX ; for ( int i = 1 ; i <= arr . size ( ) ; i ++ ) { for ( int j = 1 ; j <= target ; j ++ ) { if ( arr [ i - 1 ] > j ) { dp [ i ] [ j ] = dp [ i - 1 ] [ j ] ; } else { dp [ i ] [ j ] = min ( dp [ i - 1 ] [ j ] , ( dp [ i ] [ j - arr [ i - 1 ] ] ) != INT_MAX ? ( dp [ i ] [ j - arr [ i - 1 ] ] + 1 ) : INT_MAX ) ; } } } if ( dp [ arr . size ( ) ] [ target ] == INT_MAX ) { return -1 ; } else { return dp [ arr . size ( ) ] [ target ] ; } } int main ( ) { vector < int > arr = { 2 , 3 , 5 , 4 , 1 } ; int target = 11 ; int n = arr . size ( ) ; cout << minlt ( arr , target , n ) ; } |
Minimum absolute difference of server loads | C ++ 14 program to implement the above approach ; Function which returns the minimum difference of loads ; Compute the overall server load ; Stores the results of subproblems ; Fill the partition table in bottom up manner ; If i - th server is included ; If i - th server is excluded ; Server A load : total_sum - ans Server B load : ans Diff : abs ( total_sum - 2 * ans ) ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minServerLoads ( int n , vector < int > & servers ) { int totalLoad = 0 ; for ( int i : servers ) totalLoad += i ; int requiredLoad = totalLoad / 2 ; vector < vector < int > > dp ( n + 1 , vector < int > ( requiredLoad + 1 , 0 ) ) ; for ( int i = 1 ; i < n + 1 ; i ++ ) { for ( int j = 1 ; j < requiredLoad + 1 ; j ++ ) { if ( servers [ i - 1 ] > j ) dp [ i ] [ j ] = dp [ i - 1 ] [ j ] ; else dp [ i ] [ j ] = max ( dp [ i - 1 ] [ j ] , servers [ i - 1 ] + dp [ i - 1 ] [ j - servers [ i - 1 ] ] ) ; } } return totalLoad - 2 * dp [ n ] [ requiredLoad ] ; } int main ( ) { int N = 5 ; vector < int > servers = { 1 , 2 , 3 , 4 , 5 } ; cout << ( minServerLoads ( N , servers ) ) ; } |
Length of longest subarray with positive product | C ++ program to implement the above approach ; Function to find the length of longest subarray whose product is positive ; Stores the length of current subarray with positive product ; Stores the length of current subarray with negative product ; Stores the length of the longest subarray with positive product ; Reset the value ; If current element is positive ; Increment the length of subarray with positive product ; If at least one element is present in the subarray with negative product ; Update res ; If current element is negative ; Increment the length of subarray with negative product ; If at least one element is present in the subarray with positive product ; Update res ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxLenSub ( int arr [ ] , int N ) { int Pos = 0 ; int Neg = 0 ; int res = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == 0 ) { Pos = Neg = 0 ; } else if ( arr [ i ] > 0 ) { Pos += 1 ; if ( Neg != 0 ) { Neg += 1 ; } res = max ( res , Pos ) ; } else { swap ( Pos , Neg ) ; Neg += 1 ; if ( Pos != 0 ) { Pos += 1 ; } res = max ( res , Pos ) ; } } return res ; } int main ( ) { int arr [ ] = { -1 , -2 , -3 , 0 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxLenSub ( arr , N ) ; } |
Print all strings of maximum length from an array of strings | C ++ program to implement the above approach ; Function to find the length of the longest string from the given array of strings ; Traverse the array ; Stores the length of current string ; Update maximum length ; Return the maximum length ; Function to print the longest strings from the array ; Find the strings having length equals to len ; Print the resultant vector of strings ; Function to print all the longest strings from the array ; Find the length of longest string ; Find and print all the strings having length equals to max ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxLength ( vector < string > arr ) { int len = INT_MIN ; int N = arr . size ( ) ; for ( int i = 0 ; i < N ; i ++ ) { int l = arr [ i ] . size ( ) ; if ( len < l ) { len = l ; } } return len ; } void maxStrings ( vector < string > arr , int len ) { int N = arr . size ( ) ; vector < string > ans ; for ( int i = 0 ; i < N ; i ++ ) { if ( len == arr [ i ] . size ( ) ) { ans . push_back ( arr [ i ] ) ; } } for ( int i = 0 ; i < ans . size ( ) ; i ++ ) { cout << ans [ i ] << " β " ; } } void printStrings ( vector < string > & arr ) { int max = maxLength ( arr ) ; maxStrings ( arr , max ) ; } int main ( ) { vector < string > arr = { " aba " , " aa " , " ad " , " vcd " , " aba " } ; printStrings ( arr ) ; return 0 ; } |
Minimize count of flips required such that no substring of 0 s have length exceeding K | C ++ program to implement the above approach ; Function to return minimum number of flips required ; Base Case ; Stores the count of minimum number of flips ; Stores the count of zeros in current substring ; If current character is 0 ; Continue ongoing substring ; Start a new substring ; If k consecutive zeroes are obtained ; End segment ; Return the result ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int min_flips ( string & str , int k ) { if ( str . size ( ) == 0 ) return 0 ; int ans = 0 ; int cnt_zeros = 0 ; for ( char ch : str ) { if ( ch == '0' ) { ++ cnt_zeros ; } else { cnt_zeros = 0 ; } if ( cnt_zeros == k ) { ++ ans ; cnt_zeros = 0 ; } } return ans ; } int main ( ) { string str = "11100000011" ; int k = 3 ; cout << min_flips ( str , k ) ; return 0 ; } |
Find all possible subarrays having product less than or equal to K | C ++ program to implement the above approach ; Function to return all possible subarrays having product less than or equal to K ; Store the required subarrays ; Stores the product of current subarray ; Stores the starting index of the current subarray ; Check for empty array ; Iterate over the array ; Calculate product ; If product exceeds K ; Reduce product ; Increase starting index of current subarray ; Stores the subarray elements ; Store the subarray elements ; Add the subarrays to the list ; Return the final list of subarrays ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < vector < int > > maxSubArray ( int arr [ ] , int n , int K ) { vector < vector < int > > solution ; int multi = 1 ; int start = 0 ; if ( n <= 1 K < 0 ) { return solution ; } for ( int i = 0 ; i < n ; i ++ ) { multi = multi * arr [ i ] ; while ( multi > K ) { multi = multi / arr [ start ] ; start ++ ; } vector < int > list ; for ( int j = i ; j >= start ; j -- ) { list . insert ( list . begin ( ) , arr [ j ] ) ; solution . push_back ( list ) ; } } return solution ; } int main ( ) { int arr [ ] = { 2 , 7 , 1 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 7 ; vector < vector < int > > v = maxSubArray ( arr , n , K ) ; cout << " [ " ; bool first = true ; for ( auto x : v ) { if ( ! first ) { cout << " , β " ; } else { first = false ; } cout << " [ " ; bool ff = true ; for ( int y : x ) { if ( ! ff ) { cout << " , β " ; } else { ff = false ; } cout << y ; } cout << " ] " ; } cout << " ] " ; return 0 ; } |
Count of collisions at a point ( X , Y ) | C ++ 14 program to implement the above approach ; Function to find the count of possible pairs of collisions ; Stores the time at which points reach the origin ; Calculate time for each point ; Sort the times ; Counting total collisions ; Count of elements arriving at a given point at the same time ; Driver Code ; Given set of points with speed ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( vector < vector < int > > & D , int N , int X , int Y ) { vector < double > T ; for ( int i = 0 ; i < N ; i ++ ) { int x = D [ i ] [ 0 ] ; int y = D [ i ] [ 1 ] ; double speed = D [ i ] [ 2 ] ; double time = ( ( x * x - X * X ) + ( y * y - Y * Y ) ) / ( speed * speed ) ; T . push_back ( time ) ; } sort ( T . begin ( ) , T . end ( ) ) ; int i = 0 ; int total = 0 ; while ( i < T . size ( ) - 1 ) { int count = 1 ; while ( i < T . size ( ) - 1 and T [ i ] == T [ i + 1 ] ) { count += 1 ; i += 1 ; } total += ( count * ( count - 1 ) ) / 2 ; i += 1 ; } return total ; } int main ( ) { int N = 5 ; vector < vector < int > > D = { { 5 , 12 , 1 } , { 16 , 63 , 5 } , { -10 , 24 , 2 } , { 7 , 24 , 2 } , { -24 , 7 , 2 } } ; int X = 0 , Y = 0 ; cout << ( solve ( D , N , X , Y ) ) ; return 0 ; } |
Longest subarray forming an Arithmetic Progression ( AP ) | C ++ Program to implement the above approach ; Function to return the length of longest subarray forming an AP ; Minimum possible length of required subarray is 2 ; Stores the length of the current subarray ; Stores the common difference of the current AP ; Stores the common difference of the previous AP ; If the common differences are found to be equal ; Continue the previous subarray ; Start a new subarray ; Update the length to store maximum length ; Update the length to store maximum length ; Return the length of the longest subarray ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getMaxLength ( int arr [ ] , int N ) { int res = 2 ; int dist = 2 ; int curradj = ( arr [ 1 ] - arr [ 0 ] ) ; int prevadj = ( arr [ 1 ] - arr [ 0 ] ) ; for ( int i = 2 ; i < N ; i ++ ) { curradj = arr [ i ] - arr [ i - 1 ] ; if ( curradj == prevadj ) { dist ++ ; } else { prevadj = curradj ; res = max ( res , dist ) ; dist = 2 ; } } res = max ( res , dist ) ; return res ; } int main ( ) { int arr [ ] = { 10 , 7 , 4 , 6 , 8 , 10 , 11 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << getMaxLength ( arr , N ) ; } |
Minimize cost to empty a given string by removing characters alphabetically | C ++ program for the above approach ; Function to find the minimum cost required to remove each character of the string in alphabetical order ; Stores the frequency of characters of the string ; Iterate through the string ; Count the number of characters smaller than the present character ; If no smaller character precedes current character ; Increase the frequency of the current character ; Return the total cost ; Driver Code ; Given string str ; Function call | #include <bits/stdc++.h> NEW_LINE #include <vector> NEW_LINE using namespace std ; int minSteps ( string str , int N ) { int smaller , cost = 0 ; int f [ 26 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { int curr_ele = str [ i ] - ' a ' ; smaller = 0 ; for ( int j = 0 ; j <= curr_ele ; j ++ ) { if ( f [ j ] ) smaller += f [ j ] ; } if ( smaller == 0 ) cost += ( i + 1 ) ; else cost += ( i - smaller + 1 ) ; f [ str [ i ] - ' a ' ] ++ ; } return cost ; } int main ( ) { string str = " abcab " ; int N = str . size ( ) ; cout << minSteps ( str , N ) ; return 0 ; } |
Count of Rectangles with area K made up of only 1 s from given Binary Arrays | C ++ Program to implement the above approach ; Function to find the subarrays of all possible lengths made up of only 1 s ; Stores the frequency of the subarrays ; Check if the previous value was also 0 ; If the previous value was 1 ; Find the subarrays of each size from 1 to count ; If A [ ] is of the form ... .111 ; Function to find the count of all possible rectangles ; Size of each of the arrays ; Stores the count of subarrays of each size consisting of only 1 s from array A [ ] ; Stores the count of subarrays of each size consisting of only 1 s from array B [ ] ; Iterating over all subarrays consisting of only 1 s in A [ ] ; If i is a factor of K , then there is a subarray of size K / i in B [ ] ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > findSubarrays ( vector < int > & a ) { int n = a . size ( ) ; vector < int > freq ( n + 1 ) ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == 0 ) { if ( count == 0 ) continue ; else { int value = count ; for ( int j = 1 ; j <= count ; j ++ ) { freq [ j ] += value ; value -- ; } count = 0 ; } } else count ++ ; } if ( count > 0 ) { int value = count ; for ( int j = 1 ; j <= count ; j ++ ) { freq [ j ] += value ; value -- ; } } return freq ; } void countRectangles ( vector < int > & a , vector < int > & b , int K ) { int n = a . size ( ) ; int m = b . size ( ) ; vector < int > subA = findSubarrays ( a ) ; vector < int > subB = findSubarrays ( b ) ; int total = 0 ; for ( int i = 1 ; i < subA . size ( ) ; i ++ ) { if ( K % i == 0 and ( K / i ) <= m ) { total = total + subA [ i ] * subB [ K / i ] ; } } cout << total ; } int main ( ) { vector < int > a = { 0 , 0 , 1 , 1 } ; vector < int > b = { 1 , 0 , 1 } ; int K = 2 ; countRectangles ( a , b , K ) ; return 0 ; } |
Print Longest Bitonic subsequence ( Space Optimized Approach ) | C ++ Program to implement the above approach ; Function to print the longest bitonic subsequence ; Function to generate the longest bitonic subsequence ; Store the lengths of LIS ending at every index ; Store the lengths of LDS ending at every index ; Compute LIS for all indices ; Compute LDS for all indices ; Find the index having maximum value of lis [ i ] + lds [ i ] - 1 ; Stores the count of elements in increasing order in Bitonic subsequence ; Store the increasing subsequence ; Sort the bitonic subsequence to arrange smaller elements at the beginning ; Stores the count of elements in decreasing order in Bitonic subsequence ; Print the longest bitonic sequence ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printRes ( vector < int > & res ) { int n = res . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { cout << res [ i ] << " β " ; } } void printLBS ( int arr [ ] , int N ) { int lis [ N ] ; int lds [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { lis [ i ] = lds [ i ] = 1 ; } for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { if ( arr [ j ] < arr [ i ] ) { if ( lis [ i ] < lis [ j ] + 1 ) lis [ i ] = lis [ j ] + 1 ; } } } for ( int i = N - 1 ; i >= 0 ; i -- ) { for ( int j = N - 1 ; j > i ; j -- ) { if ( arr [ j ] < arr [ i ] ) { if ( lds [ i ] < lds [ j ] + 1 ) lds [ i ] = lds [ j ] + 1 ; } } } int MaxVal = arr [ 0 ] , inx = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( MaxVal < lis [ i ] + lds [ i ] - 1 ) { MaxVal = lis [ i ] + lds [ i ] - 1 ; inx = i ; } } int ct1 = lis [ inx ] ; vector < int > res ; for ( int i = inx ; i >= 0 && ct1 > 0 ; i -- ) { if ( lis [ i ] == ct1 ) { res . push_back ( arr [ i ] ) ; ct1 -- ; } } reverse ( res . begin ( ) , res . end ( ) ) ; int ct2 = lds [ inx ] - 1 ; for ( int i = inx ; i < N && ct2 > 0 ; i ++ ) { if ( lds [ i ] == ct2 ) { res . push_back ( arr [ i ] ) ; ct2 -- ; } } printRes ( res ) ; } int main ( ) { int arr [ ] = { 80 , 60 , 30 , 40 , 20 , 10 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printLBS ( arr , N ) ; } |
Minimum possible value T such that at most D Partitions of the Array having at most sum T is possible | C ++ Program for the above approach ; Function to check if the array can be partitioned into atmost d subarray with sum atmost T ; Initial partition ; Current sum ; If current sum exceeds T ; Create a new partition ; If count of partitions exceed d ; Function to find the minimum possible value of T ; Stores the maximum and total sum of elements ; Maximum element ; Sum of all elements ; Calculate median T ; If atmost D partitions possible ; Check for smaller T ; Otherwise ; Check for larger T ; Print the minimum T required ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool possible ( int T , int arr [ ] , int n , int d ) { int partition = 1 ; int total = 0 ; for ( int i = 0 ; i < n ; i ++ ) { total = total + arr [ i ] ; if ( total > T ) { partition = partition + 1 ; total = arr [ i ] ; if ( partition > d ) { return false ; } } } return true ; } void calcT ( int n , int d , int arr [ ] ) { int mx = -1 , sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { mx = max ( mx , arr [ i ] ) ; sum = sum + arr [ i ] ; } int lb = mx ; int ub = sum ; while ( lb < ub ) { int T_mid = lb + ( ub - lb ) / 2 ; if ( possible ( T_mid , arr , n , d ) == true ) { ub = T_mid ; } else { lb = T_mid + 1 ; } } cout << lb << endl ; } int main ( ) { int d = 2 ; int arr [ ] = { 1 , 1 , 1 , 1 , 1 } ; int n = sizeof arr / sizeof arr [ 0 ] ; calcT ( n , d , arr ) ; return 0 ; } |
Minimize splits to generate monotonous Substrings from given String | C ++ program to implement the above approach ; Function to return final result ; Initialize variable to keep track of ongoing sequence ; If current sequence is neither increasing nor decreasing ; If prev char is greater ; If prev char is same ; Otherwise ; If current sequence is Non - Decreasing ; If prev char is smaller ; If prev char is same ; Update ongoing ; Otherwise ; Update ongoing ; Increase count ; If current sequence is Non - Increasing ; If prev char is greater , then update ongoing with D ; If prev char is equal , then update current with D ; Otherwise , update ongoing with N and increment count ; Return count + 1 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minReqSubstring ( string s , int n ) { char ongoing = ' N ' ; int count = 0 , l = s . size ( ) ; for ( int i = 1 ; i < l ; i ++ ) { if ( ongoing == ' N ' ) { if ( s [ i ] < s [ i - 1 ] ) { ongoing = ' D ' ; } else if ( s [ i ] == s [ i - 1 ] ) { ongoing = ' N ' ; } else { ongoing = ' I ' ; } } else if ( ongoing == ' I ' ) { if ( s [ i ] > s [ i - 1 ] ) { ongoing = ' I ' ; } else if ( s [ i ] == s [ i - 1 ] ) { ongoing = ' I ' ; } else { ongoing = ' N ' ; count += 1 ; } } else { if ( s [ i ] < s [ i - 1 ] ) { ongoing = ' D ' ; } else if ( s [ i ] == s [ i - 1 ] ) { ongoing = ' D ' ; } else { ongoing = ' N ' ; count += 1 ; } } } return count + 1 ; } int main ( ) { string S = " aeccdhba " ; int n = S . size ( ) ; cout << ( minReqSubstring ( S , n ) ) ; return 0 ; } |
Minimum decrements required such that sum of all adjacent pairs in an Array does not exceed K | C ++ program to implement the above approach ; Function to calculate the minimum number of operations required ; Stores the total number of operations ; Iterate over the array ; If the sum of pair of adjacent elements exceed k . ; If current element exceeds k ; Reduce arr [ i ] to k ; Update arr [ i + 1 ] accordingly ; Update answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimum_required_operations ( int arr [ ] , int n , int k ) { int answer = 0 ; long long mod = 1000000007 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( arr [ i ] + arr [ i + 1 ] > k ) { if ( arr [ i ] > k ) { answer += ( arr [ i ] - k ) ; arr [ i ] = k ; } answer += ( arr [ i ] + arr [ i + 1 ] ) - k ; arr [ i + 1 ] = ( k - arr [ i ] ) ; answer %= mod ; } } return answer ; } int main ( ) { int a [ ] = { 9 , 50 , 4 , 14 , 42 , 89 } ; int k = 10 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << ( minimum_required_operations ( a , n , k ) ) ; return 0 ; } |
Lexicographic smallest permutation of a String containing the second String as a Substring | C ++ program to implement the above approach ; Function to print the desired lexicographic smaller string ; Calculate length of the string ; Stores the frequencies of characters of string str1 ; Stores the frequencies of characters of string str2 ; Decrease the frequency of second string from that of of the first string ; To store the resultant string ; To find the index of first character of the string str2 ; Append the characters in lexicographical order ; Append all the current character ( i + ' a ' ) ; If we reach first character of string str2 append str2 ; Return the resultant string ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string findSmallestString ( string str1 , string str2 ) { int freq1 [ 26 ] , freq2 [ 26 ] ; memset ( freq1 , 0 , sizeof freq1 ) ; memset ( freq2 , 0 , sizeof freq2 ) ; int n1 = str1 . length ( ) ; int n2 = str2 . length ( ) ; for ( int i = 0 ; i < n1 ; ++ i ) { freq1 [ str1 [ i ] - ' a ' ] ++ ; } for ( int i = 0 ; i < n2 ; ++ i ) { freq2 [ str2 [ i ] - ' a ' ] ++ ; } for ( int i = 0 ; i < 26 ; ++ i ) { freq1 [ i ] -= freq2 [ i ] ; } string res = " " ; int minIndex = str2 [ 0 ] - ' a ' ; for ( int i = 0 ; i < 26 ; ++ i ) { for ( int j = 0 ; j < freq1 [ i ] ; ++ j ) { res += ( char ) ( i + ' a ' ) ; } if ( i == minIndex ) { res += str2 ; } } return res ; } int main ( ) { string str1 = " geeksforgeeksfor " ; string str2 = " for " ; cout << findSmallestString ( str1 , str2 ) ; } |
Restore original String from given Encrypted String by the given operations | C ++ Program to implement the above approach ; Function to decrypt and print the original strings ; If length is exceeded ; Reverse the string ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int decryptString ( string s , unsigned int N ) { for ( unsigned int i = 0 ; i < s . size ( ) ; i += 2 * N ) { auto end = s . begin ( ) + i + N ; if ( i + N > s . size ( ) ) end = s . end ( ) ; reverse ( s . begin ( ) + i , end ) ; } cout << s << endl ; } int main ( ) { string s = " ihTs β suohld β ebeas ! y " ; unsigned int N = 3 ; decryptString ( s , N ) ; return 0 ; } |
Determine the winner of a game of deleting Characters from a String | C ++ program for the above approach ; Function to find the winner of the game when both players play optimally ; Stores the frequency of all digit ; Stores the scores of player1 and player2 respectively ; Iterate to store frequencies ; Turn for the player1 ; Add score of player1 ; Add score of player2 ; Check if its a draw ; If score of player 1 is greater ; Otherwise ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void determineWinner ( string str ) { vector < int > A ( 10 ) ; int sum1 = 0 , sum2 = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { A [ int ( str [ i ] ) - 48 ] ++ ; } for ( int i = 0 ; i <= 9 ; i ++ ) { if ( i % 2 != 0 ) { sum1 = sum1 + A [ i ] ; } else { sum2 = sum2 + A [ i ] ; } } if ( sum1 == sum2 ) { cout << " - 1" ; } else if ( sum1 > sum2 ) { cout << " Player β 1" ; } else { cout << " Player β 2" ; } } int main ( ) { string str = "78787" ; determineWinner ( str ) ; return 0 ; } |
Generate a String from given Strings P and Q based on the given conditions | C ++ program to implement the above approach ; Function to generate a string S from string P and Q according to the given conditions ; Stores the frequencies ; Counts occurrences of each characters ; Reduce the count of the character which is also present in Q ; Stores the resultant string ; Index in freq [ ] to segregate the string ; Add Q to the resulting string ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void manipulateStrings ( string P , string Q ) { int freq [ 26 ] ; memset ( freq , 0 , sizeof ( freq ) ) ; for ( int i = 0 ; i < P . size ( ) ; i ++ ) { freq [ P [ i ] - ' a ' ] ++ ; } for ( int i = 0 ; i < Q . size ( ) ; i ++ ) { freq [ Q [ i ] - ' a ' ] -- ; } string sb = " " ; int pos = Q [ 0 ] - ' a ' ; for ( int i = 0 ; i <= pos ; i ++ ) { while ( freq [ i ] > 0 ) { char c = ( char ) ( ' a ' + i ) ; sb += c ; freq [ i ] -- ; } } sb += Q ; for ( int i = pos + 1 ; i < 26 ; i ++ ) { while ( freq [ i ] > 0 ) { char c = ( char ) ( ' a ' + i ) ; sb += c ; freq [ i ] -- ; } } cout << sb << endl ; } int main ( ) { string P = " geeksforgeeksfor " ; string Q = " for " ; manipulateStrings ( P , Q ) ; } |
Minimum moves required to type a word in QWERTY based keyboard | C ++ program for the above approach ; Function that calculates the moves required to print the current string ; row1 has qwertyuiop , row2 has asdfghjkl , and row3 has zxcvbnm Store the row number of each character ; String length ; Initialise move to 1 ; Traverse the string ; If current row number is not equal to previous row then increment the moves ; Return the moves ; Driver Code ; Given String str ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int numberMoves ( string s ) { int row [ ] = { 2 , 3 , 3 , 2 , 1 , 2 , 2 , 2 , 1 , 2 , 2 , 2 , 3 , 3 , 1 , 1 , 1 , 1 , 2 , 1 , 1 , 3 , 1 , 3 , 1 , 3 } ; int n = s . length ( ) ; int move = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( row [ s [ i ] - ' a ' ] != row [ s [ i - 1 ] - ' a ' ] ) { move ++ ; } } return move ; } int main ( ) { string str = " geeksforgeeks " ; cout << numberMoves ( str ) ; return 0 ; } |
Queries to calculate the Sum of Array elements in the range [ L , R ] having indices as multiple of K | C ++ Program to implement the above approach ; Structure of a Query ; Function to calculate the sum of array elements at indices from range [ L , R ] which are multiples of K for each query ; Stores Prefix Sum ; prefixSum [ i ] [ j ] : Stores the sum from indices [ 0 , j ] which are multiples of i ; If index j is a multiple of i ; Compute prefix sum ; Otherwise ; Traverse each query ; Sum of all indices upto R which are a multiple of K ; Sum of all indices upto L - 1 which are a multiple of K ; Calculate the difference ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int L ; int R ; int K ; } ; int kMultipleSum ( int arr [ ] , Node Query [ ] , int N , int Q ) { int prefixSum [ N + 1 ] [ N ] ; for ( int i = 1 ; i <= N ; i ++ ) { prefixSum [ i ] [ 0 ] = arr [ 0 ] ; for ( int j = 0 ; j < N ; j ++ ) { if ( j % i == 0 ) { prefixSum [ i ] [ j ] = arr [ j ] + prefixSum [ i ] [ j - 1 ] ; } else { prefixSum [ i ] [ j ] = prefixSum [ i ] [ j - 1 ] ; } } } for ( int i = 0 ; i < Q ; i ++ ) { int last = prefixSum [ Query [ i ] . K ] [ Query [ i ] . R ] ; int first ; if ( Query [ i ] . L == 0 ) { first = prefixSum [ Query [ i ] . K ] [ Query [ i ] . L ] ; } else { first = prefixSum [ Query [ i ] . K ] [ Query [ i ] . L - 1 ] ; } cout << last - first << endl ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int Q = 2 ; Node Query [ Q ] ; Query [ 0 ] . L = 2 , Query [ 0 ] . R = 5 , Query [ 0 ] . K = 2 ; Query [ 1 ] . L = 3 , Query [ 1 ] . R = 5 , Query [ 1 ] . K = 5 ; kMultipleSum ( arr , Query , N , Q ) ; } |
Count of distinct Strings possible by swapping prefixes of pairs of Strings from the Array | C ++ program to implement the above approach ; Function to count the distinct strings possible after swapping the prefixes between two possible strings of the array ; Stores the count of unique characters for each index ; Store current string ; Stores the total number of distinct strings possible ; Return the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int mod = 1000000007 ; long countS ( string str [ ] , int n , int m ) { unordered_map < int , unordered_set < char > > counts ; for ( int i = 0 ; i < n ; i ++ ) { string s = str [ i ] ; for ( int j = 0 ; j < m ; j ++ ) { counts [ j ] . insert ( s [ j ] ) ; } } long result = 1 ; for ( auto index : counts ) { result = ( result * counts [ index . first ] . size ( ) ) % mod ; } return result ; } int main ( ) { string str [ ] = { "112" , "211" } ; int N = 2 , M = 3 ; cout << countS ( str , N , M ) ; return 0 ; } |
Longest Subarrays having each Array element as the maximum | C ++ Program to implement the above approach ; Function to find the maximum length of Subarrays for each element of the array having it as the maximum ; Initialize the bounds ; Iterate to find greater element on the left ; If greater element is found ; Decrement left pointer ; If boundary is exceeded ; Iterate to find greater element on the right ; If greater element is found ; Increment right pointer ; If boundary is exceeded ; Length of longest subarray where arr [ i ] is the largest ; Print the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( int n , int arr [ ] ) { int i , ans = 0 ; for ( i = 0 ; i < n ; i ++ ) { int left = max ( i - 1 , 0 ) ; int right = min ( n - 1 , i + 1 ) ; while ( left >= 0 ) { if ( arr [ left ] > arr [ i ] ) { left ++ ; break ; } left -- ; } if ( left < 0 ) left ++ ; while ( right < n ) { if ( arr [ right ] > arr [ i ] ) { right -- ; break ; } right ++ ; } if ( right >= n ) right -- ; ans = 1 + right - left ; cout << ans << " β " ; } } int main ( ) { int arr [ ] = { 4 , 2 , 1 } ; int n = sizeof arr / sizeof arr [ 0 ] ; solve ( n , arr ) ; return 0 ; } |
Count of Substrings having Sum equal to their Length | C ++ Program to implement the above approach ; Function to count the number of substrings with sum equal to length ; Stores the count of substrings ; Add character to sum ; Add count of substrings to result ; Increase count of subarrays ; Return count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubstrings ( string s , int n ) { int count = 0 , sum = 0 ; unordered_map < int , int > mp ; mp [ 0 ] ++ ; for ( int i = 0 ; i < n ; ++ i ) { sum += ( s [ i ] - '0' ) ; count += mp [ sum - ( i + 1 ) ] ; ++ mp [ sum - ( i + 1 ) ] ; } return count ; } int main ( ) { string str = "112112" ; int n = str . length ( ) ; cout << countSubstrings ( str , n ) << endl ; return 0 ; } |
Count of ways to split an Array into three contiguous Subarrays having increasing Sum | C ++ program to implement the above approach ; Function to count the number of ways to split array into three contiguous subarrays of the required type ; Stores the prefix sums ; Stores the suffix sums ; Traverse the given array ; Updating curr_subarray_sum until it is less than prefix_sum [ s - 1 ] ; Increase count ; Decrease curr_subarray_sum by arr [ s [ ] ; Return count ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findCount ( int arr [ ] , int n ) { int prefix_sum [ n ] ; prefix_sum [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) prefix_sum [ i ] = prefix_sum [ i - 1 ] + arr [ i ] ; int suffix_sum [ n ] ; suffix_sum [ n - 1 ] = arr [ n - 1 ] ; for ( int i = n - 2 ; i >= 0 ; i -- ) suffix_sum [ i ] = suffix_sum [ i + 1 ] + arr [ i ] ; int s = 1 , e = 1 ; int curr_subarray_sum = 0 , count = 0 ; while ( s < n - 1 && e < n - 1 ) { while ( e < n - 1 && curr_subarray_sum < prefix_sum [ s - 1 ] ) { curr_subarray_sum += arr [ e ++ ] ; } if ( curr_subarray_sum <= suffix_sum [ e ] ) { count ++ ; } curr_subarray_sum -= arr [ s ++ ] ; } return count ; } int32_t main ( ) { int arr [ ] = { 2 , 3 , 1 , 7 } ; int n = sizeof arr / sizeof arr [ 0 ] ; cout << ( findCount ( arr , n ) ) ; } |
Minimum number of operations required to maximize the Binary String | C ++ Program to implement the above approach ; Function to find the number of operations required ; Count of 1 's ; Count of 0 's upto (cnt1)-th index ; Return the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperation ( string s , int n ) { int cnt1 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == '1' ) cnt1 ++ ; } int cnt0 = 0 ; for ( int i = 0 ; i < cnt1 ; i ++ ) { if ( s [ i ] == '0' ) cnt0 ++ ; } return cnt0 ; } int main ( ) { int n = 8 ; string s = "01001011" ; int ans = minOperation ( s , n ) ; cout << ans << endl ; } |
Minimum number of operations required to maximize the Binary String | C ++ Program to implement the above approach ; Function to find the number of operations required ; Swap 0 ' s β and β 1' s ; Return the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperation ( string s , int n ) { int ans = 0 ; int i = 0 , j = n - 1 ; while ( i < j ) { if ( s [ i ] == '0' && s [ j ] == '1' ) { ans ++ ; i ++ ; j -- ; continue ; } if ( s [ i ] == '1' ) { i ++ ; } if ( s [ j ] == '0' ) { j -- ; } } return ans ; } int main ( ) { int n = 8 ; string s = "10100101" ; int ans = minOperation ( s , n ) ; cout << ans << endl ; } |
Count of N digit Numbers having no pair of equal consecutive Digits | C ++ Program to implement the above approach ; Function to count the number of N - digit numbers with no equal pair of consecutive digits ; Base Case ; Calculate the total count of valid ( i - 1 ) - digit numbers ; Update dp [ ] [ ] table ; Calculate the count of required N - digit numbers ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void count ( int N ) { if ( N == 1 ) { cout << ( 10 ) << endl ; return ; } int dp [ N ] [ 10 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; for ( int i = 1 ; i < 10 ; i ++ ) dp [ 0 ] [ i ] = 1 ; for ( int i = 1 ; i < N ; i ++ ) { int temp = 0 ; for ( int j = 0 ; j < 10 ; j ++ ) temp += dp [ i - 1 ] [ j ] ; for ( int j = 0 ; j < 10 ; j ++ ) dp [ i ] [ j ] = temp - dp [ i - 1 ] [ j ] ; } int ans = 0 ; for ( int i = 0 ; i < 10 ; i ++ ) ans += dp [ N - 1 ] [ i ] ; cout << ans << endl ; } int main ( ) { int N = 2 ; count ( N ) ; return 0 ; } |
Count of N digit Numbers having no pair of equal consecutive Digits | C ++ program to implement the above approach ; Iterative Function to calculate ( x ^ y ) % mod in O ( log y ) ; Initialize result ; Update x if x >= mod ; If x is divisible by mod ; If y is odd , multiply x with result ; y must be even now y = y / 2 ; Function to count the number of N - digit numbers with no equal pair of consecutive digits ; Base Case ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int power ( int x , int y , int mod ) { int res = 1 ; x = x % mod ; if ( x == 0 ) return 0 ; while ( y > 0 ) { if ( ( y & 1 ) == 1 ) res = ( res * x ) % mod ; y = y >> 1 ; x = ( x * x ) % mod ; } return res ; } void count ( int N ) { if ( N == 1 ) { cout << 10 << endl ; return ; } cout << ( power ( 9 , N , 1000000007 ) ) << endl ; } int main ( ) { int N = 3 ; count ( N ) ; return 0 ; } |
Smallest String consisting of a String S exactly K times as a Substring | C ++ Program to implement the above approach ; KMP algorithm ; Function to return the required string ; Finding the longest proper prefix which is also suffix ; ans string ; Update ans appending the substring K - 1 times ; Append the original string ; Returning min length string which contain exactly k substring of given string ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int * kmp ( string & s ) { int n = s . size ( ) ; int * lps = new int [ n ] ; lps [ 0 ] = 0 ; int i = 1 , len = 0 ; while ( i < n ) { if ( s [ i ] == s [ len ] ) { len ++ ; lps [ i ] = len ; i ++ ; } else { if ( len != 0 ) { len = lps [ len - 1 ] ; } else { lps [ i ] = 0 ; i ++ ; } } } return lps ; } string findString ( string & s , int k ) { int n = s . length ( ) ; int * lps = kmp ( s ) ; string ans = " " ; string suff = s . substr ( 0 , n - lps [ n - 1 ] ) ; for ( int i = 0 ; i < k - 1 ; ++ i ) { ans += suff ; } ans += s ; return ans ; } int main ( ) { int k = 3 ; string s = " geeksforgeeks " ; cout << findString ( s , k ) << endl ; } |
Check if an Array can be Sorted by picking only the corner Array elements | C ++ Program to implement the above approach ; Function to check if an array can be sorted using given operations ; If sequence becomes increasing after an already non - decreasing to non - increasing pattern ; If a decreasing pattern is observed ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int arr [ ] , int n ) { int i , g ; g = 0 ; for ( i = 1 ; i < n ; i ++ ) { if ( arr [ i ] - arr [ i - 1 ] > 0 && g == 1 ) return false ; if ( arr [ i ] - arr [ i - 1 ] < 0 ) g = 1 ; } return true ; } int main ( ) { int arr [ ] = { 2 , 3 , 4 , 10 , 4 , 3 , 1 } ; int n = sizeof ( arr ) / sizeof ( int ) ; if ( check ( arr , n ) == true ) cout << " Yes " " STRNEWLINE " ; else cout << " No " << " STRNEWLINE " ; return 0 ; } |
Queries to find the count of connected Non | C ++ program to implement the above approach ; Count of connected cells ; Function to return the representative of the Set to which x belongs ; If x is parent of itself ; x is representative of the Set ; Otherwise ; Path Compression ; Unites the set that includes x and the set that includes y ; Find the representatives ( or the root nodes ) for x an y ; If both are in the same set ; Decrement count ; If x ' s β rank β is β less β than β y ' s rank ; Otherwise ; Then move x under y ( doesn 't matter which one goes where) ; And increment the result tree 's rank by 1 ; Function to count the number of connected cells in the matrix ; Store result for queries ; Store representative of each element ; Initially , all elements are in their own set ; Stores the rank ( depth ) of each node ; If the grid [ x * m + y ] is already set , store the result ; Set grid [ x * m + y ] to 1 ; Increment count . ; Check for all adjacent cells to do a Union with neighbour 's set if neighbour is also 1 ; Store result . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int ctr = 0 ; int find ( vector < int > & parent , int x ) { if ( parent [ x ] == x ) return x ; parent [ x ] = find ( parent , parent [ x ] ) ; return parent [ x ] ; } void setUnion ( vector < int > & parent , vector < int > & rank , int x , int y ) { int parentx = find ( parent , x ) ; int parenty = find ( parent , y ) ; if ( parenty == parentx ) return ; ctr -- ; if ( rank [ parentx ] < rank [ parenty ] ) { parent [ parentx ] = parenty ; } else if ( rank [ parentx ] > rank [ parenty ] ) { parent [ parenty ] = parentx ; } else { parent [ parentx ] = parenty ; rank [ parenty ] ++ ; } } vector < int > solve ( int n , int m , vector < pair < int , int > > & query ) { vector < int > result ( query . size ( ) ) ; vector < int > parent ( n * m ) ; for ( int i = 0 ; i < n * m ; i ++ ) parent [ i ] = i ; vector < int > rank ( n * m , 1 ) ; vector < bool > grid ( n * m , 0 ) ; for ( int i = 0 ; i < query . size ( ) ; i ++ ) { int x = query [ i ] . first ; int y = query [ i ] . second ; if ( grid [ m * x + y ] == 1 ) { result [ i ] = ctr ; continue ; } grid [ m * x + y ] = 1 ; ctr ++ ; if ( x > 0 and grid [ m * ( x - 1 ) + y ] == 1 ) setUnion ( parent , rank , m * x + y , m * ( x - 1 ) + y ) ; if ( y > 0 and grid [ m * ( x ) + y - 1 ] == 1 ) setUnion ( parent , rank , m * x + y , m * ( x ) + y - 1 ) ; if ( x < n - 1 and grid [ m * ( x + 1 ) + y ] == 1 ) setUnion ( parent , rank , m * x + y , m * ( x + 1 ) + y ) ; if ( y < m - 1 and grid [ m * ( x ) + y + 1 ] == 1 ) setUnion ( parent , rank , m * x + y , m * ( x ) + y + 1 ) ; result [ i ] = ctr ; } return result ; } int main ( ) { int N = 3 , M = 3 , K = 4 ; vector < pair < int , int > > query = { { 0 , 0 } , { 1 , 1 } , { 1 , 0 } , { 1 , 2 } } ; vector < int > result = solve ( N , M , query ) ; for ( int i = 0 ; i < K ; i ++ ) cout << result [ i ] << " β " ; } |
Minimum Sum of a pair at least K distance apart from an Array | C ++ Program to implement the above approach ; Function to find the minimum sum of two elements that are atleast K distance apart ; Length of the array ; Find the suffix array ; Iterate in the array ; Update minimum sum ; Print the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findMinSum ( int A [ ] , int K , int len ) { int n = len ; int suffix_min [ n ] = { 0 } ; suffix_min [ n - 1 ] = A [ n - 1 ] ; for ( int i = n - 2 ; i >= 0 ; i -- ) suffix_min [ i ] = min ( suffix_min [ i + 1 ] , A [ i ] ) ; int min_sum = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { if ( i + K < n ) min_sum = min ( min_sum , A [ i ] + suffix_min [ i + K ] ) ; } cout << min_sum ; } int main ( ) { int A [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int K = 2 ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; findMinSum ( A , K , n ) ; return 0 ; } |
Maximum number of envelopes that can be put inside other bigger envelopes | C ++ program for the above approach ; Function that returns the maximum number of envelopes that can be inserted into another envelopes ; Number of envelopes ; Sort the envelopes in non - decreasing order ; Initialize dp [ ] array ; To store the result ; Loop through the array ; Find envelopes count for each envelope ; Store maximum envelopes count ; Return the result ; Driver Code ; Given the envelopes ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxEnvelopes ( vector < vector < int > > envelopes ) { int N = envelopes . size ( ) ; if ( N == 0 ) return N ; sort ( envelopes . begin ( ) , envelopes . end ( ) ) ; int dp [ N ] ; int max_envelope = 1 ; dp [ 0 ] = 1 ; for ( int i = 1 ; i < N ; ++ i ) { dp [ i ] = 1 ; for ( int j = 0 ; j < i ; ++ j ) { if ( envelopes [ i ] [ 0 ] > envelopes [ j ] [ 0 ] && envelopes [ i ] [ 1 ] > envelopes [ j ] [ 1 ] && dp [ i ] < dp [ j ] + 1 ) dp [ i ] = dp [ j ] + 1 ; } max_envelope = max ( max_envelope , dp [ i ] ) ; } return max_envelope ; } int main ( ) { vector < vector < int > > envelopes = { { 4 , 3 } , { 5 , 3 } , { 5 , 6 } , { 1 , 2 } } ; cout << maxEnvelopes ( envelopes ) ; return 0 ; } |
Maximize difference between the Sum of the two halves of the Array after removal of N elements | C ++ Program to implement the above approach ; Function to print the maximum difference possible between the two halves of the array ; Stores n maximum values from the start ; Insert first n elements ; Update sum of largest n elements from left ; For the remaining elements ; Obtain minimum value in the set ; Insert only if it is greater than minimum value ; Update sum from left ; Remove the minimum ; Insert the current element ; Clear the set ; Store n minimum elements from the end ; Insert the last n elements ; Update sum of smallest n elements from right ; For the remaining elements ; Obtain the minimum ; Insert only if it is smaller than maximum value ; Update sum from right ; Remove the minimum ; Insert the new element ; Compare the difference and store the maximum ; Return the maximum possible difference ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long FindMaxDif ( vector < long long > a , int m ) { int n = m / 3 ; vector < long long > l ( m + 5 ) , r ( m + 5 ) ; multiset < long long > s ; for ( int i = 1 ; i <= m ; i ++ ) { if ( i <= n ) { l [ i ] = a [ i - 1 ] + l [ i - 1 ] ; s . insert ( a [ i - 1 ] ) ; } else { l [ i ] = l [ i - 1 ] ; long long d = * s . begin ( ) ; if ( a [ i - 1 ] > d ) { l [ i ] -= d ; l [ i ] += a [ i - 1 ] ; s . erase ( s . find ( d ) ) ; s . insert ( a [ i - 1 ] ) ; } } } s . clear ( ) ; for ( int i = m ; i >= 1 ; i -- ) { if ( i >= m - n + 1 ) { r [ i ] = a [ i - 1 ] + r [ i + 1 ] ; s . insert ( a [ i - 1 ] ) ; } else { r [ i ] = r [ i + 1 ] ; long long d = * s . rbegin ( ) ; if ( a [ i - 1 ] < d ) { r [ i ] -= d ; r [ i ] += a [ i - 1 ] ; s . erase ( s . find ( d ) ) ; s . insert ( a [ i - 1 ] ) ; } } } long long ans = -9e18L ; for ( int i = n ; i <= m - n ; i ++ ) { ans = max ( ans , l [ i ] - r [ i + 1 ] ) ; } return ans ; } int main ( ) { vector < long long > vtr = { 3 , 1 , 4 , 1 , 5 , 9 } ; int n = vtr . size ( ) ; cout << FindMaxDif ( vtr , n ) ; return 0 ; } |
Check if each element of an Array is the Sum of any two elements of another Array | C ++ program to implement the above approach ; Function to check if each element of B [ ] can be formed by adding two elements of array A [ ] ; Store each element of B [ ] ; Traverse all possible pairs of array ; If A [ i ] + A [ j ] is present in the set ; Remove A [ i ] + A [ j ] from the set ; If set is empty ; Otherwise ; Driver Code | #include using namespace std ; string checkPossible ( int A [ ] , int B [ ] , int n ) { unordered_set values ; for ( int i = 0 ; i < n ; i ++ ) { values . insert ( B [ i ] ) ; } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( values . find ( A [ i ] + A [ j ] ) != values . end ( ) ) { values . erase ( A [ i ] + A [ j ] ) ; if ( values . empty ( ) ) break ; } } } if ( values . size ( ) == 0 ) return " Yes " ; else return " No " ; } int main ( ) { int N = 5 ; int A [ ] = { 3 , 5 , 1 , 4 , 2 } ; int B [ ] = { 3 , 4 , 5 , 6 , 7 } ; cout << checkPossible ( A , B , N ) ; } |
Count of Array elements greater than or equal to twice the Median of K trailing Array elements | C ++ Program to implement the above approach ; Function to find the count of array elements >= twice the median of K trailing array elements ; Stores frequencies ; Stores the array elements ; Count the frequencies of the array elements ; Iterating from d to n - 1 index means ( d + 1 ) th element to nth element ; To check the median ; Iterate over the frequencies of the elements ; Add the frequencies ; Check if the low_median value is obtained or not , if yes then do not change as it will be minimum ; Check if the high_median value is obtained or not , if yes then do not change it as it will be maximum ; Store 2 * median of K trailing elements ; If the current >= 2 * median ; Decrease the frequency for ( k - 1 ) - th element ; Increase the frequency of the current element ; Print the count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 2e5 ; const int V = 500 ; void solve ( int n , int d , int input [ ] ) { int a [ N ] ; int cnt [ V + 1 ] ; for ( int i = 0 ; i < n ; ++ i ) a [ i ] = input [ i ] ; int answer = 0 ; for ( int i = 0 ; i < d ; ++ i ) cnt [ a [ i ] ] ++ ; for ( int i = d ; i <= n - 1 ; ++ i ) { int acc = 0 ; int low_median = -1 , high_median = -1 ; for ( int v = 0 ; v <= V ; ++ v ) { acc += cnt [ v ] ; if ( low_median == -1 && acc >= int ( floor ( ( d + 1 ) / 2.0 ) ) ) low_median = v ; if ( high_median == -1 && acc >= int ( ceil ( ( d + 1 ) / 2.0 ) ) ) high_median = v ; } int double_median = low_median + high_median ; if ( a [ i ] >= double_median ) answer ++ ; cnt [ a [ i - d ] ] -- ; cnt [ a [ i ] ] ++ ; } cout << answer << endl ; } int main ( ) { int input [ ] = { 1 , 2 , 2 , 4 , 5 } ; int n = sizeof input / sizeof input [ 0 ] ; int k = 3 ; solve ( n , k , input ) ; return 0 ; } |
Smallest positive integer X satisfying the given equation | C ++ Program to implement the above approach ; Function to find out the smallest positive integer for the equation ; Stores the minimum ; Iterate till K ; Check if n is divisible by i ; Return the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinSoln ( int n , int k ) { int minSoln = INT_MAX ; for ( int i = 1 ; i < k ; i ++ ) { if ( n % i == 0 ) minSoln = min ( minSoln , ( n / i ) * k + i ) ; } return minSoln ; } int main ( ) { int n = 4 , k = 6 ; cout << findMinSoln ( n , k ) ; } |
Queries to find the Lower Bound of K from Prefix Sum Array with updates using Fenwick Tree | C ++ program to implement the above approach ; Function to calculate and return the sum of arr [ 0. . index ] ; Traverse ancestors of BITree [ index ] ; Update the sum of current element of BIT to ans ; Update index to that of the parent node in getSum ( ) view by subtracting LSB ( Least Significant Bit ) ; Function to update the Binary Index Tree by replacing all ancestors of index by their respective sum with val ; Traverse all ancestors and sum with ' val ' . ; Add ' val ' to current node of BIT ; Update index to that of the parent node in updateBit ( ) view by adding LSB ( Least Significant Bit ) ; Function to construct the Binary Indexed Tree for the given array ; Initialize the Binary Indexed Tree ; Store the actual values in BITree [ ] using update ( ) ; Function to obtain and return the index of lower_bound of k ; Store the Binary Indexed Tree ; Solve each query in Q ; Update the values of all ancestors of idx ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getSum ( int BITree [ ] , int index ) { int ans = 0 ; index += 1 ; while ( index > 0 ) { ans += BITree [ index ] ; index -= index & ( - index ) ; } return ans ; } static void updateBIT ( int BITree [ ] , int n , int index , int val ) { index = index + 1 ; while ( index <= n ) { BITree [ index ] += val ; index += index & ( - index ) ; } } int * constructBITree ( int arr [ ] , int n ) { int * BITree = new int [ n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) BITree [ i ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) updateBIT ( BITree , n , i , arr [ i ] ) ; return BITree ; } int getLowerBound ( int BITree [ ] , int arr [ ] , int n , int k ) { int lb = -1 ; int l = 0 , r = n - 1 ; while ( l <= r ) { int mid = l + ( r - l ) / 2 ; if ( getSum ( BITree , mid ) >= k ) { r = mid - 1 ; lb = mid ; } else l = mid + 1 ; } return lb ; } void performQueries ( int A [ ] , int n , int q [ ] [ 3 ] ) { int * BITree = constructBITree ( A , n ) ; for ( int i = 0 ; i < sizeof ( q [ 0 ] ) / sizeof ( int ) ; i ++ ) { int id = q [ i ] [ 0 ] ; if ( id == 1 ) { int idx = q [ i ] [ 1 ] ; int val = q [ i ] [ 2 ] ; A [ idx ] += val ; updateBIT ( BITree , n , idx , val ) ; } else { int k = q [ i ] [ 1 ] ; int lb = getLowerBound ( BITree , A , n , k ) ; cout << lb << endl ; } } } int main ( ) { int A [ ] = { 1 , 2 , 3 , 5 , 8 } ; int n = sizeof ( A ) / sizeof ( int ) ; int q [ ] [ 3 ] = { { 1 , 0 , 2 } , { 2 , 5 , 0 } , { 1 , 3 , 5 } } ; performQueries ( A , n , q ) ; } |
Minimum number of leaves required to be removed from a Tree to satisfy the given condition | C ++ Program to find the minimum number of leaves to be deleted ; Stores the count of safe nodes ; Function to perform DFS on the Tree to obtain the count of vertices that are not required to be deleted ; Update cost to reach the vertex ; If the vertex does not satisfy the condition ; Otherwise ; Traverse its subtree ; Driver Code ; Stores the Tree ; Perform DFS ; Print the number of nodes to be deleted | #include <bits/stdc++.h> NEW_LINE using namespace std ; int cnt = 0 ; void dfs ( int * val , int * cost , vector < vector < int > > & tr , int u , int s ) { s = s + cost [ u ] ; if ( s < 0 ) s = 0 ; if ( s > val [ u ] ) return ; cnt ++ ; for ( int i = 0 ; i < tr [ u ] . size ( ) ; i ++ ) { dfs ( val , cost , tr , tr [ u ] [ i ] , s ) ; } } int main ( ) { int n = 9 ; int val [ ] = { 88 , 22 , 83 , 14 , 95 , 91 , 98 , 53 , 11 } ; int cost [ ] = { -1 , 24 , -8 , 67 , 64 , 65 , 12 , -80 , 8 } ; vector < vector < int > > tr ( n + 1 ) ; tr [ 0 ] . push_back ( 3 ) ; tr [ 0 ] . push_back ( 4 ) ; tr [ 4 ] . push_back ( 6 ) ; tr [ 6 ] . push_back ( 2 ) ; tr [ 2 ] . push_back ( 1 ) ; tr [ 2 ] . push_back ( 8 ) ; tr [ 8 ] . push_back ( 5 ) ; tr [ 5 ] . push_back ( 7 ) ; dfs ( val , cost , tr , 0 , 0 ) ; cout << n - cnt ; return 0 ; } |
Check if an Array is made up of Subarrays of continuous repetitions of every distinct element | C ++ Program to implement the above problem ; Function to check if the array is made up of subarrays of repetitions ; Base Case ; Stores the size of current subarray ; If a different element is encountered ; If the previous subarray was a single element ; Reset to new subarray ; Increase size of subarray ; If last element differed from the second last element ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool ContinuousElements ( int a [ ] , int n ) { if ( n == 1 ) return false ; int curr = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( a [ i ] != a [ i - 1 ] ) { if ( curr == 1 ) return false ; else curr = 0 ; } curr ++ ; } if ( curr == 1 ) return false ; return true ; } int main ( ) { int a [ ] = { 1 , 1 , 2 , 2 , 1 , 3 , 3 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; if ( ContinuousElements ( a , n ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; } |
Size of all connected non | C ++ Program to implement the above approach ; Function to find size of all the islands from the given matrix ; Initialize a queue for the BFS traversal ; Iterate until the queue is empty ; Top element of queue ; Pop the element ; Check for boundaries ; Check if current element is 0 ; Check if current element is 1 ; Mark the cell visited ; Incrementing the size ; Traverse all neighbors ; Return the answer ; Function to print size of each connections ; Stores the size of each connected non - empty ; Check if the cell is non - empty ; Function call ; Print the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int BFS ( vector < vector < int > > & mat , int row , int col ) { int area = 0 ; queue < pair < int , int > > Q ; Q . push ( { row , col } ) ; while ( ! Q . empty ( ) ) { auto it = Q . front ( ) ; Q . pop ( ) ; int r = it . first , c = it . second ; if ( r < 0 c < 0 r > 4 c > 4 ) continue ; if ( mat [ r ] == 0 ) continue ; if ( mat [ r ] == 1 ) { mat [ r ] = 0 ; area ++ ; } Q . push ( { r + 1 , c } ) ; Q . push ( { r - 1 , c } ) ; Q . push ( { r , c + 1 } ) ; Q . push ( { r , c - 1 } ) ; } return area ; } void sizeOfConnections ( vector < vector < int > > mat ) { vector < int > result ; for ( int row = 0 ; row < 5 ; ++ row ) { for ( int col = 0 ; col < 5 ; ++ col ) { if ( mat [ row ] [ col ] == 1 ) { int area = BFS ( mat , row , col ) ; result . push_back ( area ) ; } } } for ( int val : result ) cout << val << " β " ; } int main ( ) { vector < vector < int > > mat = { { 1 , 1 , 0 , 0 , 0 } , { 1 , 1 , 0 , 1 , 1 } , { 1 , 0 , 0 , 1 , 1 } , { 1 , 0 , 0 , 0 , 0 } , { 0 , 0 , 1 , 1 , 1 } } ; sizeOfConnections ( mat ) ; return 0 ; } |
Find a pair in Array with second largest product | C ++ program for the above approach ; Function to find second largest product pair in arr [ 0. . n - 1 ] ; No pair exits ; Sort the array ; Initialize smallest element of the array ; Initialize largest element of the array ; Print second largest product pair ; Driver Code ; Given array ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void maxProduct ( int arr [ ] , int N ) { if ( N < 3 ) { return ; } sort ( arr , arr + N ) ; int smallest1 = arr [ 0 ] ; int smallest3 = arr [ 2 ] ; int largest1 = arr [ N - 1 ] ; int largest3 = arr [ N - 3 ] ; if ( smallest1 * smallest3 >= largest1 * largest3 ) { cout << smallest1 << " β " << smallest3 ; } else { cout << largest1 << " β " << largest3 ; } } int main ( ) { int arr [ ] = { 5 , 2 , 67 , 45 , 160 , 78 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maxProduct ( arr , N ) ; return 0 ; } |
Maximize length of Subarray of 1 's after removal of a pair of consecutive Array elements | C ++ program to implement the above approach ; Function to find the maximum subarray length of ones ; Stores the length , starting index and ending index of the subarrays ; S : starting index of the sub - array ; Traverse only continuous 1 s ; Calculate length of the sub - array ; v [ i ] [ 0 ] : Length of subarray v [ i ] [ 1 ] : Starting Index of subarray v [ i ] [ 2 ] : Ending Index of subarray ; If no such sub - array exists ; Traversing through the subarrays ; Update maximum length ; v [ i + 1 ] [ 1 ] - v [ i ] [ 2 ] - 1 : Count of zeros between the two sub - arrays ; Update length of both subarrays to the maximum ; Update length of both subarrays - 1 to the maximum ; Check if the last subarray has the maximum length ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxLen ( int A [ ] , int N ) { vector < vector < int > > v ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] == 1 ) { int s = i , len ; while ( A [ i ] == 1 && i < N ) { i ++ ; } len = i - s ; v . push_back ( { len , s , i - 1 } ) ; } } if ( v . size ( ) == 0 ) { return -1 ; } int ans = 0 ; for ( int i = 0 ; i < v . size ( ) - 1 ; i ++ ) { ans = max ( ans , v [ i ] [ 0 ] ) ; if ( v [ i + 1 ] [ 1 ] - v [ i ] [ 2 ] - 1 == 2 ) { ans = max ( ans , v [ i ] [ 0 ] + v [ i + 1 ] [ 0 ] ) ; } if ( v [ i + 1 ] [ 1 ] - v [ i ] [ 2 ] - 1 == 1 ) { ans = max ( ans , v [ i ] [ 0 ] + v [ i + 1 ] [ 0 ] - 1 ) ; } } ans = max ( v [ v . size ( ) - 1 ] [ 0 ] , ans ) ; return ans ; } int main ( ) { int arr [ ] = { 1 , 0 , 1 , 0 , 0 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxLen ( arr , N ) << endl ; return 0 ; } |
Detect cycle in Directed Graph using Topological Sort | C ++ Program to implement the above approach ; Stack to store the visited vertices in the Topological Sort ; Store Topological Order ; Adjacency list to store edges ; To ensure visited vertex ; Function to perform DFS ; Set the vertex as visited ; Visit connected vertices ; Push into the stack on complete visit of vertex ; Function to check and return if a cycle exists or not ; Stores the position of vertex in topological order ; Pop all elements from stack ; Push element to get Topological Order ; Pop from the stack ; If parent vertex does not appear first ; Cycle exists ; Return false if cycle does not exist ; Function to add edges from u to v ; Driver Code ; Insert edges ; If cycle exist | #include <bits/stdc++.h> NEW_LINE using namespace std ; int t , n , m , a ; stack < int > s ; vector < int > tsort ; vector < int > adj [ int ( 1e5 ) + 1 ] ; vector < int > visited ( int ( 1e5 ) + 1 ) ; void dfs ( int u ) { visited [ u ] = 1 ; for ( auto it : adj [ u ] ) { if ( visited [ it ] == 0 ) dfs ( it ) ; } s . push ( u ) ; } bool check_cycle ( ) { unordered_map < int , int > pos ; int ind = 0 ; while ( ! s . empty ( ) ) { pos [ s . top ( ) ] = ind ; tsort . push_back ( s . top ( ) ) ; ind += 1 ; s . pop ( ) ; } for ( int i = 0 ; i < n ; i ++ ) { for ( auto it : adj [ i ] ) { if ( pos [ i ] > pos [ it ] ) { return true ; } } } return false ; } void addEdge ( int u , int v ) { adj [ u ] . push_back ( v ) ; } int main ( ) { n = 4 , m = 5 ; addEdge ( 0 , 1 ) ; addEdge ( 0 , 2 ) ; addEdge ( 1 , 2 ) ; addEdge ( 2 , 0 ) ; addEdge ( 2 , 3 ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( visited [ i ] == 0 ) { dfs ( i ) ; } } if ( check_cycle ( ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Rearrange an Array such that Sum of same | C ++ Program to implement the above approach ; Function to rearrange the array such that no same - indexed subset have sum equal to that in the original array ; Initialize a vector ; Iterate the array ; Sort the vector ; Shift of elements to the index of its next cyclic element ; Print the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printNewArray ( vector < int > a , int n ) { vector < pair < int , int > > v ; for ( int i = 0 ; i < n ; i ++ ) { v . push_back ( { a [ i ] , i } ) ; } sort ( v . begin ( ) , v . end ( ) ) ; int ans [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { ans [ v [ ( i + 1 ) % n ] . second ] = v [ i ] . first ; } for ( int i = 0 ; i < n ; i ++ ) { cout << ans [ i ] << " β " ; } } int main ( ) { vector < int > a = { 4 , 1 , 2 , 5 , 3 } ; int n = a . size ( ) ; printNewArray ( a , n ) ; return 0 ; } |
Minimize count of array elements to be removed to maximize difference between any pair up to K | C ++ Program to implement the above approach ; Function to count the number of elements to be removed from the array based on the given condition ; Sort the array ; / Initialize the variable ; Iterate for all possible pairs ; Check the difference between the numbers ; Update the minimum removals ; Return the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int min_remove ( int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; int ans = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { if ( arr [ j ] - arr [ i ] <= k ) { ans = min ( ans , n - j + i - 1 ) ; } } } return ans ; } int main ( ) { int k = 3 ; int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = sizeof arr / sizeof arr [ 0 ] ; cout << min_remove ( arr , n , k ) ; return 0 ; } |
Reduce a given Binary Array to a single element by removal of Triplets | C ++ program to implement the above approach ; Function to check if it is possible to reduce the array to a single element ; Stores frequency of 0 's ; Stores frequency of 1 's ; Condition for array to be reduced ; Otherwise ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( int arr [ ] , int n ) { int countzeroes = 0 ; int countones = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == 0 ) countzeroes ++ ; else countones ++ ; } if ( abs ( countzeroes - countones ) == 1 ) cout << " Yes " ; else cout << " No " ; } int main ( ) { int arr [ ] = { 0 , 1 , 0 , 0 , 1 , 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; solve ( arr , n ) ; return 0 ; } |
Nearest smaller character to a character K from a Sorted Array | C ++ Program to implement the above approach ; Function to return the nearest smaller character ; Stores the nearest smaller character ; Iterate till starts cross end ; Find the mid element ; Check if K is found ; Check if current character is less than K ; Increment the start ; Otherwise ; Increment end ; Return the character ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; char bs ( char ar [ ] , int n , int ele ) { int start = 0 ; int end = n - 1 ; char ch = ' @ ' ; while ( start <= end ) { int mid = start + ( end - start ) / 2 ; if ( ar [ mid ] == ele ) end = mid - 1 ; else if ( ar [ mid ] < ele ) { ch = ar [ mid ] ; start = mid + 1 ; } else end = mid - 1 ; } return ch ; } int main ( ) { char ar [ ] = { ' e ' , ' g ' , ' t ' , ' y ' } ; int n = sizeof ( ar ) / sizeof ( ar [ 0 ] ) ; char K = ' u ' ; char ch = bs ( ar , n , K ) ; if ( ch == ' @ ' ) cout << " - 1" ; else cout << ch ; return 0 ; } |
Largest possible Subset from an Array such that no element is K times any other element in the Subset | C ++ implementation of the above approach ; Function to find the maximum size of the required subset ; Size of the array ; Sort the array ; Stores which index is included or excluded ; Stores the indices of array elements ; Count of pairs ; Iterate through all the element ; If element is included ; Check if a [ i ] * k is present in the array or not ; Increase count of pair ; Exclude the pair ; Driver code | #include <bits/stdc++.h> NEW_LINE #define ll long long NEW_LINE using namespace std ; int findMaxLen ( vector < ll > & a , ll k ) { int n = a . size ( ) ; sort ( a . begin ( ) , a . end ( ) ) ; vector < bool > vis ( n , 0 ) ; map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) { mp [ a [ i ] ] = i ; } int c = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( vis [ i ] == false ) { int check = a [ i ] * k ; if ( mp . find ( check ) != mp . end ( ) ) { c ++ ; vis [ mp [ check ] ] = true ; } } } return n - c ; } int main ( ) { int K = 3 ; vector < ll > arr = { 1 , 4 , 3 , 2 } ; cout << findMaxLen ( arr , K ) ; } |
Minimize length of prefix of string S containing all characters of another string T | C ++ program for the above approach ; Base Case - if T is empty , it matches 0 length prefix ; Convert strings to lower case for uniformity ; Update dictCount to the letter count of T ; If new character is found , initialize its entry , and increase nUnique ; Increase count of ch ; Iterate from 0 to N ; i - th character ; Skip if ch not in targetStr ; Decrease Count ; If the count of ch reaches 0 , we do not need more ch , and can decrease nUnique ; If nUnique reaches 0 , we have found required prefix ; Otherwise ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getPrefixLength ( string srcStr , string targetStr ) { if ( targetStr . length ( ) == 0 ) return 0 ; transform ( srcStr . begin ( ) , srcStr . end ( ) , srcStr . begin ( ) , :: tolower ) ; transform ( targetStr . begin ( ) , targetStr . end ( ) , targetStr . begin ( ) , :: tolower ) ; map < char , int > dictCount ; int nUnique = 0 ; for ( char ch : targetStr ) { if ( dictCount . find ( ch ) == dictCount . end ( ) ) { nUnique += 1 ; dictCount [ ch ] = 0 ; } dictCount [ ch ] += 1 ; } for ( int i = 0 ; i < srcStr . length ( ) ; i ++ ) { char ch = srcStr [ i ] ; if ( dictCount . find ( ch ) == dictCount . end ( ) ) continue ; dictCount [ ch ] -= 1 ; if ( dictCount [ ch ] == 0 ) nUnique -= 1 ; if ( nUnique == 0 ) return ( i + 1 ) ; } return -1 ; } int main ( ) { string S = " MarvoloGaunt " ; string T = " Tom " ; cout << getPrefixLength ( S , T ) ; return 0 ; } |
Minimize length of Substrings containing at least one common Character | C ++ Program to implement the above approach ; Function to check and return if substrings of length mid has a common character a ; Length of the string ; Initialise the first occurrence of character a ; Check that distance b / w the current and previous occurrence of character a is less than or equal to mid ; If distance exceeds mid ; Function to check for all the alphabets , if substrings of length mid have a character common ; Check for all 26 alphabets ; Check that char i + a is common in all the substrings of length mid ; If no characters is common ; Function to calculate and return the minm length of substrings ; Initialise low and high ; Perform binary search ; Update mid ; Check if one common character is present in the length of the mid ; Returns the minimum length that contain one common character ; Function to check if all characters are distinct ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( string & str , int mid , char a ) { int n = str . size ( ) ; int previous = -1 , i ; for ( i = 0 ; i < n ; ++ i ) { if ( str [ i ] == a ) { if ( i - previous > mid ) { return false ; } previous = i ; } } if ( i - previous > mid ) return false ; else return true ; } bool possible ( string & str , int mid ) { for ( int i = 0 ; i < 26 ; ++ i ) { if ( check ( str , mid , i + ' a ' ) ) return true ; } return false ; } int findMinLength ( string & str ) { int low = 1 , high = str . length ( ) ; while ( low <= high ) { int mid = ( low + high ) / 2 ; if ( possible ( str , mid ) ) high = mid - 1 ; else low = mid + 1 ; } return high + 1 ; } bool ifAllDistinct ( string str ) { set < char > s ; for ( char c : str ) { s . insert ( c ) ; } return s . size ( ) == str . size ( ) ; } int main ( ) { string str = " geeksforgeeks " ; if ( ifAllDistinct ( str ) ) cout << -1 << endl ; else cout << findMinLength ( str ) ; return 0 ; } |
Maximize product of absolute index difference with K | C ++ program to implement the above approach ; Function returns maximum possible value of k ; Pointer i make sure that A [ i ] will result in max k ; Stores maximum possible k ; Possible value of k for current pair ( A [ i ] and A [ j ] ) ; If current value exceeds k ; Update the value of k ; Update pointer i ; Return the maxm possible k ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( int A [ ] , int N ) { int i = 0 ; int k = 0 ; for ( int j = 1 ; j < N ; j ++ ) { int tempK = min ( A [ i ] , A [ j ] ) / ( j - i ) ; if ( tempK > k ) { k = tempK ; } if ( A [ j ] >= A [ i ] / ( j - i ) ) i = j ; } return k ; } int main ( ) { int A [ ] = { 10 , 5 , 12 , 15 , 8 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << solve ( A , N ) ; return 0 ; } |
Split Array into min number of subsets with difference between each pair greater than 1 | C ++ program for the above approach ; Function to Split the array into minimum number of subsets with difference strictly > 1 ; Sort the array ; Traverse through the sorted array ; Check the pairs of elements with difference 1 ; If we find even a single pair with difference equal to 1 , then 2 partitions else only 1 partition ; Print the count of partitions ; Driver Code ; Given array ; Size of the array ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void split ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int count = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] - arr [ i - 1 ] == 1 ) { count = 2 ; break ; } } cout << count << endl ; } int main ( ) { int arr [ ] = { 2 , 4 , 6 } ; int n = sizeof ( arr ) / sizeof ( int ) ; split ( arr , n ) ; return 0 ; } |
Check if a Palindromic String can be formed by concatenating Substrings of two given Strings | C ++ Program to implement the above approach ; Function to check if a palindromic string can be formed from the substring of given strings ; Boolean array to mark presence of characters ; Check if any of the character of str2 is already marked ; If a common character is found ; If no common character is found ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( string str1 , string str2 ) { vector < bool > mark ( 26 , false ) ; int n = str1 . size ( ) , m = str2 . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { mark [ str1 [ i ] - ' a ' ] = true ; } for ( int i = 0 ; i < m ; i ++ ) { if ( mark [ str2 [ i ] - ' a ' ] ) return true ; } return false ; } int main ( ) { string str1 = " abca " , str2 = " efad " ; if ( check ( str1 , str2 ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Generate K co | C ++ implementation of the above approach ; Function prints the required pairs ; First co - prime pair ; As a pair ( 1 n ) has already been Printed ; If i is a factor of N ; Since ( i , i ) won 't form a coprime pair ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void FindPairs ( int n , int k ) { cout << 1 << " β " << n << endl ; k -- ; for ( long long i = 2 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { cout << 1 << " β " << i << endl ; k -- ; if ( k == 0 ) break ; if ( i != n / i ) { cout << 1 << " β " << n / i << endl ; k -- ; } if ( k == 0 ) break ; } } } int main ( ) { int N = 100 ; int K = 5 ; FindPairs ( N , K ) ; return 0 ; } |
Minimum edges required to make a Directed Graph Strongly Connected | C ++ program to implement the above approach ; Perform DFS to count the in - degree and out - degree of the graph ; Mark the source as visited ; Traversing adjacent nodes ; Mark out - degree as 1 ; Mark in - degree as 1 ; If not visited ; DFS Traversal on adjacent vertex ; Function to return minimum number of edges required to make the graph strongly connected ; For Adjacency List ; Create the Adjacency List ; Initialize the in - degree array ; Initialize the out - degree array ; Initialize the visited array ; Perform DFS to count in - degrees and out - degreess ; To store the result ; To store total count of in - degree and out - degree ; Find total in - degree and out - degree ; Calculate the minimum edges required ; Return the minimum edges ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void dfs ( int u , vector < int > adj [ ] , int * vis , int * inDeg , int * outDeg ) { vis [ u ] = 1 ; for ( auto v : adj [ u ] ) { outDeg [ u ] = 1 ; inDeg [ v ] = 1 ; if ( vis [ v ] == 0 ) { dfs ( v , adj , vis , inDeg , outDeg ) ; } } } int findMinimumEdges ( int source [ ] , int N , int M , int dest [ ] ) { vector < int > adj [ N + 1 ] ; for ( int i = 0 ; i < M ; i ++ ) { adj [ source [ i ] ] . push_back ( dest [ i ] ) ; } int inDeg [ N + 1 ] = { 0 } ; int outDeg [ N + 1 ] = { 0 } ; int vis [ N + 1 ] = { 0 } ; dfs ( 1 , adj , vis , inDeg , outDeg ) ; int minEdges = 0 ; int totalIndegree = 0 ; int totalOutdegree = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { if ( inDeg [ i ] == 1 ) totalIndegree ++ ; if ( outDeg [ i ] == 1 ) totalOutdegree ++ ; } minEdges = max ( N - totalIndegree , N - totalOutdegree ) ; return minEdges ; } int main ( ) { int N = 5 , M = 5 ; int source [ ] = { 1 , 3 , 1 , 3 , 4 } ; int destination [ ] = { 2 , 2 , 3 , 4 , 5 } ; cout << findMinimumEdges ( source , N , M , destination ) ; return 0 ; } |
Count of subarrays which forms a permutation from given Array elements | C ++ Program to implement the above approach ; Function returns the required count ; Store the indices of the elements present in A [ ] . ; Store the maximum and minimum index of the elements from 1 to i . ; Update maxi and mini , to store minimum and maximum index for permutation of elements from 1 to i + 1 ; If difference between maxi and mini is equal to i ; Increase count ; Return final count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int PermuteTheArray ( int A [ ] , int n ) { int arr [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { arr [ A [ i ] - 1 ] = i ; } int mini = n , maxi = 0 ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { mini = min ( mini , arr [ i ] ) ; maxi = max ( maxi , arr [ i ] ) ; if ( maxi - mini == i ) count ++ ; } return count ; } int main ( ) { int A [ ] = { 4 , 5 , 1 , 3 , 2 , 6 } ; cout << PermuteTheArray ( A , 6 ) ; return 0 ; } |
Find Second largest element in an array | Set 2 | C ++ program to implement the above approach ; Function to find the largest element in the array arr [ ] ; Base Condition ; Initialize an empty list ; Divide the array into two equal length subarrays and recursively find the largest among the two ; Store length of compared1 [ ] in the first index ; Store the maximum element ; Return compared1 which contains the maximum element ; Store length of compared2 [ ] in the first index ; Store the maximum element ; Return compared2 [ ] which contains the maximum element ; Function to print the second largest element in the array arr [ ] ; Find the largest element in arr [ ] ; Find the second largest element in arr [ ] ; Print the second largest element ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > findLargest ( int beg , int end , vector < int > arr , int n ) { if ( beg == end ) { vector < int > compared ( n , 0 ) ; compared [ 0 ] = 1 ; compared [ 1 ] = arr [ beg ] ; return compared ; } vector < int > compared1 = findLargest ( beg , ( beg + end ) / 2 , arr , n ) ; vector < int > compared2 = findLargest ( ( beg + end ) / 2 + 1 , end , arr , n ) ; if ( compared1 [ 1 ] > compared2 [ 1 ] ) { int k = compared1 [ 0 ] + 1 ; compared1 [ 0 ] = k ; compared1 [ k ] = compared2 [ 1 ] ; return compared1 ; } else { int k = compared2 [ 0 ] + 1 ; compared2 [ 0 ] = k ; compared2 [ k ] = compared1 [ 1 ] ; return compared2 ; } } void findSecondLargest ( int end , vector < int > arr ) { vector < int > compared1 = findLargest ( 0 , end - 1 , arr , end ) ; vector < int > compared2 = findLargest ( 2 , compared1 [ 0 ] + 2 , compared1 , compared1 [ 0 ] ) ; cout << compared2 [ 1 ] ; } int main ( ) { int N = 10 ; vector < int > arr { 20 , 1990 , 12 , 1110 , 1 , 59 , 12 , 15 , 120 , 1110 } ; findSecondLargest ( N , arr ) ; return 0 ; } |
Count of Reverse Bitonic Substrings in a given String | C ++ Program to implement the above approach ; Function to calculate the number of reverse bitonic substrings ; Stores the count ; All possible lengths of substrings ; Starting point of a substring ; Ending point of a substring ; Condition for reverse bitonic substrings of length 1 ; Check for decreasing sequence ; If end of substring is reached ; For increasing sequence ; If end of substring is reached ; Return the number of bitonic substrings ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int CountsubString ( char str [ ] , int n ) { int c = 0 ; for ( int len = 1 ; len <= n ; len ++ ) { for ( int i = 0 ; i <= n - len ; i ++ ) { int j = i + len - 1 ; char temp = str [ i ] , f = 0 ; if ( j == i ) { c ++ ; continue ; } int k = i + 1 ; while ( temp > str [ k ] && k <= j ) { temp = str [ k ] ; k ++ ; } if ( k > j ) { c ++ ; f = 2 ; } while ( temp < str [ k ] && k <= j && f != 2 ) { temp = str [ k ] ; k ++ ; } if ( k > j && f != 2 ) { c ++ ; f = 0 ; } } } return c ; } int main ( ) { char str [ ] = " bade " ; cout << CountsubString ( str , strlen ( str ) ) ; return 0 ; } |
Maximum subsequence sum from a given array which is a perfect square | C ++ Program to implement the above approach ; If sum is 0 , then answer is true ; If sum is not 0 and arr [ ] is empty , then answer is false ; Fill the subset table in bottom up manner ; Function to find the sum ; Find sum of all values ; return the value ; ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isSubsetSum ( int arr [ ] , int n , int sum ) { bool subset [ n + 1 ] [ sum + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) subset [ i ] [ 0 ] = true ; for ( int i = 1 ; i <= sum ; i ++ ) subset [ 0 ] [ i ] = false ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= sum ; j ++ ) { if ( j < arr [ i - 1 ] ) subset [ i ] [ j ] = subset [ i - 1 ] [ j ] ; if ( j >= arr [ i - 1 ] ) subset [ i ] [ j ] = subset [ i - 1 ] [ j ] || subset [ i - 1 ] [ j - arr [ i - 1 ] ] ; } } return subset [ n ] [ sum ] ; } int findSum ( int * arr , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; } int val = sqrt ( sum ) ; for ( int i = val ; i >= 0 ; i -- ) { if ( isSubsetSum ( arr , n , i * i ) ) { return i * i ; } } return 0 ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findSum ( arr , n ) << endl ; return 0 ; } |
Smallest subarray whose product leaves remainder K when divided by size of the array | C ++ Program to implement the above approach ; Function to find the subarray of minimum length ; Initialize the minimum subarray size to N + 1 ; Generate all possible subarray ; Initialize the product ; Find the product ; Return the minimum size of subarray ; Driver Code ; Given array | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findsubArray ( int arr [ ] , int N , int K ) { int res = N + 1 ; for ( int i = 0 ; i < N ; i ++ ) { int curr_prod = 1 ; for ( int j = i ; j < N ; j ++ ) { curr_prod = curr_prod * arr [ j ] ; if ( curr_prod % N == K && res > ( j - i + 1 ) ) { res = min ( res , j - i + 1 ) ; break ; } } } return ( res == N + 1 ) ? 0 : res ; } int main ( ) { int arr [ ] = { 2 , 2 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 1 ; int answer = findsubArray ( arr , N , K ) ; if ( answer != 0 ) cout << answer ; else cout << " - 1" ; return 0 ; } |
Count of array elements whose order of deletion precedes order of insertion | C ++ Program to implement the above approach ; Function returns maximum number of required elements ; Insert the elements of array B in the queue and set ; Stores the answer ; If A [ i ] is already processed ; Until we find A [ i ] in the queue ; Remove elements from the queue ; Increment the count ; Remove the current element A [ i ] from the queue and set . ; Return total count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumCount ( int A [ ] , int B [ ] , int n ) { queue < int > q ; unordered_set < int > s ; for ( int i = 0 ; i < n ; i ++ ) { s . insert ( B [ i ] ) ; q . push ( B [ i ] ) ; } int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . find ( A [ i ] ) == s . end ( ) ) continue ; while ( ! q . empty ( ) && q . front ( ) != A [ i ] ) { s . erase ( q . front ( ) ) ; q . pop ( ) ; count ++ ; } if ( A [ i ] == q . front ( ) ) { q . pop ( ) ; s . erase ( A [ i ] ) ; } if ( q . empty ( ) ) break ; } cout << count << endl ; } int main ( ) { int N = 4 ; int A [ ] = { 1 , 2 , 3 , 4 } ; int B [ ] = { 1 , 2 , 4 , 3 } ; maximumCount ( A , B , N ) ; return 0 ; } |
Check if a Matrix is Bitonic or not | C ++ Program to check if a matrix is Bitonic or not ; Function to check if an array is Bitonic or not ; Check for increasing sequence ; Check for decreasing sequence ; Function to check whether given matrix is bitonic or not ; Check row - wise ; Check column wise ; Generate an array consisting of elements of the current column ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 3 , M = 3 ; bool checkBitonic ( int arr [ ] , int n ) { int i , j , f = 0 ; for ( i = 1 ; i < n ; i ++ ) { if ( arr [ i ] > arr [ i - 1 ] ) continue ; if ( arr [ i ] == arr [ i - 1 ] ) return false ; else { f = 1 ; break ; } } if ( i == n ) return true ; for ( j = i + 1 ; j < n ; j ++ ) { if ( arr [ j ] < arr [ j - 1 ] ) continue ; if ( arr [ i ] == arr [ i - 1 ] ) return false ; else { if ( f == 1 ) return false ; } } return true ; } void check ( int arr [ N ] [ M ] ) { int f = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( ! checkBitonic ( arr [ i ] , M ) ) { cout << " NO " << endl ; return ; } } for ( int i = 0 ; i < N ; i ++ ) { int temp [ N ] ; for ( int j = 0 ; j < N ; j ++ ) { temp [ j ] = arr [ j ] [ i ] ; } if ( ! checkBitonic ( temp , N ) ) { cout << " NO " << endl ; return ; } } cout << " YES " ; } int main ( ) { int m [ N ] [ M ] = { { 1 , 2 , 3 } , { 3 , 4 , 5 } , { 2 , 6 , 4 } } ; check ( m ) ; return 0 ; } |
Maximum possible GCD for a pair of integers with product N | C ++ Program to implement the above approach ; Function to return / the maximum GCD ; To find all divisors of N ; If i is a factor ; Store the pair of factors ; Store the maximum GCD ; Return the maximum GCD ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getMaxGcd ( int N ) { int maxGcd = INT_MIN , A , B ; for ( int i = 1 ; i <= sqrt ( N ) ; i ++ ) { if ( N % i == 0 ) { A = i , B = N / i ; maxGcd = max ( maxGcd , __gcd ( A , B ) ) ; } } return maxGcd ; } int main ( ) { int N = 18 ; cout << getMaxGcd ( N ) ; return 0 ; } |
Maximum of minimum difference of all pairs from subsequences of given size | C ++ Program to implement the above approach ; Function to check a subsequence can be formed with min difference mid ; If a subsequence of size B with min diff = mid is possible return true else false ; Function to find the maximum of all minimum difference of pairs possible among the subsequence ; Sort the Array ; Stores the boundaries of the search space ; Store the answer ; Binary Search ; If subsequence can be formed with min diff mid and size B ; Right half ; Left half ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool can_place ( int A [ ] , int n , int B , int mid ) { int count = 1 ; int last_position = A [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { if ( A [ i ] - last_position >= mid ) { last_position = A [ i ] ; count ++ ; if ( count == B ) { return true ; } } } return false ; } int find_min_difference ( int A [ ] , int n , int B ) { sort ( A , A + n ) ; int s = 0 ; int e = A [ n - 1 ] - A [ 0 ] ; int ans = 0 ; while ( s <= e ) { long long int mid = ( s + e ) / 2 ; if ( can_place ( A , n , B , mid ) ) { ans = mid ; s = mid + 1 ; } else { e = mid - 1 ; } } return ans ; } int main ( ) { int A [ ] = { 1 , 2 , 3 , 5 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int B = 3 ; int min_difference = find_min_difference ( A , n , B ) ; cout << min_difference ; return 0 ; } |
Count of triplets in an Array such that A [ i ] * A [ j ] = A [ k ] and i < j < k | C ++ Program to implement the above approach ; Returns total number of valid triplets possible ; Stores the count ; Map to store frequency of array elements ; Increment the frequency of A [ j + 1 ] as it can be a valid A [ k ] ; If target exists in the map ; Return the final count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countTriplets ( int A [ ] , int N ) { int ans = 0 ; map < int , int > map ; for ( int j = N - 2 ; j >= 1 ; j -- ) { map [ A [ j + 1 ] ] ++ ; for ( int i = 0 ; i < j ; i ++ ) { int target = A [ i ] * A [ j ] ; if ( map . find ( target ) != map . end ( ) ) ans += map [ target ] ; } } return ans ; } int main ( ) { int N = 5 ; int A [ ] = { 2 , 3 , 4 , 6 , 12 } ; cout << countTriplets ( A , N ) ; return 0 ; } |
Missing vertex among N axis | C ++ Program to implement the above approach ; Driver Code ; Number of rectangles ; Stores the coordinates ; Insert the coordinates | #include <bits/stdc++.h> NEW_LINE using namespace std ; void MissingPoint ( vector < pair < int , int > > V , int N ) { map < int , int > mp ; for ( int i = 0 ; i < V . size ( ) ; i ++ ) { mp [ V [ i ] . first ] ++ ; } int x , y ; for ( auto it : mp ) { if ( it . second % 2 == 1 ) { x = it . first ; break ; } } mp . clear ( ) ; for ( int i = 0 ; i < V . size ( ) ; i ++ ) { mp [ V [ i ] . second ] ++ ; } for ( auto it : mp ) { if ( it . second % 2 == 1 ) { y = it . first ; break ; } } cout << x << " β " << y ; } int main ( ) { int N = 2 ; vector < pair < int , int > > V ; V . push_back ( { 1 , 1 } ) ; V . push_back ( { 1 , 2 } ) ; V . push_back ( { 4 , 6 } ) ; V . push_back ( { 2 , 1 } ) ; V . push_back ( { 9 , 6 } ) ; V . push_back ( { 9 , 3 } ) ; V . push_back ( { 4 , 3 } ) ; MissingPoint ( V , N ) ; return 0 ; } |
Longest alternating subsequence with maximum sum | Set 2 | C ++ Program to implement the above approach ; Function to check the sign of the element ; Function to calculate and return the maximum sum of longest alternating subsequence ; Iterate through the array ; Stores the first element of a sequence of same sign ; Traverse until an element with opposite sign is encountered ; Update the maximum ; Update the maximum sum ; Update i ; Return the maximum sum ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sign ( int x ) { if ( x > 0 ) return 1 ; else return -1 ; } int findMaxSum ( int arr [ ] , int size ) { int max_sum = 0 , pres , i , j ; for ( i = 0 ; i < size ; i ++ ) { pres = arr [ i ] ; j = i ; while ( j < size && sign ( arr [ i ] ) == sign ( arr [ j ] ) ) { pres = max ( pres , arr [ j ] ) ; j ++ ; } max_sum = max_sum + pres ; i = j - 1 ; } return max_sum ; } int main ( ) { int arr [ ] = { -2 , 8 , 3 , 8 , -4 , -15 , 5 , -2 , -3 , 1 } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findMaxSum ( arr , size ) ; return 0 ; } |
Check if an array can be split into subsets of K consecutive elements | C ++ Program to implement the above approach ; Function to check if a given array can be split into subsets of K consecutive elements ; Stores the frequencies of array elements ; Traverse the map ; Check if all its occurrences can be grouped into K subsets ; Traverse next K elements ; If the element is not present in the array ; If it cannot be split into required number of subsets ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool groupInKConsecutive ( vector < int > & arr , int K ) { map < int , int > count ; for ( int h : arr ) { ++ count [ h ] ; } for ( auto c : count ) { int cur = c . first ; int n = c . second ; if ( n > 0 ) { for ( int i = 1 ; i < K ; ++ i ) { if ( ! count . count ( cur + i ) ) { return false ; } count [ cur + i ] -= n ; if ( count [ cur + i ] < 0 ) return false ; } } } return true ; } int main ( ) { vector < int > arr = { 1 , 2 , 3 , 6 , 2 , 3 , 4 , 7 , 8 } ; int k = 3 ; if ( groupInKConsecutive ( arr , k ) ) { cout << " True " ; } else { cout << " False " ; } } |
Count of substrings of a given Binary string with all characters same | C ++ program for the above approach ; Function to count number of sub - strings of a given binary string that contains only 1 ; Iterate untill L and R cross each other ; Check if reached the end of string ; Check if encountered '1' then extend window ; Check if encountered '0' then add number of strings of current window and change the values for both l and r ; Return the answer ; Function to flip the bits of string ; Function to count number of sub - strings of a given binary string that contains only 0 s & 1 s ; count of substring which contains only 1 s ; Flip the character of string s 0 to 1 and 1 to 0 to count the substring with consecutive 0 s ; count of substring which contains only 0 s ; Driver Code ; Given string str ; Function Call | #include <iostream> NEW_LINE using namespace std ; int countSubAllOnes ( string s ) { int l = 0 , r = 0 , ans = 0 ; while ( l <= r ) { if ( r == s . length ( ) ) { ans += ( ( r - l ) * ( r - l + 1 ) ) / 2 ; break ; } if ( s [ r ] == '1' ) r ++ ; else { ans += ( ( r - l ) * ( r - l + 1 ) ) / 2 ; l = r + 1 ; r ++ ; } } return ans ; } void flip ( string & s ) { for ( int i = 0 ; s [ i ] ; i ++ ) { if ( s [ i ] == '1' ) s [ i ] = '0' ; else s [ i ] = '1' ; } cout << s << endl ; } int countSubAllZerosOnes ( string s ) { int only_1s = countSubAllOnes ( s ) ; flip ( s ) ; cout << s << endl ; int only_0s = countSubAllOnes ( s ) ; return only_0s + only_1s ; } int main ( ) { string s = "011" ; cout << countSubAllZerosOnes ( s ) << endl ; return 0 ; } |
Count of primes in a given range that can be expressed as sum of perfect squares | C ++ Program to implement the above approach ; Function to check if a prime number satisfies the condition to be expressed as sum of two perfect squares ; Function to check if a number is prime or not ; Corner cases ; Function to return the count of primes in the range which can be expressed as the sum of two squares ; If i is a prime ; If i can be expressed as the sum of two squares ; Return the count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool sumSquare ( int p ) { return ( p - 1 ) % 4 == 0 ; } bool isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; return true ; } int countOfPrimes ( int L , int R ) { int count = 0 ; for ( int i = L ; i <= R ; i ++ ) { if ( isPrime ( i ) ) { if ( sumSquare ( i ) ) count ++ ; } } return count ; } int main ( ) { int L = 5 , R = 41 ; cout << countOfPrimes ( L , R ) ; } |
Count of array elements which are greater than all elements on its left | C ++ program to implement the above approach ; Function to return the count of array elements with all elements to its left smaller than it ; Stores the count ; Stores the maximum ; Iterate over the array ; If an element greater than maximum is obtained ; Increase count ; Update maximum ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int count_elements ( int arr [ ] , int n ) { int count = 1 ; int max = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] > max ) { count += 1 ; max = arr [ i ] ; } } return count ; } int main ( ) { int arr [ ] = { 2 , 1 , 4 , 6 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ( count_elements ( arr , n ) ) ; } |
Count of bitonic substrings from the given string | C ++ + program for the above approach ; Function to find all the bitonic sub strings ; Pick starting point ; Iterate till length of the string ; Pick ending point for string ; Substring from i to j is obtained ; Substrings of length 1 ; Increase count ; For increasing sequence ; Check for strictly increasing ; Increase count ; Check for decreasing sequence ; Increase count ; Print the result ; Driver Code ; Given string ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void subString ( char str [ ] , int n ) { int c = 0 ; for ( int len = 1 ; len <= n ; len ++ ) { for ( int i = 0 ; i <= n - len ; i ++ ) { int j = i + len - 1 ; char temp = str [ i ] , f = 0 ; if ( j == i ) { c ++ ; continue ; } int k = i + 1 ; while ( temp < str [ k ] && k <= j ) { temp = str [ k ] ; k ++ ; f = 2 ; } if ( k > j ) { c ++ ; f = 2 ; } while ( temp > str [ k ] && k <= j && f != 2 ) { k ++ ; f = 0 ; } if ( k > j && f != 2 ) { c ++ ; f = 0 ; } } } cout << c << endl ; } int main ( ) { char str [ ] = " bade " ; subString ( str , strlen ( str ) ) ; return 0 ; } |
Check if ceil of number divided by power of two exist in sorted array | C ++ 14 implementation to check if a number divided by power of two exist in the sorted array ; Function to find there exist a number or not in the array ; Loop to check if there exist a number by divided by power of 2 ; Binary Search ; Condition to check the number is found in the array or not ; Otherwise divide the number by increasing the one more power of 2 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findNumberDivByPowerofTwo ( int ar [ ] , int k , int n ) { int found = -1 , m = k ; while ( m > 0 ) { int l = 0 ; int r = n - 1 ; while ( l <= r ) { int mid = ( l + r ) / 2 ; if ( ar [ mid ] == m ) { found = m ; break ; } else if ( ar [ mid ] > m ) { r = mid - 1 ; } else if ( ar [ mid ] < m ) { l = mid + 1 ; } } if ( found != -1 ) { break ; } m = m / 2 ; } return found ; } int main ( ) { int arr [ ] = { 3 , 5 , 7 , 8 , 10 } ; int k = 4 , n = 5 ; cout << findNumberDivByPowerofTwo ( arr , k , n ) ; } |
Largest subset having with sum less than equal to sum of respective indices | C ++ Program to implement the above approach ; Function to find the length of the longest subset ; Stores the sum of differences between elements and their respective index ; Stores the size of the subset ; Iterate over the array ; If an element which is smaller than or equal to its index is encountered ; Increase count and sum ; Store the difference with index of the remaining elements ; Sort the differences in increasing order ; Include the differences while sum remains positive or ; Return the size ; Driver Code ; Function Calling | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findSubset ( int * a , int n ) { int sum = 0 ; int cnt = 0 ; vector < int > v ; for ( int i = 1 ; i <= n ; i ++ ) { if ( a [ i - 1 ] - i <= 0 ) { sum += a [ i - 1 ] - i ; cnt += 1 ; } else { v . push_back ( a [ i - 1 ] - i ) ; } } sort ( v . begin ( ) , v . end ( ) ) ; int ptr = 0 ; while ( ptr < v . size ( ) && sum + v [ ptr ] <= 0 ) { cnt += 1 ; ptr += 1 ; sum += v [ ptr ] ; } return cnt ; } int main ( ) { int arr [ ] = { 4 , 1 , 6 , 7 , 8 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findSubset ( arr , n ) << endl ; } |
Queries for count of array elements with values in given range with updates | C ++ code for queries for number of elements that lie in range [ l , r ] ( with updates ) ; Function to set arr [ index ] = x ; Function to get count of elements that lie in range [ l , r ] ; Traverse array ; If element lies in the range [ L , R ] ; Increase count ; Function to solve each query ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void setElement ( int * arr , int n , int index , int x ) { arr [ index ] = x ; } int getCount ( int * arr , int n , int l , int r ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] >= l && arr [ i ] <= r ) { count ++ ; } } return count ; } void SolveQuery ( int arr [ ] , int n , vector < pair < int , pair < int , int > > > Q ) { int x ; for ( int i = 0 ; i < Q . size ( ) ; i ++ ) { if ( Q [ i ] . first == 1 ) { x = getCount ( arr , n , Q [ i ] . second . first , Q [ i ] . second . second ) ; cout << x << " β " ; } else { setElement ( arr , n , Q [ i ] . second . first , Q [ i ] . second . second ) ; } } } int main ( ) { int arr [ ] = { 1 , 2 , 2 , 3 , 4 , 4 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; vector < pair < int , pair < int , int > > > Q = { { 1 , { 3 , 5 } } , { 1 , { 2 , 4 } } , { 1 , { 1 , 2 } } , { 2 , { 1 , 7 } } , { 1 , { 1 , 2 } } } ; SolveQuery ( arr , n , Q ) ; return 0 ; } |
Construct a sequence from given frequencies of N consecutive integers with unit adjacent difference | C ++ program for the above approach ; Function generates the sequence ; Map to store the frequency of numbers ; Sum of all frequencies ; Try all possibilities for the starting element ; If the frequency of current element is non - zero ; vector to store the answer ; Copy of the map for every possible starting element ; Decrement the frequency ; Push the starting element to the vector ; The last element inserted is i ; Try to fill the rest of the positions if possible ; If the frequency of last - 1 is non - zero ; Decrement the frequency of last - 1 ; Insert it into the sequence ; Update last number added to sequence ; Break from the inner loop ; If the size of the sequence vector is equal to sum of total frequqncies ; Return sequence ; If no such sequence if found return empty sequence ; Function Call to print the sequence ; The required sequence ; If the size of sequence if zero it means no such sequence was found ; Otherwise print the sequence ; Driver Code ; Frequency of all elements from 0 to n - 1 ; Number of elements whose frequencies are given ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > generateSequence ( int * freq , int n ) { map < int , int > m ; int total = 0 ; for ( int i = 0 ; i < n ; i ++ ) { m [ i ] = freq [ i ] ; total += freq [ i ] ; } for ( int i = 0 ; i < n ; i ++ ) { if ( m [ i ] ) { vector < int > sequence ; auto mcopy = m ; mcopy [ i ] -- ; sequence . push_back ( i ) ; int last = i ; for ( int i = 0 ; i < total - 1 ; i ++ ) { if ( mcopy [ last - 1 ] ) { mcopy [ last - 1 ] -- ; sequence . push_back ( last - 1 ) ; last -- ; } else if ( mcopy [ last + 1 ] ) { mcopy [ last + 1 ] -- ; sequence . push_back ( last + 1 ) ; last ++ ; } else break ; } if ( sequence . size ( ) == total ) { return sequence ; } } } vector < int > empty ; return empty ; } void PrintSequence ( int freq [ ] , int n ) { vector < int > sequence = generateSequence ( freq , n ) ; if ( sequence . size ( ) == 0 ) { cout << " - 1" ; } else { for ( int i = 0 ; i < sequence . size ( ) ; i ++ ) { cout << sequence [ i ] << " β " ; } } } int main ( ) { int freq [ ] = { 2 , 2 , 2 , 3 , 1 } ; int N = 5 ; PrintSequence ( freq , N ) ; return 0 ; } |
Minimum distance between any most frequent and least frequent element of an array | C ++ implementation of the approach ; Function to find the minimum distance between any two most and least frequent element ; Initialize sets to store the least and the most frequent elements ; Initialize variables to store max and min frequency ; Initialize HashMap to store frequency of each element ; Loop through the array ; Store the count of each element ; Store the least and most frequent elements in the respective sets ; Store count of current element ; If count is equal to max count ; Store in max set ; If count is greater then max count ; Empty max set ; Update max count ; Store in max set ; If count is equal to min count ; Store in min set ; If count is less then max count ; Empty min set ; Update min count ; Store in min set ; Initialize a variable to store the minimum distance ; Initialize a variable to store the last index of least frequent element ; Traverse array ; If least frequent element ; Update last index of least frequent element ; If most frequent element ; Update minimum distance ; Traverse array from the end ; If least frequent element ; Update last index of least frequent element ; If most frequent element ; Update minimum distance ; Print the minimum distance ; Driver Code ; Given array ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void getMinimumDistance ( int a [ ] , int n ) { set < int > min_set ; set < int > max_set ; int max = 0 , min = INT_MAX ; map < int , int > frequency ; for ( int i = 0 ; i < n ; i ++ ) { frequency [ a [ i ] ] += 1 ; } for ( int i = 0 ; i < n ; i ++ ) { int count = frequency [ a [ i ] ] ; if ( count == max ) { max_set . insert ( a [ i ] ) ; } else if ( count > max ) { max_set . clear ( ) ; max = count ; max_set . insert ( a [ i ] ) ; } if ( count == min ) { min_set . insert ( a [ i ] ) ; } else if ( count < min ) { min_set . clear ( ) ; min = count ; min_set . insert ( a [ i ] ) ; } } int min_dist = INT_MAX ; int last_min_found = -1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( min_set . find ( a [ i ] ) != min_set . end ( ) ) last_min_found = i ; if ( max_set . find ( a [ i ] ) != max_set . end ( ) && last_min_found != -1 ) { if ( ( i - last_min_found ) < min_dist ) min_dist = i - last_min_found ; } } last_min_found = -1 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( min_set . find ( a [ i ] ) != min_set . end ( ) ) last_min_found = i ; if ( max_set . find ( a [ i ] ) != max_set . end ( ) && last_min_found != -1 ) { if ( ( last_min_found - i ) > min_dist ) min_dist = last_min_found - i ; } } cout << ( min_dist ) ; } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 3 , 2 , 3 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; getMinimumDistance ( arr , N ) ; } |
Construct a string that has exactly K subsequences from given string | C ++ program for the above approach ; Function that computes the string s ; Length of the given string str ; List that stores all the prime factors of given k ; Find the prime factors ; Initialize the count of each character position as 1 ; Loop until the list becomes empty ; Increase the character count by multiplying it with the prime factor ; If we reach end then again start from beginning ; Store the output ; Print the string ; Driver code ; Given String ; Function Call | #include <bits/stdc++.h> NEW_LINE #include <iostream> NEW_LINE using namespace std ; void printSubsequenceString ( string str , long long k ) { int n = str . size ( ) ; int i ; vector < long long > factors ; for ( long long i = 2 ; i <= sqrt ( k ) ; i ++ ) { while ( k % i == 0 ) { factors . push_back ( i ) ; k /= i ; } } if ( k > 1 ) factors . push_back ( k ) ; vector < long long > count ( n , 1 ) ; int index = 0 ; while ( factors . size ( ) > 0 ) { count [ index ++ ] *= factors . back ( ) ; factors . pop_back ( ) ; if ( index == n ) index = 0 ; } string s ; for ( i = 0 ; i < n ; i ++ ) { while ( count [ i ] -- > 0 ) { s += str [ i ] ; } } cout << s ; } int main ( ) { string str = " code " ; long long k = 20 ; printSubsequenceString ( str , k ) ; return 0 ; } |
Replace each element of Array with it 's corresponding rank | C ++ program for the above approach ; Function to assign rank to array elements ; Copy input array into newArray ; Sort newArray [ ] in ascending order ; Map to store the rank of the array element ; Update rank of element ; Assign ranks to elements ; Driver code ; Given array arr [ ] ; Function call ; Print the array elements | #include <bits/stdc++.h> NEW_LINE using namespace std ; void changeArr ( int input [ ] , int N ) { int newArray [ N ] ; copy ( input , input + N , newArray ) ; sort ( newArray , newArray + N ) ; int i ; map < int , int > ranks ; int rank = 1 ; for ( int index = 0 ; index < N ; index ++ ) { int element = newArray [ index ] ; if ( ranks [ element ] == 0 ) { ranks [ element ] = rank ; rank ++ ; } } for ( int index = 0 ; index < N ; index ++ ) { int element = input [ index ] ; input [ index ] = ranks [ input [ index ] ] ; } } int main ( ) { int arr [ ] = { 100 , 2 , 70 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; changeArr ( arr , N ) ; cout << " [ " ; for ( int i = 0 ; i < N - 1 ; i ++ ) { cout << arr [ i ] << " , β " ; } cout << arr [ N - 1 ] << " ] " ; return 0 ; } |
Find pairs in array whose sum does not exist in Array | C ++ program to implement the above approach ; Function to print all pairs with sum not present in the array ; Corner Case ; Stores the distinct array elements ; Generate all possible pairs ; Calculate sum of current pair ; Check if the sum exists in the HashSet or not ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findPair ( int arr [ ] , int n ) { int i , j ; if ( n < 2 ) { cout << " - 1" << endl ; } set < int > hashMap ; for ( int k = 0 ; k < n ; k ++ ) { hashMap . insert ( arr [ k ] ) ; } for ( i = 0 ; i < n - 1 ; i ++ ) { for ( j = i + 1 ; j < n ; j ++ ) { int sum = arr [ i ] + arr [ j ] ; if ( hashMap . find ( sum ) == hashMap . end ( ) ) { cout << " ( " << arr [ i ] << " , β " << arr [ j ] << " ) " << endl ; } } } } int main ( ) { int arr [ ] = { 2 , 4 , 2 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findPair ( arr , n ) ; return 0 ; } |
Largest subset with M as smallest missing number | C ++ Program to implement the above approach ; Function to find and return the length of the longest subset whose smallest missing value is M ; Initialize a set ; If array element is not equal to M ; Insert into set ; Increment frequency ; Stores minimum missing number ; Iterate to find the minimum missing integer ; If minimum obtained is less than M ; Update answer ; Return answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE using namespace std ; ll findLengthOfMaxSubset ( int arr [ ] , int n , int m ) { set < int > s ; int answer = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int tmp = arr [ i ] ; if ( tmp != m ) { s . insert ( tmp ) ; answer ++ ; } } int min = 1 ; while ( s . count ( min ) ) { min ++ ; } if ( min != m ) { answer = -1 ; } return answer ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int M = 3 ; cout << findLengthOfMaxSubset ( arr , N , M ) ; return 0 ; } |
Count of submatrix with sum X in a given Matrix | C ++ program for the above approach ; Size of a column ; Function to find the count of submatrix whose sum is X ; Copying arr to dp and making it indexed 1 ; Precalculate and store the sum of all rectangles with upper left corner at ( 0 , 0 ) ; ; Calculating sum in a 2d grid ; Stores the answer ; Minimum length of square ; Maximum length of square ; Flag to set if sub - square with sum X is found ; Calculate lower right index if upper right corner is at { i , j } ; Calculate the sum of elements in the submatrix with upper left column { i , j } and lower right column at { ni , nj } ; ; If sum X is found ; If sum > X , then size of the square with sum X must be less than mid ; If sum < X , then size of the square with sum X must be greater than mid ; If found , increment count by 1 ; ; Driver Code ; Given Matrix arr [ ] [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define m 5 NEW_LINE int countSubsquare ( int arr [ ] [ m ] , int n , int X ) { int dp [ n + 1 ] [ m + 1 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { dp [ i + 1 ] [ j + 1 ] = arr [ i ] [ j ] ; } } for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { dp [ i ] [ j ] += dp [ i - 1 ] [ j ] + dp [ i ] [ j - 1 ] - dp [ i - 1 ] [ j - 1 ] ; } } int cnt = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { int lo = 1 ; int hi = min ( n - i , m - j ) + 1 ; bool found = false ; while ( lo <= hi ) { int mid = ( lo + hi ) / 2 ; int ni = i + mid - 1 ; int nj = j + mid - 1 ; int sum = dp [ ni ] [ nj ] - dp [ ni ] [ j - 1 ] - dp [ i - 1 ] [ nj ] + dp [ i - 1 ] [ j - 1 ] ; if ( sum >= X ) { if ( sum == X ) { found = true ; } hi = mid - 1 ; } else { lo = mid + 1 ; } } if ( found == true ) { cnt ++ ; } } } return cnt ; } int main ( ) { int N = 4 , X = 10 ; int arr [ N ] [ m ] = { { 2 , 4 , 3 , 2 , 10 } , { 3 , 1 , 1 , 1 , 5 } , { 1 , 1 , 2 , 1 , 4 } , { 2 , 1 , 1 , 1 , 3 } } ; cout << countSubsquare ( arr , N , X ) << endl ; return 0 ; } |
Check if two arrays can be made equal by reversing any subarray once | C ++ implementation to check whether two arrays can be made equal by reversing a sub - array only once ; Function to check whether two arrays can be made equal by reversing a sub - array only once ; Integer variable for storing the required starting and ending indices in the array ; Finding the smallest index for which A [ i ] != B [ i ] i . e the starting index of the unequal sub - array ; Finding the largest index for which A [ i ] != B [ i ] i . e the ending index of the unequal sub - array ; Reversing the sub - array A [ start ] , A [ start + 1 ] . . A [ end ] ; Checking whether on reversing the sub - array A [ start ] ... A [ end ] makes the arrays equal ; If any element of the two arrays is unequal print No and return ; Print Yes if arrays are equal after reversing the sub - array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void checkArray ( int A [ ] , int B [ ] , int N ) { int start = 0 ; int end = N - 1 ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] != B [ i ] ) { start = i ; break ; } } for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( A [ i ] != B [ i ] ) { end = i ; break ; } } reverse ( A + start , A + end + 1 ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] != B [ i ] ) { cout << " No " << endl ; return ; } } cout << " Yes " << endl ; } int main ( ) { int A [ ] = { 1 , 3 , 2 , 4 } ; int B [ ] = { 1 , 2 , 3 , 4 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; checkArray ( A , B , N ) ; return 0 ; } |
Count of substrings having all distinct characters | C ++ Program to implement the above appraoach ; Function to count total number of valid substrings ; Stores the count of substrings ; Stores the frequency of characters ; Initialised both pointers to beginning of the string ; If all characters in substring from index i to j are distinct ; Increment count of j - th character ; Add all substring ending at j and starting at any index between i and j to the answer ; Increment 2 nd pointer ; If some characters are repeated or j pointer has reached to end ; Decrement count of j - th character ; Increment first pointer ; Return the final count of substrings ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long int countSub ( string str ) { int n = ( int ) str . size ( ) ; long long int ans = 0 ; int cnt [ 26 ] ; memset ( cnt , 0 , sizeof ( cnt ) ) ; int i = 0 , j = 0 ; while ( i < n ) { if ( j < n && ( cnt [ str [ j ] - ' a ' ] == 0 ) ) { cnt [ str [ j ] - ' a ' ] ++ ; ans += ( j - i + 1 ) ; j ++ ; } else { cnt [ str [ i ] - ' a ' ] -- ; i ++ ; } } return ans ; } int main ( ) { string str = " gffg " ; cout << countSub ( str ) ; return 0 ; } |
Find largest factor of N such that N / F is less than K | C ++ program for the above approach ; Function to find the largest factor of N which is less than or equal to K ; Initialise the variable to store the largest factor of N <= K ; Loop to find all factors of N ; Check if j is a factor of N or not ; Check if j <= K If yes , then store the larger value between ans and j in ans ; Check if N / j <= K If yes , then store the larger value between ans and j in ans ; Since max value is always stored in ans , the maximum value divisible by N less than or equal to K will be returned . ; Driver Code ; Given N and K ; Function Call | #include <iostream> NEW_LINE using namespace std ; int solve ( int n , int k ) { int ans = 0 ; for ( int j = 1 ; j * j <= n ; j ++ ) { if ( n % j == 0 ) { if ( j <= k ) { ans = max ( ans , j ) ; } if ( n / j <= k ) { ans = max ( ans , n / j ) ; } } } return ans ; } int main ( ) { int N = 8 , K = 7 ; cout << ( N / solve ( N , K ) ) ; return 0 ; } |
Maximum sum subarray of size range [ L , R ] | C ++ program to find Maximum sum subarray of size between L and R . ; function to find Maximum sum subarray of size between L and R ; calculating prefix sum ; maintain 0 for initial values of i upto R Once i = R , then we need to erase that 0 from our multiset as our first index of subarray cannot be 0 anymore . ; we maintain flag to counter if that initial 0 was erased from set or not . ; erase 0 from multiset once i = b ; insert pre [ i - L ] ; find minimum value in multiset . ; erase pre [ i - R ] ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void max_sum_subarray ( vector < int > arr , int L , int R ) { int n = arr . size ( ) ; int pre [ n ] = { 0 } ; pre [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { pre [ i ] = pre [ i - 1 ] + arr [ i ] ; } multiset < int > s1 ; s1 . insert ( 0 ) ; int ans = INT_MIN ; ans = max ( ans , pre [ L - 1 ] ) ; int flag = 0 ; for ( int i = L ; i < n ; i ++ ) { if ( i - R >= 0 ) { if ( flag == 0 ) { auto it = s1 . find ( 0 ) ; s1 . erase ( it ) ; flag = 1 ; } } if ( i - L >= 0 ) s1 . insert ( pre [ i - L ] ) ; ans = max ( ans , pre [ i ] - * s1 . begin ( ) ) ; if ( i - R >= 0 ) { auto it = s1 . find ( pre [ i - R ] ) ; s1 . erase ( it ) ; } } cout << ans << endl ; } int main ( ) { int L , R ; L = 1 ; R = 3 ; vector < int > arr = { 1 , 2 , 2 , 1 } ; max_sum_subarray ( arr , L , R ) ; return 0 ; } |
Count of ways to select K consecutive empty cells from a given Matrix | C ++ program to find no of ways to select K consecutive empty cells from a row or column ; Function to Traverse the matrix row wise ; Initialize ans ; Traverse row wise ; Initialize no of consecutive empty cells ; Check if blocked cell is encountered then reset countcons to 0 ; Check if empty cell is encountered , then increment countcons ; Check if number of empty consecutive cells is greater or equal to K , increment the ans ; Return the count ; Function to Traverse the matrix column wise ; Initialize ans ; Traverse column wise ; Initialize no of consecutive empty cells ; Check if blocked cell is encountered then reset countcons to 0 ; Check if empty cell is encountered , increment countcons ; Check if number of empty consecutive cells is greater than or equal to K , increment the ans ; Return the count ; Driver Code ; If k = 1 only traverse row wise ; Traverse both row and column wise | #include <bits/stdc++.h> NEW_LINE using namespace std ; int rowWise ( char * v , int n , int m , int k ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int countcons = 0 ; for ( int j = 0 ; j < m ; j ++ ) { if ( * ( v + i * m + j ) == '1' ) { countcons = 0 ; } else { countcons ++ ; } if ( countcons >= k ) { ans ++ ; } } } return ans ; } int colWise ( char * v , int n , int m , int k ) { int ans = 0 ; for ( int i = 0 ; i < m ; i ++ ) { int countcons = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( * ( v + j * n + i ) == '1' ) { countcons = 0 ; } else { countcons ++ ; } if ( countcons >= k ) { ans ++ ; } } } return ans ; } int main ( ) { int n = 3 , m = 3 , k = 1 ; char v [ n ] [ m ] = { '0' , '0' , '0' , '0' , '0' , '0' , '0' , '0' , '0' } ; if ( k == 1 ) { cout << rowWise ( v [ 0 ] , n , m , k ) ; } else { cout << colWise ( v [ 0 ] , n , m , k ) + rowWise ( v [ 0 ] , n , m , k ) ; } return 0 ; } |
Check if the count of inversions of two given types on an Array are equal or not | C ++ Program to implement the above approach ; Function to check if the count of inversion of two types are same or not ; If maximum value is found to be greater than a [ j ] , then that pair of indices ( i , j ) will add extra value to inversion of Type 1 ; Update max ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool solve ( int a [ ] , int n ) { int mx = INT_MIN ; for ( int j = 1 ; j < n ; j ++ ) { if ( mx > a [ j ] ) return false ; mx = max ( mx , a [ j - 1 ] ) ; } return true ; } int main ( ) { int a [ ] = { 1 , 0 , 2 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; bool possible = solve ( a , n ) ; if ( possible ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; } |
How to validate an IP address using ReGex | C ++ program to validate IP address using Regex ; Function for Validating IP ; Regex expression for validating IPv4 ; Regex expression for validating IPv6 ; Checking if it is a valid IPv4 addresses ; Checking if it is a valid IPv6 addresses ; Return Invalid ; Driver Code ; IP addresses to validate | #include <bits/stdc++.h> NEW_LINE using namespace std ; string Validate_It ( string IP ) { regex ipv4 ( " ( ( [ 0-9 ] β [ 1-9 ] [ 0-9 ] β 1[0-9 ] [ 0-9 ] β 2[0-4 ] [ 0-9 ] β 25[0-5 ] ) \\ . ) { 3 } ( [0-9 ] β [ 1-9 ] [ 0-9 ] β 1[0-9 ] [ 0-9 ] β 2[0-4 ] [ 0-9 ] β 25[0-5 ] ) " ) ; regex ipv6 ( " ( ( ( [0-9a - fA - F ] ) { 1,4 } ) \\ : ) { 7 } ( [0-9a - fA - F ] ) { 1,4 } " ) ; if ( regex_match ( IP , ipv4 ) ) return " Valid β IPv4" ; else if ( regex_match ( IP , ipv6 ) ) return " Valid β IPv6" ; return " Invalid β IP " ; } int main ( ) { string IP = "203.120.223.13" ; cout << Validate_It ( IP ) << endl ; IP = " fffe : 3465 : efab : 23fe : 2235:6565 : aaab : 0001" ; cout << Validate_It ( IP ) << endl ; IP = "2F33:12a0:3Ea0:0302" ; cout << Validate_It ( IP ) << endl ; return 0 ; } |
Count of prime factors of N to be added at each step to convert N to M | C ++ program to find the minimum steps required to convert a number N to M . ; Array to store shortest prime factor of every integer ; Function to precompute shortest prime factors ; Function to insert distinct prime factors of every integer into a set ; Store distinct prime factors ; Function to return minimum steps using BFS ; Queue of pairs to store the current number and distance from root . ; Set to store distinct prime factors ; Run BFS ; Find out the prime factors of newNum ; Iterate over every prime factor of newNum . ; If M is obtained ; Return number of operations ; If M is exceeded ; Otherwise ; Update and store the new number obtained by prime factor ; If M cannot be obtained ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int spf [ 100009 ] ; void sieve ( ) { memset ( spf , -1 , 100005 ) ; for ( int i = 2 ; i * i <= 100005 ; i ++ ) { for ( int j = i ; j <= 100005 ; j += i ) { if ( spf [ j ] == -1 ) { spf [ j ] = i ; } } } } set < int > findPrimeFactors ( set < int > s , int n ) { while ( n > 1 ) { s . insert ( spf [ n ] ) ; n /= spf [ n ] ; } return s ; } int MinimumSteps ( int n , int m ) { queue < pair < int , int > > q ; set < int > s ; q . push ( { n , 0 } ) ; while ( ! q . empty ( ) ) { int newNum = q . front ( ) . first ; int distance = q . front ( ) . second ; q . pop ( ) ; set < int > k = findPrimeFactors ( s , newNum ) ; for ( auto i : k ) { if ( newNum == m ) { return distance ; } else if ( newNum > m ) { break ; } else { q . push ( { newNum + i , distance + 1 } ) ; } } } return -1 ; } int main ( ) { int N = 7 , M = 16 ; sieve ( ) ; cout << MinimumSteps ( N , M ) ; } |
Count of elements which is product of a pair or an element square | C ++ Program to implement the above approach ; Stores all factors a number ; Function to calculate and store in a vector ; Function to return the count of array elements which are a product of two array elements ; Copy elements into a a duplicate array ; Sort the duplicate array ; Store the count of elements ; If the factors are not calculated already ; Traverse its factors ; If a pair of factors is found ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > v [ 100000 ] ; void div ( int n ) { for ( int i = 2 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { v [ n ] . push_back ( i ) ; } } } int prodof2elements ( int arr [ ] , int n ) { int arr2 [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { arr2 [ i ] = arr [ i ] ; } sort ( arr2 , arr2 + n ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( v [ arr [ i ] ] . size ( ) == 0 ) div ( arr [ i ] ) ; for ( auto j : v [ arr [ i ] ] ) { if ( binary_search ( arr2 , arr2 + n , j ) and binary_search ( arr2 , arr2 + n , arr [ i ] / j ) ) { ans ++ ; break ; } } } return ans ; } int main ( ) { int arr [ ] = { 2 , 1 , 8 , 4 , 32 , 18 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << prodof2elements ( arr , N ) ; return 0 ; } |
Largest subarray with frequency of all elements same | C ++ program for the above approach ; Function to find maximum subarray size ; Generating all subarray i -> starting index j -> end index ; Map 1 to hash frequency of all elements in subarray ; Map 2 to hash frequency of all frequencies of elements ; ele_count is the previous frequency of arr [ j ] ; Finding previous frequency of arr [ j ] in map 1 ; Increasing frequency of arr [ j ] by 1 ; Check if previous frequency is present in map 2 ; Delete previous frequency if hash is equal to 1 ; Decrement the hash of previous frequency ; Incrementing hash of new frequency in map 2 ; Check if map2 size is 1 and updating answer ; Return the maximum size of subarray ; Driver Code ; Given array arr [ ] ; Function Call | #include <iostream> NEW_LINE #include <unordered_map> NEW_LINE using namespace std ; int max_subarray_size ( int N , int arr [ ] ) { int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { unordered_map < int , int > map1 ; unordered_map < int , int > map2 ; for ( int j = i ; j < N ; j ++ ) { int ele_count ; if ( map1 . find ( arr [ j ] ) == map1 . end ( ) ) { ele_count = 0 ; } else { ele_count = map1 [ arr [ j ] ] ; } map1 [ arr [ j ] ] ++ ; if ( map2 . find ( ele_count ) != map2 . end ( ) ) { if ( map2 [ ele_count ] == 1 ) { map2 . erase ( ele_count ) ; } else { map2 [ ele_count ] -- ; } } map2 [ ele_count + 1 ] ++ ; if ( map2 . size ( ) == 1 ) ans = max ( ans , j - i + 1 ) ; } } return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 2 , 5 , 6 , 5 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << max_subarray_size ( N , arr ) ; return 0 ; } |
Longest substring consisting of vowels using Binary Search | C ++ implementation of the above approach ; Function to check if a character is vowel or not ; 0 - a 1 - b 2 - c and so on 25 - z ; Function to check if any substring of length k exists which contains only vowels ; Applying sliding window to get all substrings of length K ; Remove the occurence of ( i - k + 1 ) th character ; Function to perform Binary Search ; Doing binary search on the lengths ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool vowel ( int vo ) { if ( vo == 0 vo == 4 vo == 8 vo == 14 vo == 20 ) return true ; else return false ; } bool check ( string s , int k ) { vector < int > cnt ( 26 , 0 ) ; for ( int i = 0 ; i < k - 1 ; i ++ ) { cnt [ s [ i ] - ' a ' ] ++ ; } for ( int i = k - 1 ; i < s . size ( ) ; i ++ ) { cnt [ s [ i ] - ' a ' ] ++ ; int flag1 = 0 ; for ( int j = 0 ; j < 26 ; j ++ ) { if ( vowel ( j ) == false && cnt [ j ] > 0 ) { flag1 = 1 ; break ; } } if ( flag1 == 0 ) return true ; cnt [ s [ i - k + 1 ] - ' a ' ] -- ; } return false ; } int longestSubstring ( string s ) { int l = 1 , r = s . size ( ) ; int maxi = 0 ; while ( l <= r ) { int mid = ( l + r ) / 2 ; if ( check ( s , mid ) ) { l = mid + 1 ; maxi = max ( maxi , mid ) ; } else r = mid - 1 ; } return maxi ; } int main ( ) { string s = " sedrewaefhoiu " ; cout << longestSubstring ( s ) ; return 0 ; } |
Find number of pairs ( x , y ) in an Array such that x ^ y > y ^ x | Set 2 | C ++ program to finds the number of pairs ( x , y ) from X [ ] and Y [ ] such that x ^ y > y ^ x ; Function to return the count of pairs ; Compute suffix sums till i = 3 ; Base Case : x = 0 ; No valid pairs ; Base Case : x = 1 ; Store the count of 0 's ; Base Case : x = 2 ; Store suffix sum upto 5 ; Base Case : x = 3 ; Store count of 2 and suffix sum upto 4 ; For all other values of x ; For all x >= 2 , every y = 0 and every y = 1 makes a valid pair ; Return the count of pairs ; Driver Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int X [ ] , int Y [ ] , int m , int n ) { vector < int > suffix ( 1005 ) ; long long total_pairs = 0 ; for ( int i = 0 ; i < n ; i ++ ) suffix [ Y [ i ] ] ++ ; for ( int i = 1e3 ; i >= 3 ; i -- ) suffix [ i ] += suffix [ i + 1 ] ; for ( int i = 0 ; i < m ; i ++ ) { if ( X [ i ] == 0 ) continue ; else if ( X [ i ] == 1 ) { total_pairs += suffix [ 0 ] ; continue ; } else if ( X [ i ] == 2 ) total_pairs += suffix [ 5 ] ; else if ( X [ i ] == 3 ) total_pairs += suffix [ 2 ] + suffix [ 4 ] ; else total_pairs += suffix [ X [ i ] + 1 ] ; total_pairs += suffix [ 0 ] + suffix [ 1 ] ; } return total_pairs ; } int main ( ) { int X [ ] = { 10 , 19 , 18 } ; int Y [ ] = { 11 , 15 , 9 } ; int m = sizeof ( X ) / sizeof ( X [ 0 ] ) ; int n = sizeof ( Y ) / sizeof ( Y [ 0 ] ) ; cout << countPairs ( X , Y , m , n ) ; return 0 ; } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.