text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Rearrange array to maximize count of local minima | C ++ program to implement the above approach ; Function to rearrange array elements to maximize count of local minima in the array ; Sort the array in ascending order ; Stores index of left pointer ; Stores index of right pointer ; Traverse the array elements ; if right is less than N ; Print array element ; Update right ; Print array element ; Update left ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void rearrangeArrMaxcntMinima ( int arr [ ] , int N ) { sort ( arr , arr + N ) ; int left = 0 ; int right = N / 2 ; while ( left < N / 2 right < N ) { if ( right < N ) { cout << arr [ right ] << " ▁ " ; right ++ ; } if ( left < N / 2 ) { cout << arr [ left ] << " ▁ " ; left ++ ; } } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; rearrangeArrMaxcntMinima ( arr , N ) ; return 0 ; }
Minimum jumps required to make a group of persons sit together | C ++ program for the above approach ; Function to find the minimum jumps required to make the whole group sit adjacently ; Store the indexes ; Stores the count of occupants ; Length of the string ; Traverse the seats ; If current place is occupied ; Push the current position in the vector ; Base Case : ; The index of the median element ; The value of the median element ; Traverse the position [ ] ; Update the ans ; Return the final count ; Driver Code ; Given arrange of seats ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long int MOD = 1e9 + 7 ; int minJumps ( string seats ) { vector < int > position ; int count = 0 ; int len = seats . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { if ( seats [ i ] == ' x ' ) { position . push_back ( i - count ) ; count ++ ; } } if ( count == len count == 0 ) return 0 ; int med_index = ( count - 1 ) / 2 ; int med_val = position [ med_index ] ; int ans = 0 ; for ( int i = 0 ; i < position . size ( ) ; i ++ ) { ans = ( ans % MOD + abs ( position [ i ] - med_val ) % MOD ) % MOD ; } return ans % MOD ; } int main ( ) { string S = " . . . . x . . xx . . . x . . " ; cout << minJumps ( S ) ; return 0 ; }
Count pairs whose product contains single distinct prime factor | C ++ program to implement the above approach ; Function to find a single distinct prime factor of N ; Stores distinct prime factors of N ; Calculate prime factor of N ; Calculate distinct prime factor ; Insert i into disPrimeFact ; Update N ; If N is not equal to 1 ; Insert N into disPrimeFact ; If N contains a single distinct prime factor ; Return single distinct prime factor of N ; If N contains more than one distinct prime factor ; Function to count pairs in the array whose product contains only single distinct prime factor ; Stores count of 1 s in the array ; mp [ i ] : Stores count of array elements whose distinct prime factor is only i ; Traverse the array arr [ ] ; If current element is 1 ; Store distinct prime factor of arr [ i ] ; If arr [ i ] contains more than one prime factor ; If arr [ i ] contains a single prime factor ; Stores the count of pairs whose product of elements contains only a single distinct prime factor ; Traverse the map mp [ ] ; Stores count of array elements whose prime factor is ( it . first ) ; Update res ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int singlePrimeFactor ( int N ) { unordered_set < int > disPrimeFact ; for ( int i = 2 ; i * i <= N ; ++ i ) { while ( N % i == 0 ) { disPrimeFact . insert ( i ) ; N /= i ; } } if ( N != 1 ) { disPrimeFact . insert ( N ) ; } if ( disPrimeFact . size ( ) == 1 ) { return * disPrimeFact . begin ( ) ; } return -1 ; } int cntsingleFactorPair ( int arr [ ] , int N ) { int countOf1 = 0 ; unordered_map < int , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == 1 ) { countOf1 ++ ; continue ; } int factorValue = singlePrimeFactor ( arr [ i ] ) ; if ( factorValue == -1 ) { continue ; } else { mp [ factorValue ] ++ ; } } int res = 0 ; for ( auto it : mp ) { int X = it . second ; res += countOf1 * X + ( X * ( X - 1 ) ) / 2 ; } return res ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << cntsingleFactorPair ( arr , N ) ; return 0 ; }
Minimize replacements or swapping of same indexed characters required to make two given strings palindromic | C ++ program to implement the above approach ; Function to find minimum operations to make both the strings palindromic ; Stores index of the left pointer ; Stores index of the right pointer ; Stores count of minimum operations to make both the strings palindromic ; if str1 [ i ] equal to str1 [ j ] and str2 [ i ] not equal to str2 [ j ] ; Update cntOp ; If str1 [ i ] not equal to str1 [ j ] and str2 [ i ] equal to str2 [ j ] ; Update cntOp ; If str1 [ i ] is not equal to str1 [ j ] and str2 [ i ] is not equal to str2 [ j ] ; If str1 [ i ] is equal to str2 [ j ] and str2 [ i ] is equal to str1 [ j ] ; Update cntOp ; Update cntOp ; Update i and j ; Driver Code ; Stores length of str1
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MincntBothPalin ( string str1 , string str2 , int N ) { int i = 0 ; int j = N - 1 ; int cntOp = 0 ; while ( i < j ) { if ( str1 [ i ] == str1 [ j ] && str2 [ i ] != str2 [ j ] ) { cntOp += 1 ; } else if ( str1 [ i ] != str1 [ j ] && str2 [ i ] == str2 [ j ] ) { cntOp += 1 ; } else if ( str1 [ i ] != str1 [ j ] && str2 [ i ] != str2 [ j ] ) { if ( str1 [ i ] == str2 [ j ] && str2 [ i ] == str1 [ j ] ) { cntOp += 1 ; } else { cntOp += 2 ; } } i += 1 ; j -= 1 ; } return cntOp ; } int main ( ) { string str1 = " dbba " ; string str2 = " abcd " ; int N = str1 . length ( ) ; cout << MincntBothPalin ( str1 , str2 , N ) ; }
Find an integral solution of the non | C ++ program to implement the above approach ; Function to find the value of power ( X , N ) ; Stores the value of ( X ^ N ) ; Calculate the value of power ( x , N ) ; If N is odd ; Update res ; Update x ; Update N ; Function to find the value of X and Y that satisfy the condition ; Base Case ; Stores maximum possible of X . ; Update xMax ; Stores maximum possible of Y . ; Update yMax ; Iterate over all possible values of X ; Iterate over all possible values of Y ; Stores value of 2 ^ i ; Stores value of 5 ^ j ; If the pair ( i , j ) satisfy the equation ; If no solution exists ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long power ( long long x , long long N ) { long long res = 1 ; while ( N > 0 ) { if ( N & 1 ) { res = ( res * x ) ; } x = ( x * x ) ; N = N >> 1 ; } return res ; } void findValX_Y ( long long N ) { if ( N <= 1 ) { cout << -1 << endl ; return ; } int xMax ; xMax = log2 ( N ) ; int yMax ; yMax = ( log2 ( N ) / log2 ( 5.0 ) ) ; for ( long long i = 1 ; i <= xMax ; i ++ ) { for ( long long j = 1 ; j <= yMax ; j ++ ) { long long a = power ( 2 , i ) ; long long b = power ( 5 , j ) ; if ( a + b == N ) { cout << i << " ▁ " << j << endl ; return ; } } } cout << -1 << endl ; } int main ( ) { long long N = 129 ; findValX_Y ( N ) ; return 0 ; }
Count pairs from two arrays with difference exceeding K | set 2 | C ++ program for the above approach ; Function to count pairs that satisfy the given conditions ; Stores the count of pairs ; If v1 [ ] is smaller than v2 [ ] ; Sort the array v1 [ ] ; Traverse the array v2 [ ] ; Returns the address of the first number which is >= v2 [ j ] - k ; Increase the count by all numbers less than v2 [ j ] - k ; Otherwise ; Sort the array v2 [ ] ; Traverse the array v1 [ ] ; Returns the address of the first number which is > v1 [ i ] + k ; Increase the count by all numbers greater than v1 [ i ] + k ; Return the total count of pairs ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int v1 [ ] , int v2 [ ] , int n , int m , int k ) { int count = 0 ; if ( n <= m ) { sort ( v1 , v1 + n ) ; for ( int j = 0 ; j < m ; j ++ ) { int index = lower_bound ( v1 , v1 + n , v2 [ j ] - k ) - v1 ; count += index ; } } else { sort ( v2 , v2 + m ) ; for ( int i = 0 ; i < n ; i ++ ) { int index = upper_bound ( v2 , v2 + m , v1 [ i ] + k ) - v2 ; count += m - index ; } } return count ; } int main ( ) { int arr [ ] = { 5 , 9 , 1 , 8 } ; int brr [ ] = { 10 , 12 , 7 , 4 , 2 , 3 } ; int K = 3 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int M = sizeof ( brr ) / sizeof ( brr [ 0 ] ) ; cout << countPairs ( arr , brr , N , M , K ) ; return 0 ; }
Print siblings of a given Node in N | C ++ program for the above approach ; Structure of a node of N - ary tree ; Function to create a new node ; Function to find the siblings of the node value ; Stores nodes level wise ; Push the root ; Continue until all levels are traversed ; Stores current node ; Enqueue all children of the current node ; If node value is found ; Print all children of current node except value as the answer ; Push the child nodes of temp into the queue ; Driver Code ; Stores root of the constructed tree ; Print siblings of Node X
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; vector < Node * > child ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; return temp ; } void Siblings ( Node * root , int value ) { int flag = 0 ; if ( root == NULL ) return ; queue < Node * > q ; q . push ( root ) ; while ( ! q . empty ( ) ) { Node * temp = q . front ( ) ; q . pop ( ) ; for ( int i = 0 ; i < temp -> child . size ( ) ; i ++ ) { if ( temp -> child [ i ] -> key == value ) { flag = 1 ; for ( int j = 0 ; j < temp -> child . size ( ) ; j ++ ) { if ( value != temp -> child [ j ] -> key ) cout << temp -> child [ j ] -> key << " ▁ " ; } break ; } q . push ( temp -> child [ i ] ) ; } } if ( flag == 0 ) cout << " No ▁ siblings ! ! " ; } Node * constructTree ( ) { Node * root = newNode ( 10 ) ; ( root -> child ) . push_back ( newNode ( 20 ) ) ; ( root -> child ) . push_back ( newNode ( 30 ) ) ; ( root -> child ) . push_back ( newNode ( 40 ) ) ; ( root -> child [ 0 ] -> child ) . push_back ( newNode ( 50 ) ) ; ( root -> child [ 0 ] -> child ) . push_back ( newNode ( 60 ) ) ; ( root -> child [ 1 ] -> child ) . push_back ( newNode ( 70 ) ) ; ( root -> child [ 1 ] -> child ) . push_back ( newNode ( 80 ) ) ; ( root -> child [ 2 ] -> child ) . push_back ( newNode ( 90 ) ) ; ( root -> child [ 2 ] -> child ) . push_back ( newNode ( 100 ) ) ; ( root -> child [ 2 ] -> child ) . push_back ( newNode ( 110 ) ) ; return root ; } int main ( ) { Node * root = constructTree ( ) ; int X = 30 ; Siblings ( root , X ) ; return 0 ; }
Maximum sum subarray of size K with sum less than X | C ++ program for the above approach ; Function to calculate maximum sum among all subarrays of size K with the sum less than X ; Initialize sum_K to 0 ; Calculate sum of first K elements ; If sum_K is less than X ; Initialize MaxSum with sum_K ; Iterate over the array from ( K + 1 ) - th index ; Subtract the first element from the previous K elements and add the next element ; If sum_K is less than X ; Update the Max_Sum ; Driver Code ; Size of Array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxSumSubarr ( int A [ ] , int N , int K , int X ) { int sum_K = 0 ; for ( int i = 0 ; i < K ; i ++ ) { sum_K += A [ i ] ; } int Max_Sum = 0 ; if ( sum_K < X ) { Max_Sum = sum_K ; } for ( int i = K ; i < N ; i ++ ) { sum_K -= ( A [ i - K ] - A [ i ] ) ; if ( sum_K < X ) { Max_Sum = max ( Max_Sum , sum_K ) ; } } cout << Max_Sum << endl ; } int main ( ) { int arr [ ] = { -5 , 8 , 7 , 2 , 10 , 1 , 20 , -4 , 6 , 9 } ; int K = 5 ; int X = 30 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maxSumSubarr ( arr , N , K , X ) ; return 0 ; }
Rearrange array to make sum of all subarrays starting from first index non | C ++ program for the above approach ; Function to rearrange the array such that sum of all elements of subarrays from the 1 st index is non - zero ; Initialize sum of subarrays ; Sum of all elements of array ; If sum is 0 , the required array could never be formed ; If sum is non zero , array might be formed ; Sort array in ascending order ; When current subarray sum becomes 0 replace it with the largest element ; Swap Operation ; If largest element is same as element to be replaced , then rearrangement impossible ; If b = 1 , then rearrangement is not possible . Hence check with reverse configuration ; Sort array in descending order ; When current subarray sum becomes 0 replace it with the smallest element ; Swap Operation ; If smallest element is same as element to be replaced , then rearrangement impossible ; If neither of the configurations worked then print " - 1" ; Otherwise , print the formed rearrangement ; Driver Code ; Given array ; Size of array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void rearrangeArray ( int a [ ] , int N ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += a [ i ] ; } if ( sum == 0 ) { cout << " - 1" ; return ; } sum = 0 ; int b = 0 ; sort ( a , a + N ) ; for ( int i = 0 ; i < N ; i ++ ) { sum += a [ i ] ; if ( sum == 0 ) { if ( a [ i ] != a [ N - 1 ] ) { sum -= a [ i ] ; swap ( a [ i ] , a [ N - 1 ] ) ; sum += a [ i ] ; } else { b = 1 ; break ; } } } if ( b == 1 ) { b = 0 ; sum = 0 ; sort ( a , a + N , greater < int > ( ) ) ; for ( int i = N - 1 ; i >= 0 ; i -- ) { sum += a [ i ] ; if ( sum == 0 ) { if ( a [ i ] != a [ 0 ] ) { sum -= a [ i ] ; swap ( a [ i ] , a [ 0 ] ) ; sum += a [ i ] ; } else { b = 1 ; break ; } } } } if ( b == 1 ) { cout << " - 1" ; return ; } for ( int i = 0 ; i < N ; i ++ ) { cout << a [ i ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 1 , -1 , 2 , 4 , 0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; rearrangeArray ( arr , N ) ; return 0 ; }
Length of smallest subarray to be removed to make sum of remaining elements divisible by K | C ++ program for the above approach ; Function to find the length of the smallest subarray to be removed such that sum of elements is divisible by K ; Stores the remainder of each arr [ i ] when divided by K ; Stores total sum of elements ; K has been added to each arr [ i ] to handle - ve integers ; Update the total sum ; Remainder when total_sum is divided by K ; If given array is already divisible by K ; Stores curr_remainder and the most recent index at which curr_remainder has occurred ; Stores required answer ; Add current element to curr_sum and take mod ; Update current remainder index ; If mod already exists in map the subarray exists ; If not possible ; Print the result ; Driver Code ; Given array arr [ ] ; Size of array ; Given K ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void removeSmallestSubarray ( int arr [ ] , int n , int k ) { int mod_arr [ n ] ; int total_sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { mod_arr [ i ] = ( arr [ i ] + k ) % k ; total_sum += arr [ i ] ; } int target_remainder = total_sum % k ; if ( target_remainder == 0 ) { cout << "0" ; return ; } unordered_map < int , int > map1 ; map1 [ 0 ] = -1 ; int curr_remainder = 0 ; int res = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { curr_remainder = ( curr_remainder + arr [ i ] + k ) % k ; map1 [ curr_remainder ] = i ; int mod = ( curr_remainder - target_remainder + k ) % k ; if ( map1 . find ( mod ) != map1 . end ( ) ) res = min ( res , i - map1 [ mod ] ) ; } if ( res == INT_MAX res == n ) { res = -1 ; } cout << res ; } int main ( ) { int arr [ ] = { 3 , 1 , 4 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 6 ; removeSmallestSubarray ( arr , N , K ) ; return 0 ; }
Queries to flip characters of a binary string in given range | C ++ program to implement the above approach ; Function to find the binary string by performing all the given queries ; Stores length of the string ; prefixCnt [ i ] : Stores number of times str [ i ] toggled by performing all the queries ; Update prefixCnt [ Q [ i ] [ 0 ] ] ; Update prefixCnt [ Q [ i ] [ 1 ] + 1 ] ; Calculate prefix sum of prefixCnt [ i ] ; Traverse prefixCnt [ ] array ; If ith element toggled odd number of times ; Toggled i - th element of binary string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string toggleQuery ( string str , int Q [ ] [ 2 ] , int M ) { int N = str . length ( ) ; int prefixCnt [ N + 1 ] = { 0 } ; for ( int i = 0 ; i < M ; i ++ ) { prefixCnt [ Q [ i ] [ 0 ] ] += 1 ; prefixCnt [ Q [ i ] [ 1 ] + 1 ] -= 1 ; } for ( int i = 1 ; i <= N ; i ++ ) { prefixCnt [ i ] += prefixCnt [ i - 1 ] ; } for ( int i = 0 ; i < N ; i ++ ) { if ( prefixCnt [ i ] % 2 ) { str [ i ] = '1' - str [ i ] + '0' ; } } return str ; } int main ( ) { string str = "101010" ; int Q [ ] [ 2 ] = { { 0 , 1 } , { 2 , 5 } , { 2 , 3 } , { 1 , 4 } , { 0 , 5 } } ; int M = sizeof ( Q ) / sizeof ( Q [ 0 ] ) ; cout << toggleQuery ( str , Q , M ) ; }
Maximum length possible by cutting N given woods into at least K pieces | C ++ program to implement the above approach ; Function to check if it is possible to cut woods into K pieces of length len ; Stores count of pieces having length equal to K ; Traverse wood [ ] array ; Update count ; Function to find the maximum value of L ; Stores minimum possible of L ; Stores maximum possible value of L ; Apply binary search over the range [ left , right ] ; Stores mid value of left and right ; If it is possible to cut woods into K pieces having length of each piece equal to mid ; Update left ; Update right ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isValid ( int wood [ ] , int N , int len , int K ) { int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { count += wood [ i ] / len ; } return count >= K ; } int findMaxLen ( int wood [ ] , int N , int K ) { int left = 1 ; int right = * max_element ( wood , wood + N ) ; while ( left <= right ) { int mid = left + ( right - left ) / 2 ; if ( isValid ( wood , N , mid , K ) ) { left = mid + 1 ; } else { right = mid - 1 ; } } return right ; } int main ( ) { int wood [ ] = { 5 , 9 , 7 } ; int N = sizeof ( wood ) / sizeof ( wood [ 0 ] ) ; int K = 4 ; cout << findMaxLen ( wood , N , K ) ; }
Count quadruplets with sum K from given array | C ++ program for the above approach ; Function to return the number of quadruplets with the given sum ; Initialize variables ; Initialize answer ; All possible first elements ; All possible second elements ; All possible third elements ; All possible fourth elements ; Increment counter by 1 if quadruplet sum is S ; Return the final count ; Driver Code ; Given array arr [ ] ; Given sum S ; Function Call
#include <iostream> NEW_LINE using namespace std ; int countSum ( int a [ ] , int n , int sum ) { int i , j , k , l ; int count = 0 ; for ( i = 0 ; i < n - 3 ; i ++ ) { for ( j = i + 1 ; j < n - 2 ; j ++ ) { for ( k = j + 1 ; k < n - 1 ; k ++ ) { for ( l = k + 1 ; l < n ; l ++ ) { if ( a [ i ] + a [ j ] + a [ k ] + a [ l ] == sum ) count ++ ; } } } } return count ; } int main ( ) { int arr [ ] = { 4 , 5 , 3 , 1 , 2 , 4 } ; int S = 13 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countSum ( arr , N , S ) ; return 0 ; }
Minimum adjacent swaps to group similar characters together | C ++ program for the above approach ; Function to find minimum adjacent swaps required to make all the same character adjacent ; Initialize answer ; Create a 2D array of size 26 ; Traverse the string ; Get character ; Append the current index in the corresponding vector ; Traverse each character from a to z ; Add difference of adjacent index ; Return answer ; Driver Code ; Given string ; Size of string ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minSwaps ( string S , int n ) { int swaps = 0 ; vector < vector < int > > arr ( 26 ) ; for ( int i = 0 ; i < n ; i ++ ) { int pos = S [ i ] - ' a ' ; arr [ pos ] . push_back ( i ) ; } for ( char ch = ' a ' ; ch <= ' z ' ; ++ ch ) { int pos = ch - ' a ' ; for ( int i = 1 ; i < arr [ pos ] . size ( ) ; ++ i ) { swaps += abs ( arr [ pos ] [ i ] - arr [ pos ] [ i - 1 ] - 1 ) ; } } return swaps ; } int main ( ) { string S = " abbccabbcc " ; int N = S . length ( ) ; cout << minSwaps ( S , N ) ; return 0 ; }
Construct a graph which does not contain any pair of adjacent nodes with same value | C ++ program for the above approach ; Function that prints the edges of the generated graph ; First print connections stored in store [ ] ; Check if there is more than one occurrence of 1 st unique element ; Print all other occurrence of 1 st unique element with second unique element ; Function to construct the graph such that the every adjacent nodes have different value ; Stores pair of edges formed ; Stores first unique occurrence ; Check for the second unique occurrence ; Store indices of 2 nd unique occurrence ; To check if arr has only 1 unique element or not ; Store the connections of all unique elements with Node 1 ; If value at node ( i + 1 ) is same as value at Node 1 then store its indices ; If count is zero then it 's not possible to construct the graph ; If more than 1 unique element is present ; Print the edges ; Driver Code ; Given array having node values ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printConnections ( vector < pair < int , int > > store , vector < int > ind , int ind1 ) { for ( auto pr : store ) { cout << pr . first << " ▁ " << pr . second << " STRNEWLINE " ; } if ( ind . size ( ) != 0 ) { for ( auto x : ind ) { cout << ind1 << " ▁ " << x + 1 << " STRNEWLINE " ; } } } void constructGraph ( char arr [ ] , int N ) { vector < int > ind ; vector < pair < int , int > > store ; char x = arr [ 0 ] ; int count = 0 , ind1 ; for ( int i = 1 ; i <= N - 1 ; ++ i ) { if ( arr [ i ] != x ) { ind1 = i + 1 ; count ++ ; store . push_back ( { 1 , i + 1 } ) ; } else { ind . push_back ( i ) ; } } if ( count == 0 ) { cout << " Not ▁ Possible " ; } else { cout << " Possible " << " STRNEWLINE " ; printConnections ( store , ind , ind1 ) ; } } int main ( ) { int N = 5 ; char arr [ ] = { ' a ' , ' b ' , ' a ' , ' b ' , ' c ' } ; constructGraph ( arr , N ) ; return 0 ; }
Minimum substring flips required to convert given binary string to another | C ++ program for the above approach ; Function that finds the minimum number of operations required such that string A and B are the same ; Stores the count of steps ; Stores the last index whose bits are not same ; Iterate until both string are unequal ; Check till end of string to find rightmost unequals bit ; Update the last index ; Flipping characters up to the last index ; Flip the bit ; Increasing steps by one ; Print the count of steps ; Driver Code ; Given strings A and B ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMinimumOperations ( string a , string b ) { int step = 0 ; int last_index ; while ( a != b ) { for ( int i = 0 ; i < a . length ( ) ; i ++ ) { if ( a [ i ] != b [ i ] ) { last_index = i ; } } for ( int i = 0 ; i <= last_index ; i ++ ) { a [ i ] = ( a [ i ] == '0' ) ? '1' : '0' ; } step ++ ; } cout << step ; } int main ( ) { string A = "101010" , B = "110011" ; findMinimumOperations ( A , B ) ; return 0 ; }
Count all disjoint pairs having absolute difference at least K from a given array | C ++ program for the above approach ; Function to check if it is possible to form M pairs with abs diff at least K ; Traverse the array over [ 0 , M ] ; If valid index ; Return 1 ; Function to count distinct pairs with absolute difference atleasr K ; Stores the count of all possible pairs ; Initialize left and right ; Sort the array ; Perform Binary Search ; Find the value of mid ; Check valid index ; Update ans ; Print the answer ; Driver Code ; Given array arr [ ] ; Given difference K ; Size of the array ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isValid ( int arr [ ] , int n , int m , int d ) { for ( int i = 0 ; i < m ; i ++ ) { if ( abs ( arr [ n - m + i ] - arr [ i ] ) < d ) { return 0 ; } } return 1 ; } int countPairs ( int arr [ ] , int N , int K ) { int ans = 0 ; int left = 0 , right = N / 2 + 1 ; sort ( arr , arr + N ) ; while ( left < right ) { int mid = ( left + right ) / 2 ; if ( isValid ( arr , N , mid , K ) ) { ans = mid ; left = mid + 1 ; } else right = mid - 1 ; } cout << ans << ' ▁ ' ; } int main ( ) { int arr [ ] = { 1 , 3 , 3 , 5 } ; int K = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countPairs ( arr , N , K ) ; return 0 ; }
Minimum common element in subarrays of all possible lengths | C ++ Program to implement the above approach ; Function to find maximum distance between every two element ; Stores index of last occurence of each array element ; Initialize temp [ ] with - 1 ; Traverse the array ; If array element has not occurred previously ; Update index in temp ; Otherwise ; Compare temp [ a [ i ] ] with distance from its previous occurence and store the maximum ; Compare temp [ i ] with distance of its last occurence from the end of the array and store the maximum ; Function to find the minimum common element in subarrays of all possible lengths ; Function call to find a the maximum distance between every pair of repetition ; Initialize ans [ ] to - 1 ; Check if subarray of length temp [ i ] contains i as one of the common elements ; Find the minimum of all common elements ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void max_distance ( int a [ ] , int temp [ ] , int n ) { map < int , int > mp ; for ( int i = 1 ; i <= n ; i ++ ) { temp [ i ] = -1 ; } for ( int i = 0 ; i < n ; i ++ ) { if ( mp . find ( a [ i ] ) == mp . end ( ) ) temp [ a [ i ] ] = i + 1 ; else temp [ a [ i ] ] = max ( temp [ a [ i ] ] , i - mp [ a [ i ] ] ) ; mp [ a [ i ] ] = i ; } for ( int i = 1 ; i <= n ; i ++ ) { if ( temp [ i ] != -1 ) temp [ i ] = max ( temp [ i ] , n - mp [ i ] ) ; } } void min_comm_ele ( int a [ ] , int ans [ ] , int temp [ ] , int n ) { max_distance ( a , temp , n ) ; for ( int i = 1 ; i <= n ; i ++ ) { ans [ i ] = -1 ; } for ( int i = 1 ; i <= n ; i ++ ) { if ( ans [ temp [ i ] ] == -1 ) ans [ temp [ i ] ] = i ; } for ( int i = 1 ; i <= n ; i ++ ) { if ( i > 1 && ans [ i - 1 ] != -1 ) { if ( ans [ i ] == -1 ) ans [ i ] = ans [ i - 1 ] ; else ans [ i ] = min ( ans [ i ] , ans [ i - 1 ] ) ; } cout << ans [ i ] << " ▁ " ; } } int main ( ) { int N = 6 ; int a [ ] = { 1 , 3 , 4 , 5 , 6 , 7 } ; int temp [ 100 ] , ans [ 100 ] ; min_comm_ele ( a , ans , temp , N ) ; return 0 ; }
Find a triplet in an array such that arr [ i ] arr [ k ] and i < j < k | C ++ program to implement the above approach ; Function to find a triplet that satisfy the conditions ; Traverse the given array ; Stores current element ; Stores element just before the current element ; Stores element just after the current element ; Check the given conditions ; Print a triplet ; If no triplet found ; Driver Code
#include <iostream> NEW_LINE using namespace std ; void FindTrip ( int arr [ ] , int N ) { for ( int i = 1 ; i < N - 1 ; i ++ ) { int p = arr [ i - 1 ] ; int q = arr [ i ] ; int r = arr [ i + 1 ] ; if ( p < q && q > r ) { cout << i - 1 << " ▁ " << i << " ▁ " << i + 1 ; return ; } } cout << -1 ; } int main ( ) { int arr [ ] = { 2 , 1 , 4 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; FindTrip ( arr , N ) ; return 0 ; }
Count subarrays having each distinct element occurring at least twice | C ++ program to implement the above approach ; Function to get the count of subarrays having each element occurring at least twice ; Stores count of subarrays having each distinct element occurring at least twice ; Stores count of unique elements in a subarray ; Store frequency of each element of a subarray ; Traverse the given array ; Count frequency and check conditions for each subarray ; Update frequency ; Check if frequency of arr [ j ] equal to 1 ; Update Count of unique elements ; Update count of unique elements ; If each element of subarray occurs at least twice ; Update cntSub ; Remove all elements from the subarray ; Update cntUnique ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int cntSubarrays ( int arr [ ] , int N ) { int cntSub = 0 ; int cntUnique = 0 ; unordered_map < int , int > cntFreq ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = i ; j < N ; j ++ ) { cntFreq [ arr [ j ] ] ++ ; if ( cntFreq [ arr [ j ] ] == 1 ) { cntUnique ++ ; } else if ( cntFreq [ arr [ j ] ] == 2 ) { cntUnique -- ; } if ( cntUnique == 0 ) { cntSub ++ ; } } cntFreq . clear ( ) ; cntUnique = 0 ; } return cntSub ; } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 2 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << cntSubarrays ( arr , N ) ; }
Check if permutation of a given string can be made palindromic by removing at most K characters | C ++ program to implement the above approach ; Function to check if the string satisfies the given conditions or not ; Stores length of given string ; Stores frequency of each character of str ; Update frequency of current character ; Stores count of distinct character whose frequency is odd ; Traverse the cntFreq [ ] array . ; If frequency of character i is odd ; Update cntOddFreq ; If count of distinct character having odd frequency is <= K + 1 ; Driver Code ; If str satisfy the given conditions
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkPalinK ( string str , int K ) { int N = str . length ( ) ; int cntFreq [ 256 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { cntFreq [ str [ i ] ] ++ ; } int cntOddFreq = 0 ; for ( int i = 0 ; i < 256 ; i ++ ) { if ( cntFreq [ i ] % 2 == 1 ) { cntOddFreq ++ ; } } if ( cntOddFreq <= ( K + 1 ) ) { return true ; } return false ; } int main ( ) { string str = " geeksforgeeks " ; int K = 2 ; if ( checkPalinK ( str , K ) ) { cout << " Yes " ; } else { cout << " No " ; } }
Maximum number of elements that can be removed such that MEX of the given array remains unchanged | C ++ program for the above approach ; Function to find the maximum number of elements that can be removed ; Initialize hash [ ] with 0 s ; Initialize MEX ; Set hash [ i ] = 1 , if i is present in arr [ ] ; Find MEX from the hash ; Print the maximum numbers that can be removed ; Driver Code ; Given array ; Size of the array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countRemovableElem ( int arr [ ] , int N ) { int hash [ N + 1 ] = { 0 } ; int mex = N + 1 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] <= N ) hash [ arr [ i ] ] = 1 ; } for ( int i = 1 ; i <= N ; i ++ ) { if ( hash [ i ] == 0 ) { mex = i ; break ; } } cout << N - ( mex - 1 ) ; } int main ( ) { int arr [ ] = { 2 , 3 , 5 , 1 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countRemovableElem ( arr , N ) ; return 0 ; }
Print all positions of a given string having count of smaller characters equal on both sides | C ++ program to implement the above approach ; Function to find indexes of the given string that satisfy the condition ; Stores length of given string ; Stores frequency of each character of str ; Update frequency of current character ; cntLeftFreq [ i ] Stores frequency of characters present on the left side of index i . ; Traverse the given string ; Stores count of smaller characters on left side of i . ; Stores count of smaller characters on Right side of i . ; Traverse smaller characters on left side of index i . ; Update cntLeft ; Update cntRight ; Update cntLeftFreq [ str [ i ] ] ; If count of smaller elements on both sides equal ; Print current index ; ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printIndexes ( string str ) { int N = str . length ( ) ; int cntFreq [ 256 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { cntFreq [ str [ i ] ] ++ ; } int cntLeftFreq [ 256 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { int cntLeft = 0 ; int cntRight = 0 ; for ( int j = str [ i ] - 1 ; j >= 0 ; j -- ) { cntLeft += cntLeftFreq [ j ] ; cntRight += cntFreq [ j ] - cntLeftFreq [ j ] ; } cntLeftFreq [ str [ i ] ] ++ ; if ( cntLeft == cntRight && cntLeft != 0 ) { cout << i << " ▁ " ; } } } int main ( ) { string str = " aabacdabbb " ; printIndexes ( str ) ; }
Count three | C ++ Program to implement the above approach ; Function to count three - digit numbers having difference x with its reverse ; if x is not multiple of 99 ; No solution exists ; Generate all possible pairs of digits [ 1 , 9 ] ; If any pair is obtained with difference x / 99 ; Increase count ; Return the count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Count_Number ( int x ) { int ans = 0 ; if ( x % 99 != 0 ) { ans = -1 ; } else { int diff = x / 99 ; for ( int i = 1 ; i < 10 ; i ++ ) { for ( int j = 1 ; j < 10 ; j ++ ) { if ( ( i - j ) == diff ) { ans += 10 ; } } } } return ans ; } int main ( ) { int x = 792 ; cout << Count_Number ( x ) << endl ; return 0 ; }
Check if a point having maximum X and Y coordinates exists or not | C ++ program for the above approach ; Initialize INF as inifnity ; Function to return the point having maximum X and Y coordinates ; Base Case ; Stores if valid point exists ; If point arr [ i ] is valid ; Check for the same point ; Check for a valid point ; If current point is the required point ; Otherwise ; Function to find the required point ; Stores the point with maximum X and Y - coordinates ; If no required point exists ; Driver Code ; Given array of points ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int INF = INT_MAX ; int * findMaxPoint ( int arr [ ] [ 2 ] , int i , int n ) { if ( i == n ) { arr [ 0 ] [ 0 ] = INF ; arr [ 0 ] [ 1 ] = INF ; return arr [ 0 ] ; } bool flag = true ; for ( int j = 0 ; j < n ; j ++ ) { if ( j == i ) continue ; if ( arr [ j ] [ 0 ] >= arr [ i ] [ 0 ] arr [ j ] [ 1 ] >= arr [ i ] [ 1 ] ) { flag = false ; break ; } } if ( flag ) return arr [ i ] ; return findMaxPoint ( arr , i + 1 , n ) ; } void findMaxPoints ( int arr [ ] [ 2 ] , int n ) { int ans [ 2 ] ; memcpy ( ans , findMaxPoint ( arr , 0 , n ) , 2 * sizeof ( int ) ) ; if ( ans [ 0 ] == INF ) { cout << -1 ; } else { cout << " ( " << ans [ 0 ] << " ▁ " << ans [ 1 ] << " ) " ; } } int main ( ) { int arr [ ] [ 2 ] = { { 1 , 2 } , { 2 , 1 } , { 3 , 4 } , { 4 , 3 } , { 5 , 5 } } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findMaxPoints ( arr , N ) ; return 0 ; }
Check if a point having maximum X and Y coordinates exists or not | C ++ program for the above approach ; Function to find the point having max X and Y coordinates ; Initialize maxX and maxY ; Length of the given array ; Get maximum X & Y coordinates ; Check if the required point i . e . , ( maxX , maxY ) is present ; If point with maximum X and Y coordinates is present ; If no such point exists ; Driver Code ; Given array of points ; Print answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 5 NEW_LINE #define P 2 NEW_LINE void findMaxPoint ( int arr [ N ] [ P ] ) { int maxX = INT_MIN ; int maxY = INT_MIN ; int n = N ; for ( int i = 0 ; i < n ; i ++ ) { maxX = max ( maxX , arr [ i ] [ 0 ] ) ; maxY = max ( maxY , arr [ i ] [ 1 ] ) ; } for ( int i = 0 ; i < n ; i ++ ) { if ( maxX == arr [ i ] [ 0 ] && maxY == arr [ i ] [ 1 ] ) { cout << " ( " << maxX << " , ▁ " << maxY << " ) " ; return ; } } cout << ( -1 ) ; } int main ( ) { int arr [ N ] [ P ] = { { 1 , 2 } , { 2 , 1 } , { 3 , 4 } , { 4 , 3 } , { 5 , 5 } } ; findMaxPoint ( arr ) ; }
Search insert position of K in a sorted array | C ++ program for the above approach ; Function to find insert position of K ; Traverse the array ; If K is found ; If current array element exceeds K ; If all elements are smaller than K ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find_index ( int arr [ ] , int n , int K ) { for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] == K ) return i ; else if ( arr [ i ] > K ) return i ; return n ; } int main ( ) { int arr [ ] = { 1 , 3 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 2 ; cout << find_index ( arr , n , K ) << endl ; return 0 ; }
Count subarrays for every array element in which they are the minimum | Set 2 | C ++ program for the above approach ; Function to calculate total number of sub - arrays for each element where that element is occurring as the minimum element ; Map for storing the number of sub - arrays for each element ; Traverse over all possible subarrays ; Minimum in each subarray ; Print the result ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minSubarray ( int * arr , int N ) { unordered_map < int , int > m ; for ( int i = 0 ; i < N ; i ++ ) { int mini = INT_MAX ; for ( int j = i ; j < N ; j ++ ) { mini = min ( mini , arr [ j ] ) ; m [ mini ] ++ ; } } for ( int i = 0 ; i < N ; i ++ ) { cout << m [ arr [ i ] ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 3 , 2 , 1 , 4 } ; int N = sizeof ( arr ) / sizeof ( int ) ; minSubarray ( arr , N ) ; return 0 ; }
Count subarrays for every array element in which they are the minimum | Set 2 | C ++ program for the above approach ; Function to count subarrays for each element where it is the minimum ; For the length of strictly larger numbers on the left of A [ i ] ; Storing x in result [ i ] ; For the length of strictly larger numbers on the right of A [ i ] ; Store x * y in result array ; Print the result ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minSubarray ( int * arr , int N ) { int result [ N ] ; stack < pair < int , int > > l , r ; for ( int i = 0 ; i < N ; i ++ ) { int count = 1 ; while ( ! l . empty ( ) && l . top ( ) . first > arr [ i ] ) { count += l . top ( ) . second ; l . pop ( ) ; } l . push ( { arr [ i ] , count } ) ; result [ i ] = count ; } for ( int i = N - 1 ; i >= 0 ; i -- ) { int count = 1 ; while ( ! r . empty ( ) && r . top ( ) . first >= arr [ i ] ) { count += r . top ( ) . second ; r . pop ( ) ; } r . push ( { arr [ i ] , count } ) ; result [ i ] *= count ; } for ( int i = 0 ; i < N ; i ++ ) { cout << result [ i ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 3 , 2 , 1 , 4 } ; int N = sizeof ( arr ) / sizeof ( int ) ; minSubarray ( arr , N ) ; return 0 ; }
Count Full Prime numbers in a given range | C ++ Program to implement the above approach ; Function to check if a number is prime or not ; If a divisor of n exists ; Function to check if a number is Full Prime or not ; If n is not a prime ; Otherwise ; Extract digit ; If any digit of n is non - prime ; Function to print count of Full Primes in a range [ L , R ] ; Stores count of full primes ; Check if i is full prime ; Driver Code ; Stores count of full primes
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int num ) { if ( num <= 1 ) return false ; for ( int i = 2 ; i * i <= num ; i ++ ) if ( num % i == 0 ) return false ; return true ; } bool isFulPrime ( int n ) { if ( ! isPrime ( n ) ) return false ; else { while ( n > 0 ) { int rem = n % 10 ; if ( ! ( rem == 2 rem == 3 rem == 5 rem == 7 ) ) return false ; n = n / 10 ; } } return true ; } int countFulPrime ( int L , int R ) { int cnt = 0 ; for ( int i = L ; i <= R ; i ++ ) { if ( ( i % 2 ) != 0 && isFulPrime ( i ) ) { cnt ++ ; } } return cnt ; } int main ( ) { int L = 1 , R = 100 ; int ans = 0 ; if ( L < 3 ) ans ++ ; cout << ans + countFulPrime ( L , R ) ; return 0 ; }
Print alternate elements of an array | C ++ program to implement the above approach ; Function to print Alternate elements of the given array ; Print elements at odd positions ; If currIndex stores even index or odd position ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printAlter ( int arr [ ] , int N ) { for ( int currIndex = 0 ; currIndex < N ; currIndex ++ ) { if ( currIndex % 2 == 0 ) { cout << arr [ currIndex ] << " ▁ " ; } } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printAlter ( arr , N ) ; }
Minimize deletions in a Binary String to remove all subsequences of the form "0101" | C ++ Program to implement the above approach ; Function to find minimum characters to be removed such that no subsequence of the form "0101" exists in the string ; Stores the partial sums ; Calculate partial sums ; Setting endpoints and deleting characters indices . ; Return count of deleted characters ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findmin ( string s ) { int n = s . length ( ) ; int i , j , maximum = 0 ; int incr [ n + 1 ] = { 0 } ; for ( i = 0 ; i < n ; i ++ ) { incr [ i + 1 ] = incr [ i ] ; if ( s [ i ] == '0' ) { incr [ i + 1 ] ++ ; } } for ( i = 0 ; i < n ; i ++ ) { for ( j = i + 1 ; j < n ; j ++ ) { maximum = max ( maximum , incr [ i ] + j - i + 1 - ( incr [ j + 1 ] - incr [ i ] ) + incr [ n ] - incr [ j + 1 ] ) ; } } return n - maximum ; } int main ( ) { string S = "0110100110" ; int minimum = findmin ( S ) ; cout << minimum << ' ' ; }
Length of longest subarray with product equal to a power of 2 | C ++ program for the above approach ; Function to check whether a number is power of 2 or not ; Function to find maximum length subarray having product of element as a perfect power of 2 ; Stores current subarray length ; Stores maximum subarray length ; Traverse the given array ; If arr [ i ] is power of 2 ; Increment max_length ; Update max_len_subarray ; Otherwise ; Print the maximum length ; Driver Code ; Given arr [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPower ( int x ) { return ( x && ( ! ( x & ( x - 1 ) ) ) ) ; } int maximumlength ( int arr [ ] , int N ) { int max_length = 0 ; int max_len_subarray = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( isPower ( arr [ i ] ) == 1 ) { max_length ++ ; max_len_subarray = max ( max_length , max_len_subarray ) ; } else { max_length = 0 ; } } cout << max_len_subarray ; } int main ( ) { int arr [ ] = { 2 , 5 , 4 , 6 , 8 , 8 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maximumlength ( arr , N ) ; return 0 ; }
Length of smallest subarray to be removed such that the remaining array is sorted | C ++ program for the above approach ; Find the length of the shortest subarray ; To store the result ; Calculate the possible length of the sorted subarray from left ; Array is sorted ; Calculate the possible length of the sorted subarray from left ; Update the result ; Calculate the possible length in the middle we can delete and update the result ; Update the result ; Return the result ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findLengthOfShortestSubarray ( int arr [ ] , int N ) { int minlength = INT_MAX ; int left = 0 ; int right = N - 1 ; while ( left < right && arr [ left + 1 ] >= arr [ left ] ) { left ++ ; } if ( left == N - 1 ) return 0 ; while ( right > left && arr [ right - 1 ] <= arr [ right ] ) { right -- ; } minlength = min ( N - left - 1 , right ) ; int j = right ; for ( int i = 0 ; i < left + 1 ; i ++ ) { if ( arr [ i ] <= arr [ j ] ) { minlength = min ( minlength , j - i - 1 ) ; } else if ( j < N - 1 ) { j ++ ; } else { break ; } } return minlength ; } int main ( ) { int arr [ ] = { 6 , 3 , 10 , 11 , 15 , 20 , 13 , 3 , 18 , 12 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ( findLengthOfShortestSubarray ( arr , N ) ) ; }
Smallest number to be subtracted to convert given number to a palindrome | C ++ program for the above approach ; Function to evaluate minimum subtraction required to make a number palindrome ; Counts number of subtractions required ; Run a loop till N >= 0 ; Store the current number ; Store reverse of current number ; Reverse the number ; Check if N is palindrome ; Increment the counter ; Reduce the number by 1 ; Print the result ; Driver Code ; Function call
#include <iostream> NEW_LINE using namespace std ; void minSub ( int N ) { int count = 0 ; while ( N >= 0 ) { int num = N ; int rev = 0 ; while ( num != 0 ) { int digit = num % 10 ; rev = ( rev * 10 ) + digit ; num = num / 10 ; } if ( N == rev ) { break ; } count ++ ; N -- ; } cout << count ; } int main ( ) { int N = 3456 ; minSub ( N ) ; return 0 ; }
Count subarrays of atleast size 3 forming a Geometric Progression ( GP ) | C ++ program for the above approach ; Function to count all the subarrays of size at least 3 forming GP ; If array size is less than 3 ; Stores the count of subarray ; Stores the count of subarray for each iteration ; Traverse the array ; Check if L [ i ] forms GP ; Otherwise , update count to 0 ; Update the final count ; Return the final count ; Driver Code ; Given array arr [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int numberOfGP ( int L [ ] , int N ) { if ( N <= 2 ) return 0 ; int count = 0 ; int res = 0 ; for ( int i = 2 ; i < N ; ++ i ) { if ( L [ i - 1 ] * L [ i - 1 ] == L [ i ] * L [ i - 2 ] ) { ++ count ; } else { count = 0 ; } res += count ; } return res ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 8 , 16 , 24 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << numberOfGP ( arr , N ) ; return 0 ; }
Count even length subarrays having bitwise XOR equal to 0 | C ++ program to implement the above approach ; Function to count the number of even - length subarrays having Bitwise XOR equal to 0 ; Stores the count of required subarrays ; Stores prefix - XOR of arr [ i , i + 1 , ... N - 1 ] ; Traverse the array ; Calculate the prefix - XOR of current subarray ; Check if XOR of the current subarray is 0 and length is even ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int cntSubarr ( int arr [ ] , int N ) { int res = 0 ; int prefixXor = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { prefixXor = arr [ i ] ; for ( int j = i + 1 ; j < N ; j ++ ) { prefixXor ^= arr [ j ] ; if ( prefixXor == 0 && ( j - i + 1 ) % 2 == 0 ) { res ++ ; } } } return res ; } int main ( ) { int arr [ ] = { 2 , 2 , 3 , 3 , 6 , 7 , 8 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << cntSubarr ( arr , N ) ; }
Count even length subarrays having bitwise XOR equal to 0 | C ++ program to implement the above approach ; Function to get the count of even length subarrays having bitwise xor 0 ; Stores prefix - xor of the given array ; Stores prefix - xor at even index of the array . ; Stores prefix - xor at odd index of the array . ; Stores count of subarrays that satisfy the condition ; length from 0 index to odd index is even ; Traverse the array . ; Take prefix - xor ; If index is odd ; Calculate pairs ; Increment prefix - xor at odd index ; Calculate pairs ; Increment prefix - xor at odd index ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define M 1000000 NEW_LINE int cntSubXor ( int arr [ ] , int N ) { int prefixXor = 0 ; int Even [ M ] ; int Odd [ M ] ; int cntSub = 0 ; Odd [ 0 ] = 1 ; for ( int i = 0 ; i < N ; i ++ ) { prefixXor ^= arr [ i ] ; if ( i % 2 == 1 ) { cntSub += Odd [ prefixXor ] ; Odd [ prefixXor ] ++ ; } else { cntSub += Even [ prefixXor ] ; Even [ prefixXor ] ++ ; } } return cntSub ; } int main ( ) { int arr [ ] = { 2 , 2 , 3 , 3 , 6 , 7 , 8 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << cntSubXor ( arr , N ) ; return 0 ; }
Maximize sum of array elements removed by performing the given operations | C ++ program for the above approach ; Function to find the maximum sum of the array arr [ ] where each element can be reduced to at most min [ i ] ; Stores the pair of arr [ i ] & min [ i ] ; Sorting vector of pairs ; Traverse the vector of pairs ; Add to the value of S ; Update K ; Driver Code ; Given array arr [ ] , min [ ] ; Given K ; Function Call ; Print the value of S
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMaxSum ( vector < int > arr , int n , vector < int > min , int k , int & S ) { vector < pair < int , int > > A ; for ( int i = 0 ; i < n ; i ++ ) { A . push_back ( { arr [ i ] , min [ i ] } ) ; } sort ( A . begin ( ) , A . end ( ) , greater < pair < int , int > > ( ) ) ; int K = 0 ; for ( int i = 0 ; i < n ; i ++ ) { S += max ( A [ i ] . first - K , A [ i ] . second ) ; K += k ; } } int main ( ) { vector < int > arr , min ; arr = { 3 , 5 , 2 , 1 } ; min = { 3 , 2 , 1 , 3 } ; int N = arr . size ( ) ; int K = 3 ; int S = 0 ; findMaxSum ( arr , N , min , K , S ) ; cout << S ; return 0 ; }
Length of smallest substring of a given string which contains another string as subsequence | C ++ program to implement the above approach ; Function to find the length of smallest substring of a having string b as a subsequence ; Stores the characters present in string b ; Find index of characters of a that are also present in string b ; If character is present in string b ; Store the index of character ; Flag is used to check if substring is possible ; Assume that substring is possible ; Stores first and last indices of the substring respectively ; For first character of string b ; If the first character of b is not present in a ; If the first character of b is present in a ; Remove the index from map ; Update indices of the substring ; For the remaining characters of b ; If index possible for current character ; If no index is possible ; If no more substring is possible ; Update the minimum length of substring ; Return the result ; Driver Code ; Given two string
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minLength ( string a , string b ) { map < char , int > Char ; for ( int i = 0 ; i < b . length ( ) ; i ++ ) { Char [ b [ i ] ] ++ ; } map < char , vector < int > > CharacterIndex ; for ( int i = 0 ; i < a . length ( ) ; i ++ ) { char x = a [ i ] ; if ( Char . find ( x ) != Char . end ( ) ) { CharacterIndex [ x ] . push_back ( i ) ; } } int len = INT_MAX ; int flag ; while ( true ) { flag = 1 ; int firstVar , lastVar ; for ( int i = 0 ; i < b . length ( ) ; i ++ ) { if ( i == 0 ) { if ( CharacterIndex . find ( b [ i ] ) == CharacterIndex . end ( ) ) { flag = 0 ; break ; } else { int x = * ( CharacterIndex [ b [ i ] ] . begin ( ) ) ; CharacterIndex [ b [ i ] ] . erase ( CharacterIndex [ b [ i ] ] . begin ( ) ) ; firstVar = x ; lastVar = x ; } } else { int elementFound = 0 ; for ( auto e : CharacterIndex [ b [ i ] ] ) { if ( e > lastVar ) { elementFound = 1 ; lastVar = e ; break ; } } if ( elementFound == 0 ) { flag = 0 ; break ; } } } if ( flag == 0 ) { break ; } len = min ( len , abs ( lastVar - firstVar ) + 1 ) ; } return len ; } int main ( ) { string a = " abcdefababaef " ; string b = " abf " ; int len = minLength ( a , b ) ; if ( len != INT_MAX ) { cout << len << endl ; } else { cout << " Impossible " << endl ; } }
Count smaller primes on the right of each array element | C ++ Program for the above approach ; Function to check if a number is prime or not ; Function to find the count of smaller primes on the right of each array element ; Stores the count of smaller primes ; If A [ j ] <= A [ i ] and A [ j ] is prime ; Increase count ; Print the count for the current element ; Driver Code ; Function call
#include " bits / stdc + + . h " NEW_LINE using namespace std ; bool is_prime ( int n ) { if ( n <= 1 ) return 0 ; for ( int i = 2 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) return 0 ; } return 1 ; } void countSmallerPrimes ( int ar [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { int count = 0 ; for ( int j = i + 1 ; j < N ; j ++ ) { if ( ar [ j ] <= ar [ i ] && is_prime ( ar [ j ] ) ) { count ++ ; } } cout << count << " ▁ " ; } } int main ( ) { int ar [ ] = { 43 , 3 , 5 , 7 , 2 , 41 } ; int N = sizeof ar / sizeof ar [ 0 ] ; countSmallerPrimes ( ar , N ) ; return 0 ; }
Check if a string is concatenation of another given string | C ++ program to implement the above approach ; Function to check if a string is concatenation of another string ; Stores the length of str2 ; Stores the length of str1 ; If M is not multiple of N ; Traverse both the strings ; If str1 is not concatenation of str2 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkConcat ( string str1 , string str2 ) { int N = str1 . length ( ) ; int M = str2 . length ( ) ; if ( N % M != 0 ) { return false ; } for ( int i = 0 ; i < N ; i ++ ) { if ( str1 [ i ] != str2 [ i % M ] ) { return false ; } } return true ; } int main ( ) { string str1 = " abcabcabc " ; string str2 = " abc " ; if ( checkConcat ( str1 , str2 ) ) { cout << " Yes " ; } else { cout << " No " ; } }
Minimize length of string by replacing K pairs of distinct adjacent characters | C ++ program to implement the above approach ; Function to minimize the length of the string by replacing distinct pairs of adjacent characters ; Stores the length of the given string ; Stores the index of the given string ; Traverse the given string ; If two adjacent characters are distinct ; If all characters are equal ; If all characters are distinct ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MinLen ( string str , int K ) { int N = str . length ( ) ; int i = 0 ; while ( i < N - 1 ) { if ( str [ i ] != str [ i + 1 ] ) { break ; } i ++ ; } if ( i == N - 1 ) { return N ; } return max ( 1 , N - K ) ; } int main ( ) { string str = " aabc " ; int K = 1 ; cout << MinLen ( str , K ) ; }
Length of smallest sequence having sum X and product Y | C ++ program for the above approach ; Function for checking valid or not ; Function for checking boundary of binary search ; Function to calculate the minimum sequence size using binary search ; Initialize high and low ; Base case ; Print - 1 if a sequence cannot be generated ; Otherwise ; Iterate until difference between high and low exceeds 1 ; Calculate mid ; Reset values of high and low accordingly ; Print the answer ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long NEW_LINE #define pb push_back NEW_LINE double temp ( int n , int x ) { return pow ( x * 1.0 / n , n ) ; } bool check ( int n , int y , int x ) { double v = temp ( n , x ) ; return ( v >= y ) ; } void find ( int x , int y ) { int high = ( int ) floor ( x / exp ( 1.0 ) ) ; int low = 1 ; if ( x == y ) cout << 1 << endl ; else if ( ! check ( high , y , x ) ) cout << -1 << endl ; else { while ( high - low > 1 ) { int mid = ( high + low ) / 2 ; if ( check ( mid , y , x ) ) high = mid ; else low = mid ; } cout << high << endl ; } } int main ( ) { int x = 9 , y = 8 ; find ( x , y ) ; return 0 ; }
Print the middle nodes of each level of a Binary Tree | C ++ program for the above approach ; Structure Node of Binary Tree ; Function to create a new node ; Return the created node ; Function that performs the DFS traversal on Tree to store all the nodes at each level in map M ; Base Case ; Push the current level node ; Left Recursion ; Right Recursion ; Function that print all the middle nodes for each level in Binary Tree ; Stores all node in each level ; Perform DFS traversal ; Traverse the map M ; Get the size of vector ; For odd number of elements ; Print ( M / 2 ) th Element ; Otherwise ; Print ( M / 2 ) th and ( M / 2 + 1 ) th Element ; Driver Code ; Given Tree ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int data ; struct node * left ; struct node * right ; } ; struct node * newnode ( int d ) { struct node * temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ; temp -> data = d ; temp -> left = NULL ; temp -> right = NULL ; return temp ; } void dfs ( node * root , int l , map < int , vector < int > > & M ) { if ( root == NULL ) return ; M [ l ] . push_back ( root -> data ) ; dfs ( root -> left , l + 1 , M ) ; dfs ( root -> right , l + 1 , M ) ; } void printMidNodes ( node * root ) { map < int , vector < int > > M ; dfs ( root , 0 , M ) ; for ( auto & it : M ) { int size = it . second . size ( ) ; if ( size & 1 ) { cout << it . second [ ( size - 1 ) / 2 ] << endl ; } else { cout << it . second [ ( size - 1 ) / 2 ] << ' ▁ ' << it . second [ ( size - 1 ) / 2 + 1 ] << endl ; } } } int main ( ) { struct node * root = newnode ( 1 ) ; root -> left = newnode ( 2 ) ; root -> right = newnode ( 3 ) ; root -> left -> left = newnode ( 4 ) ; root -> left -> right = newnode ( 5 ) ; root -> left -> right -> left = newnode ( 11 ) ; root -> left -> right -> right = newnode ( 6 ) ; root -> left -> right -> right -> left = newnode ( 7 ) ; root -> left -> right -> right -> right = newnode ( 9 ) ; root -> right -> left = newnode ( 10 ) ; root -> right -> right = newnode ( 8 ) ; printMidNodes ( root ) ; return 0 ; }
Smallest array that can be obtained by replacing adjacent pairs with their products | C ++ implementation of the above approach ; Function to minimize the size of array by performing given operations ; If all array elements are not same ; If all array elements are same ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minLength ( int arr [ ] , int N ) { for ( int i = 1 ; i < N ; i ++ ) { if ( arr [ 0 ] != arr [ i ] ) { return 1 ; } } return N ; } int main ( ) { int arr [ ] = { 2 , 1 , 3 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minLength ( arr , N ) ; return 0 ; }
Maximum XOR of Two Numbers in an Array | Set 2 | C ++ program for the above approach ; Structure of Trie ; Function to insert binary representation of element x in the Trie ; Store the head ; Find the i - th bit ; If curr -> left is NULL ; Update curr to curr -> left ; If curr -> right is NULL ; Update curr to curr -> right ; Function that finds the maximum Bitwise XOR value for all such pairs ; head Node of Trie ; Insert each element in trie ; Stores the maximum XOR value ; Traverse the given array ; Stores the XOR with current value arr [ i ] ; Finding ith bit ; Check if the bit is 0 ; If right node exists ; Update the currentXOR ; Check if left node exists ; Update the currentXOR ; Update M to M / 2 for next set bit ; Update the maximum XOR ; Return the maximum XOR found ; Driver Code ; Given array arr [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : node * left ; node * right ; } ; void insert ( int x , node * head ) { node * curr = head ; for ( int i = 30 ; i >= 0 ; i -- ) { int val = ( x >> i ) & 1 ; if ( val == 0 ) { if ( ! curr -> left ) curr -> left = new node ( ) ; curr = curr -> left ; } else { if ( ! curr -> right ) curr -> right = new node ( ) ; curr = curr -> right ; } } } int findMaximumXOR ( int arr [ ] , int n ) { node * head = new node ( ) ; for ( int i = 0 ; i < n ; i ++ ) { insert ( arr [ i ] , head ) ; } int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int curr_xor = 0 ; int M = pow ( 2 , 30 ) ; node * curr = head ; for ( int j = 30 ; j >= 0 ; j -- ) { int val = ( arr [ i ] >> j ) & 1 ; if ( val == 0 ) { if ( curr -> right ) { curr_xor += M ; curr = curr -> right ; } else { curr = curr -> left ; } } else { if ( curr -> left ) { curr_xor += M ; curr = curr -> left ; } else { curr = curr -> right ; } } M /= 2 ; } ans = max ( ans , curr_xor ) ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findMaximumXOR ( arr , N ) ; return 0 ; }
Subarrays whose sum is a perfect square | C ++ program to implement the above approach ; Function to print the start and end indices of all subarrays whose sum is a perfect square ; Stores the current subarray sum ; Update current subarray sum ; Stores the square root of currSubSum ; Check if currSubSum is a perfect square or not ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void PrintIndexes ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { int currSubSum = 0 ; for ( int j = i ; j < N ; j ++ ) { currSubSum += arr [ j ] ; int sq = sqrt ( currSubSum ) ; if ( sq * sq == currSubSum ) { cout << " ( " << i << " , ▁ " << j << " ) ▁ " ; } } } } int main ( ) { int arr [ ] = { 65 , 79 , 81 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; PrintIndexes ( arr , N ) ; }
Count positions in Binary Matrix having equal count of set bits in corresponding row and column | C ++ 14 program to implement above approach ; Function to return the count of indices in from the given binary matrix having equal count of set bits in its row and column ; Stores count of set bits in corresponding column and row ; Traverse matrix ; Since 1 contains a set bit ; Update count of set bits for current row and col ; Stores the count of required indices ; Traverse matrix ; If current row and column has equal count of set bits ; Return count of required position ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPosition ( vector < vector < int > > mat ) { int n = mat . size ( ) ; int m = mat [ 0 ] . size ( ) ; vector < int > row ( n ) ; vector < int > col ( m ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( mat [ i ] [ j ] == 1 ) { col [ j ] ++ ; row [ i ] ++ ; } } } int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( row [ i ] == col [ j ] ) { count ++ ; } } } return count ; } int main ( ) { vector < vector < int > > mat = { { 0 , 1 } , { 1 , 1 } } ; cout << ( countPosition ( mat ) ) ; }
Maximum value at each level in an N | C ++ program for the above approach ; Function to find the maximum value at each level of N - ary tree ; Stores the adjacency list ; Create the adjacency list ; Perform level order traversal of nodes at each level ; Push the root node ; Iterate until queue is empty ; Get the size of queue ; Iterate for all the nodes in the queue currently ; Dequeue an node from queue ; Enqueue the children of dequeued node ; Print the result ; Driver Code ; Number of nodes ; Edges of the N - ary tree ; Given cost ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxAtLevel ( int N , int M , vector < int > Value , int Edges [ ] [ 2 ] ) { vector < int > adj [ N ] ; for ( int i = 0 ; i < M ; i ++ ) { int u = Edges [ i ] [ 0 ] ; int v = Edges [ i ] [ 1 ] ; adj [ u ] . push_back ( v ) ; } queue < int > q ; q . push ( 0 ) ; while ( ! q . empty ( ) ) { int count = q . size ( ) ; int maxVal = 0 ; while ( count -- ) { int temp = q . front ( ) ; q . pop ( ) ; maxVal = max ( maxVal , Value [ temp ] ) ; for ( int i = 0 ; i < adj [ temp ] . size ( ) ; i ++ ) { q . push ( adj [ temp ] [ i ] ) ; } } cout << maxVal << " ▁ " ; } } int main ( ) { int N = 10 ; int Edges [ ] [ 2 ] = { { 0 , 1 } , { 0 , 2 } , { 0 , 3 } , { 1 , 4 } , { 1 , 5 } , { 3 , 6 } , { 6 , 7 } , { 6 , 8 } , { 6 , 9 } } ; vector < int > Value = { 1 , 2 , -1 , 3 , 4 , 5 , 8 , 6 , 12 , 7 } ; maxAtLevel ( N , N - 1 , Value , Edges ) ; return 0 ; }
Rearrange array to maximize count of triplets ( i , j , k ) such that arr [ i ] > arr [ j ] < arr [ k ] and i < j < k | C ++ program to implement the above approach ; Function to rearrange the array to maximize the count of triplets ; Sort the given array ; Stores the permutations of the given array ; Stores the index of the given array ; Place the first half of the given array ; Place the last half of the given array ; Stores the count of triplets ; Check the given conditions ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void ctTriplets ( int arr [ ] , int N ) { sort ( arr , arr + N ) ; vector < int > temp ( N ) ; int index = 0 ; for ( int i = 1 ; i < N ; i += 2 ) { temp [ i ] = arr [ index ++ ] ; } for ( int i = 0 ; i < N ; i += 2 ) { temp [ i ] = arr [ index ++ ] ; } int ct = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( i > 0 && i + 1 < N ) { if ( temp [ i ] < temp [ i + 1 ] && temp [ i ] < temp [ i - 1 ] ) { ct ++ ; } } } cout << " Count ▁ of ▁ triplets : " << ct << endl ; cout << " Array : " ; for ( int i = 0 ; i < N ; i ++ ) { cout << temp [ i ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; ctTriplets ( arr , N ) ; }
Rearrange array to make it non | C ++ program for above approach ; Function to check if the array can be made non - decreasing ; Iterate till N ; Find the minimum element ; Sort the array ; Iterate till N ; Check if the element is at its correct position ; Return the answer ; Driver Code ; Print the answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int a [ ] , int n ) { int b [ n ] ; int minElement = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { b [ i ] = a [ i ] ; minElement = min ( minElement , a [ i ] ) ; } sort ( b , b + n ) ; int k = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] != b [ i ] && a [ i ] % minElement != 0 ) { k = 0 ; break ; } } return k == 1 ? true : false ; } int main ( ) { int a [ ] = { 4 , 3 , 6 , 6 , 2 , 9 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; if ( check ( a , n ) == true ) cout << " Yes ▁ STRNEWLINE " ; else cout << " No ▁ STRNEWLINE " ; return 0 ; }
Count 1 s in binary matrix having remaining indices of its row and column filled with 0 s | C ++ program for the above approach ; Function to count required 1 s from the given matrix ; Stores the dimensions of the mat [ ] [ ] ; Calculate sum of rows ; Calculate sum of columns ; Stores required count of 1 s ; If current cell is 1 and sum of row and column is 1 ; Increment count of 1 s ; Return the final count ; Driver Code ; Given matrix ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int numSpecial ( vector < vector < int > > & mat ) { int m = mat . size ( ) , n = mat [ 0 ] . size ( ) ; int rows [ m ] ; int cols [ n ] ; int i , j ; for ( i = 0 ; i < m ; i ++ ) { rows [ i ] = 0 ; for ( j = 0 ; j < n ; j ++ ) rows [ i ] += mat [ i ] [ j ] ; } for ( i = 0 ; i < n ; i ++ ) { cols [ i ] = 0 ; for ( j = 0 ; j < m ; j ++ ) cols [ i ] += mat [ j ] [ i ] ; } int cnt = 0 ; for ( i = 0 ; i < m ; i ++ ) { for ( j = 0 ; j < n ; j ++ ) { if ( mat [ i ] [ j ] == 1 && rows [ i ] == 1 && cols [ j ] == 1 ) cnt ++ ; } } return cnt ; } int main ( ) { vector < vector < int > > mat = { { 1 , 0 , 0 } , { 0 , 0 , 1 } , { 0 , 0 , 0 } } ; cout << numSpecial ( mat ) << endl ; return 0 ; }
Find all matrix elements which are minimum in their row and maximum in their column | C ++ program for the above approach ; Functionto find all the matrix elements which are minimum in its row and maximum in its column ; Initialize unordered set ; Traverse the matrix ; Update the minimum element of current row ; Insert the minimum element of the row ; Update the maximum element of current column ; Checking if it is already present in the unordered_set or not ; Driver Code ; Function call ; If no such matrix element is found
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > minmaxNumbers ( vector < vector < int > > & matrix , vector < int > & res ) { unordered_set < int > set ; for ( int i = 0 ; i < matrix . size ( ) ; i ++ ) { int minr = INT_MAX ; for ( int j = 0 ; j < matrix [ i ] . size ( ) ; j ++ ) { minr = min ( minr , matrix [ i ] [ j ] ) ; } set . insert ( minr ) ; } for ( int j = 0 ; j < matrix [ 0 ] . size ( ) ; j ++ ) { int maxc = INT_MIN ; for ( int i = 0 ; i < matrix . size ( ) ; i ++ ) { maxc = max ( maxc , matrix [ i ] [ j ] ) ; } if ( set . find ( maxc ) != set . end ( ) ) { res . push_back ( maxc ) ; } } return res ; } int main ( ) { vector < vector < int > > mat = { { 1 , 10 , 4 } , { 9 , 3 , 8 } , { 15 , 16 , 17 } } ; vector < int > ans ; minmaxNumbers ( mat , ans ) ; if ( ans . size ( ) == 0 ) cout << " - 1" << endl ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) cout << ans [ i ] << endl ; return 0 ; }
Node whose removal minimizes the maximum size forest from an N | C ++ program to implement the above approach ; Function to create the graph ; Function to traverse the graph and find the minimum of maximum size forest after removing a node ; Traversing every child subtree except the parent node ; Traverse all subtrees ; Update the maximum size of forests ; Update the minimum of maximum size of forests obtained ; Condition to find the minimum of maximum size forest ; Update and store the corresponding node ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int mini = 105 , ans , n ; vector < vector < int > > g ( 100 ) ; int size [ 100 ] ; void create_graph ( ) { g [ 1 ] . push_back ( 2 ) ; g [ 2 ] . push_back ( 1 ) ; g [ 1 ] . push_back ( 3 ) ; g [ 3 ] . push_back ( 1 ) ; g [ 1 ] . push_back ( 4 ) ; g [ 4 ] . push_back ( 1 ) ; g [ 2 ] . push_back ( 5 ) ; g [ 5 ] . push_back ( 2 ) ; g [ 2 ] . push_back ( 6 ) ; g [ 6 ] . push_back ( 2 ) ; } void dfs ( int node , int parent ) { size [ node ] = 1 ; int mx = 0 ; for ( int y : g [ node ] ) { if ( y == parent ) continue ; dfs ( y , node ) ; size [ node ] += size [ y ] ; mx = max ( mx , size [ y ] ) ; } mx = max ( mx , n - size [ node ] ) ; if ( mx < mini ) { mini = mx ; ans = node ; } } int main ( ) { n = 6 ; create_graph ( ) ; dfs ( 1 , -1 ) ; cout << ans << " STRNEWLINE " ; return 0 ; }
Minimum non | C ++ program for the above approach ; Function to find minimum flips required to remove all 0 s from a given binary string ; Length of given string ; Stores the indices of previous 0 s ; Stores the minimum operations ; Traverse string to find minimum operations to obtain required string ; Current character ; If current character is '0' ; Update temp1 with current index , if both temp variables are empty ; Update temp2 with current index , if temp1 contains prev index but temp2 is empty ; If temp1 is not empty ; Reset temp1 to - 1 ; Increase ans ; If temp2 is not empty but temp1 is empty ; Reset temp2 to - 1 ; Increase ans ; If both temp variables are not empty ; Otherwise ; Return the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperation ( string s ) { int n = s . length ( ) ; int temp1 = -1 , temp2 = -1 ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int curr = s [ i ] ; if ( curr == '0' ) { if ( temp1 == -1 && temp2 == -1 ) { temp1 = i ; } else if ( temp1 != -1 && temp2 == -1 && i - temp1 == 1 ) { temp2 = i ; } else if ( temp1 != -1 ) { temp1 = -1 ; ans ++ ; } else if ( temp1 == -1 && temp2 != -1 && i - temp2 != 1 ) { temp2 = -1 ; ans ++ ; } } } if ( temp1 != -1 && temp2 != -1 ) { ans += 2 ; } else if ( temp1 != -1 temp2 != -1 ) { ans += 1 ; } return ans ; } int main ( ) { string s = "110010" ; cout << ( minOperation ( s ) ) ; }
Smallest prefix to be deleted such that remaining array can be rearranged to form a sorted array | C ++ program for above approach ; Function to find the minimum length of prefix required to be deleted ; Stores index to be returned ; Iterate until previous element is <= current index ; Decrementing index ; Return index ; Driver Code ; Given arr [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinLength ( vector < int > & arr ) { int index = ( int ) arr . size ( ) - 1 ; while ( index > 0 && arr [ index ] >= arr [ index - 1 ] ) { index -- ; } return index ; } int main ( ) { vector < int > arr = { 7 , 8 , 5 , 0 , -1 , -1 , 0 , 1 , 2 , 3 , 4 } ; cout << findMinLength ( arr ) ; return 0 ; }
Count array elements exceeding sum of preceding K elements | C ++ program for the above approach ; Function to count array elements exceeding sum of preceding K elements ; Iterate over the array ; Update prefix sum ; Check if arr [ K ] > arr [ 0 ] + . . + arr [ K - 1 ] ; Increment count ; Check if arr [ i ] > arr [ i - K - 1 ] + . . + arr [ i - 1 ] ; Increment count ; Driver Code ; Given array
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPrecedingK ( int a [ ] , int n , int K ) { int prefix [ n ] ; prefix [ 0 ] = a [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { prefix [ i ] = prefix [ i - 1 ] + a [ i ] ; } int ctr = 0 ; if ( prefix [ K - 1 ] < a [ K ] ) ctr ++ ; for ( int i = K + 1 ; i < n ; i ++ ) { if ( prefix [ i - 1 ] - prefix [ i - K - 1 ] < a [ i ] ) ctr ++ ; } return ctr ; } int main ( ) { int arr [ ] = { 2 , 3 , 8 , 10 , -2 , 7 , 5 , 5 , 9 , 15 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 2 ; cout << countPrecedingK ( arr , N , K ) ; return 0 ; }
Count minimum moves required to convert A to B | C ++ program for the above approach ; Function to find minimum number of moves to obtained B from A ; Stores the minimum number of moves ; Absolute difference ; K is in range [ 0 , 10 ] ; Print the required moves ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void convertBfromA ( int a , int b ) { int moves = 0 ; int x = abs ( a - b ) ; for ( int i = 10 ; i > 0 ; i -- ) { moves += x / i ; x = x % i ; } cout << moves << " ▁ " ; } int main ( ) { int A = 188 , B = 4 ; convertBfromA ( A , B ) ; return 0 ; }
Count N digits numbers with sum divisible by K | C ++ Program to implement the above approach ; Function to count the N digit numbers whose sum is divisible by K ; Base case ; If already computed subproblem occurred ; Store the count of N digit numbers whose sum is divisible by K ; Check if the number does not contain any leading 0. ; Recurrence relation ; Driver Code ; Stores the values of overlapping subproblems
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define M 1000 NEW_LINE int countNum ( int N , int sum , int K , bool st , int dp [ M ] [ M ] [ 2 ] ) { if ( N == 0 and sum == 0 ) { return 1 ; } if ( N < 0 ) { return 0 ; } if ( dp [ N ] [ sum ] [ st ] != -1 ) { return dp [ N ] [ sum ] [ st ] ; } int res = 0 ; int start = st == 1 ? 0 : 1 ; for ( int i = start ; i <= 9 ; i ++ ) { res += countNum ( N - 1 , ( sum + i ) % K , K , ( st i > 0 ) , dp ) ; } return dp [ N ] [ sum ] [ st ] = res ; } int main ( ) { int N = 2 , K = 7 ; int dp [ M ] [ M ] [ 2 ] ; memset ( dp , -1 , sizeof ( dp ) ) ; cout << countNum ( N , 0 , K , 0 , dp ) ; }
Minimize Nth term of an Arithmetic progression ( AP ) | C ++ program to implement the above approach ; Function to find the smallest Nth term of an AP possible ; Stores the smallest Nth term ; Check if common difference of AP is an integer ; Store the common difference ; Store the First Term of that AP ; Store the Nth term of that AP ; Check if all elements of an AP are positive ; Return the least Nth term obtained ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int smallestNth ( int A , int B , int N ) { int res = INT_MAX ; for ( int i = 1 ; i < N ; i ++ ) { for ( int j = N ; j > i ; j -- ) { if ( ( B - A ) % ( j - i ) == 0 ) { int D = ( B - A ) / ( j - i ) ; int FirstTerm = A - ( i - 1 ) * D ; int NthTerm = FirstTerm + ( N - 1 ) * D ; if ( FirstTerm > 0 ) res = min ( res , NthTerm ) ; } } } return res ; } int main ( ) { int N = 3 ; int A = 1 ; int B = 6 ; cout << smallestNth ( A , B , N ) ; }
Subarray of size K with prime sum | C ++ program to implement the above approach ; Generate all prime numbers in the range [ 1 , 1000000 ] ; Set all numbers as prime initially ; Mark 0 and 1 as non - prime ; If current element is prime ; Mark all its multiples as non - prime ; Function to print the subarray whose sum of elements is prime ; Store the current subarray of size K ; Calculate the sum of first K elements ; Check if currSum is prime ; Store the start and last index of subarray of size K ; Iterate over remaining array ; Check if currSum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void sieve ( bool prime [ ] ) { for ( int i = 0 ; i < 1000000 ; i ++ ) { prime [ i ] = true ; } prime [ 0 ] = prime [ 1 ] = false ; for ( int i = 2 ; i * i <= 1000000 ; i ++ ) { if ( prime [ i ] ) { for ( int j = i * i ; j <= 1000000 ; j += i ) { prime [ j ] = false ; } } } } void subPrimeSum ( int N , int K , int arr [ ] , bool prime [ ] ) { int currSum = 0 ; for ( int i = 0 ; i < K ; i ++ ) { currSum += arr [ i ] ; } if ( prime [ currSum ] ) { for ( int i = 0 ; i < K ; i ++ ) { cout << arr [ i ] << " ▁ " ; } return ; } int st = 1 , en = K ; while ( en < N ) { currSum += arr [ en ] - arr [ st - 1 ] ; if ( prime [ currSum ] ) { for ( int i = st ; i <= en ; i ++ ) { cout << arr [ i ] << " ▁ " ; } return ; } en ++ ; st ++ ; } } int main ( ) { int arr [ ] = { 20 , 7 , 5 , 4 , 3 , 11 , 99 , 87 , 23 , 45 } ; int K = 4 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; bool prime [ 1000000 ] ; sieve ( prime ) ; subPrimeSum ( N , K , arr , prime ) ; }
Minimum characters required to be removed to sort binary string in ascending order | C ++ program for the above approach ; Function to find the minimum count of characters to be removed to make the string sorted in ascending order ; Length of given string ; Stores the first occurrence of '1' ; Stores the last occurrence of '0' ; Traverse the string to find the first occurrence of '1' ; Traverse the string to find the last occurrence of '0' ; Return 0 if the str have only one type of character ; Initialize count1 and count0 to count '1' s before lastIdx0 and '0' s after firstIdx1 ; Traverse the string to count0 ; Traverse the string to count1 ; Return the minimum of count0 and count1 ; Driver code ; Given string str ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minDeletion ( string str ) { int n = str . length ( ) ; int firstIdx1 = -1 ; int lastIdx0 = -1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == '1' ) { firstIdx1 = i ; break ; } } for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( str [ i ] == '0' ) { lastIdx0 = i ; break ; } } if ( firstIdx1 == -1 lastIdx0 == -1 ) return 0 ; int count1 = 0 , count0 = 0 ; for ( int i = 0 ; i < lastIdx0 ; i ++ ) { if ( str [ i ] == '1' ) { count1 ++ ; } } for ( int i = firstIdx1 + 1 ; i < n ; i ++ ) { if ( str [ i ] == '1' ) { count0 ++ ; } } return min ( count0 , count1 ) ; } int main ( ) { string str = "1000101" ; cout << minDeletion ( str ) ; return 0 ; }
Maximum score assigned to a subsequence of numerically consecutive and distinct array elements | C ++ program for the above approach ; Function to find the maximum score with unique element in the subset ; Base Case ; Check if the previously picked element differs by 1 from the current element ; Calculate score by including the current element ; Calculate score by excluding the current element ; Return maximum of the two possibilities ; Driver code ; Given arrays ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumSum ( int a [ ] , int b [ ] , int n , int index , int lastpicked ) { if ( index == n ) return 0 ; int option1 = 0 , option2 = 0 ; if ( lastpicked == -1 a [ lastpicked ] != a [ index ] ) option1 = b [ index ] + maximumSum ( a , b , n , index + 1 , index ) ; option2 = maximumSum ( a , b , n , index + 1 , lastpicked ) ; return max ( option1 , option2 ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 3 , 3 , 1 } ; int brr [ ] = { -1 , 2 , 10 , 20 , -10 , -9 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ( maximumSum ( arr , brr , N , 0 , -1 ) ) ; }
Replace every element in a circular array by sum of next K elements | C ++ program for the above approach ; Function to print the required resultant array ; Reverse the array ; Traverse the range ; Store prefix sum ; Find the prefix sum ; Store the answer ; Calculate the answers ; Count of remaining elements ; Add the sum of all elements y times ; Add the remaining elements ; Update ans [ i ] ; If array is reversed print ans [ ] in reverse ; Driver Code ; Given array arr [ ] ; Given K ; Function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void sumOfKElements ( int arr [ ] , int n , int k ) { bool rev = false ; if ( k < 0 ) { rev = true ; k *= -1 ; int l = 0 , r = n - 1 ; while ( l < r ) { int tmp = arr [ l ] ; arr [ l ] = arr [ r ] ; arr [ r ] = tmp ; l ++ ; r -- ; } } int dp [ n ] = { 0 } ; dp [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { dp [ i ] += dp [ i - 1 ] + arr [ i ] ; } int ans [ n ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { if ( i + k < n ) ans [ i ] = dp [ i + k ] - dp [ i ] ; else { int x = k - ( n - 1 - i ) ; int y = x / n ; int rem = x % n ; ans [ i ] = dp [ n - 1 ] - dp [ i ] + y * dp [ n - 1 ] + ( rem - 1 >= 0 ? dp [ rem - 1 ] : 0 ) ; } } if ( rev ) { for ( int i = n - 1 ; i >= 0 ; i -- ) { cout << ans [ i ] << " ▁ " ; } } else { for ( int i = 0 ; i < n ; i ++ ) { cout << ans [ i ] << " ▁ " ; } } } int main ( ) { int arr [ ] = { 4 , 2 , -5 , 11 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; sumOfKElements ( arr , N , K ) ; }
Count subarrays for every array element in which they are the minimum | C ++ 14 program for the above approach ; Function to find the boundary of every element within which it is minimum ; Perform Binary Search ; Find mid m ; Update l ; Update r ; Inserting the index ; Function to required count subarrays ; Stores the indices of element ; Initialize the output array ; Left boundary , till the element is smallest ; Right boundary , till the element is smallest ; Calculate the number of subarrays based on its boundary ; Adding cnt to the ans ; Driver Code ; Given array arr [ ] ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int binaryInsert ( vector < int > & boundary , int i ) { int l = 0 ; int r = boundary . size ( ) - 1 ; while ( l <= r ) { int m = ( l + r ) / 2 ; if ( boundary [ m ] < i ) l = m + 1 ; else r = m - 1 ; } boundary . insert ( boundary . begin ( ) + l , i ) ; return l ; } vector < int > countingSubarray ( vector < int > arr , int n ) { unordered_map < int , int > index ; for ( int i = 0 ; i < n ; i ++ ) index [ arr [ i ] ] = i ; vector < int > boundary = { -1 , n } ; sort ( arr . begin ( ) , arr . end ( ) ) ; vector < int > ans ( n , 0 ) ; for ( int num : arr ) { int i = binaryInsert ( boundary , index [ num ] ) ; int l = boundary [ i ] - boundary [ i - 1 ] - 1 ; int r = boundary [ i + 1 ] - boundary [ i ] - 1 ; int cnt = l + r + l * r + 1 ; ans [ index [ num ] ] += cnt ; } return ans ; } int main ( ) { int N = 5 ; vector < int > arr = { 3 , 2 , 4 , 1 , 5 } ; auto a = countingSubarray ( arr , N ) ; cout << " [ " ; int n = a . size ( ) - 1 ; for ( int i = 0 ; i < n ; i ++ ) cout << a [ i ] << " , ▁ " ; cout << a [ n ] << " ] " ; return 0 ; }
Check if digit cube limit of an integer arrives at fixed point or a limit cycle | C ++ program for the above approach ; Define the limit ; Function to get the sum of cube of digits of a number ; Convert to string to get sum of the cubes of its digits ; return sum ; Function to check if the number arrives at a fixed point or a cycle ; Stores the values obtained ; Insert N to set s ; Get the next number using F ( N ) ; Check if the next number is repeated or not ; Function to check if digit cube limit of an integer arrives at fixed point or in a limit cycle ; N is a non negative integer ; Function Call ; If the value received is greater than limit ; If the value received is an Armstrong number ; Driver Code ; Function Call
#include <algorithm> NEW_LINE #include <bits/stdc++.h> NEW_LINE #define limit 1000000000 NEW_LINE using namespace std ; long long F ( long long N ) { string str = to_string ( N ) ; long long sum = 0 ; for ( long long i = 0 ; i < str . size ( ) ; i ++ ) { long long val = int ( str [ i ] - '0' ) ; sum += val * val * val ; } return sum ; } long long findDestination ( long long N ) { set < long long > s ; long long prev = N , next ; s . insert ( N ) ; while ( N <= limit ) { next = F ( N ) ; auto it = s . find ( next ) ; if ( it != s . end ( ) ) { return next ; } prev = next ; s . insert ( prev ) ; N = next ; } return next ; } void digitCubeLimit ( long long N ) { if ( N < 0 ) cout << " N ▁ cannot ▁ be ▁ negative STRNEWLINE " ; else { long long ans = findDestination ( N ) ; if ( ans > limit ) cout << " Limit ▁ exceeded STRNEWLINE " ; else if ( ans == F ( ans ) ) { cout << N ; cout << " ▁ reaches ▁ to ▁ a " << " ▁ fixed ▁ point : ▁ " ; cout << ans ; } else { cout << N ; cout << " ▁ reaches ▁ to ▁ a " << " ▁ limit ▁ cycle : ▁ " ; cout << ans ; } } } int main ( ) { long long N = 3 ; digitCubeLimit ( N ) ; return 0 ; }
Count quadruples ( i , j , k , l ) in an array such that i < j < k < l and arr [ i ] = arr [ k ] and arr [ j ] = arr [ l ] | C ++ program for the above approach ; Function to count total number of required tuples ; Initialize unordered map ; Find the pairs ( j , l ) such that arr [ j ] = arr [ l ] and j < l ; elements are equal ; Update the count ; Add the frequency of arr [ l ] to val ; Update the frequency of element arr [ j ] ; Return the answer ; Driver code ; Given array arr [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countTuples ( int arr [ ] , int N ) { int ans = 0 , val = 0 ; unordered_map < int , int > freq ; for ( int j = 0 ; j < N - 2 ; j ++ ) { val = 0 ; for ( int l = j + 1 ; l < N ; l ++ ) { if ( arr [ j ] == arr [ l ] ) { ans += val ; } val += freq [ arr [ l ] ] ; } freq [ arr [ j ] ] ++ ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 1 , 2 , 2 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countTuples ( arr , N ) ; return 0 ; }
Minimize subarray increments / decrements required to reduce all array elements to 0 | C ++ Program to implement the above approach ; Function to count the minimum number of operations required ; Traverse the array ; If array element is negative ; Update minimum negative ; Update maximum positive ; Return minOp ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperation ( int arr [ ] , int N ) { int minOp = INT_MIN ; int minNeg = 0 , maxPos = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] < 0 ) { if ( arr [ i ] < minNeg ) minNeg = arr [ i ] ; } else { if ( arr [ i ] > maxPos ) maxPos = arr [ i ] ; } } return abs ( minNeg ) + maxPos ; } int main ( ) { int arr [ ] = { 1 , 3 , 4 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minOperation ( arr , N ) ; }
Pair of integers having least GCD among all given pairs having GCD exceeding K | C ++ program for the above approach ; Function to calculate the GCD of two numbers ; Function to print the pair having a gcd value just greater than the given integer ; Initialize variables ; Iterate until low less than equal to high ; Calculate mid ; Reducing the search space ; Print the answer ; Driver Code ; Given array and K ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int GCD ( int a , int b ) { if ( b == 0 ) { return a ; } return GCD ( b , a % b ) ; } void GcdPair ( vector < pair < int , int > > arr , int k ) { int lo = 0 , hi = arr . size ( ) - 1 , mid ; pair < int , int > ans ; ans = make_pair ( -1 , 0 ) ; while ( lo <= hi ) { mid = lo + ( hi - lo ) / 2 ; if ( GCD ( arr [ mid ] . first , arr [ mid ] . second ) > k ) { ans = arr [ mid ] ; hi = mid - 1 ; } else lo = mid + 1 ; } if ( ans . first == -1 ) cout << " - 1" ; else cout << " ( ▁ " << ans . first << " , ▁ " << ans . second << " ▁ ) " ; return ; } int main ( ) { vector < pair < int , int > > arr = { { 3 , 6 } , { 15 , 30 } , { 25 , 75 } , { 30 , 120 } } ; int K = 16 ; GcdPair ( arr , K ) ; return 0 ; }
Check if array can be sorted by swapping pairs having GCD equal to the smallest element in the array | C ++ implementation of the above approach ; Function to check if it is possible to sort array or not ; Store the smallest element ; Copy the original array ; Iterate over the given array ; Update smallest element ; Copy elements of arr [ ] to array B [ ] ; Sort original array ; Iterate over the given array ; If the i - th element is not in its sorted place ; Not possible to swap ; Driver Code ; Given array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void isPossible ( int arr [ ] , int N ) { int mn = INT_MAX ; int B [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { mn = min ( mn , arr [ i ] ) ; B [ i ] = arr [ i ] ; } sort ( arr , arr + N ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] != B [ i ] ) { if ( B [ i ] % mn != 0 ) { cout << " No " ; return ; } } } cout << " Yes " ; return ; } int main ( ) { int N = 6 ; int arr [ ] = { 4 , 3 , 6 , 6 , 2 , 9 } ; isPossible ( arr , N ) ; return 0 ; }
Check if every vertex triplet in graph contains two vertices connected to third vertex | C ++ program of the above approach ; Function to add edge into the graph ; Finding the maximum and minimum values in each component ; Function for checking whether the given graph is valid or not ; Checking for intersecting intervals ; If intersection is found ; Graph is not valid ; Function for the DFS Traversal ; Traversing for every vertex ; Storing maximum and minimum values of each component ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void addEdge ( vector < int > adj [ ] , int u , int v ) { adj [ u ] . push_back ( v ) ; adj [ v ] . push_back ( u ) ; } void DFSUtil ( int u , vector < int > adj [ ] , vector < bool > & visited , int & componentMin , int & componentMax ) { visited [ u ] = true ; componentMax = max ( componentMax , u ) ; componentMin = min ( componentMin , u ) ; for ( int i = 0 ; i < adj [ u ] . size ( ) ; i ++ ) if ( visited [ adj [ u ] [ i ] ] == false ) DFSUtil ( adj [ u ] [ i ] , adj , visited , componentMin , componentMax ) ; } bool isValid ( vector < pair < int , int > > & v ) { int MAX = -1 ; bool ans = 0 ; for ( auto i : v ) { if ( i . first <= MAX ) { ans = 1 ; } MAX = max ( MAX , i . second ) ; } return ( ans == 0 ? 1 : 0 ) ; } void DFS ( vector < int > adj [ ] , int V ) { std :: vector < pair < int , int > > v ; vector < bool > visited ( V , false ) ; for ( int u = 1 ; u <= V ; u ++ ) { if ( visited [ u ] == false ) { int componentMax = u ; int componentMin = u ; DFSUtil ( u , adj , visited , componentMin , componentMax ) ; v . push_back ( { componentMin , componentMax } ) ; } } bool check = isValid ( v ) ; if ( check ) cout << " Yes " ; else cout << " No " ; return ; } int main ( ) { int N = 4 , K = 3 ; vector < int > adj [ N + 1 ] ; addEdge ( adj , 1 , 2 ) ; addEdge ( adj , 2 , 3 ) ; addEdge ( adj , 3 , 4 ) ; DFS ( adj , N ) ; return 0 ; }
Check if all array elements are present in a given stack or not | C ++ program of the above approach ; Function to check if all array elements is present in the stack ; Store the frequency of array elements ; Loop while the elements in the stack is not empty ; Condition to check if the element is present in the stack ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkArrInStack ( stack < int > s , int arr [ ] , int n ) { map < int , int > freq ; for ( int i = 0 ; i < n ; i ++ ) freq [ arr [ i ] ] ++ ; while ( ! s . empty ( ) ) { int poppedEle = s . top ( ) ; s . pop ( ) ; if ( freq [ poppedEle ] ) freq [ poppedEle ] -= 1 ; } if ( freq . size ( ) == 0 ) return 0 ; return 1 ; } int main ( ) { stack < int > s ; s . push ( 10 ) ; s . push ( 20 ) ; s . push ( 30 ) ; s . push ( 40 ) ; s . push ( 50 ) ; int arr [ ] = { 20 , 30 } ; int n = sizeof arr / sizeof arr [ 0 ] ; if ( checkArrInStack ( s , arr , n ) ) cout << " YES STRNEWLINE " ; else cout << " NO STRNEWLINE " ; }
Length of longest substring to be deleted to make a string equal to another string | C ++ Program to implement the above approach ; Function to print the length of longest substring to be deleted ; Stores the length of string ; Store the position of previous matched character of str1 ; Store the position of first occurrence of str2 in str1 ; Find the position of the first occurrence of str2 ; Store the index of str1 ; If both characters not matched ; Store the length of the longest deleted substring ; Store the position of last occurrence of str2 in str1 ; If both characters not matched ; Update res ; Update res . ; Driver Code ; Given string ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longDelSub ( string str1 , string str2 ) { int N = str1 . size ( ) ; int M = str2 . size ( ) ; int prev_pos = 0 ; int pos [ M ] ; for ( int i = 0 ; i < M ; i ++ ) { int index = prev_pos ; while ( index < N && str1 [ index ] != str2 [ i ] ) { index ++ ; } pos [ i ] = index ; prev_pos = index + 1 ; } int res = N - prev_pos ; prev_pos = N - 1 ; for ( int i = M - 1 ; i >= 0 ; i -- ) { int index = prev_pos ; while ( index >= 0 && str1 [ index ] != str2 [ i ] ) { index -- ; } if ( i != 0 ) { res = max ( res , index - pos [ i - 1 ] - 1 ) ; } prev_pos = index - 1 ; } res = max ( res , prev_pos + 1 ) ; return res ; } int main ( ) { string str1 = " GeeksforGeeks " ; string str2 = " forks " ; cout << longDelSub ( str1 , str2 ) ; return 0 ; }
Maximized partitions of a string such that each character of the string appears in one substring | C ++ program for the above approach ; Function to print all the substrings ; Stores the substrings ; Stores last index of characters of string s ; Find the last position of each character in the string ; Update the last index ; Iterate the given string ; Get the last index of s [ i ] ; Extend the current partition characters last pos ; If the current pos of character equals the min pos then the end of partition ; Add the respective character first ; Store the partition 's len and reset variables ; Update the minp and str ; Driver Code ; Input string ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void print_substring ( string s ) { int n = s . size ( ) ; string str = " " ; vector < int > ans ; if ( n == 0 ) { cout << " - 1" ; return ; } vector < int > last_pos ( 26 , -1 ) ; for ( int i = n - 1 ; i >= 0 ; -- i ) { if ( last_pos [ s [ i ] - ' a ' ] == -1 ) { last_pos [ s [ i ] - ' a ' ] = i ; } } int minp = -1 ; for ( int i = 0 ; i < n ; ++ i ) { int lp = last_pos [ s [ i ] - ' a ' ] ; minp = max ( minp , lp ) ; if ( i == minp ) { str += s [ i ] ; cout << str << ' ▁ ' ; minp = -1 ; str = " " ; } else { str += s [ i ] ; } } } int main ( ) { string S = " ababcbacadefegdehijhklij " ; print_substring ( S ) ; return 0 ; }
Lengths of maximized partitions of a string such that each character of the string appears in one substring | C ++ program for the above approach ; Function to find the length of all partitions oof a string such that each characters occurs in a single substring ; Stores last index of string s ; Find the last position of each letter in the string ; Update the last index ; Iterate the given string ; Get the last index of s [ i ] ; Extend the current partition characters last pos ; Increase len of partition ; if the current pos of character equals the min pos then the end of partition ; Store the length ; Print all the partition lengths ; Driver Code ; Given string str ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void partitionString ( string s ) { int n = s . size ( ) ; vector < int > ans ; if ( n == 0 ) { cout << " - 1" ; return ; } vector < int > last_pos ( 26 , -1 ) ; for ( int i = n - 1 ; i >= 0 ; -- i ) { if ( last_pos [ s [ i ] - ' a ' ] == -1 ) { last_pos [ s [ i ] - ' a ' ] = i ; } } int minp = -1 , plen = 0 ; for ( int i = 0 ; i < n ; ++ i ) { int lp = last_pos [ s [ i ] - ' a ' ] ; minp = max ( minp , lp ) ; ++ plen ; if ( i == minp ) { ans . push_back ( plen ) ; minp = -1 ; plen = 0 ; } } for ( int i = 0 ; i < ( int ) ans . size ( ) ; i ++ ) { cout << ans [ i ] << " ▁ " ; } } int main ( ) { string str = " acbbcc " ; partitionString ( str ) ; return 0 ; }
Find the maximum occurring character after performing the given operations | C ++ program for the above approach ; Function to find the maximum occurring character ; Initialize count of zero and one ; Iterate over the given string ; Count the zeros ; Count the ones ; Iterate over the given string ; Check if character is * then continue ; Check if first character after * is X ; Add all * to the frequency of X ; Set prev to the i - th character ; Check if first character after * is Y ; Set prev to the i - th character ; Check if prev character is 1 and current character is 0 ; Half of the * will be converted to 0 ; Half of the * will be converted to 1 ; Check if prev and current are 1 ; All * will get converted to 1 ; No * can be replaced by either 0 or 1 ; Prev becomes the ith character ; Check if prev and current are 0 ; All * will get converted to 0 ; If frequency of 0 is more ; If frequency of 1 is more ; Driver code ; Given string ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( string S ) { int count_0 = 0 , count_1 = 0 ; int prev = -1 ; for ( int i = 0 ; i < S . length ( ) ; i ++ ) { if ( S [ i ] == '0' ) count_0 ++ ; else if ( S [ i ] == '1' ) count_1 ++ ; } for ( int i = 0 ; i < S . length ( ) ; i ++ ) { if ( S [ i ] == ' * ' ) continue ; else if ( S [ i ] == '0' && prev == -1 ) { count_0 = count_0 + i ; prev = i ; } else if ( S [ i ] == '1' && prev == -1 ) { prev = i ; } else if ( S [ prev ] == '1' && S [ i ] == '0' ) { count_0 = count_0 + ( i - prev - 1 ) / 2 ; count_1 = count_1 + ( i - prev - 1 ) / 2 ; prev = i ; } else if ( S [ prev ] == '1' && S [ i ] == '1' ) { count_1 = count_1 + ( i - prev - 1 ) ; prev = i ; } else if ( S [ prev ] == '0' && S [ i ] == '1' ) prev = i ; else if ( S [ prev ] == '0' && S [ i ] == '0' ) { count_0 = count_0 + ( i - prev - 1 ) ; prev = i ; } } if ( count_0 > count_1 ) cout << "0" ; else if ( count_1 > count_0 ) cout << "1" ; else { cout << -1 ; } } int main ( ) { string str = " * *0 * * 1 * * *0" ; solve ( str ) ; return 0 ; }
Arithmetic Progression containing X and Y with least possible first term | C ++ program for the approach ; Function that finds the minimum positive first term including X with given common difference and the number of terms ; Stores the first term ; Initialize the low and high ; Perform binary search ; Find the mid ; Check if first term is greater than 0 ; Store the possible first term ; Search between mid + 1 to high ; Search between low to mid - 1 ; Return the minimum first term ; Function that finds the Arithmetic Progression with minimum possible first term containing X and Y ; Considering X to be smaller than Y always ; Stores the max common difference ; Stores the minimum first term and the corresponding common difference of the resultant AP ; Iterate over all the common difference ; Check if X and Y is included for current common difference ; Store the possible common difference ; Number of terms from X to Y with diff1 common difference ; Number of terms from X to Y with diff2 common difference ; Find the corresponding first terms with diff1 and diff2 ; Store the minimum first term and the corresponding common difference ; Print the resultant AP ; Driver Code ; Given length of AP and the two terms ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minFirstTerm ( int X , int diff , int N ) { int first_term ; int low = 0 , high = N ; while ( low <= high ) { int mid = ( low + high ) / 2 ; if ( X - mid * diff > 0 ) { first_term = X - mid * diff ; low = mid + 1 ; } else high = mid - 1 ; } return first_term ; } void printAP ( int N , int X , int Y ) { if ( X > Y ) swap ( X , Y ) ; int maxDiff = Y - X ; int first_term = INT_MAX , diff ; for ( int i = 1 ; i * i <= maxDiff ; i ++ ) { if ( maxDiff % i == 0 ) { int diff1 = i ; int diff2 = maxDiff / diff1 ; int terms1 = diff2 + 1 ; int terms2 = diff1 + 1 ; int first_term1 = minFirstTerm ( X , diff1 , N - terms1 ) ; int first_term2 = minFirstTerm ( X , diff2 , N - terms2 ) ; if ( first_term1 < first_term ) { first_term = first_term1 ; diff = diff1 ; } if ( first_term2 < first_term ) { first_term = first_term2 ; diff = diff2 ; } } } for ( int i = 0 ; i < N ; i ++ ) { cout << first_term << " ▁ " ; first_term += diff ; } } int main ( ) { int N = 5 , X = 10 , Y = 15 ; printAP ( N , X , Y ) ; return 0 ; }
Check if a number can be represented as sum of two consecutive perfect cubes | C ++ Program of the above approach ; Function to check if a number can be expressed as the sum of cubes of two consecutive numbers ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isCubeSum ( int n ) { for ( int i = 1 ; i * i * i <= n ; i ++ ) { if ( i * i * i + ( i + 1 ) * ( i + 1 ) * ( i + 1 ) == n ) return true ; } return false ; } int main ( ) { int n = 35 ; if ( isCubeSum ( n ) ) cout << " Yes " ; else cout << " No " ; }
Check if a number can be represented as sum of two consecutive perfect cubes | C ++ Program to implement above approach ; Function to check that a number is the sum of cubes of 2 consecutive numbers or not ; Condition to check if a number is the sum of cubes of 2 consecutive numbers or not ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isSumCube ( int N ) { int a = cbrt ( N ) ; int b = a - 1 ; return ( ( a * a * a + b * b * b ) == N ) ; } int main ( ) { int i = 35 ; if ( isSumCube ( i ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; }
Maximize sum of remaining elements after every removal of the array half with greater sum | C ++ 14 program to implement the above approach ; Function to find the maximum sum ; Base case len of array is 1 ; Stores the final result ; Traverse the array ; Store left prefix sum ; Store right prefix sum ; Compare the left and right ; If both are equal apply the optimal method ; Update with minimum ; Return the final ans ; Function to print maximum sum ; Dicitionary to store prefix sums ; Traversing the array ; Add prefix sum of the array ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxweight ( int s , int e , unordered_map < int , int > & pre ) { if ( s == e ) return 0 ; int ans = 0 ; for ( int i = s ; i < e ; i ++ ) { int left = pre [ i ] - pre [ s - 1 ] ; int right = pre [ e ] - pre [ i ] ; if ( left < right ) ans = max ( ans , left + maxweight ( s , i , pre ) ) ; if ( left == right ) { ans = max ( { ans , left + maxweight ( s , i , pre ) , right + maxweight ( i + 1 , e , pre ) } ) ; } if ( left > right ) ans = max ( ans , right + maxweight ( i + 1 , e , pre ) ) ; } return ans ; } void maxSum ( vector < int > arr ) { unordered_map < int , int > pre ; pre [ -1 ] = 0 ; pre [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < arr . size ( ) ; i ++ ) { pre [ i ] = pre [ i - 1 ] + arr [ i ] ; } cout << maxweight ( 0 , arr . size ( ) - 1 , pre ) ; } int main ( ) { vector < int > arr = { 6 , 2 , 3 , 4 , 5 , 5 } ; maxSum ( arr ) ; return 0 ; }
Maximum time in HH : MM : SS format that can be represented by given six digits | C ++ Program of the above approach ; Function to return the maximum possible time in 24 - Hours format that can be represented by array elements ; Stores the frequency of the array elements ; Maximum possible time ; Iterate to minimum possible time ; Conditions to reduce the the time iteratively ; If all required digits are present in the Map ; Retrieve Original Count ; If seconds is reduced to 0 ; If minutes is reduced to 0 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string largestTimeFromDigits ( vector < int > & A ) { map < int , int > mp1 , mp2 ; for ( auto x : A ) { mp1 [ x ] ++ ; } mp2 = mp1 ; int hr = 23 , m = 59 , s = 59 ; while ( hr >= 0 ) { int h0 = hr / 10 , h1 = hr % 10 ; int m0 = m / 10 , m1 = m % 10 ; int s0 = s / 10 , s1 = s % 10 ; int p = 0 ; vector < int > arr { h0 , h1 , m0 , m1 , s0 , s1 } ; for ( auto & it : arr ) { if ( mp1 [ it ] > 0 ) { mp1 [ it ] -- ; } else { p = 1 ; } } if ( p == 0 ) { string s = " " ; s = to_string ( h0 ) + to_string ( h1 ) ; s += ' : ' + to_string ( m0 ) + to_string ( m1 ) ; s += ' : ' + to_string ( s0 ) + to_string ( s1 ) ; return s ; } mp1 = mp2 ; if ( s == 0 ) { s = 59 ; m -- ; } else if ( m < 0 ) { m = 59 ; hr -- ; } if ( s > 0 ) { s -- ; } } return " - 1" ; } int main ( ) { vector < int > v = { 0 , 2 , 1 , 9 , 3 , 2 } ; cout << largestTimeFromDigits ( v ) ; }
Minimum size substring to be removed to make a given string palindromic | C ++ program of the above approach ; Function to find palindromic prefix of maximum length ; Finding palindromic prefix of maximum length ; Checking if curr substring is palindrome or not . ; Condition to check if the prefix is a palindrome ; if no palindrome exist ; Function to find the maximum size palindrome such that after removing minimum size substring ; Finding prefix and suffix of same length ; Matching the ranges ; Case 1 : Length is even and whole string is palindrome ; Case 2 : Length is odd and whole string is palindrome ; Adding that mid character ; Add prefix or suffix of the remaining string or suffix , whichever is longer ; Reverse the remaining string to find the palindromic suffix ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string palindromePrefix ( string S ) { int n = S . size ( ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { string curr = S . substr ( 0 , i + 1 ) ; int l = 0 , r = curr . size ( ) - 1 ; bool is_palindrome = 1 ; while ( l < r ) { if ( curr [ l ] != curr [ r ] ) { is_palindrome = 0 ; break ; } l ++ ; r -- ; } if ( is_palindrome ) return curr ; } return " " ; } string maxPalindrome ( string S ) { int n = S . size ( ) ; if ( n <= 1 ) { return S ; } string pre = " " , suff = " " ; int i = 0 , j = n - 1 ; while ( S [ i ] == S [ j ] && i < j ) { i ++ ; j -- ; } i -- ; j ++ ; pre = S . substr ( 0 , i + 1 ) ; suff = S . substr ( j ) ; if ( j - i == 1 ) { return pre + suff ; } if ( j - i == 2 ) { string mid_char = S . substr ( i + 1 , 1 ) ; return pre + mid_char + suff ; } string rem_str = S . substr ( i + 1 , j - i - 1 ) ; string pre_of_rem_str = palindromePrefix ( rem_str ) ; reverse ( rem_str . begin ( ) , rem_str . end ( ) ) ; string suff_of_rem_str = palindromePrefix ( rem_str ) ; if ( pre_of_rem_str . size ( ) >= suff_of_rem_str . size ( ) ) { return pre + pre_of_rem_str + suff ; } else { return pre + suff_of_rem_str + suff ; } } int main ( ) { string S = " geeksforskeeg " ; cout << maxPalindrome ( S ) ; return 0 ; }
Count numbers from a given range that contains a given number as the suffix | C ++ Program of the above approach ; Function to count the number ends with given number in range ; Find number of digits in A ; Find the power of 10 ; Incrementing the A ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countNumEnds ( int A , int L , int R ) { int temp , count = 0 , digits ; int cycle ; digits = log10 ( A ) + 1 ; temp = pow ( 10 , digits ) ; cycle = temp ; while ( temp <= R ) { if ( temp >= L ) count ++ ; temp += cycle ; } cout << count ; } int main ( ) { int A = 2 , L = 2 , R = 20 ; countNumEnds ( A , L , R ) ; }
Minimize replacement of characters to its nearest alphabet to make a string palindromic | C ++ program for the above approach ; Function to find the minimum number of operations required to convert th given string into palindrome ; Iterate till half of the string ; Find the absolute difference between the characters ; Adding the minimum difference of the two result ; Return the result ; Driver Code ; Given string ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperations ( string s ) { int len = s . length ( ) ; int result = 0 ; for ( int i = 0 ; i < len / 2 ; i ++ ) { int D1 = max ( s [ i ] , s [ len - 1 - i ] ) - min ( s [ i ] , s [ len - 1 - i ] ) ; int D2 = 26 - D1 ; result += min ( D1 , D2 ) ; } return result ; } int main ( ) { string s = " abccdb " ; cout << minOperations ( s ) ; return 0 ; }
Check if all the pairs of an array are coprime with each other | C ++ implementation of the above approach ; Function to store and check the factors ; Check if factors are equal ; Check if the factor is already present ; Insert the factor in set ; Check if the factor is already present ; Insert the factors in set ; Function to check if all the pairs of array elements are coprime with each other ; Check if factors of A [ i ] haven 't occurred previously ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool findFactor ( int value , unordered_set < int > & factors ) { factors . insert ( value ) ; for ( int i = 2 ; i * i <= value ; i ++ ) { if ( value % i == 0 ) { if ( value / i == i ) { if ( factors . find ( i ) != factors . end ( ) ) { return true ; } else { factors . insert ( i ) ; } } else { if ( factors . find ( i ) != factors . end ( ) || factors . find ( value / i ) != factors . end ( ) ) { return true ; } else { factors . insert ( i ) ; factors . insert ( value / i ) ; } } } } return false ; } bool allCoprime ( int A [ ] , int n ) { bool all_coprime = true ; unordered_set < int > factors ; for ( int i = 0 ; i < n ; i ++ ) { if ( A [ i ] == 1 ) continue ; if ( findFactor ( A [ i ] , factors ) ) { all_coprime = false ; break ; } } return all_coprime ; } int main ( ) { int A [ ] = { 3 , 5 , 11 , 7 , 19 } ; int arr_size = sizeof ( A ) / sizeof ( A [ 0 ] ) ; if ( allCoprime ( A , arr_size ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; }
Count subsequences which contains both the maximum and minimum array element | C ++ program for the above approach ; Function to calculate the count of subsequences ; Find the maximum from the array ; Find the minimum from the array ; If array contains only one distinct element ; Find the count of maximum ; Find the count of minimum ; Finding the result with given condition ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count ( int arr [ ] , int n , int value ) ; double countSubSequence ( int arr [ ] , int n ) { int maximum = * max_element ( arr , arr + n ) ; int minimum = * min_element ( arr , arr + n ) ; if ( maximum == minimum ) return pow ( 2 , n ) - 1 ; int i = count ( arr , n , maximum ) ; int j = count ( arr , n , minimum ) ; double res = ( pow ( 2 , i ) - 1 ) * ( pow ( 2 , j ) - 1 ) * pow ( 2 , n - i - j ) ; return res ; } int count ( int arr [ ] , int n , int value ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] == value ) sum ++ ; return sum ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countSubSequence ( arr , n ) << endl ; }
Minimize elements to be added to a given array such that it contains another given array as its subsequence | C ++ 14 program for the above approach ; Function that finds the minimum number of the element must be added to make A as a subsequence in B ; Base Case ; dp [ i ] [ j ] indicates the length of LCS of A of length i & B of length j ; If there are no elements either in A or B then the length of lcs is 0 ; If the element present at ith and jth index of A and B are equal then include in LCS ; If they are not equal then take the max ; Return difference of length of A and lcs of A and B ; Driver Code ; Given sequence A and B ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int transformSubsequence ( int n , int m , vector < int > A , vector < int > B ) { if ( B . size ( ) == 0 ) return n ; vector < vector < int > > dp ( n + 1 , vector < int > ( m + 1 , 0 ) ) ; for ( int i = 0 ; i < n + 1 ; i ++ ) { for ( int j = 0 ; j < m + 1 ; j ++ ) { if ( i == 0 or 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 n - dp [ n ] [ m ] ; } int main ( ) { int N = 5 ; int M = 6 ; vector < int > A = { 1 , 2 , 3 , 4 , 5 } ; vector < int > B = { 2 , 5 , 6 , 4 , 9 , 12 } ; cout << transformSubsequence ( N , M , A , B ) ; return 0 ; }
Check if the sum of a subarray within a given range is a perfect square or not | C ++ implementation of the above approach ; Function to calculate the square root of the sum of a subarray in a given range ; Calculate the sum of array elements within a given range ; Finding the square root ; If a perfect square is found ; Reduce the search space if the value is greater than sum ; Reduce the search space if the value if smaller than sum ; Driver Code ; Given Array ; Given range ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int checkForPerfectSquare ( vector < int > arr , int i , int j ) { int mid , sum = 0 ; for ( int m = i ; m <= j ; m ++ ) { sum += arr [ m ] ; } int low = 0 , high = sum / 2 ; while ( low <= high ) { mid = low + ( high - low ) / 2 ; if ( mid * mid == sum ) { return mid ; } else if ( mid * mid > sum ) { high = mid - 1 ; } else { low = mid + 1 ; } } return -1 ; } int main ( ) { vector < int > arr ; arr = { 2 , 19 , 33 , 48 , 90 , 100 } ; int L = 1 , R = 3 ; cout << checkForPerfectSquare ( arr , L , R ) ; return 0 ; }
Count of subarrays forming an Arithmetic Progression ( AP ) | C ++ implementation of the above approach ; Function to find the total count of subarrays ; Iterate over each subarray ; Difference between first two terms of subarray ; Iterate over the subarray from i to j ; Check if the difference of all adjacent elements is same ; Driver Code ; Given array ; Function Call
#include <iostream> NEW_LINE using namespace std ; int calcSubarray ( int A [ ] , int N ) { int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { bool flag = true ; int comm_diff = A [ i + 1 ] - A [ i ] ; for ( int k = i ; k < j ; k ++ ) { if ( A [ k + 1 ] - A [ k ] == comm_diff ) { continue ; } else { flag = false ; break ; } } if ( flag ) { count ++ ; } } } return count ; } int main ( ) { int A [ 5 ] = { 8 , 7 , 4 , 1 , 0 } ; int N = sizeof ( A ) / sizeof ( int ) ; cout << calcSubarray ( A , N ) ; }
Largest Sum Contiguous Subarray having unique elements | C ++ program for the above approach ; Function to calculate required maximum subarray sum ; Initialize two pointers ; Stores the unique elements ; Insert the first element ; Current max sum ; Global maximum sum ; Update sum & increment j auto pos = s . find ( 3 ) ; ; Add the current element ; Update sum and increment i and remove arr [ i ] from set ; Remove the element from start position ; Return the maximum sum ; Driver Code ; Given array arr [ ] ; Function Call ; Print the maximum sum
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSumSubarray ( int arr [ ] , int n ) { int i = 0 , j = 1 ; set < int > set ; set . insert ( arr [ 0 ] ) ; int sum = arr [ 0 ] ; int maxsum = sum ; while ( i < n - 1 && j < n ) { const bool is_in = set . find ( arr [ j ] ) != set . end ( ) ; if ( ! is_in ) { sum = sum + arr [ j ] ; maxsum = max ( sum , maxsum ) ; set . insert ( arr [ j ++ ] ) ; } else { sum -= arr [ i ] ; set . erase ( arr [ i ++ ] ) ; } } return maxsum ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 1 , 5 } ; int ans = maxSumSubarray ( arr , 5 ) ; cout << ( ans ) ; }
Count of numbers having only one unset bit in a range [ L , R ] | C ++ program for the above approach ; Function to count numbers in the range [ l , r ] having exactly one unset bit ; Stores the required count ; Iterate over the range ; Calculate number of bits ; Calculate number of set bits ; If count of unset bits is 1 ; Increment answer ; Return the answer ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count_numbers ( int L , int R ) { int ans = 0 ; for ( int n = L ; n <= R ; n ++ ) { int no_of_bits = log2 ( n ) + 1 ; int no_of_set_bits = __builtin_popcount ( n ) ; if ( no_of_bits - no_of_set_bits == 1 ) { ans ++ ; } } return ans ; } int main ( ) { int L = 4 , R = 9 ; cout << count_numbers ( L , R ) ; return 0 ; }
Count of numbers having only one unset bit in a range [ L , R ] | C ++ program for the above approach ; Function to count numbers in the range [ L , R ] having exactly one unset bit ; Stores the count elements having one zero in binary ; Stores the maximum number of bits needed to represent number ; Loop over for zero bit position ; Number having zero_bit as unset and remaining bits set ; Sets all bits before zero_bit ; Set the bit at position j ; Set the bit position at j ; If cur is in the range [ L , R ] , then increment ans ; Return ans ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count_numbers ( int L , int R ) { int ans = 0 ; int LogR = log2 ( R ) + 1 ; for ( int zero_bit = 0 ; zero_bit < LogR ; zero_bit ++ ) { int cur = 0 ; for ( int j = 0 ; j < zero_bit ; j ++ ) { cur |= ( 1LL << j ) ; } for ( int j = zero_bit + 1 ; j < LogR ; j ++ ) { cur |= ( 1LL << j ) ; if ( cur >= L && cur <= R ) { ans ++ ; } } } return ans ; } int main ( ) { long long L = 4 , R = 9 ; cout << count_numbers ( L , R ) ; return 0 ; }
Sum of all distances between occurrences of same characters in a given string | C ++ program for the above approach ; Function to calculate the sum of distances between occurrences of same characters in a string ; If similar characters are found ; Add the difference of their positions ; Return the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findSum ( string s ) { int sum = 0 ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { for ( int j = i + 1 ; j < s . size ( ) ; j ++ ) { if ( s [ i ] == s [ j ] ) { sum += ( j - i ) ; } } } return sum ; } int main ( ) { string s = " ttt " ; cout << findSum ( s ) << endl ; }
Count array elements that can be represented as sum of at least two consecutive array elements | C ++ program for above approach ; Function to find the number of array elements that can be represented as the sum of two or more consecutive array elements ; Stores the frequencies of array elements ; Stores required count ; Update frequency of each array element ; Find sum of all subarrays ; Increment ans by cnt [ sum ] ; Reset cnt [ sum ] by 0 ; Return ans ; Driver Code ; Given array ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countElements ( int a [ ] , int n ) { int cnt [ n + 1 ] = { 0 } ; memset ( cnt , 0 , sizeof ( cnt ) ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { ++ cnt [ a [ i ] ] ; } for ( int l = 0 ; l < n ; ++ l ) { int sum = 0 ; for ( int r = l ; r < n ; ++ r ) { sum += a [ r ] ; if ( l == r ) continue ; if ( sum <= n ) { ans += cnt [ sum ] ; cnt [ sum ] = 0 ; } } } return ans ; } int main ( ) { int a [ ] = { 1 , 1 , 1 , 1 , 1 } ; int N = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << countElements ( a , N ) ; }
Maximum GCD among all pairs ( i , j ) of first N natural numbers | C ++ program for the above approach ; Function to find maximum gcd of all pairs possible from first n natural numbers ; Stores maximum gcd ; Iterate over all possible pairs ; Update maximum GCD ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxGCD ( int n ) { int maxHcf = INT_MIN ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = i + 1 ; j <= n ; j ++ ) { maxHcf = max ( maxHcf , __gcd ( i , j ) ) ; } } return maxHcf ; } int main ( ) { int n = 4 ; cout << maxGCD ( n ) ; return 0 ; }
Maximum GCD among all pairs ( i , j ) of first N natural numbers | C ++ implementation of the above approach ; Function to find the maximum GCD among all the pairs from first n natural numbers ; Return max GCD ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxGCD ( int n ) { return ( n / 2 ) ; } int main ( ) { int n = 4 ; cout << maxGCD ( n ) ; return 0 ; }
Modify given array by incrementing first occurrence of every element by K | C ++ Program to implement the above approach ; Print the required final sequence ; Stores the array element - index pairs ; Stores the required sequence ; Insert all array elements ; If current element has not occurred previously ; Otherwise ; Iterator to the first index containing sol [ i ] ; Remove that occurrence ; Increment by K ; Insert the incremented element at that index ; Print the final sequence ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printSequence ( vector < int > & A , int n , int k ) { unordered_map < int , set < int > > mp ; vector < int > sol ; for ( int x : A ) sol . push_back ( x ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp . find ( sol [ i ] ) == mp . end ( ) || mp [ sol [ i ] ] . size ( ) == 0 ) { mp [ sol [ i ] ] . insert ( i ) ; } else { auto idxx = mp [ sol [ i ] ] . begin ( ) ; int idx = * idxx ; mp [ sol [ i ] ] . erase ( idxx ) ; sol [ idx ] += k ; mp [ sol [ idx ] ] . insert ( idx ) ; mp [ sol [ i ] ] . insert ( i ) ; } } for ( int x : sol ) { cout << x << " ▁ " ; } } int main ( ) { int N = 5 ; int K = 6 ; vector < int > A = { 1 , 4 , 1 , 1 , 4 } ; printSequence ( A , N , K ) ; }
Remove odd indexed characters from a given string | C ++ program to implement the above approach ; Function to remove the odd indexed characters from a given string ; Stores the resultant string ; If current index is odd ; Skip the character ; Otherwise , append the character ; Return the result ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string removeOddIndexCharacters ( string s ) { string new_string = " " ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( i % 2 == 1 ) { continue ; } new_string += s [ i ] ; } return new_string ; } int main ( ) { string str = " abcdef " ; cout << removeOddIndexCharacters ( str ) ; return 0 ; }
Longest subarray forming a Geometic Progression ( GP ) | C ++ Program to implement the above approach ; Function to return the length of the longest subarray forming a GP in a sorted array ; Base Case ; Stores the length of GP and the common ratio ; Stores the maximum length of the GP ; Traverse the array ; Check if the common ratio is valid for GP ; If the current common ratio is equal to previous common ratio ; Increment the length of the GP ; Store the max length of GP ; Otherwise ; Update the common ratio ; Update the length of GP ; Store the max length of GP ; Update the length of GP ; Store the max length of GP ; Return the max length of GP ; Driver Code ; Given array ; Length of the array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longestGP ( int A [ ] , int N ) { if ( N < 2 ) return N ; int length = 1 , common_ratio = 1 ; int maxlength = 1 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( A [ i + 1 ] % A [ i ] == 0 ) { if ( A [ i + 1 ] / A [ i ] == common_ratio ) { length = length + 1 ; maxlength = max ( maxlength , length ) ; } else { common_ratio = A [ i + 1 ] / A [ i ] ; length = 2 ; } } else { maxlength = max ( maxlength , length ) ; length = 1 ; } } maxlength = max ( maxlength , length ) ; return maxlength ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 7 , 14 , 28 , 56 , 89 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << longestGP ( arr , N ) ; return 0 ; }