text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Count positions in a chessboard that can be visited by the Queen which are not visited by the King | C ++ program for the above approach ; Function to print the number of cells only visited by the queen ; Find all the moves ; Find all moves for x + 1 , y + 1 ; Find all moves for x - 1 , y - 1 ; Find all moves for x - 1 , y + 1 ; Find all moves for x + 1 , y - 1 ; Find all squares visited by King x + 1 , in same row ; x - 1 , in same row ; y + 1 , in same column ; y - 1 , in same column ; Return answer ; Driver Code ; Dimension of Board ; Position of Cell ; Function Call | #include <iostream> NEW_LINE using namespace std ; int Moves_Calculator ( int x , int y , int row , int col ) { int total_moves = 0 ; if ( ( row - x ) > 0 && ( col - y ) > 0 ) total_moves += min ( ( row - x ) , ( col - y ) ) ; if ( ( y - 1 ) > 0 && ( x - 1 ) > 0 ) total_moves += min ( ( y - 1 ) , ( x - 1 ) ) ; if ( ( x - 1 ) > 0 && ( col - y ) > 0 ) total_moves += min ( ( x - 1 ) , ( col - y ) ) ; if ( ( row - x ) > 0 && ( y - 1 ) > 0 ) total_moves += min ( ( row - x ) , ( y - 1 ) ) ; total_moves += ( row - 1 ) + ( col - 1 ) ; int king_moves = 0 ; if ( x + 1 <= row ) king_moves += 1 ; if ( x - 1 > 0 ) king_moves += 1 ; if ( y + 1 <= col ) king_moves += 1 ; if ( y - 1 > 0 ) king_moves += 1 ; if ( x + 1 <= row && y + 1 <= col ) king_moves += 1 ; if ( x + 1 <= row && y - 1 > 0 ) king_moves += 1 ; if ( x - 1 > 0 && y - 1 > 0 ) king_moves += 1 ; if ( x - 1 > 0 && y + 1 <= col ) king_moves += 1 ; return total_moves - king_moves ; } int main ( ) { int n = 8 , m = 8 ; int x = 1 , y = 1 ; cout << ( Moves_Calculator ( x , y , m , n ) ) ; return 0 ; } |
Nearest smaller number to N having multiplicative inverse under modulo N equal to that number | C ++ program to implement the above approach ; Function to find the nearest smaller number satisfying the condition ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int clstNum ( int N ) { return ( N - 1 ) ; } int main ( ) { int N = 11 ; cout << clstNum ( N ) ; } |
Count array elements having modular inverse under given prime number P equal to itself | C ++ program to implement the above approach ; Function to get the count of elements that satisfy the given condition . ; Stores count of elements that satisfy the condition ; Traverse the given array . ; If square of current element is equal to 1 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int equvInverse ( int arr [ ] , int N , int P ) { int cntElem = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( ( arr [ i ] * arr [ i ] ) % P == 1 ) { cntElem ++ ; } } return cntElem ; } int main ( ) { int arr [ ] = { 1 , 6 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int P = 7 ; cout << equvInverse ( arr , N , P ) ; } |
Count ways to split array into K non | C ++ program to implement the above approach ; Function to get the value of pow ( K , M ) ; Stores value of pow ( K , M ) ; Calculate value of pow ( K , N ) ; If N is odd , update res ; Update M to M / 2 ; Update K ; Function to print total ways to split the array that satisfies the given condition ; Stores total ways that satisfies the given condition ; Stores count of distinct elements in the given arr ; Store distinct elements of the given array ; Traverse the given array ; Insert current element into set st . ; Update M ; Update cntways ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int power ( int K , int M ) { int res = 1 ; while ( M > 0 ) { if ( ( M & 1 ) == 1 ) { res = ( res * K ) ; } M = M >> 1 ; K = ( K * K ) ; } return res ; } int cntWays ( int arr [ ] , int N , int K ) { int cntways = 0 ; int M = 0 ; unordered_set < int > st ; for ( int i = 0 ; i < N ; i ++ ) { st . insert ( arr [ i ] ) ; } M = st . size ( ) ; cntways = power ( K , M ) ; return cntways ; } int main ( ) { int arr [ ] = { 2 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 2 ; cout << cntWays ( arr , N , K ) ; return 0 ; } |
Minimize product of first N | C ++ program for the above approach ; Function to find the minimum product of 1 to N - 1 after performing the given operations ; Initialize ans with 1 ; Multiply ans with N - 2 ( ( N - 4 ) / 2 ) times ; Multiply ans with N - 1 and N - 2 once ; Print ans ; Driver Code ; Given Number N ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int mod = 1e9 + 7 ; void minProduct ( int n ) { int ans = 1 ; for ( int i = 1 ; i <= ( n - 4 ) / 2 ; i ++ ) { ans = ( 1LL * ans * ( n - 2 ) ) % mod ; } ans = ( 1LL * ans * ( n - 2 ) * ( n - 1 ) ) % mod ; cout << ans << endl ; } int main ( ) { int N = 8 ; minProduct ( N ) ; return 0 ; } |
Bitwise XOR of all unordered pairs from a given array | C ++ program to implement the above approach ; Function to get bitwise XOR of all possible pairs of the given array ; Stores bitwise XOR of all possible pairs ; Generate all possible pairs and calculate bitwise XOR of all possible pairs ; Calculate bitwise XOR of each pair ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int TotalXorPair ( int arr [ ] , int N ) { int totalXOR = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { totalXOR ^= arr [ i ] ^ arr [ j ] ; } } return totalXOR ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << TotalXorPair ( arr , N ) ; } |
Count permutations of all integers upto N that can form an acyclic graph based on given conditions | C ++ implementation of above approach ; Find the count of possible graphs ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void possibleAcyclicGraph ( int N ) { cout << pow ( 2 , N - 1 ) ; return ; } int main ( ) { int N = 4 ; possibleAcyclicGraph ( N ) ; return 0 ; } |
Minimize positive product of two given numbers by at most N decrements | C ++ program to implement the above approach ; Function to minimize the product of two numbers ; Reducing X , N times , minimizes the product ; Reduce X to 1 and reduce remaining N from Y ; Reducing Y , N times , minimizes the product ; Reduce Y to 1 and reduce remaining N from X ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minProd ( int X , int Y , int N ) { if ( X <= Y ) { if ( N < X ) return ( X - N ) * Y ; else { return max ( Y - ( N - X + 1 ) , 1 ) ; } } if ( Y >= N ) return ( Y - N ) * X ; return max ( X - ( N - Y + 1 ) , 1 ) ; ; } int main ( ) { int X = 47 , Y = 42 , N = 167 ; cout << minProd ( X , Y , N ) ; } |
Count pairs from an array having product of their sum and difference equal to 1 | C ++ program for the above approach ; Function to count the desired number of pairs ; Initialize oneCount ; Initialize the desiredPair ; Traverse the given array ; If 1 is encountered ; If 0 is encountered ; Update count of pairs ; Return the final count ; Driver Code ; Given array arr [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int arr [ ] , int n ) { int oneCount = 0 ; int desiredPair = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == 1 ) { oneCount ++ ; } if ( arr [ i ] == 0 ) { desiredPair += oneCount ; } } return desiredPair ; } int main ( ) { int arr [ ] = { 3 , 1 , 1 , 0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , N ) ; return 0 ; } |
Smallest missing non | C ++ program to implement the above approach ; Function to print the smallest missing non - negative integer up to every array indices ; Stores the smallest missing non - negative integers between start index to current index ; Store the boolean value to check smNonNeg present between start index to each index of the array ; Traverse the array ; Since output always lies in the range [ 0 , N - 1 ] ; Check if smNonNeg is present between start index and current index or not ; Print smallest missing non - negative integer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void smlstNonNeg ( int arr [ ] , int N ) { int smNonNeg = 0 ; bool hash [ N + 1 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] >= 0 and arr [ i ] < N ) { hash [ arr [ i ] ] = true ; } while ( hash [ smNonNeg ] ) { smNonNeg ++ ; } cout << smNonNeg << " β " ; } } int main ( ) { int arr [ ] = { 0 , 1 , 2 , 3 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; smlstNonNeg ( arr , N ) ; } |
Split array into two subsequences having minimum count of pairs with sum equal to X | C ++ program for above approach ; Function to split the array into two subsequences ; Stores the two subsequences ; Flag to set / reset to split arrays elements alternately into two arrays ; Traverse the given array ; If 2 * arr [ i ] is less than X ; Push element into the first array ; If 2 * arr [ i ] is greater than X ; Push element into the second array ; If 2 * arr [ i ] is equal to X ; Alternatively place the elements into the two arrays ; Print both the arrays ; Driver Code ; Size of the array ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( int arr [ ] , int N , int X ) { vector < int > A , B ; int c = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( ( 2 * arr [ i ] ) < X ) { A . push_back ( arr [ i ] ) ; } else if ( ( 2 * arr [ i ] ) > X ) { B . push_back ( arr [ i ] ) ; } else { if ( c % 2 == 0 ) { A . push_back ( arr [ i ] ) ; } else { B . push_back ( arr [ i ] ) ; } c ++ ; } } cout << " The β First β Array β is β - β " ; for ( int i = 0 ; i < A . size ( ) ; i ++ ) { cout << A [ i ] << " β " ; } cout << endl ; cout << " The β Second β Array β is β - β " ; for ( int i = 0 ; i < B . size ( ) ; i ++ ) { cout << B [ i ] << " β " ; } } int main ( ) { int arr [ ] = { 1 , 5 , 4 , 3 , 6 , 2 , 4 , 3 } ; int X = 7 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; solve ( arr , N , X ) ; } |
Split array into minimum number of subsets having maximum pair sum at most K | C ++ program to implement the above approach ; Function to get the minimum count of subsets that satisfy the given condition ; Store the minimum count of subsets that satisfy the given condition ; Stores start index of the sorted array . ; Stores end index of the sorted array ; Sort the given array ; Traverse the array ; If only two elements of sorted array left ; If only one elements left in the array ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int cntMinSub ( int arr [ ] , int N , int K ) { int res = 0 ; int start = 0 ; int end = N - 1 ; sort ( arr , arr + N ) ; while ( end - start > 1 ) { if ( arr [ start ] + arr [ end ] <= K ) { start ++ ; } else { res ++ ; end -- ; } } if ( end - start == 1 ) { if ( arr [ start ] + arr [ end ] <= K ) { res ++ ; start ++ ; end -- ; } else { res ++ ; end -- ; } } if ( start == end ) { res ++ ; } return res ; } int main ( ) { int arr [ ] = { 2 , 6 , 8 , 10 , 20 , 25 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 26 ; cout << cntMinSub ( arr , N , K ) ; } |
Count possible values of K such that X | C ++ program for the above approach ; Function to count integers K satisfying given equation ; Calculate the absoluter difference between a and b ; Iterate till sqrt of the difference ; Return the count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int condition ( int a , int b ) { int d = abs ( a - b ) , count = 0 ; for ( int i = 1 ; i <= sqrt ( d ) ; i ++ ) { if ( d % i == 0 ) { if ( d / i == i ) count += 1 ; else count += 2 ; } } return count ; } int main ( ) { int x = 2 , y = 6 ; cout << condition ( x , y ) << endl ; return 0 ; } |
Count pairs in an array whose product is composite number | C ++ program to implement the above approach ; Function to check if a number is prime or not ; Check if N is multiple of i or not . ; If N is multiple of i . ; Function to get the count of pairs whose product is a composite number . ; Stores the count of pairs whose product is a composite number ; Generate all possible pairs ; Stores the product of element of current pair ; If prod is a composite number ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isComposite ( int N ) { for ( int i = 2 ; i * i <= N ; i ++ ) { if ( N % i == 0 ) { return true ; } } return false ; } int compositePair ( int arr [ ] , int N ) { int res = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { int prod = arr [ i ] * arr [ j ] ; if ( isComposite ( prod ) ) { res ++ ; } } } return res ; } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 2 , 8 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << compositePair ( arr , N ) ; return 0 ; } |
Count N | C ++ Program for the above approach ; Function for calculate ( x ^ y ) % mod in O ( log y ) ; Base Condition ; Transition state of power Function ; Function for counting total numbers that can be formed such that digits X , Y are present in each number ; Calculate the given expression ; Return the final answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int mod = 1e9 + 7 ; long long power ( int x , int y ) { if ( y == 0 ) return 1 ; long long int p = power ( x , y / 2 ) % mod ; p = ( p * p ) % mod ; if ( y & 1 ) { p = ( x * p ) % mod ; } return p ; } int TotalNumber ( int N ) { int ans = ( power ( 10 , N ) - 2 * power ( 9 , N ) + power ( 8 , N ) + 2 * mod ) % mod ; return ans ; } int main ( ) { int N = 10 , X = 3 , Y = 4 ; cout << TotalNumber ( N ) << endl ; return 0 ; } |
Array obtained by repeatedly reversing array after every insertion from given array | C ++ program of the above approach ; Function to generate the array by inserting array elements one by one followed by reversing the array ; Doubly ended Queue ; Iterate over the array ; Push array elements alternately to the front and back ; If size of list is odd ; Reverse the list ; Print the elements of the array ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void generateArray ( int arr [ ] , int n ) { deque < int > ans ; for ( int i = 0 ; i < n ; i ++ ) { if ( i & 1 ) ans . push_front ( arr [ i ] ) ; else ans . push_back ( arr [ i ] ) ; } if ( n & 1 ) { reverse ( ans . begin ( ) , ans . end ( ) ) ; } for ( auto x : ans ) { cout << x << " β " ; } cout << endl ; } int32_t main ( ) { int n = 4 ; int arr [ n ] = { 1 , 2 , 3 , 4 } ; generateArray ( arr , n ) ; return 0 ; } |
Find the greater number closest to N having at most one non | C ++ program to implement the above approach ; Function to get closest greater number with at most non zero digit ; Stores the closest greater number with at most one non - zero digit ; Stores length of str ; Append 10 to the end of resultant string ; Append n - 1 times '0' to the end of resultant string ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string closestgtNum ( string str ) { string res = " " ; int n = str . length ( ) ; if ( str [ 0 ] < '9' ) { res . push_back ( str [ 0 ] + 1 ) ; } else { res . push_back ( '1' ) ; res . push_back ( '0' ) ; } for ( int i = 0 ; i < n - 1 ; i ++ ) { res . push_back ( '0' ) ; } return res ; } int main ( ) { string str = "120" ; cout << closestgtNum ( str ) ; } |
Count maximum non | C ++ program for the above approach ; Function to count maximum number of non - overlapping subarrays with sum equals to the target ; Stores the final count ; Next subarray should start from index >= availIdx ; Tracks the prefix sum ; Map to store the prefix sum for respective indices ; Check if cur_sum - target is present in the array or not ; Update the index of current prefix sum ; Return the count of subarrays ; Driver Code ; Given array arr [ ] ; Given sum target ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumSubarrays ( int arr [ ] , int N , int target ) { int ans = 0 ; int availIdx = -1 ; int cur_sum = 0 ; unordered_map < int , int > mp ; mp [ 0 ] = -1 ; for ( int i = 0 ; i < N ; i ++ ) { cur_sum += arr [ i ] ; if ( mp . find ( cur_sum - target ) != mp . end ( ) && mp [ cur_sum - target ] >= availIdx ) { ans ++ ; availIdx = i ; } mp [ cur_sum ] = i ; } return ans ; } int main ( ) { int arr [ ] = { 2 , -1 , 4 , 3 , 6 , 4 , 5 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int target = 6 ; cout << maximumSubarrays ( arr , N , target ) ; return 0 ; } |
Maximize array sum by replacing equal adjacent pairs by their sum and X respectively | C ++ program for the above approach ; Function to calculate x ^ y ; Base Case ; Find the value in temp ; If y is even ; Function that find the maximum possible sum of the array ; Print the result using the formula ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int power ( int x , int y ) { int temp ; if ( y == 0 ) return 1 ; temp = power ( x , y / 2 ) ; if ( y % 2 == 0 ) return temp * temp ; else return x * temp * temp ; } void maximumPossibleSum ( int N , int X ) { cout << ( X * ( power ( 2 , N ) - 1 ) ) << endl ; } int main ( ) { int N = 3 , X = 5 ; maximumPossibleSum ( N , X ) ; } |
Count ways to generate pairs having Bitwise XOR and Bitwise AND equal to X and Y respectively | C ++ program for the above approach ; Function to return the count of possible pairs of A and B whose Bitwise XOR is X and Y respectively ; Stores the count of pairs ; Iterate till any bit are set ; Extract i - th bit of X and Y ; Divide X and Y by 2 ; If Xi = 1 and Yi = 2 , multiply counter by 2 ; Increase required count ; If Xi = 1 and Yi = 1 ; No answer exists ; Return the final count ; Driver Code ; Given X and Y ; Function Call | #include <iostream> NEW_LINE using namespace std ; int countOfPairs ( int x , int y ) { int counter = 1 ; while ( x y ) { int bit1 = x % 2 ; int bit2 = y % 2 ; x >>= 1 ; y >>= 1 ; if ( bit1 == 1 and bit2 == 0 ) { counter *= 2 ; continue ; } if ( bit1 & bit2 ) { counter = 0 ; break ; } } return counter ; } int main ( ) { int X = 2 , Y = 5 ; cout << countOfPairs ( X , Y ) ; return 0 ; } |
Make all array elements equal by repeated subtraction of absolute difference of pairs from their maximum | C ++ Program to implement the above approach ; Function to return gcd of a and b ; Base Case ; Recursive Call ; Function to find gcd of array ; Initialise the result ; Traverse the array arr [ ] ; Update result as gcd of the result and arr [ i ] ; Return the resultant GCD ; Driver Code ; Given array arr [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } int findGCD ( int arr [ ] , int N ) { int result = 0 ; for ( int i = 0 ; i < N ; i ++ ) { result = gcd ( result , arr [ i ] ) ; if ( result == 1 ) { return 1 ; } } return result ; } int main ( ) { int arr [ ] = { 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findGCD ( arr , N ) ; return 0 ; } |
Check if any permutation of array contains sum of every adjacent pair not divisible by 3 | C ++ program for the above approach ; Function to checks if any permutation of the array exists whose sum of adjacent pairs is not divisible by 3 ; Count remainder 0 ; Count remainder 1 ; Count remainder 2 ; Condition for valid arrangements ; Driver Code ; Given array arr [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void factorsOf3 ( int arr [ ] , int N ) { int a = 0 , b = 0 , c = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] % 3 == 0 ) a ++ ; else if ( arr [ i ] % 3 == 1 ) b ++ ; else if ( arr [ i ] % 3 == 2 ) c ++ ; } if ( a >= 1 && a <= b + c + 1 ) cout << " Yes " << endl ; else if ( a == 0 && b == 0 && c > 0 ) cout << " Yes " << endl ; else if ( a == 0 && c == 0 && b > 0 ) cout << " Yes " << endl ; else cout << " No " << endl ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; factorsOf3 ( arr , N ) ; return 0 ; } |
Check if a number is a perfect square having all its digits as a perfect square | C ++ program for the above approach ; Function to check if digits of N is a perfect square or not ; Iterate over the digits ; Extract the digit ; Check if digit is a perfect square or not ; Divide N by 10 ; Return true ; Function to check if N is a perfect square or not ; If floor and ceil of n is not same ; Function to check if N satisfies the required conditions or not ; If both the conditions are satisfied ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool check_digits ( long N ) { while ( N > 0 ) { int n = N % 10 ; if ( ( n != 0 ) && ( n != 1 ) && ( n != 4 ) && ( n != 9 ) ) { return 0 ; } N = N / 10 ; } return 1 ; } bool is_perfect ( long N ) { long double n = sqrt ( N ) ; if ( floor ( n ) != ceil ( n ) ) { return 0 ; } return 1 ; } void isFullSquare ( long N ) { if ( is_perfect ( N ) && check_digits ( N ) ) { cout << " Yes " ; } else { cout << " No " ; } } int main ( ) { long N = 144 ; isFullSquare ( N ) ; return 0 ; } |
Count substrings with different first and last characters | C ++ program for the above approach ; Function to count the substrings having different first & last character ; Stores frequency of each char ; Loop to store frequency of the characters in a Map ; To store final result ; Traversal of string ; Store answer for every iteration ; Map traversal ; Compare current char ; Print the final count ; Driver Code ; Given string ; Length of the string ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubstring ( string s , int n ) { map < char , int > m ; for ( int i = 0 ; i < n ; i ++ ) m [ s [ i ] ] ++ ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int cnt = 0 ; m [ s [ i ] ] -- ; for ( auto value : m ) { if ( value . first == s [ i ] ) { continue ; } else { cnt += value . second ; } } ans += cnt ; } cout << ans ; } int main ( ) { string S = " abcab " ; int N = 5 ; countSubstring ( S , N ) ; return 0 ; } |
Maximize count of empty water bottles from N filled bottles | C ++ program for the above approach ; Function to find the maximum bottles that can be emptied ; Iterate until a is non - zero ; Add the number of bottles that are emptied ; Update a after exchanging empty bottles ; Stores the number of bottles left after the exchange ; Return the answer ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxBottles ( int n , int e ) { int s = 0 , b = 0 ; int a = n ; while ( a != 0 ) { s = s + a ; a = ( a + b ) / e ; b = n - ( a * e ) ; n = a + b ; } return s ; } int main ( ) { int n = 9 , e = 3 ; int s = maxBottles ( n , e ) ; cout << s << endl ; } |
Count all N digit numbers whose digits are multiple of X | C ++ program for the above approach ; Function to calculate x ^ n using binary - exponentiation ; Stores the resultant power ; Stores the value of x ^ ( n / 2 ) ; Function to count all N - digit numbers whose digits are multiples of x ; Count all digits which are multiples of x ; Check if current number is a multiple of X ; Increase count of multiples ; Check if it 's a 1 digit number ; Count the total numbers ; Return the total numbers ; Driver Code ; Given N and X ; Function Call | #include <stdio.h> NEW_LINE #define ll long long NEW_LINE ll power ( ll x , ll n ) { ll temp ; if ( n == 0 ) return 1 ; temp = power ( x , n / 2 ) ; if ( n % 2 == 0 ) return temp * temp ; else return x * temp * temp ; } ll count_Total_Numbers ( ll n , ll x ) { ll total , multiples = 0 ; for ( int i = 0 ; i < 10 ; i ++ ) { if ( i % x == 0 ) multiples ++ ; } if ( n == 1 ) return multiples ; total = ( multiples - 1 ) * power ( multiples , n - 1 ) ; return total ; } int main ( ) { ll N = 1 , X = 3 ; printf ( " % lld β " , count_Total_Numbers ( N , X ) ) ; return 0 ; } |
Find the vertex diagonally opposite to the vertex M from an N | C ++ program for the above approach ; Function to return the required vertex ; Case 1 : ; Case 2 : ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getPosition ( int N , int M ) { if ( M > ( N / 2 ) ) { return ( M - ( N / 2 ) ) ; } return ( M + ( N / 2 ) ) ; } int main ( ) { int N = 8 , M = 5 ; cout << getPosition ( N , M ) ; return 0 ; } |
Maximize count of strings of length 3 that can be formed from N 1 s and M 0 s | C ++ program for the above approach ; Function that counts the number of strings of length three that can be made with given m 0 s and n 1 s ; Iterate until N & M are positive ; Case 1 : ; Case 2 : ; Print the count of strings ; Driver Code ; Given count of 1 s and 0 s ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void number_of_strings ( int N , int M ) { int ans = 0 ; while ( N > 0 && M > 0 ) { if ( N > M ) { if ( N >= 2 ) { N -= 2 ; -- M ; ++ ans ; } else { break ; } } else { if ( M >= 2 ) { M -= 2 ; -- N ; ++ ans ; } else { break ; } } } cout << ans ; } int main ( ) { int N = 4 , M = 19 ; number_of_strings ( N , M ) ; return 0 ; } |
Minimize array length by repeatedly replacing pairs of unequal adjacent array elements by their sum | C ++ program for the above approach ; Function that returns the minimum length of the array after merging unequal adjacent elements ; Stores the first element and its frequency ; Traverse the array ; If all elements are equal ; No merge - pair operations can be performed ; Otherwise ; Driver Code ; Given array ; Length of the array ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minLength ( int A [ ] , int N ) { int elem = A [ 0 ] , count = 1 ; for ( int i = 1 ; i < N ; i ++ ) { if ( A [ i ] == elem ) { count ++ ; } else { break ; } } if ( count == N ) return N ; else return 1 ; } int main ( ) { int arr [ ] = { 2 , 1 , 3 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minLength ( arr , N ) << endl ; return 0 ; } |
Reduce N to 0 or less by given X and Y operations | C ++ Program to implement the above approach ; Function to check if N can be reduced to <= 0 or not ; Update N to N / 2 + 10 at most X times ; Update N to N - 10 Y times ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool NegEqu ( int N , int X , int Y ) { while ( X -- and N > N / 2 + 10 ) { N = N / 2 + 10 ; } while ( Y -- ) { N = N - 10 ; } if ( N <= 0 ) return true ; return false ; } int main ( ) { int N = 100 ; int X = 3 ; int Y = 4 ; if ( NegEqu ( N , X , Y ) ) { cout << " Yes " ; } else { cout << " No " ; } } |
Split array into minimum number of subarrays having GCD of its first and last element exceeding 1 | C ++ program for the above approach ; Function to find the minimum number of subarrays ; Right pointer ; Left pointer ; Count of subarrays ; Find GCD ( left , right ) ; Found a valid large subarray between arr [ left , right ] ; Searched the arr [ 0. . right ] and found no subarray having size > 1 and having gcd ( left , right ) > 1 ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minSubarrays ( int arr [ ] , int n ) { int right = n - 1 ; int left = 0 ; int subarrays = 0 ; while ( right >= 0 ) { for ( left = 0 ; left <= right ; left += 1 ) { if ( __gcd ( arr [ left ] , arr [ right ] ) > 1 ) { subarrays += 1 ; right = left - 1 ; break ; } if ( left == right && __gcd ( arr [ left ] , arr [ right ] ) == 1 ) { return 0 ; } } } return subarrays ; } int main ( ) { int N = 6 ; int arr [ ] = { 2 , 3 , 4 , 4 , 4 , 3 } ; cout << minSubarrays ( arr , N ) ; return 0 ; } |
Find the largest possible value of K such that K modulo X is Y | C ++ program for the above approach ; Function to find the largest positive integer K such that K % x = y ; Stores the minimum solution ; Return the maximum possible value ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaxSoln ( int n , int x , int y ) { int ans = INT_MIN ; for ( int k = 0 ; k <= n ; k ++ ) { if ( k % x == y ) { ans = max ( ans , k ) ; } } return ( ( ans >= 0 && ans <= n ) ? ans : -1 ) ; } int main ( ) { int n = 15 , x = 10 , y = 5 ; cout << findMaxSoln ( n , x , y ) ; return 0 ; } |
Count all numbers up to N having M as the last digit | C ++ Program to implement the above approach ; Function to count the numbers ending with M ; Stores the count of numbers required ; Calculate count upto nearest power of 10 ; Computing the value of x ; Adding the count of numbers ending at M from x to N ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getCount ( int N , int M ) { int total_count = 0 ; total_count += ( N / 10 ) ; int x = ( N / 10 ) * 10 ; if ( ( N - x ) >= M ) { total_count = total_count + 1 ; } return total_count ; } int main ( ) { int N = 100 , M = 1 ; cout << getCount ( N , M ) ; return 0 ; } |
Count of Right | C ++ program for the above approach ; Function to find the number of right angled triangle that are formed from given N points whose perpendicular or base is parallel to X or Y axis ; To store the number of points has same x or y coordinates ; Store the total count of triangle ; Iterate to check for total number of possible triangle ; Add the count of triangles formed ; Total possible triangle ; Driver Code ; Given N points ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int RightAngled ( int a [ ] [ 2 ] , int n ) { unordered_map < int , int > xpoints ; unordered_map < int , int > ypoints ; for ( int i = 0 ; i < n ; i ++ ) { xpoints [ a [ i ] [ 0 ] ] ++ ; ypoints [ a [ i ] [ 1 ] ] ++ ; } int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( xpoints [ a [ i ] [ 0 ] ] >= 1 && ypoints [ a [ i ] [ 1 ] ] >= 1 ) { count += ( xpoints [ a [ i ] [ 0 ] ] - 1 ) * ( ypoints [ a [ i ] [ 1 ] ] - 1 ) ; } } return count ; } int main ( ) { int N = 5 ; int arr [ ] [ 2 ] = { { 1 , 2 } , { 2 , 1 } , { 2 , 2 } , { 2 , 3 } , { 3 , 2 } } ; cout << RightAngled ( arr , N ) ; return 0 ; } |
Smallest subarray which upon repetition gives the original array | C ++ program for the above approach ; Function to print the array ; Function to find the smallest subarray ; Corner Case ; Initialize the auxiliary subarray ; Push the first 2 elements into the subarray brr [ ] ; Iterate over the length of subarray ; If array can be divided into subarray of i equal length ; Check if on repeating the current subarray gives the original array or not ; Subarray found ; Add current element into subarray ; No subarray found ; Driver Code ; Function call | #include <iostream> NEW_LINE #include <vector> NEW_LINE using namespace std ; void printArray ( vector < int > & brr ) { for ( auto & it : brr ) { cout << it << ' β ' ; } } void RepeatingSubarray ( int arr [ ] , int N ) { if ( N < 2 ) { cout << " - 1" ; } vector < int > brr ; brr . push_back ( arr [ 0 ] ) ; brr . push_back ( arr [ 1 ] ) ; for ( int i = 2 ; i < N / 2 + 1 ; i ++ ) { if ( N % i == 0 ) { bool a = false ; int n = brr . size ( ) ; int j = i ; while ( j < N ) { int K = j % i ; if ( arr [ j ] == brr [ K ] ) { j ++ ; } else { a = true ; break ; } } if ( ! a && j == N ) { printArray ( brr ) ; return ; } } brr . push_back ( arr [ i ] ) ; } cout << " - 1" ; return ; } int main ( ) { int arr [ ] = { 1 , 2 , 2 , 1 , 2 , 2 , 1 , 2 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; RepeatingSubarray ( arr , N ) ; return 0 ; } |
Find all missing numbers from a given sorted array | C ++ program for the above approach ; Function to find the missing elements ; Initialize diff ; Check if diff and arr [ i ] - i both are equal or not ; Loop for consecutive missing elements ; Driver Code ; Given array arr [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printMissingElements ( int arr [ ] , int N ) { int diff = arr [ 0 ] - 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] - i != diff ) { while ( diff < arr [ i ] - i ) { cout << i + diff << " β " ; diff ++ ; } } } } int main ( ) { int arr [ ] = { 6 , 7 , 10 , 11 , 13 } ; int N = sizeof ( arr ) / sizeof ( int ) ; printMissingElements ( arr , N ) ; return 0 ; } |
Find all missing numbers from a given sorted array | C ++ program for the above approach ; Function to find the missing elements ; Initialize an array with zero of size equals to the maximum element in the array ; Make b [ i ] = 1 if i is present in the array ; If the element is present make b [ arr [ i ] ] = 1 ; Print the indices where b [ i ] = 0 ; Driver Code ; Given array arr [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printMissingElements ( int arr [ ] , int N ) { int b [ arr [ N - 1 ] + 1 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { b [ arr [ i ] ] = 1 ; } for ( int i = arr [ 0 ] ; i <= arr [ N - 1 ] ; i ++ ) { if ( b [ i ] == 0 ) { cout << i << " β " ; } } } int main ( ) { int arr [ ] = { 6 , 7 , 10 , 11 , 13 } ; int N = sizeof ( arr ) / sizeof ( int ) ; printMissingElements ( arr , N ) ; return 0 ; } |
Least common element in given two Arithmetic sequences | C ++ program to implement the above approach ; Function to find the smallest element common in both the subsequences ; If a is equal to c ; If a exceeds c ; Check for the satisfying equation ; Least value of possible_y satisfying the given equation will yield true in the below if and break the loop ; If the value of possible_y satisfying the given equation lies in range [ 0 , b ] ; If no value of possible_y satisfies the given equation ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long smallestCommon ( long a , long b , long c , long d ) { if ( a == c ) return a ; if ( a > c ) { swap ( a , c ) ; swap ( b , d ) ; } long first_term_diff = ( c - a ) ; long possible_y ; for ( possible_y = 0 ; possible_y < b ; possible_y ++ ) { if ( ( first_term_diff % b + possible_y * d ) % b == 0 ) { break ; } } if ( possible_y != b ) { return c + possible_y * d ; } return -1 ; } int main ( ) { long A = 2 , B = 20 , C = 19 , D = 9 ; cout << smallestCommon ( A , B , C , D ) ; return 0 ; } |
Minimum number of flips with rotation to make binary string alternating | C ++ program for the above approach ; Function that finds the minimum number of flips to make the binary string alternating if left circular rotation is allowed ; Initialize prefix arrays to store number of changes required to put 1 s at either even or odd position ; If i is odd ; Update the oddone and evenone count ; Else i is even ; Update the oddone and evenone count ; Initialize minimum flips ; Check if substring [ 0 , i ] is appended at end how many changes will be required ; Return minimum flips ; Driver Code ; Given String ; Length of given string ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int MinimumFlips ( string s , int n ) { int a [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { a [ i ] = ( s [ i ] == '1' ? 1 : 0 ) ; } int oddone [ n + 1 ] ; int evenone [ n + 1 ] ; oddone [ 0 ] = 0 ; evenone [ 0 ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 != 0 ) { oddone [ i + 1 ] = oddone [ i ] + ( a [ i ] == 1 ? 1 : 0 ) ; evenone [ i + 1 ] = evenone [ i ] + ( a [ i ] == 0 ? 1 : 0 ) ; } else { oddone [ i + 1 ] = oddone [ i ] + ( a [ i ] == 0 ? 1 : 0 ) ; evenone [ i + 1 ] = evenone [ i ] + ( a [ i ] == 1 ? 1 : 0 ) ; } } int minimum = min ( oddone [ n ] , evenone [ n ] ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( n % 2 != 0 ) { minimum = min ( minimum , oddone [ n ] - oddone [ i + 1 ] + evenone [ i + 1 ] ) ; minimum = min ( minimum , evenone [ n ] - evenone [ i + 1 ] + oddone [ i + 1 ] ) ; } } return minimum ; } int main ( ) { string S = "000001100" ; int n = S . length ( ) ; cout << ( MinimumFlips ( S , n ) ) ; } |
Create a Graph by connecting divisors from N to M and find shortest path | C ++ program for the above approach ; Function to check the number is prime or not ; Base Cases ; Iterate till [ 5 , sqrt ( N ) ] to detect primarility of numbers ; Function to print the shortest path ; Use vector to store the factor of m and n ; Use map to check if largest common factor previously present or not ; First store m ; Check whether m is prime or not ; Largest common factor of m ; If m is divisible by i ; Store the largest common factor ; For number n ; Check whether n is prime ; Largest common factor of n ; Store the largest common factor ; Print the path Print factors from m ; To avoid duplicate printing of same element ; Print the factors from n ; Driver Code ; Given N and M ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int isprm ( int n ) { if ( n <= 1 ) return 0 ; if ( n <= 3 ) return 1 ; if ( n % 2 == 0 n % 3 == 0 ) return 0 ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return 0 ; return 1 ; } void shortestpath ( int m , int n ) { vector < int > mfactor , nfactor ; map < int , int > fre ; mfactor . push_back ( m ) ; fre [ m ] = 1 ; while ( m != 1 ) { if ( isprm ( m ) ) { mfactor . push_back ( 1 ) ; fre [ 1 ] = 1 ; m = 1 ; } else { for ( int i = 2 ; i <= sqrt ( m ) ; i ++ ) { if ( m % i == 0 ) { mfactor . push_back ( m / i ) ; fre [ m / i ] = 1 ; m = ( m / i ) ; break ; } } } } nfactor . push_back ( n ) ; while ( fre [ n ] != 1 ) { if ( isprm ( n ) ) { nfactor . push_back ( 1 ) ; n = 1 ; } else { for ( int i = 2 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { nfactor . push_back ( n / i ) ; n = ( n / i ) ; break ; } } } } for ( int i = 0 ; i < mfactor . size ( ) ; i ++ ) { if ( mfactor [ i ] == n ) break ; cout << mfactor [ i ] << " β < - - > β " ; } for ( int i = nfactor . size ( ) - 1 ; i >= 0 ; i -- ) { if ( i == 0 ) cout << nfactor [ i ] ; else cout << nfactor [ i ] << " β < - - > β " ; } } int main ( ) { int m = 18 , n = 19 ; shortestpath ( m , n ) ; return 0 ; } |
Possible number of Trees having N vertex | C ++ program for the above approach ; Function to count the total number of trees possible ; Find the max element in the given array ; Level array store the number of nodes on level i initially all values are zero ; In this case tree can not be created ; To store the count of trees ; Iterate until maxElement ; Calculate level [ i ] ^ level [ i + 1 ] ; Update the count of tree ; Return the final count of trees ; Driver Code ; Given array arr [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int mod = 1e9 + 7 ; int NumberOfTrees ( int arr [ ] , int N ) { int maxElement = * max_element ( arr , arr + N ) ; int level [ maxElement + 1 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { level [ arr [ i ] ] ++ ; } if ( arr [ 0 ] != 0 level [ 0 ] != 1 ) { return 0 ; } int ans = 1 ; for ( int i = 0 ; i < maxElement ; i ++ ) { for ( int j = 0 ; j < level [ i + 1 ] ; j ++ ) { ans = ( ans * level [ i ] ) % mod ; } } return ans ; } int main ( ) { int N = 7 ; int arr [ ] = { 0 , 3 , 2 , 1 , 2 , 2 , 1 } ; cout << NumberOfTrees ( arr , N ) ; return 0 ; } |
Possible number of Trees having N vertex | C ++ program for the above approach ; Function that finds the value of x ^ y using Modular Exponentiation ; Base Case ; If y is odd , multiply x with result ; Return the value ; Function that counts the total number of trees possible ; Find the max element in array ; Level array store the number nodes on level i initially all values are 0 ; In this case tree can not be created ; Calculate level [ i ] ^ level [ i + 1 ] ; Return the final count ; Driver Code ; Given array arr [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int mod = 1e9 + 7 ; int power ( int x , int y ) { if ( y == 0 ) return 1 ; int p = power ( x , y / 2 ) % mod ; p = ( p * p ) % mod ; if ( y & 1 ) p = ( x * p ) % mod ; return p ; } int NumberOfTrees ( int arr [ ] , int N ) { int maxElement = * max_element ( arr , arr + N ) ; int level [ maxElement + 1 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { level [ arr [ i ] ] ++ ; } if ( arr [ 0 ] != 0 level [ 0 ] != 1 ) { return 0 ; } int ans = 1 ; for ( int i = 0 ; i < maxElement ; i ++ ) { ans = ( ans * power ( level [ i ] , level [ i + 1 ] ) ) % mod ; } return ans ; } int main ( ) { int N = 7 ; int arr [ ] = { 0 , 3 , 2 , 1 , 2 , 2 , 1 } ; cout << NumberOfTrees ( arr , N ) ; return 0 ; } |
A Binary String Game | C ++ program for the above approach ; Function to return the result of the game ; length of the string ; List to maintain the lengths of consecutive '1' s in the string ; Variable that keeps a track of the current length of the block of consecutive '1' s ; Adds non - zero lengths ; This takes care of the case when the last character is '1' ; Sorts the lengths in descending order ; Scores of the 2 players ; For player 1 ; For player 2 ; In case of a tie ; Print the result ; Driver Code ; Given string S ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; string gameMax ( string S ) { int N = S . length ( ) ; vector < int > list ; int one = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] == '1' ) { one ++ ; } else { if ( one != 0 ) { list . push_back ( one ) ; } one = 0 ; } } if ( one != 0 ) { list . push_back ( one ) ; } sort ( list . begin ( ) , list . end ( ) , greater < int > ( ) ) ; int score_1 = 0 , score_2 = 0 ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { if ( list [ i ] % 2 == 1 ) { score_1 += list [ i ] ; } else { score_2 += list [ i ] ; } } if ( score_1 == score_2 ) return " - 1" ; return ( score_1 > score_2 ) ? " Player β 1" : " Player β 2" ; } int main ( ) { string S = "11111101" ; cout << gameMax ( S ) ; } |
Count of carry operations on adding two Binary numbers | C ++ Program for the above approach ; Function to count the number of carry operations to add two binary numbers ; To Store the carry count ; Iterate till there is no carry ; Carry now contains common set bits of x and y ; Sum of bits of x and y where at least one of the bits is not set ; Carry is shifted by one so that adding it to x gives the required sum ; Adding number of 1 's of carry to final count ; Return the final count ; Driver Code ; Given two numbers ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int carryCount ( int num1 , int num2 ) { int count = 0 ; while ( num2 != 0 ) { int carry = num1 & num2 ; num1 = num1 ^ num2 ; num2 = carry << 1 ; count += __builtin_popcount ( num2 ) ; } return count ; } int main ( ) { int A = 15 , B = 10 ; cout << carryCount ( 15 , 10 ) ; return 0 ; } |
Count of all possible ways to reach a target by a Knight | C ++ Program to implement the above approach ; Function to return X ^ Y % Mod ; Base Case ; Function to return the inverse of factorial of N ; Base case ; Function to return factorial of n % Mod ; Base case ; Function to return the value of n ! / ( ( n - k ) ! * k ! ) ; Function to return the count of ways to reach ( n , m ) from ( 0 , 0 ) ; If ( N + M ) % 3 != 0 ; No possible way exists ; Calculate X and Y from the equations X + 2 Y = N and 2 X + Y == M ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int Mod = 1e9 + 7 ; int power ( int X , int Y , int Mod ) { if ( Y == 0 ) return 1 ; int p = power ( X , Y / 2 , Mod ) % Mod ; p = ( p * p ) % Mod ; if ( Y & 1 ) { p = ( X * p ) % Mod ; } return p ; } int Inversefactorial ( int N ) { if ( N <= 0 ) return 1 ; int fact = 1 ; for ( int i = 1 ; i <= N ; i ++ ) { fact = ( fact * i ) % Mod ; } return power ( fact , Mod - 2 , Mod ) ; } int factorial ( int N ) { if ( N <= 0 ) return 1 ; int fact = 1 ; for ( int i = 1 ; i <= N ; i ++ ) { fact = ( fact * i ) % Mod ; } return fact ; } int nck ( int N , int K ) { int factN = factorial ( N ) ; int inv = Inversefactorial ( K ) ; int invFact = Inversefactorial ( N - K ) ; return ( ( ( factN * inv ) % Mod ) * invFact ) % Mod ; } int TotalWaYs ( int N , int M ) { if ( ( N + M ) % 3 != 0 ) return 0 ; int X = N - ( N + M ) / 3 ; int Y = M - ( N + M ) / 3 ; if ( X < 0 Y < 0 ) return 0 ; return nck ( X + Y , Y ) ; } int main ( ) { int N = 3 , M = 3 ; cout << TotalWaYs ( N , M ) ; return 0 ; } |
Lead a life problem | C ++ program for the above approach ; Function that calculates the profit with the earning and cost of expenses ; To store the total Profit ; Loop for n number of days ; If last day , no need to buy food ; Else buy food to gain energy for next day ; Update earning per day ; Update profit with daily spent ; Print the profit ; Driver Code ; Given days ; Given earnings ; Given cost ; Given energy e ; Function Call | #include <iostream> NEW_LINE using namespace std ; int calculateProfit ( int n , int * earnings , int * cost , int e ) { int profit = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int earning_per_day = 0 ; int daily_spent_food = 0 ; if ( i == ( n - 1 ) ) { earning_per_day = earnings [ i ] * e ; profit = profit + earning_per_day ; break ; } if ( cost [ i ] < earnings [ i ] ) { earning_per_day = earnings [ i ] * e ; daily_spent_food = cost [ i ] * e ; profit = profit + earning_per_day - daily_spent_food ; } } cout << profit << endl ; } int main ( ) { int n = 4 ; int earnings [ ] = { 1 , 8 , 6 , 7 } ; int cost [ ] = { 1 , 3 , 4 , 1 } ; int e = 5 ; calculateProfit ( n , earnings , cost , e ) ; } |
Check if N numbers with Even Sum can be selected from a given Array | C ++ efficient program to check if N numbers with Odd sum can be selected from the given array ; Function to check if an odd sum can be made using N integers from the array ; Initialize odd and even counts ; Iterate over the array to count the no . of even and odd integers ; If element is odd ; If element is even ; Check if even_freq is more than N ; If odd_freq is odd ; Consider even count of odd ; Calculate even required ; If even count is less than required count ; Calculate even required ; If even count is less than required count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkEvenSum ( int arr [ ] , int N , int size ) { int even_freq = 0 , odd_freq = 0 ; for ( int i = 0 ; i < size ; i ++ ) { if ( arr [ i ] & 1 ) odd_freq ++ ; else even_freq ++ ; } if ( even_freq >= N ) return true ; else { if ( odd_freq & 1 ) { int taken = odd_freq - 1 ; int req = N - taken ; if ( even_freq < req ) { return false ; } else return true ; } else { int taken = odd_freq ; int req = N - taken ; if ( even_freq < req ) { return false ; } else return true ; } } return false ; } int main ( ) { int arr [ ] = { 9 , 2 , 3 , 4 , 18 , 7 , 7 , 6 } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int N = 5 ; if ( checkEvenSum ( arr , N , size ) ) cout << " Yes " << endl ; else cout << " No " << endl ; } |
Minimum count of digits required to obtain given Sum | C ++ program to implement the above approach ; Function to return the minimum count of digits ; IF N is divisible by 9 ; Count of 9 's is the answer ; If remainder is non - zero ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void mindigits ( int n ) { if ( n % 9 == 0 ) { cout << n / 9 << endl ; } else { cout << ( n / 9 ) + 1 << endl ; } } int main ( ) { int n1 = 24 ; int n2 = 14 ; mindigits ( n1 ) ; mindigits ( n2 ) ; } |
Count of all possible numbers not exceeding M having suffix N | C ++ Program to implement the above approach ; Function to count the no . of digits of N ; Function to count all possible numbers having Suffix as N ; Difference of the A . P ; Count of the number of terms ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int digitsOf ( int num ) { return to_string ( num ) . size ( ) ; } int count ( int a , int tn ) { int diff = pow ( 10 , digitsOf ( a ) ) ; return ( ( tn - a ) / diff ) + 1 ; } int main ( ) { int n , m ; n = 25 , m = 4500 ; cout << count ( n , m ) ; return 0 ; } |
Minimum increment / decrement operations required on Array to satisfy given conditions | C ++ program for the above approach ; Function to find minimum number of operations to get desired array ; For odd ' i ' , sum of elements till ' i ' is positive ; If i is even and sum is positive , make it negative by subtracting 1 + | s | from a [ i ] ; If i is odd and sum is negative , make it positive by adding 1 + | s | into a [ i ] ; For odd ' i ' , sum of elements till ' i ' is negative ; Check if ' i ' is odd and sum is positive , make it negative by subtracting 1 + | s | from a [ i ] ; Check if ' i ' is even and sum is negative , make it positive by adding 1 + | s | into a [ i ] ; Return the minimum of the two ; Driver Code ; Given array arr [ ] ; Function Call | #include <iostream> NEW_LINE using namespace std ; int minOperations ( int a [ ] , int N ) { int num_of_ops1 , num_of_ops2 , sum ; num_of_ops1 = num_of_ops2 = sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += a [ i ] ; if ( i % 2 == 0 && sum >= 0 ) { num_of_ops1 += ( 1 + abs ( sum ) ) ; sum = -1 ; } else if ( i % 2 == 1 && sum <= 0 ) { num_of_ops1 += ( 1 + abs ( sum ) ) ; sum = 1 ; } } sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += a [ i ] ; if ( i % 2 == 1 && sum >= 0 ) { num_of_ops2 += ( 1 + abs ( sum ) ) ; sum = -1 ; } else if ( i % 2 == 0 && sum <= 0 ) { num_of_ops2 += ( 1 + abs ( sum ) ) ; sum = 1 ; } } return min ( num_of_ops1 , num_of_ops2 ) ; } int main ( ) { int arr [ ] = { 3 , -4 , 5 , 0 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minOperations ( arr , N ) ; return 0 ; } |
Check if all elements of a Circular Array can be made equal by increments of adjacent pairs | C ++ Program to implement the above approach ; Function to check if all array elements can be made equal ; Stores the sum of even and odd array elements ; If index is odd ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkEquall ( int arr [ ] , int N ) { int sumEven = 0 , sumOdd = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( i & 1 ) sumOdd += arr [ i ] ; else sumEven += arr [ i ] ; } if ( sumEven == sumOdd ) return true ; else return false ; } int main ( ) { int arr [ ] = { 2 , 7 , 3 , 5 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( checkEquall ( arr , N ) ) cout << " YES " << endl ; else cout << " NO " << endl ; return 0 ; } |
Check if a number can be expressed as sum of two Perfect powers | C ++ program for the above approach ; Function that returns true if n can be written as a ^ m + b ^ n ; Taking isSum boolean array for check the sum exist or not ; To store perfect squares ; Initially all sums as false ; If sum exist then push that sum into perfect square vector ; Mark all perfect powers as false ; Traverse each perfectPowers ; Calculating Sum with perfect powers array ; Driver Code ; Given Number n ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isSumOfPower ( int n ) { bool isSum [ n + 1 ] ; vector < int > perfectPowers ; perfectPowers . push_back ( 1 ) ; for ( int i = 0 ; i < ( n + 1 ) ; i ++ ) { isSum [ i ] = false ; } for ( long long int i = 2 ; i < ( n + 1 ) ; i ++ ) { if ( isSum [ i ] == true ) { perfectPowers . push_back ( i ) ; continue ; } for ( long long int j = i * i ; j > 0 && j < ( n + 1 ) ; j *= i ) { isSum [ j ] = true ; } } for ( int i = 0 ; i < perfectPowers . size ( ) ; i ++ ) { isSum [ perfectPowers [ i ] ] = false ; } for ( int i = 0 ; i < perfectPowers . size ( ) ; i ++ ) { for ( int j = i ; j < perfectPowers . size ( ) ; j ++ ) { int sum = perfectPowers [ i ] + perfectPowers [ j ] ; if ( sum < ( n + 1 ) ) isSum [ sum ] = true ; } } return isSum [ n ] ; } int main ( ) { int n = 9 ; if ( isSumOfPower ( n ) ) { cout << " true STRNEWLINE " ; } else { cout << " false STRNEWLINE " ; } } |
Minimum increments by index value required to obtain at least two equal Array elements | C ++ Program to implement the above approach ; Function to update every element adding to it its index value ; Function to check if at least two elements are equal or not ; Count the frequency of arr [ i ] ; Function to calculate the number of increment operations required ; Stores the minimum number of steps ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void update ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { arr [ i ] += ( i + 1 ) ; } } bool check ( int arr [ ] , int N ) { bool f = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < N ; j ++ ) { if ( arr [ i ] == arr [ j ] ) { count ++ ; } } if ( count >= 2 ) { f = 1 ; break ; } } if ( f == 1 ) return true ; else return false ; } void incrementCount ( int arr [ ] , int N ) { int min = 0 ; while ( check ( arr , N ) != true ) { update ( arr , N ) ; min ++ ; } cout << min ; } int main ( ) { int N = 3 ; int arr [ N ] = { 12 , 8 , 4 } ; incrementCount ( arr , N ) ; return 0 ; } |
Rearrange array such that all even | C ++ Program to implement the above approach ; Function to check if it the array can be rearranged such such that every even indices contains an even element ; Stores the count of even elements ; Traverse array to count even numbers ; If even_no_count exceeds count of even indices ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void checkPossible ( int a [ ] , int n ) { int even_no_count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] % 2 == 0 ) even_no_count ++ ; } if ( n / 2 > even_no_count ) { cout << " No " << endl ; return ; } cout << " Yes " << endl ; int j = 0 ; for ( int i = 1 ; i < n ; i += 2 ) { if ( a [ i ] % 2 == 0 ) continue ; else { while ( j < n && a [ j ] % 2 != 0 ) j += 2 ; a [ i ] += a [ j ] ; a [ j ] = a [ i ] - a [ j ] ; a [ i ] -= a [ j ] ; } } for ( int i = 0 ; i < n ; i ++ ) { cout << a [ i ] << " β " ; } } int main ( ) { int arr [ ] = { 2 , 3 , 4 , 5 , 6 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; checkPossible ( arr , n ) ; return 0 ; } |
Largest number M having bit count of N such that difference between their OR and XOR value is maximized | C ++ program for the above approach ; Function to find the largest number M having the same length in binary form as N such that the difference between N | M and N ^ M is maximum ; Find the most significant bit of N ; Initialize M ; Set all the bits of M ; Return the answer ; Driver Code ; Given Number N ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxORminusXOR ( int N ) { int MSB = log2 ( N ) ; int M = 0 ; for ( int i = 0 ; i <= MSB ; i ++ ) M += ( 1 << i ) ; return M ; } int main ( ) { int N = 10 ; cout << maxORminusXOR ( N ) ; return 0 ; } |
Maximum count of Equilateral Triangles that can be formed within given Equilateral Triangle | C ++ program for the above approach ; Function to find the number of equilateral triangle formed within another triangle ; Check for the valid condition ; Number of triangles having upward peak ; Number of inverted triangles ; Total no . of K sized triangle ; Driver Code ; Given N and K ; Function Call | #include <iostream> NEW_LINE using namespace std ; int No_of_Triangle ( int N , int K ) { if ( N < K ) return -1 ; else { int Tri_up = 0 ; Tri_up = ( ( N - K + 1 ) * ( N - K + 2 ) ) / 2 ; int Tri_down = 0 ; Tri_down = ( ( N - 2 * K + 1 ) * ( N - 2 * K + 2 ) ) / 2 ; return Tri_up + Tri_down ; } } int main ( ) { int N = 4 , K = 2 ; cout << No_of_Triangle ( N , K ) ; return 0 ; } |
Check if Array forms an increasing | C ++ program for the above approach ; Function to check if the given array forms an increasing decreasing sequence or vice versa ; Base Case ; First subarray is stricly increasing ; Check for strictly increasing condition & find the break point ; Check for strictly decreasing condition & find the break point ; If i is equal to length of array ; First subarray is strictly Decreasing ; Check for strictly increasing condition & find the break point ; Check for strictly increasing condition & find the break point ; If i is equal to length of array - 1 ; Condition if ar [ 0 ] == ar [ 1 ] ; Driver Code ; Given array arr [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool canMake ( int n , int ar [ ] ) { if ( n == 1 ) return true ; else { if ( ar [ 0 ] < ar [ 1 ] ) { int i = 1 ; while ( i < n && ar [ i - 1 ] < ar [ i ] ) { i ++ ; } while ( i + 1 < n && ar [ i ] > ar [ i + 1 ] ) { i ++ ; } if ( i >= n - 1 ) return true ; else return false ; } else if ( ar [ 0 ] > ar [ 1 ] ) { int i = 1 ; while ( i < n && ar [ i - 1 ] > ar [ i ] ) { i ++ ; } while ( i + 1 < n && ar [ i ] < ar [ i + 1 ] ) { i ++ ; } if ( i >= n - 1 ) return true ; else return false ; } else { for ( int i = 2 ; i < n ; i ++ ) { if ( ar [ i - 1 ] <= ar [ i ] ) return false ; } return true ; } } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = sizeof arr / sizeof arr [ 0 ] ; if ( canMake ( n , arr ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; } |
Minimum Count of Bit flips required to make a Binary String Palindromic | C ++ Program to implement the above approach ; Function to calculate the length of the binary string ; Length ; Right shift of n ; Increment the length ; Return the length ; Function to check if the bit present at i - th position is a set bit or not ; Returns true if the bit is set ; Function to count the minimum number of bit flips required ; Length of the binary form ; Number of flips ; Pointer to the LSB ; Pointer to the MSB ; Check if the bits are equal ; Decrementing the left pointer ; Incrementing the right pointer ; Returns the number of bits to flip . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int check_length ( int n ) { int ans = 0 ; while ( n ) { n = n >> 1 ; ans ++ ; } return ans ; } int check_ith_bit ( int n , int i ) { return ( n & ( 1 << ( i - 1 ) ) ) ? true : false ; } int no_of_flips ( int n ) { int len = check_length ( n ) ; int ans = 0 ; int right = 1 ; int left = len ; while ( right < left ) { if ( check_ith_bit ( n , right ) != check_ith_bit ( n , left ) ) ans ++ ; left -- ; right ++ ; } return ans ; } int main ( ) { int n = 12 ; cout << no_of_flips ( n ) ; return 0 ; } |
Split N into two integers whose addition to A and B makes them equal | C ++ Program to implement the above approach ; Function to calculate the splitted numbers ; Calculate X ; If X is odd ; No pair is possible ; Otherwise ; Calculate X ; Calculate Y ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findPair ( int A , int B , int N ) { int X , Y ; X = N - B + A ; if ( X % 2 != 0 ) { cout << " - 1" ; } else { X = X / 2 ; Y = N - X ; cout << X << " β " << Y ; } } int main ( ) { int A = 1 ; int B = 3 ; int N = 4 ; findPair ( A , B , N ) ; return 0 ; } |
Find the amplitude and number of waves for the given array | C ++ program for the above approach ; Function to find the amplitude and number of waves for the given array ; Check for both sides adjacent elements that both must be less or both must be greater than current element ; Update amplitude with max value ; Print the Amplitude ; Driver Code ; Given array a [ ] ; Calculate number of waves ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int a [ ] , int n ) { int ma = a [ 1 ] - a [ 0 ] ; for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( ( a [ i ] > a [ i - 1 ] && a [ i + 1 ] < a [ i ] ) || ( a [ i ] < a [ i - 1 ] && a [ i + 1 ] > a [ i ] ) ) ma = max ( ma , abs ( a [ i ] - a [ i + 1 ] ) ) ; else return false ; } cout << " Amplitude β = β " << ma ; cout << endl ; return true ; } int main ( ) { int a [ ] = { 1 , 2 , 1 , 5 , 0 , 7 , -6 } ; int n = sizeof a / sizeof a [ 0 ] ; int wave = ( n - 1 ) / 2 ; if ( check ( a , n ) ) cout << " Waves β = β " << wave ; else cout << " - 1" ; return 0 ; } |
Find relative rank of each element in array | C ++ program for the above approach ; Function to find relative rank for each element in the array A [ ] ; Create Rank Array ; Stack to store numbers in non - decreasing order from right ; Push last element in stack ; Iterate from second last element to first element ; If current element is less than the top of stack and push A [ i ] in stack ; Rank is stack size - 1 for current element ; Pop elements from stack till current element is greater than the top ; Push current element in Stack ; Rank is stack size - 1 ; Print rank of all elements ; Driver Code ; Given array A [ ] ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findRank ( int A [ ] , int N ) { int rank [ N ] = { } ; stack < int > s ; s . push ( A [ N - 1 ] ) ; for ( int i = N - 2 ; i >= 0 ; i -- ) { if ( A [ i ] < s . top ( ) ) { s . push ( A [ i ] ) ; rank [ i ] = s . size ( ) - 1 ; } else { while ( ! s . empty ( ) && A [ i ] >= s . top ( ) ) { s . pop ( ) ; } s . push ( A [ i ] ) ; rank [ i ] = s . size ( ) - 1 ; } } for ( int i = 0 ; i < N ; i ++ ) { cout << rank [ i ] << " β " ; } } int main ( ) { int A [ ] = { 1 , 2 , 3 , 5 , 4 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; findRank ( A , N ) ; return 0 ; } |
Largest string obtained in Dictionary order after deleting K characters | C ++ program for the above approach ; Function to find the largest string after deleting k characters ; Deque dq used to find the largest string in dictionary after deleting k characters ; Iterate till the length of the string ; Condition for popping characters from deque ; To store the resultant string ; To form resultant string ; Return the resultant string ; Driver code ; Given String ; Function call ; Print the answer | #include <bits/stdc++.h> NEW_LINE using namespace std ; string largestString ( int n , int k , string s ) { deque < char > deq ; for ( int i = 0 ; i < n ; ++ i ) { while ( deq . size ( ) > 0 && deq . back ( ) < s [ i ] && k > 0 ) { deq . pop_front ( ) ; k -- ; } deq . push_back ( s [ i ] ) ; } string st = " " ; for ( char c : deq ) st = st + c ; return st ; } int main ( ) { int n = 4 ; int k = 2 ; string sc = " ritz " ; string result = largestString ( n , k , sc ) ; cout << result << endl ; return 0 ; } |
Count total set bits in all numbers from range L to R | C ++ program for the above approach ; Function that counts the set bits from 0 to N ; To store sum of set bits from 0 - N ; Until n >= to 2 ^ i ; This k will get flipped after 2 ^ i iterations ; Change is iterator from 2 ^ i to 1 ; This will loop from 0 to n for every bit position ; When change = 1 flip the bit ; Again set change to 2 ^ i ; Increment the position ; Function that counts the set bit in the range ( L , R ) ; Return the count ; Driver Code ; Given L and R ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSetBit ( int n ) { int i = 0 ; int ans = 0 ; while ( ( 1 << i ) <= n ) { bool k = 0 ; int change = 1 << i ; for ( int j = 0 ; j <= n ; j ++ ) { ans += k ; if ( change == 1 ) { k = ! k ; change = 1 << i ; } else { change -- ; } } i ++ ; } return ans ; } int countSetBits ( int L , int R ) { return abs ( countSetBit ( R ) - countSetBit ( L - 1 ) ) ; } int main ( ) { int L = 3 , R = 5 ; cout << " Total β set β bit β count β is β " << countSetBits ( L , R ) << endl ; return 0 ; } |
Count total set bits in all numbers from range L to R | C ++ program for the above approach ; Function to count set bit in range ; Count variable ; Find the set bit in Nth number ; If last bit is set ; Left sift by one bit ; Return count ; Driver Code ; Given Range L and R ; Function Call | #include <iostream> NEW_LINE using namespace std ; int countSetBits ( int L , int R ) { int count = 0 ; for ( int i = L ; i <= R ; i ++ ) { int n = i ; while ( n > 0 ) { count += ( n & 1 ) ; n = n >> 1 ; } } return count ; } int main ( ) { int L = 3 , R = 5 ; cout << " Total β set β Bit β count β is β " << countSetBits ( L , R ) ; return 0 ; } |
Count total set bits in all numbers from range L to R | C ++ program for the above approach ; Function to count set bit in [ L , R ] ; Variable for count set bit in range ; Count set bit for all number in range ; Use inbuilt function ; Driver Code ; Given range L and R ; Function Call | #include <iostream> NEW_LINE using namespace std ; int countSetBits ( int L , int R ) { int count = 0 ; for ( int i = L ; i <= R ; i ++ ) { count += __builtin_popcount ( i ) ; } return count ; } int main ( ) { int L = 3 , R = 5 ; cout << " Total β set β bit β count β is β " << countSetBits ( L , R ) ; return 0 ; } |
Make max elements in B [ ] equal to that of A [ ] by adding / subtracting integers in range [ 0 , K ] | C ++ program for the above approach ; Function that count the number of integers from array B [ ] such that subtracting element in the range [ 0 , K ] given any element in A [ ] ; To store the count of element ; Traverse the array B [ ] ; Traverse the array A [ ] ; Find the difference ; If difference is atmost K then increment the cnt ; Print the count ; Driver Code ; Given array A [ ] and B [ ] ; Given K ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void countElement ( int A [ ] , int N , int B [ ] , int M , int K ) { int cnt = 0 ; for ( int i = 0 ; i < M ; i ++ ) { int currentElement = B [ i ] ; for ( int j = 0 ; j < N ; j ++ ) { int diff = abs ( currentElement - A [ j ] ) ; if ( diff <= K ) { cnt ++ ; break ; } } } cout << cnt ; } int main ( ) { int A [ ] = { 100 , 65 , 35 , 85 , 55 } ; int B [ ] = { 30 , 60 , 75 , 95 } ; int K = 5 ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int M = sizeof ( B ) / sizeof ( B [ 0 ] ) ; countElement ( A , N , B , M , K ) ; return 0 ; } |
Generate a String of having N * N distinct non | C ++ Program to implement the above approach ; Function to construct a string having N * N non - palindromic substrings ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void createString ( int N ) { for ( int i = 0 ; i < N ; i ++ ) { cout << ' a ' ; } for ( int i = 0 ; i < N ; i ++ ) { cout << ' b ' ; } } int main ( ) { int N = 4 ; createString ( N ) ; return 0 ; } |
Maximum Subset Sum possible by negating the entire sum after selecting the first Array element | C ++ Program to implement the above approach ; Function returns maximum subset sum from the given array = ; Case 2 : Negate values from A [ 1 ] to A [ N - 1 ] ; Include only positives for max subset sum ; Return max sum obtained ; Function to return maximum of the maximum subset sum calculated for the two cases ; Case 1 ; Case 2 ; Modifying the sum ; Including first element ; Negating again ; Return the required answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSubset ( vector < int > & A , bool flag ) { int n = A . size ( ) ; int sum = 0 ; if ( flag ) { for ( int i = 1 ; i < n ; i ++ ) A [ i ] = - A [ i ] ; } for ( int i = 1 ; i < n ; i ++ ) { if ( A [ i ] > 0 ) { sum += A [ i ] ; } } return sum ; } int findBest ( vector < int > A ) { int x = maxSubset ( A , 0 ) ; int y = maxSubset ( A , 1 ) ; y = - y ; y += A [ 0 ] ; y = - y ; return max ( x , y ) ; } int main ( ) { vector < int > A = { 1 , 10 , 4 , -6 , 3 } ; cout << findBest ( A ) << endl ; return 0 ; } |
Construct an Array of Strings having Longest Common Prefix specified by the given Array | C ++ Program to implement the above approach ; Function to find the array of strings ; Marks the ( N + 1 ) th string ; To generate remaining N strings ; Find i - th string using ( i + 1 ) - th string ; Check if current character is b ; Otherwise ; Insert the string ; Return the answer ; Driver Code ; Print the strings | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < string > solve ( int n , int arr [ ] ) { string s = string ( n , ' a ' ) ; vector < string > ans ; ans . push_back ( s ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { char ch = s [ arr [ i ] ] ; if ( ch == ' b ' ) ch = ' a ' ; else ch = ' b ' ; s [ arr [ i ] ] = ch ; ans . push_back ( s ) ; } return ans ; } int main ( ) { int arr [ ] = { 2 , 0 , 3 } ; int n = sizeof arr / sizeof arr [ 0 ] ; vector < string > ans = solve ( n , arr ) ; for ( int i = ans . size ( ) - 1 ; i >= 0 ; i -- ) { cout << ans [ i ] << endl ; } return 0 ; } |
Minimize swaps required to maximize the count of elements replacing a greater element in an Array | C ++ Program to implement the above approach ; Function to find the minimum number of swaps required ; Sort the array in ascending order ; Iterate until a greater element is found ; Keep incrementing ind ; If a greater element is found ; Increase count of swap ; Increment ind ; If end of array is reached ; Return the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSwaps ( int A [ ] , int n ) { sort ( A , A + n ) ; int ind = 1 , res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { while ( ind < n and A [ ind ] == A [ i ] ) ind ++ ; if ( ind < n and A [ ind ] > A [ i ] ) { res ++ ; ind ++ ; } if ( ind >= n ) break ; } return res ; } int main ( ) { int A [ ] = { 4 , 3 , 3 , 2 , 5 } ; cout << countSwaps ( A , 5 ) ; return 0 ; } |
Minimize swaps required to maximize the count of elements replacing a greater element in an Array | C ++ Program to implement the above approach ; Function to find the minimum number of swaps required ; Stores the frequency of the array elements ; Stores maximum frequency ; Find the max frequency ; Update frequency ; Update maximum frequency ; Driver Code ; function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSwaps ( int A [ ] , int n ) { map < int , int > mp ; int max_frequency = 0 ; for ( int i = 0 ; i < n ; i ++ ) { mp [ A [ i ] ] ++ ; max_frequency = max ( max_frequency , mp [ A [ i ] ] ) ; } return n - max_frequency ; } int main ( ) { int A [ ] = { 6 , 5 , 4 , 3 , 2 , 1 } ; cout << countSwaps ( A , 6 ) ; return 0 ; } |
Minimum number of steps required to obtain the given Array by the given operations | C ++ Program to implement the above approach ; Function to calculate the minimum steps to obtain the desired array ; Initialize variable ; Iterate over the array arr [ ] ; Check if i > 0 ; Update the answer ; Return the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int min_operation ( int a [ ] , int n ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i > 0 ) ans += abs ( a [ i ] - a [ i - 1 ] ) ; else ans += abs ( a [ i ] ) ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << min_operation ( arr , n ) ; return 0 ; } |
Construct a Matrix with no element exceeding X and sum of two adjacent elements not exceeding Y | C ++ implementation of the above approach ; Function to print the required matrix ; For 1 * 1 matrix ; Greater number ; Smaller number ; Sets / Resets for alternate filling of the matrix ; Print the matrix ; If end of row is reached ; Driver Code | #include <iostream> NEW_LINE using namespace std ; void FindMatrix ( int n , int m , int x , int y ) { int a , b , i , j ; if ( n * m == 1 ) { if ( x > y ) { cout << y << " STRNEWLINE " ; } else { cout << x << " STRNEWLINE " ; } return ; } a = min ( x , y ) ; b = min ( 2 * x , y ) - a ; bool flag = true ; for ( i = 0 ; i < n ; i ++ ) { for ( j = 0 ; j < m ; j ++ ) { if ( flag ) cout << a << ' β ' ; else cout << b << ' β ' ; flag = ! flag ; } if ( ( ( n % 2 != 0 && m % 2 == 0 ) || ( n % 2 == 0 && m % 2 == 0 ) ) ) flag = ! flag ; cout << " STRNEWLINE " ; } } int main ( ) { int N , M , X , Y ; N = 3 ; M = 3 ; X = 5 ; Y = 3 ; FindMatrix ( N , M , X , Y ) ; } |
Travelling Salesman Problem | Greedy Approach | C ++ program for the above approach ; Function to find the minimum cost path for all the paths ; Starting from the 0 th indexed city i . e . , the first city ; Traverse the adjacency matrix tsp [ ] [ ] ; Corner of the Matrix ; If this path is unvisited then and if the cost is less then update the cost ; Check all paths from the ith indexed city ; Update the ending city in array from city which was last visited ; Started from the node where we finished as well . ; Driver Code ; Input Matrix ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findMinRoute ( vector < vector < int > > tsp ) { int sum = 0 ; int counter = 0 ; int j = 0 , i = 0 ; int min = INT_MAX ; map < int , int > visitedRouteList ; visitedRouteList [ 0 ] = 1 ; int route [ tsp . size ( ) ] ; while ( i < tsp . size ( ) && j < tsp [ i ] . size ( ) ) { if ( counter >= tsp [ i ] . size ( ) - 1 ) { break ; } if ( j != i && ( visitedRouteList [ j ] == 0 ) ) { if ( tsp [ i ] [ j ] < min ) { min = tsp [ i ] [ j ] ; route [ counter ] = j + 1 ; } } j ++ ; if ( j == tsp [ i ] . size ( ) ) { sum += min ; min = INT_MAX ; visitedRouteList [ route [ counter ] - 1 ] = 1 ; j = 0 ; i = route [ counter ] - 1 ; counter ++ ; } } i = route [ counter - 1 ] - 1 ; for ( j = 0 ; j < tsp . size ( ) ; j ++ ) { if ( ( i != j ) && tsp [ i ] [ j ] < min ) { min = tsp [ i ] [ j ] ; route [ counter ] = j + 1 ; } } sum += min ; cout << ( " Minimum β Cost β is β : β " ) ; cout << ( sum ) ; } int main ( ) { vector < vector < int > > tsp = { { -1 , 10 , 15 , 20 } , { 10 , -1 , 35 , 25 } , { 15 , 35 , -1 , 30 } , { 20 , 25 , 30 , -1 } } ; findMinRoute ( tsp ) ; } |
Count distinct elements after adding each element of First Array with Second Array | C ++ program for the above approach ; Function to find Occurrence of each element from 1 to 2 * MAX ; Initialise MAX ; Count vector to store count of each element from 1 to 2 * MAX ; Size of Arr1 and Arr2 ; Find the elements of arr3 [ ] and increase count of element by 1 ; Print the result ; Driver Code ; Given arrays arr1 [ ] and arr2 [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findCount ( vector < int > & Arr1 , vector < int > & Arr2 ) { int MAX = max ( * max_element ( Arr1 . begin ( ) , Arr1 . end ( ) ) , * max_element ( Arr2 . begin ( ) , Arr2 . end ( ) ) ) ; vector < int > Count ( 2 * MAX + 1 , 0 ) ; int n = Arr1 . size ( ) , m = Arr2 . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { int element = Arr1 [ i ] + Arr2 [ j ] ; Count [ element ] ++ ; } } for ( int i = 1 ; i <= 2 * MAX ; i ++ ) { if ( Count [ i ] > 0 ) { cout << i << " - > " << Count [ i ] << endl ; } } } int main ( ) { vector < int > arr1 = { 1 , 2 } ; vector < int > arr2 = { 1 , 2 , 1 } ; findCount ( arr1 , arr2 ) ; } |
Find two numbers with difference and division both same as N | C ++ program for the above approach ; Function to find two numbers with difference and division both as N ; Condition if the answer is not possible ; Calculate a and b ; Print the values ; Driver Code ; Given N ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findAandB ( double N ) { if ( N == 1 ) { cout << " No " ; return ; } double a = N * N / ( N - 1 ) ; double b = a / N ; cout << " a β = β " << a << endl ; cout << " b β = β " << b << endl ; } int main ( ) { double N = 6 ; findAandB ( N ) ; return 0 ; } |
Maximize number of elements from Array with sum at most K | C ++ program for the above approach ; Function to select a maximum number of elements in array whose sum is at most K ; Sort the array ; Calculate the sum and count while iterating the sorted array ; Iterate for all the elements in the array ; Add the current element to sum ; Increment the count ; Return the answer ; Driver Code ; Given array ; Given sum k ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSelections ( int A [ ] , int n , int k ) { sort ( A , A + n ) ; int sum = 0 ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum = sum + A [ i ] ; if ( sum > k ) { break ; } count ++ ; } return count ; } int main ( ) { int A [ ] = { 3 , 7 , 2 , 9 , 4 } ; int k = 15 ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << maxSelections ( A , n , k ) ; return 0 ; } |
Pair of integers with difference K having an element as the K | C ++ Program to implement the above problem ; Function to find the required pair ; No pair possible ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void computePair ( double K ) { if ( K == 1 ) { cout << " No " ; return ; } else { cout << K * K / ( K - 1 ) << " β " ; cout << K / ( K - 1 ) << endl ; } } int main ( ) { double K = 6 ; computePair ( K ) ; return 0 ; } |
Generate a Binary String without any consecutive 0 ' s β and β at β most β K β consecutive β 1' s | C ++ Program to implement the above approach ; Function to construct the binary string ; Conditions when string construction is not possible ; Stores maximum 1 's that can be placed in between ; Place 0 's ; Place 1 's in between ; Count remaining M 's ; Place 1 's at the end ; Place 1 's at the beginning ; Return the final string ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string ConstructBinaryString ( int N , int M , int K ) { if ( M < ( N - 1 ) || M > K * ( N + 1 ) ) return " - 1" ; string ans = " " ; int l = min ( K , M / ( N - 1 ) ) ; int temp = N ; while ( temp -- ) { ans += '0' ; if ( temp == 0 ) break ; for ( int i = 0 ; i < l ; i ++ ) { ans += '1' ; } } M -= ( N - 1 ) * l ; if ( M == 0 ) return ans ; l = min ( M , K ) ; for ( int i = 0 ; i < l ; i ++ ) ans += '1' ; M -= l ; while ( M > 0 ) { ans = '1' + ans ; M -- ; } return ans ; } int main ( ) { int N = 5 , M = 9 , K = 2 ; cout << ConstructBinaryString ( N , M , K ) ; } |
Find smallest number formed by inverting digits of given number N | C ++ program for the above approach ; Function to invert the digits of integer N to form minimum possible number ; Initialize the array ; Iterate till the number N exists ; Last digit of the number N ; Checking if the digit is smaller than 9 - digit ; Store the smaller digit in the array ; Reduce the number each time ; Check if the digit starts with 0 or not ; Print the answer ; Driver Code ; Given Number ; Function Call | #include <iostream> NEW_LINE using namespace std ; void number ( int num ) { int a [ 20 ] , r , i = 0 , j ; while ( num > 0 ) { r = num % 10 ; if ( 9 - r > r ) a [ i ] = r ; else a [ i ] = 9 - r ; i ++ ; num = num / 10 ; } if ( a [ i - 1 ] == 0 ) { cout << 9 ; i -- ; } for ( j = i - 1 ; j >= 0 ; j -- ) cout << a [ j ] ; } int main ( ) { long long int num = 4545 ; number ( num ) ; return 0 ; } |
Check if the concatenation of first N natural numbers is divisible by 3 | C ++ program for the above approach ; Function that returns True if concatenation of first N natural numbers is divisible by 3 ; Check using the formula ; Driver Code ; Given Number ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isDivisible ( int N ) { return ( N - 1 ) % 3 != 0 ; } int main ( ) { int N = 6 ; if ( isDivisible ( N ) ) cout << ( " Yes " ) ; else cout << ( " No " ) ; return 0 ; } |
Count of N digit Numbers whose sum of every K consecutive digits is equal | C ++ program for the above approach ; Function to count the number of N - digit numbers such that sum of every k consecutive digits are equal ; Range of numbers ; Extract digits of the number ; Store the sum of first K digits ; Check for every k - consecutive digits ; If sum is not equal then break the loop ; Increment the count if it satisfy the given condition ; Driver Code ; Given N and K ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countDigitSum ( int N , int K ) { int l = ( int ) pow ( 10 , N - 1 ) , r = ( int ) pow ( 10 , N ) - 1 ; int count = 0 ; for ( int i = l ; i <= r ; i ++ ) { int num = i ; int digits [ N ] ; for ( int j = N - 1 ; j >= 0 ; j -- ) { digits [ j ] = num % 10 ; num /= 10 ; } int sum = 0 , flag = 0 ; for ( int j = 0 ; j < K ; j ++ ) sum += digits [ j ] ; for ( int j = 1 ; j < N - K + 1 ; j ++ ) { int curr_sum = 0 ; for ( int m = j ; m < j + K ; m ++ ) curr_sum += digits [ m ] ; if ( sum != curr_sum ) { flag = 1 ; break ; } } if ( flag == 0 ) { count ++ ; } } return count ; } int main ( ) { int N = 2 , K = 1 ; cout << countDigitSum ( N , K ) ; return 0 ; } |
Perfect Square factors of a Number | C ++ Program to implement the above approach ; Function that returns the count of factors that are perfect squares ; Stores the count of number of times a prime number divides N . ; Stores the number of factors that are perfect square ; Count number of 2 's that divides N ; Calculate ans according to above formula ; Check for all the possible numbers that can divide it ; Check the number of times prime number i divides it ; Calculate ans according to above formula ; Return final count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int noOfFactors ( int N ) { if ( N == 1 ) return 1 ; int count = 0 ; int ans = 1 ; while ( N % 2 == 0 ) { count ++ ; N = N / 2 ; } ans *= ( count / 2 + 1 ) ; for ( int i = 3 ; i * i <= N ; i = i + 2 ) { count = 0 ; while ( N % i == 0 ) { count ++ ; N = N / i ; } ans *= ( count / 2 + 1 ) ; } return ans ; } int main ( ) { int N = 100 ; cout << noOfFactors ( N ) ; return 0 ; } |
Nth angle of a Polygon whose initial angle and per angle increment is given | C ++ program for the above approach ; Function to check if the angle is possible or not ; Angular sum of a N - sided polygon ; Angular sum of N - sided given polygon ; Check if both sum are equal ; Function to find the nth angle ; Calculate nth angle ; Return the nth angle ; Driver Code ; Checks the possibility of the polygon exist or not ; Print nth angle of the polygon | #include <iostream> NEW_LINE using namespace std ; bool possible ( int N , int a , int b , int n ) { int sum_of_angle = 180 * ( N - 2 ) ; int Total_angle = ( N * ( ( 2 * a ) + ( N - 1 ) * b ) ) / 2 ; if ( sum_of_angle != Total_angle ) return false ; else return true ; } int nth_angle ( int N , int a , int b , int n ) { int nth = 0 ; nth = a + ( n - 1 ) * b ; return nth ; } int main ( ) { int N = 3 , a = 30 , b = 30 , n = 3 ; if ( possible ( N , a , b , n ) ) cout << nth_angle ( N , a , b , n ) ; else cout << " Not β Possible " ; return 0 ; } |
Check if the given string is linear or not | C ++ program for the above approach ; Function to check if the given string is linear or not ; Iterate over string ; If character is not same as the first character then return false ; Increment the tmp ; Driver Code ; Given String str ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int is_linear ( string s ) { int tmp = 0 ; char first = s [ 0 ] ; for ( int pos = 0 ; pos < s . length ( ) ; pos += tmp ) { if ( s [ pos ] != first ) { return false ; } tmp ++ ; } return true ; } int main ( ) { string str = " aapaxyayziabcde " ; if ( is_linear ( str ) ) { cout << " Yes " << endl ; } else { cout << " No " << endl ; } return 0 ; } |
Minimize cost to color all the vertices of an Undirected Graph | C ++ Program to implement the above approach ; Function to implement DFS Traversal to marks all the vertices visited from vertex U ; Mark U as visited ; Traverse the adjacency list of U ; Function to find the minimum cost to color all the vertices of graph ; To store adjacency list ; Loop through the edges to create adjacency list ; To check if a vertex of the graph is visited ; Mark visited to all the vertices that can be reached by colored vertices ; Perform DFS ; To store count of uncolored sub - graphs ; Loop through vertex to count uncolored sub - graphs ; If vertex not visited ; Increase count of uncolored sub - graphs ; Perform DFS to mark visited to all vertices of current sub - graphs ; Calculate minimum cost to color all vertices ; Print the result ; Driver Code ; Given number of vertices and edges ; Given edges ; Given cost of coloring and adding an edge ; Given array of colored vertices | #include <bits/stdc++.h> NEW_LINE using namespace std ; void DFS ( int U , int * vis , vector < int > adj [ ] ) { vis [ U ] = 1 ; for ( int V : adj [ U ] ) { if ( vis [ V ] == 0 ) DFS ( V , vis , adj ) ; } } void minCost ( int N , int M , int vCost , int eCost , int sorc [ ] , vector < int > colored , int destination [ ] ) { vector < int > adj [ N + 1 ] ; for ( int i = 0 ; i < M ; i ++ ) { adj [ sorc [ i ] ] . push_back ( destination [ i ] ) ; adj [ destination [ i ] ] . push_back ( sorc [ i ] ) ; } int vis [ N + 1 ] = { 0 } ; for ( int i = 0 ; i < colored . size ( ) ; i ++ ) { DFS ( colored [ i ] , vis , adj ) ; } int X = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { if ( vis [ i ] == 0 ) { X ++ ; DFS ( i , vis , adj ) ; } } int mincost = X * min ( vCost , eCost ) ; cout << mincost << endl ; } int main ( ) { int N = 3 , M = 1 ; int sorc [ ] = { 1 } ; int destination [ ] = { 2 } ; int vCost = 3 , eCost = 2 ; vector < int > colored = { 1 } ; minCost ( N , M , vCost , eCost , sorc , colored , destination ) ; return 0 ; } |
Minimum cost to reduce the integer N to 1 as per given conditions | C ++ program for the above approach ; Function to find the minimum cost to reduce the integer N to 1 by the given operations ; Check if x is 1 ; Print the answer ; Prestore the answer ; Iterate till n exists ; Divide N by x ; Reduce n by x ; Add the cost ; Update the answer ; Return the answer ; Driver Code ; Initialize the variables ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int min_cost ( int n , int x , int p , int q ) { if ( x == 1 ) { cout << ( n - 1 ) * p << endl ; return 0 ; } int ans = ( n - 1 ) * p ; int pre = 0 ; while ( n > 1 ) { int tmp = n / x ; if ( tmp < 0 ) break ; pre += ( n - tmp * x ) * p ; n /= x ; pre += q ; ans = min ( ans , pre + ( n - 1 ) * p ) ; } return ans ; } int main ( ) { int n = 5 , x = 2 , p = 2 , q = 3 ; cout << min_cost ( n , x , p , q ) ; return 0 ; } |
Number of ways to sum up a total of N from limited denominations | C ++ program for the above approach ; Function to find the number of ways to sum up a total of N from limited denominations ; Store the count of denominations ; Stores the final result ; As one of the denominations is rupee 1 , so we can reduce the computation by checking the equality for N - ( A * 1 ) = N - A ; Increment the count for number of ways ; Driver Code ; Given Denominations ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int calculateWays ( int arr1 [ ] , int arr2 [ ] , int N ) { int A = arr2 [ 0 ] , B = arr2 [ 1 ] ; int C = arr2 [ 2 ] , D = arr2 [ 3 ] ; int ans = 0 ; for ( int b = 0 ; b <= B && b * 5 <= ( N ) ; b ++ ) for ( int c = 0 ; c <= C && b * 5 + c * 10 <= ( N ) ; c ++ ) for ( int d = 0 ; d <= D && b * 5 + c * 10 + d * 20 <= ( N ) ; d ++ ) if ( ( b * 5 ) + ( c * 10 ) + ( d * 20 ) >= ( N - A ) ) ans ++ ; return ans ; } int main ( ) { int N = 123 ; int arr1 [ ] = { 1 , 5 , 10 , 20 } ; int arr2 [ ] = { 6 , 4 , 3 , 5 } ; cout << calculateWays ( arr1 , arr2 , N ) ; return 0 ; } |
Number of ways to sum up a total of N from limited denominations | C ++ program for the above approach ; Function to find the number of ways to sum up a total of N from limited denominations ; Store the count of denominations ; Stores the final result ; This will give the number of coins for all combinations of coins with value 1 and 5 ; L2 will sum the values of those indices of ways [ ] which is equal to ( N - ( c * 10 + d * 20 ) ) ; Return the final count ; Driver Code ; Given Denominations ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int ways [ 1010 ] ; int calculateWays ( int arr1 [ ] , int arr2 [ ] , int N ) { int A = arr2 [ 0 ] , B = arr2 [ 1 ] ; int C = arr2 [ 2 ] , D = arr2 [ 3 ] ; int ans = 0 ; for ( int b = 0 ; b <= B && b * 5 <= N ; b ++ ) { for ( int a = 0 ; a <= A && a * 1 + b * 5 <= N ; a ++ ) { ways [ a + b * 5 ] ++ ; } } for ( int c = 0 ; c <= C && c * 10 <= ( N ) ; c ++ ) { for ( int d = 0 ; d <= D && c * 10 + d * 20 <= ( N ) ; d ++ ) { ans += ways [ N - c * 10 - d * 20 ] ; } } return ans ; } int main ( ) { int N = 123 ; int arr1 [ ] = { 1 , 5 , 10 , 20 } ; int arr2 [ ] = { 6 , 4 , 3 , 5 } ; cout << calculateWays ( arr1 , arr2 , N ) ; return 0 ; } |
Count of Missing Numbers in a sorted array | C ++ Program for the above approach ; Function that find the count of missing numbers in array a [ ] ; Calculate the count of missing numbers in the array ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void countMissingNum ( int a [ ] , int N ) { int count = a [ N - 1 ] - a [ 0 ] + 1 - N ; cout << count << endl ; } int main ( ) { int arr [ ] = { 5 , 10 , 20 , 40 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countMissingNum ( arr , N ) ; return 0 ; } |
Length of longest subsequence whose XOR value is odd | C ++ program for the above approach ; Function for find max XOR subsequence having odd value ; Initialize odd and even count ; Count the number of odd and even numbers in given array ; if all values are odd in given array ; if all values are even in given array ; if both odd and even are present in given array ; Driver Code ; Given array arr [ ] ; Function Call | #include <iostream> NEW_LINE using namespace std ; int maxXORSubsequence ( int arr [ ] , int n ) { int odd = 0 , even = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] & 1 ) odd ++ ; else even ++ ; } int maxlen ; if ( odd == n ) { if ( odd % 2 == 0 ) maxlen = n - 1 ; else maxlen = n ; } else if ( even == n ) { maxlen = 0 ; } else { if ( odd % 2 == 0 ) maxlen = even + odd - 1 ; else maxlen = even + odd ; } } int main ( ) { int arr [ ] = { 2 , 3 , 4 , 5 , 6 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxXORSubsequence ( arr , n ) ; } |
Count of pairs with sum N from first N natural numbers | C ++ program to count the number of pairs among the first N natural numbers with sum N ; Function to return the count of pairs ; If n is even ; Count of pairs ; Otherwise ; Driver Code | #include <iostream> NEW_LINE using namespace std ; int numberOfPairs ( int n ) { if ( n % 2 == 0 ) return n / 2 - 1 ; else return n / 2 ; } int main ( ) { int n = 8 ; cout << numberOfPairs ( n ) ; return 0 ; } |
Count pair of strings whose concatenation has every vowel | C ++ program for the above approach ; Function to return the count of all concatenated string with each vowel at least once ; Concatenating all possible pairs of string ; Creating an array which checks , the presence of each vowel ; Checking for each vowel by traversing the concatenated string ; Checking if all the elements are set in vowel [ ] ; Check if all vowels are present or not ; Return the final count ; Driver Code ; Given array of strings ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int good_pair ( string str [ ] , int N ) { int countStr = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { string res = str [ i ] + str [ j ] ; int vowel [ 5 ] = { 0 } ; for ( int k = 0 ; k < res . length ( ) ; k ++ ) { if ( res [ k ] == ' a ' ) vowel [ 0 ] = 1 ; else if ( res [ k ] == ' e ' ) vowel [ 1 ] = 1 ; else if ( res [ k ] == ' i ' ) vowel [ 2 ] = 1 ; else if ( res [ k ] == ' o ' ) vowel [ 3 ] = 1 ; else if ( res [ k ] == ' u ' ) vowel [ 4 ] = 1 ; } int temp = 0 ; for ( int ind = 0 ; ind < 5 ; ind ++ ) { if ( vowel [ ind ] == 1 ) temp ++ ; } if ( temp == 5 ) countStr ++ ; } } return countStr ; } int main ( ) { string arr [ ] = { " aaweiolkju " , " oxdfgujkmi " } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << good_pair ( arr , N ) ; } |
Find sum of exponents of prime factors of numbers 1 to N | C ++ program for the above approach ; Function to implement sieve of erastosthenes ; Create a boolean array and initialize all entries as false ; Initializing smallest factor equal to 2 for all the even numbers ; Iterate for odd numbers less then equal to n ; s ( i ) for a prime is the number itself ; For all multiples of current prime number ; i is the smallest prime factor for number " i * j " ; Function to generate prime factors and its power ; s [ i ] is going to store smallest prime factor of i ; Current prime factor of N ; Power of current prime factor ; Calculating prime factors and their powers sum ; Increment the count and continue the process ; Add count to the sum ; Reinitialize count ; Return the result ; Function to find the sum of all the power of prime factors of N ; Iterate for in [ 2 , N ] ; Driver Code ; Given Number N ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sieveOfEratosthenes ( int N , int s [ ] ) { vector < bool > prime ( N + 1 , false ) ; for ( int i = 2 ; i <= N ; i += 2 ) s [ i ] = 2 ; for ( int i = 3 ; i <= N ; i += 2 ) { if ( prime [ i ] == false ) { s [ i ] = i ; for ( int j = i ; j * i <= N ; j += 2 ) { if ( prime [ i * j ] == false ) { prime [ i * j ] = true ; s [ i * j ] = i ; } } } } } int generatePrimeFactors ( int N ) { int s [ N + 1 ] ; int sum = 0 ; sieveOfEratosthenes ( N , s ) ; int curr = s [ N ] ; int cnt = 1 ; while ( N > 1 ) { N /= s [ N ] ; if ( curr == s [ N ] ) { cnt ++ ; continue ; } sum = sum + cnt ; curr = s [ N ] ; cnt = 1 ; } return sum ; } void findSum ( int N ) { int sum = 0 ; for ( int i = 2 ; i <= N ; i ++ ) { sum += generatePrimeFactors ( i ) ; } cout << sum << endl ; } int main ( ) { int N = 4 ; findSum ( N ) ; return 0 ; } |
Minimum LCM of all subarrays of length at least 2 | C ++ program for the above approach ; Function to find LCM pf two numbers ; Initialise lcm value ; Check for divisibility of a and b by the lcm ; Function to find the Minimum LCM of all subarrays of length greater than 1 ; Store the minimum LCM ; Traverse the array ; Find LCM of consecutive element ; Check if the calculated LCM is less than the minLCM then update it ; Print the minimum LCM ; Driver Code ; Given array arr [ ] ; Size of the array ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int LCM ( int a , int b ) { int lcm = a > b ? a : b ; while ( true ) { if ( lcm % a == 0 && lcm % b == 0 ) break ; else lcm ++ ; } return lcm ; } void findMinLCM ( int arr [ ] , int n ) { int minLCM = INT_MAX ; for ( int i = 0 ; i < n - 1 ; i ++ ) { int val = LCM ( arr [ i ] , arr [ i + 1 ] ) ; if ( val < minLCM ) { minLCM = val ; } } cout << minLCM << endl ; } int main ( ) { int arr [ ] = { 4 , 8 , 12 , 16 , 20 , 24 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findMinLCM ( arr , n ) ; return 0 ; } |
Minimum integer with at most K bits set such that their bitwise AND with N is maximum | C ++ program for the above approach ; Function to find the integer with maximum bitwise with N ; Store answer in the bitset Initialized with 0 ; To maintain the count of set bits that should exceed k ; Start traversing from the Most significantif that bit is set in n then we will set in our answer i . e in X ; Checking if the ith bit is set in n or not ; Converting into integer ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int find_max ( int n , int k ) { bitset < 32 > X ( 0 ) ; int cnt = 0 ; for ( int i = 31 ; i >= 0 && cnt != k ; i -- ) { if ( n & ( 1 << i ) ) { X [ i ] = 1 ; cnt ++ ; } } return X . to_ulong ( ) ; } int main ( ) { int n = 10 , k = 2 ; cout << find_max ( n , k ) << endl ; return 0 ; } |
Convert string to integer without using any in | C ++ program for the above approach ; Function to convert string to integer without using functions ; Initialize a variable ; Iterate till length of the string ; Subtract 48 from the current digit ; Print the answer ; Driver Code ; Given string of number ; Function Call | #include <iostream> NEW_LINE using namespace std ; void convert ( string s ) { int num = 0 ; int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) num = num * 10 + ( int ( s [ i ] ) - 48 ) ; cout << num ; } int main ( ) { char s [ ] = "123" ; convert ( s ) ; return 0 ; } |
Permutation of Array such that sum of adjacent elements are not divisible by 3 | C ++ implementation to find the permutation of the array such that sum of adjacent elements is not divisible by 3 ; Function to segregate numbers based on their remainder when divided by three ; Loop to iterate over the elements of the given array ; Condition to check the remainder of the number ; Function to find the permutation of the array such that sum of adjacent elements is not divisible by 3 ; Condition to check when it 's impossible to arrange ; Condition to check when there are no zeros , and only ones or only twos ; Array to store the permutation ; Place the ones on alternate places in the answer array , leaving spaces for zeros remainder elements in the array ; Adding a zero to connect it with a two ; Place the twos on alternate places in the answer array , leaving spaces for zeros ; Fill the zeros finally , between the ones and the twos ; Print the arrangement of the array ; Function to solve the problem ; As there can be only 3 remainders ; Function Call ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define hell 1000000007 NEW_LINE #define N 100005 NEW_LINE void count_k ( vector < int > & arr , int & c_0 , int & c_1 , int & c_2 , stack < int > & ones , stack < int > & twos , stack < int > & zeros ) { for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { if ( arr [ i ] % 3 == 0 ) { c_0 ++ ; zeros . push ( arr [ i ] ) ; } else if ( arr [ i ] % 3 == 1 ) { c_1 ++ ; ones . push ( arr [ i ] ) ; } else { c_2 ++ ; twos . push ( arr [ i ] ) ; } } return ; } void printArrangement ( vector < int > & arr , int & c_0 , int & c_1 , int & c_2 , stack < int > & ones , stack < int > & twos , stack < int > & zeros ) { if ( ( c_0 == 0 && c_1 != 0 && c_2 != 0 ) or c_0 > c_1 + c_2 + 1 ) { cout << " - 1" ; return ; } if ( c_0 == 0 ) { for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { cout << arr [ i ] << " β " ; } return ; } int i , j , ans [ N ] ; memset ( ans , -1 , sizeof ( ans ) ) ; for ( i = 1 , j = 0 ; j < c_1 ; i += 2 , j ++ ) { ans [ i ] = ones . top ( ) ; ones . pop ( ) ; } ans [ i - 1 ] = zeros . top ( ) ; zeros . pop ( ) ; c_0 -- ; for ( j = 0 ; j < c_2 ; j ++ , i += 2 ) { ans [ i ] = twos . top ( ) ; twos . pop ( ) ; } for ( int k = 0 ; c_0 > 0 ; k += 2 ) { if ( ans [ k ] == -1 ) { ans [ k ] = zeros . top ( ) ; c_0 -- ; } } for ( int i = 0 ; i < N ; i ++ ) { if ( ans [ i ] != -1 ) cout << ans [ i ] << " β " ; } return ; } void solve ( int n , vector < int > & arr ) { stack < int > ones , zeros , twos ; int c_0 = 0 , c_1 = 0 , c_2 = 0 ; count_k ( arr , c_0 , c_1 , c_2 , ones , twos , zeros ) ; printArrangement ( arr , c_0 , c_1 , c_2 , ones , twos , zeros ) ; } signed main ( ) { int n = 5 ; vector < int > arr { 1 , 2 , 3 , 4 , 5 } ; solve ( n , arr ) ; return 0 ; } |
Count of unique digits in a given number N | C ++ program for the above approach ; Function that returns the count of unique digits of the given number ; Initialize a variable to store count of unique digits ; Initialize cnt array to store digit count ; Iterate through the digits of N ; Retrieve the last digit of N ; Increase the count of the last digit ; Remove the last digit of N ; Iterate through the cnt array ; If frequency of digit is 1 ; Increment the count of unique digits ; Return the count / of unique digit ; Driver Code ; Given array arr [ ] ; Function Call | #include <iostream> NEW_LINE using namespace std ; int countUniqueDigits ( int N ) { int res = 0 ; int cnt [ 10 ] = { 0 } ; while ( N > 0 ) { int rem = N % 10 ; cnt [ rem ] ++ ; N = N / 10 ; } for ( int i = 0 ; i < 10 ; i ++ ) { if ( cnt [ i ] == 1 ) { res ++ ; } } return res ; } int main ( ) { int N = 2234262 ; cout << countUniqueDigits ( N ) ; return 0 ; } |
Check if frequency of each element in given array is unique or not | C ++ code for the above approach ; Function to check whether the frequency of elements in array is unique or not . ; Freq map will store the frequency of each element of the array ; Store the frequency of each element from the array ; Check whether frequency of any two or more elements are same or not . If yes , return false ; Return true if each frequency is unique ; Driver Code ; Given array arr [ ] ; Function Call ; Print the result | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkUniqueFrequency ( int arr [ ] , int n ) { unordered_map < int , int > freq ; for ( int i = 0 ; i < n ; i ++ ) { freq [ arr [ i ] ] ++ ; } unordered_set < int > uniqueFreq ; for ( auto & i : freq ) { if ( uniqueFreq . count ( i . second ) ) return false ; else uniqueFreq . insert ( i . second ) ; } return true ; } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 5 , 5 } ; int n = sizeof arr / sizeof arr [ 0 ] ; bool res = checkUniqueFrequency ( arr , n ) ; if ( res ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.