text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Maximum index a pointer can reach in N steps by avoiding a given index B | Set 2 | C ++ program for the above approach ; Function to find the maximum index the pointer can reach ; Initialize two pointers ; Stores number of steps ; Stores sum of first N natural numbers ; Increment i with j ; Increment j with 1 ; Increment count ; If i points to B ; Break ; Print the pointer index ; Driver Code ; Given value of N & B ; Function call to find maximum index the pointer can reach | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumIndex ( int N , int B ) { int i = 0 , j = 1 ; int cnt = 0 ; int sum = N * ( N + 1 ) / 2 ; bool flag = false ; while ( cnt < N ) { i += j ; j ++ ; cnt ++ ; if ( i == B ) { flag = true ; break ; } } if ( ! flag ) { cout << sum ; } else cout << sum - 1 ; } int main ( ) { int N = 4 , B = 6 ; maximumIndex ( N , B ) ; return 0 ; } |
Generate longest possible array with product K such that each array element is divisible by its previous adjacent element | C ++ program for the above approach ; Function to construct longest array with product K such that each element is divisible by its previous element ; Stores the prime factors of K ; Stores the power to which primefactor i is raised ; Sort prime factors in descending order ; Stores the final array ; Multiply the last element by K ; Print the constructed array ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findLongestArray ( int K ) { vector < pair < int , int > > primefactors ; int K_temp = K ; for ( int i = 2 ; i * i <= K ; i ++ ) { int count = 0 ; while ( K_temp % i == 0 ) { K_temp /= i ; count ++ ; } if ( count > 0 ) primefactors . push_back ( { count , i } ) ; } if ( K_temp != 1 ) primefactors . push_back ( { 1 , K_temp } ) ; sort ( primefactors . rbegin ( ) , primefactors . rend ( ) ) ; vector < int > answer ( primefactors [ 0 ] . first , primefactors [ 0 ] . second ) ; answer . back ( ) *= K ; for ( int i = 0 ; i < primefactors [ 0 ] . first ; i ++ ) { answer . back ( ) /= primefactors [ 0 ] . second ; } cout << " { " ; for ( int i = 0 ; i < ( int ) answer . size ( ) ; i ++ ) { if ( i == answer . size ( ) - 1 ) cout << answer [ i ] << " } " ; else cout << answer [ i ] << " , β " ; } } int main ( ) { int K = 4 ; findLongestArray ( K ) ; } |
Minimum number of steps required to place all 1 s at a single index | C ++ implementation of the above approach ; Function to print minimum steps required to shift all 1 s to a single index in a binary array ; Size of array ; Used to store cumulative sum ; Initialize count ; Traverse the array in forward direction ; Steps needed to store all previous ones to ith index ; Count number of 1 s present till i - th index ; Initialize count ; Traverse the array in backward direction ; Steps needed to store all 1 s to the right of i at current index ; Count number of 1 s present after i - th index ; Print the number of steps required ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minsteps ( vector < int > & A ) { int n = A . size ( ) ; vector < int > left ( n , 0 ) , right ( n , 0 ) , res ( n , 0 ) ; int count = A [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { left [ i ] = left [ i - 1 ] + count ; count += A [ i ] ; } count = A [ n - 1 ] ; for ( int i = n - 2 ; i >= 0 ; i -- ) { right [ i ] = right [ i + 1 ] + count ; count += A [ i ] ; } for ( int i = 0 ; i < n ; i ++ ) { res [ i ] = left [ i ] + right [ i ] ; cout << res [ i ] << " β " ; } cout << " STRNEWLINE " ; } int main ( ) { vector < int > A = { 1 , 0 , 1 , 0 } ; minsteps ( A ) ; } |
Minimize flips on K | C ++ program for the above approach ; Function to find the minimum number K - length subarrays required to be flipped to make all array elements 1 ; Stores whether an element can be flipped or not ; Store the required number of flips ; Traverse the array , A [ ] ; Find the prefix sum for the indices i > 0 ; Check if the current element is required to be flipped ; If subarray of size K is not possible , then print - 1 and return ; Increment ans by 1 ; Change the current state of the element ; Decrement isFlipped [ i + K ] ; If subarray of size K is not possible , then print - 1 and return ; Increment ans by 1 ; Change the current state of the element ; Decrement isFlipped [ i + K ] ; Print the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumOperations ( vector < int > & A , int K ) { vector < int > isflipped ( A . size ( ) , 0 ) ; int ans = 0 ; for ( int i = 0 ; i < A . size ( ) ; i ++ ) { if ( i > 0 ) { isflipped [ i ] += isflipped [ i - 1 ] ; isflipped [ i ] %= 2 ; } if ( A [ i ] == 0 && ! isflipped [ i ] ) { if ( ( A . size ( ) - i + 1 ) <= K ) { cout << -1 ; return ; } ans ++ ; isflipped [ i ] ++ ; isflipped [ i + K ] -- ; } else if ( A [ i ] == 1 && isflipped [ i ] ) { if ( ( A . size ( ) - i + 1 ) <= K ) { cout << -1 ; return ; } ans ++ ; isflipped [ i ] ++ ; isflipped [ i + K ] -- ; } } cout << ans ; } int main ( ) { vector < int > arr = { 0 , 1 , 0 } ; int K = 1 ; minimumOperations ( arr , K ) ; return 0 ; } |
Calculate sum of scores after N days based on given conditions | C ++ program for the above approach ; Function to c sum of calculate sum of scores after n days ; Store the required sum ; Store the score on previous monday and current day respectively ; Iterate over the range [ 1 , n ] ; If the current day is monday ; Increment score of prev_monday by 1 ; Update score of current day ; Add score of current day and increment score for next day ; Print the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findScoreSum ( int n ) { int total = 0 ; int prev_monday = 0 , curr_day = 0 ; for ( int day = 1 ; day <= n ; day ++ ) { if ( day % 7 == 1 ) { prev_monday ++ ; curr_day = prev_monday ; } total += curr_day ++ ; } cout << total ; } int main ( ) { int N = 8 ; findScoreSum ( N ) ; return 0 ; } |
Calculate sum of scores after N days based on given conditions | C ++ program for the above approach ; Function to calculate sum of scores after n days ; Store the number of full weeks ; Stores the remaining days in the last week ; Store the sum of scores in the first F full weeks ; Store the sum of scores in the last week ; Print the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findScoreSum ( int n ) { int F = n / 7 ; int D = n % 7 ; int fullWeekScore = ( 49 + 7 * F ) * F / 2 ; int lastNonFullWeekScore = ( 2 * F + D + 1 ) * D / 2 ; cout << fullWeekScore + lastNonFullWeekScore ; } int main ( ) { int N = 8 ; findScoreSum ( N ) ; return 0 ; } |
Largest number up to N whose modulus with X is equal to Y modulo X | C ++ program for the above approach ; Function to print the largest number upto N whose modulus with X is same as Y % X ; Stores the required number ; Update num as the result ; Return the resultant number ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long maximumNum ( long long X , long long Y , long long N ) { long long num = 0 ; if ( N - N % X + Y <= N ) { num = N - N % X + Y ; } else { num = N - N % X - ( X - Y ) ; } return num ; } int main ( ) { long long X = 10 ; long long Y = 5 ; long long N = 15 ; cout << maximumNum ( X , Y , N ) ; return 0 ; } |
Number of points lying inside a rectangle as well as a triangle | C ++ program for the above approach ; Function to calculate area of a triangle ; Return the resultant area ; Function to check if a point lies inside a triangle or not ; Calculate area of triangle ABC ; Calculate area of triangle formed by connecting B , C , point ; Calculate area of triangle formed by connecting A , C , point ; Calculate area of triangle formed by connecting A , B , point ; Check if the sum of the areas of above three triangles the same as ABC ; Function to count the number of points lying inside a triangle & rectangle ; Stores the coordinates of the vertices of the triangles ; Stores the number of points lying inside the triangle and rectangle ; Traverse the array of points ; Stores whether the current point lies inside triangle1 or not ; Stores whether the current point lies inside triangle2 or not ; Stores whether the current point lies inside triangle3 or not ; Stores whether the current point lies inside triangle4 or not ; Stores whether the current point lies inside given triangle or not ; If current point lies inside given triangle as well as inside any of the four obtained triangles ; Print the count of points ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getArea ( int x1 , int y1 , int x2 , int y2 , int x3 , int y3 ) { return abs ( ( x1 * ( y2 - y3 ) + x2 * ( y3 - y1 ) + x3 * ( y1 - y2 ) ) / 2 ) ; } int isInside ( vector < vector < int > > triangle , vector < int > point ) { vector < int > A = triangle [ 0 ] ; vector < int > B = triangle [ 1 ] ; vector < int > C = triangle [ 2 ] ; int x = point [ 0 ] ; int y = point [ 1 ] ; int ABC = getArea ( A [ 0 ] , A [ 1 ] , B [ 0 ] , B [ 1 ] , C [ 0 ] , C [ 1 ] ) ; int BPC = getArea ( x , y , B [ 0 ] , B [ 1 ] , C [ 0 ] , C [ 1 ] ) ; int APC = getArea ( A [ 0 ] , A [ 1 ] , x , y , C [ 0 ] , C [ 1 ] ) ; int APB = getArea ( A [ 0 ] , A [ 1 ] , B [ 0 ] , B [ 1 ] , x , y ) ; return ABC == ( APC + APB + BPC ) ; } void countPoints ( vector < vector < int > > rectangle , vector < vector < int > > triangle , vector < vector < int > > points ) { int n = rectangle . size ( ) ; vector < vector < int > > triangle1 ; for ( int i = 1 ; i < n ; i ++ ) triangle1 . push_back ( rectangle [ i ] ) ; vector < vector < int > > triangle2 ; for ( int i = 0 ; i < 3 ; i ++ ) triangle2 . push_back ( rectangle [ i ] ) ; vector < vector < int > > triangle3 ; for ( int i = 0 ; i < 2 ; i ++ ) triangle3 . push_back ( rectangle [ i ] ) ; triangle3 . push_back ( rectangle [ 3 ] ) ; vector < vector < int > > triangle4 ; for ( int i = n - 2 ; i < n ; i ++ ) triangle4 . push_back ( rectangle [ i ] ) ; triangle4 . push_back ( rectangle [ 0 ] ) ; int ans = 0 ; for ( auto point : points ) { int condOne = isInside ( triangle1 , point ) ; int condTwo = isInside ( triangle2 , point ) ; int condThree = isInside ( triangle3 , point ) ; int condFour = isInside ( triangle4 , point ) ; int condFive = isInside ( triangle , point ) ; if ( ( condOne condTwo condThree condFour ) && condFive ) ans += 1 ; } cout << ans ; } int main ( ) { vector < vector < int > > rectangle = { { 6 , 5 } , { 2 , 2 } , { 2 , 1 } , { 5 , 5 } } ; vector < vector < int > > points = { { 1 , 1 } , { 6 , 1 } , { 6 , 6 } , { 1 , 6 } } ; vector < vector < int > > triangle = { { 4 , 4 } , { 0 , 4 } , { 0 , -2 } } ; countPoints ( points , triangle , rectangle ) ; return 0 ; } |
Generate an N | C ++ program for the above approach ; Function to calculate GCD of two integers ; Function to calculate GCD of a given array ; Utility function to check for all the possible combinations ; If an N - length sequence is obtained ; If GCD of the sequence is K ; Otherwise ; Add an element from the first array ; Recursively proceed further ; If combination satisfies the necessary condition ; Remove the element from the combination ; Add an element from the second array ; Recursive proceed further ; If combination satisfies the necessary condition ; Remove the element from the combination ; Function to check all the possible combinations ; Stores the subsequence ; If GCD is not equal to K for any combination ; Driver Code ; Given arrays ; Given value of K ; Function call to generate the required subsequence | #include <bits/stdc++.h> NEW_LINE using namespace std ; int GCD ( int a , int b ) { if ( ! b ) return a ; return GCD ( b , a % b ) ; } int GCDArr ( vector < int > a ) { int ans = a [ 0 ] ; for ( int i : a ) ans = GCD ( ans , i ) ; return ans ; } bool findSubseqUtil ( vector < int > a , vector < int > b , vector < int > & ans , int k , int i ) { if ( ans . size ( ) == a . size ( ) ) { if ( GCDArr ( ans ) == k ) { cout << " [ " ; int m = ans . size ( ) ; for ( int i = 0 ; i < m - 1 ; i ++ ) cout << ans [ i ] << " , β " ; cout << ans [ m - 1 ] << " ] " ; return true ; } else return false ; } ans . push_back ( a [ i ] ) ; bool temp = findSubseqUtil ( a , b , ans , k , i + 1 ) ; if ( temp ) return true ; ans . pop_back ( ) ; ans . push_back ( b [ i ] ) ; temp = findSubseqUtil ( a , b , ans , k , i + 1 ) ; if ( temp ) return true ; ans . pop_back ( ) ; return false ; } void findSubseq ( vector < int > A , vector < int > B , int K , int i ) { vector < int > ans ; findSubseqUtil ( A , B , ans , K , i ) ; if ( ! ans . size ( ) ) cout << -1 ; } int main ( ) { vector < int > A = { 5 , 3 , 6 , 2 , 9 } ; vector < int > B = { 21 , 7 , 14 , 12 , 28 } ; int K = 3 ; findSubseq ( A , B , K , 0 ) ; return 0 ; } |
Minimize count of swaps of adjacent elements required to make an array increasing | C ++ program for the above approach ; Function to count minimum number of operations required to obtain an increasing array from given array A [ ] ; Store the required result ; Traverse the array A [ ] ; If the current element is not in its correct position ; Check if it is present at index i - 1 ; Check if it is present at index i - 2 ; Otherwise , print - 1 ( Since A [ i ] can not be swapped more than twice ) ; Print the result ; Driver Code ; Given array ; Store the size of the array | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumOperations ( int A [ ] , int n ) { int cnt = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( A [ i ] != ( i + 1 ) ) { if ( ( ( i - 1 ) >= 0 ) && A [ i - 1 ] == ( i + 1 ) ) { cnt ++ ; swap ( A [ i ] , A [ i - 1 ] ) ; } else if ( ( ( i - 2 ) >= 0 ) && A [ i - 2 ] == ( i + 1 ) ) { cnt += 2 ; A [ i - 2 ] = A [ i - 1 ] ; A [ i - 1 ] = A [ i ] ; A [ i ] = i + 1 ; } else { cout << -1 ; return ; } } } cout << cnt ; } int main ( ) { int A [ ] = { 7 , 3 , 2 , 1 , 4 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; minimumOperations ( A , n ) ; return 0 ; } |
Count occurrences of an element in a matrix of size N * N generated such that each element is equal to product of its indices | Set | C ++ program for the above approach ; Function to count the occurrences of X in the generated square matrix ; Store the required result ; Iterate over the range [ 1 , N ] ; Check if x is a multiple of i or not ; Check if the other multiple exists in the range or not ; Print the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countOccurrences ( int n , int x ) { int count = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { if ( x % i == 0 ) { if ( x / i <= n ) count ++ ; } } cout << count ; } int main ( ) { int N = 7 , X = 12 ; countOccurrences ( N , X ) ; return 0 ; } |
Reduce all array elements to zero by performing given operations thrice | C ++ program of the above approach ; Function to reduce all array elements to zero ; If size of array is 1 ; First operation ; 2 nd Operation ; 3 rd Operation ; Otherwise ; 1 st Operation ; 2 nd Operation ; 3 rd Operation ; Driver Code ; Input ; Function call to make all array elements equal to 0 | #include <bits/stdc++.h> NEW_LINE using namespace std ; void ConvertArray ( int arr [ ] , int N ) { if ( N == 1 ) { cout << " Operation β 1 β : β " << 1 << " β " << 1 << endl ; cout << " Added β elements : β " << -1 * arr [ 0 ] << endl ; cout << endl ; cout << " Operation β 2 β : β " << 1 << " β " << 1 << endl ; cout << " Added β elements : β " << 1 * arr [ 0 ] << endl ; cout << endl ; cout << " Operation β 3 β : β " << 1 << " β " << 1 << endl ; cout << " Added β elements : β " << -1 * arr [ 0 ] << endl ; } else { cout << " Operation β 1 β : β " << 1 << " β " << N << endl ; cout << " Added β elements : β " ; for ( int i = 0 ; i < N ; i ++ ) { cout << -1 * arr [ i ] * N << " β " ; } cout << endl ; cout << endl ; cout << " Operation β 2 β : β " << 1 << " β " << N - 1 << endl ; cout << " Added β elements : β " ; for ( int i = 0 ; i < N - 1 ; i ++ ) { cout << arr [ i ] * ( N - 1 ) << " β " ; } cout << endl ; cout << endl ; cout << " Operation β 3 β : β " << N << " β " << N << endl ; cout << " Added β elements : β " ; cout << arr [ N - 1 ] * ( N - 1 ) << endl ; } } int main ( ) { int arr [ ] = { 1 , 3 , 2 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; ConvertArray ( arr , N ) ; return 0 ; } |
Count pairs from an array with even product of count of distinct prime factors | C ++ implementation of the above approach ; Function to calculate count of distinct prime factors of a number ; Sieve of Eratosthenes ; Function to count pairs with even product of distinct prime factors ; Stores count of distinct prime factors ; Stores the count of numbers with even prime factors in B [ ] ; Stores the count of numbers with odd prime factors in B [ ] ; Even Product Pairs ; Traverse the array B [ ] ; Since , product has to be positive i . e > 0 ; If count of prime factors is odd ; Increment oddCount by 1 ; Increment evenCount by 1 ; Since , product has to be positive i . e > 0 ; If count of prime factors is odd ; odd * even = even ; If count of prime factors is even ; even * odd = even even * even = even ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1000000 NEW_LINE void countOfPrimefactors ( vector < int > & CountDistinct ) { bool prime [ MAX + 1 ] ; for ( int i = 0 ; i <= MAX ; i ++ ) { CountDistinct [ i ] = 0 ; prime [ i ] = true ; } for ( long long int i = 2 ; i <= MAX ; i ++ ) { if ( prime [ i ] == true ) { CountDistinct [ i ] = 1 ; for ( long long int j = i * 2 ; j <= MAX ; j += i ) { CountDistinct [ j ] ++ ; prime [ j ] = false ; } } } } int CountEvenPair ( int A [ ] , int B [ ] , int N , int M ) { vector < int > countDistinct ( MAX + 1 ) ; countOfPrimefactors ( countDistinct ) ; int evenCount = 0 ; int oddCount = 0 ; int evenPairs = 0 ; for ( int i = 0 ; i < M ; i ++ ) { if ( countDistinct [ B [ i ] ] == 0 ) continue ; if ( countDistinct [ B [ i ] ] & 1 ) { oddCount ++ ; } else { evenCount ++ ; } } for ( int i = 0 ; i < N ; i ++ ) { if ( countDistinct [ A [ i ] ] == 0 ) continue ; if ( countDistinct [ A [ i ] ] & 1 ) { evenPairs += ( evenCount ) ; } else { evenPairs += evenCount + oddCount ; } } return evenPairs ; } int main ( ) { int A [ ] = { 1 , 2 , 3 } ; int B [ ] = { 4 , 5 , 6 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int M = sizeof ( B ) / sizeof ( B [ 0 ] ) ; cout << CountEvenPair ( A , B , N , M ) ; return 0 ; } |
Minimum array elements required to be subtracted from either end to reduce K to 0 | C ++ program for the above approach ; Function to find the length of longest subarray having sum K ; Stores the index of the prefix sum ; Traverse the given array ; Update sum ; If the subarray starts from index 0 ; Add the current prefix sum with index if it is not present in the map um ; Check if sum - K is present in Map um or not ; Update the maxLength ; Return the required maximum length ; Function to find the minimum removal of array elements required to reduce K to 0 ; Stores the sum of the array ; Traverse the array arr [ ] ; Update sum of the array ; Find maxLen ; If the subarray with sum doesn 't exist ; Otherwise , print the required maximum length ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int longestSubarray ( int arr [ ] , int N , int K ) { unordered_map < int , int > um ; int sum = 0 , maxLen = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += arr [ i ] ; if ( sum == K ) maxLen = i + 1 ; if ( um . find ( sum ) == um . end ( ) ) um [ sum ] = i ; if ( um . find ( sum - K ) != um . end ( ) ) { if ( maxLen < ( i - um [ sum - K ] ) ) maxLen = i - um [ sum - K ] ; } } return maxLen ; } void minRequiredOperation ( int arr [ ] , int N , int K ) { int TotalSum = 0 ; for ( int i = 0 ; i < N ; i ++ ) TotalSum += arr [ i ] ; int maxLen = longestSubarray ( arr , N , TotalSum - K ) ; if ( maxLen == -1 ) { cout << -1 ; } else cout << N - maxLen ; } int main ( ) { int arr [ ] = { 1 , 3 , 1 , 1 , 2 } ; int K = 4 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minRequiredOperation ( arr , N , K ) ; return 0 ; } |
Minimum number of digits required to be removed to make a number divisible by 4 | C ++ program for the above approach ; Function to count the minimum number of digits required to be removed to make a given number divisible by 4 ; Store the size of the string ; Stores the required result ; Check for every pair of digits if the number formed by them is divisible by 4 or not ; Store s [ i ] in a variable ; If it is divisible by 2 ; Store the number formed by s [ j ] and s [ i ] ; Check if it is divisible by 4 ; Store the number of digits required to be deleted ; Update ans ; If value of ans is unchanged , then check if any s [ i ] is divisible by 4 ; If true , update ans to n - 1 ; Print the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumDeletions ( string s ) { int n = s . length ( ) ; int ans = n ; for ( int i = n - 1 ; i >= 0 ; i -- ) { int t = s [ i ] - '0' ; if ( t % 2 == 0 ) { for ( int j = i - 1 ; j >= 0 ; j -- ) { int num = ( s [ j ] - '0' ) * 10 + t ; if ( num % 4 == 0 ) { int k1 = i - j - 1 ; int k2 = n - i - 1 ; ans = min ( ans , k1 + k2 ) ; } } } } if ( ans == n ) { for ( int i = 0 ; i < n ; i ++ ) { int num = s [ i ] - '0' ; if ( num % 4 == 0 ) { ans = n - 1 ; } } } cout << ans ; } int main ( ) { string str = "12367" ; minimumDeletions ( str ) ; return 0 ; } |
Generate a sequence such that float division of array elements is maximized | C ++ program for the above approach ; Function to place the parenthesis such that the result is maximized ; Store the required string ; Add the first integer to string ; If the size of array is 1 ; If the size of array is 2 , print the 1 st integer followed by / operator followed by the next integer ; If size of array is exceeds two , print 1 st integer concatenated with operators ' / ' , ' ( ' and next integers with the operator ' / ' ; Add parenthesis at the end ; Print the final expression ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void generateSequence ( int arr [ ] , int n ) { string ans ; ans = to_string ( arr [ 0 ] ) ; if ( n == 1 ) cout << ans ; else if ( n == 2 ) { cout << ans + " / " << to_string ( arr [ 1 ] ) ; } else { ans += " / ( " + to_string ( arr [ 1 ] ) ; for ( int i = 2 ; i < n ; i ++ ) { ans += " / " + to_string ( arr [ i ] ) ; } ans += " ) " ; cout << ans ; } } int main ( ) { int arr [ ] = { 1000 , 100 , 10 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; generateSequence ( arr , N ) ; return 0 ; } |
Count of pairs having even and odd LCM from an array | C ++ program for the above approach ; Function to find count of distinct pairs having even LCM and odd LCM ; Store the total number of pairs ; Stores the count of odd numbers in the array ; Traverse the array arr [ ] ; Update the count of pairs with odd LCM ; Print the count of required pairs ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void LCMPairs ( int arr [ ] , int N ) { int total_pairs = ( N * ( N - 1 ) ) / 2 ; int odd = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] & 1 ) odd ++ ; } odd = ( odd * ( odd - 1 ) ) / 2 ; cout << " Even β = β " << total_pairs - odd << " , β Odd β = β " << odd ; } int main ( ) { int arr [ ] = { 3 , 6 , 5 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; LCMPairs ( arr , N ) ; return 0 ; } |
Value required to be added to N to obtain the sum of first M multiples of K | C ++ program for the above approach ; Function to print the value to be added to N to obtain sum of first M multiples of K ; Store the sum of the first M multiples of K ; Store the value to be added to obtain N ; Driver Code ; Input | #include <iostream> NEW_LINE using namespace std ; static int printNumber ( int N , int K , int M ) { int sum = K * ( M * ( M + 1 ) / 2 ) ; return sum - N ; } int main ( ) { int N = 17 ; int K = 3 ; int M = 4 ; cout << printNumber ( N , K , M ) ; return 0 ; } |
Count even and odd Bitwise XORs of consecutive numbers in a range [ L , R ] starting from L | C ++ program for the above approach ; Print count of even and odd numbers of XOR value from L to R ; Store the number of elements between L and R ; Count of even XOR values ; If L is odd and range % 4 = 3 ; Increment even by 1 ; If L is even and range % 4 != 0 ; Increment even by 1 ; Print the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void countEvenOdd ( int L , int R ) { int range = R - L + 1 ; int even = ( range / 4 ) * 2 ; if ( ( L & 1 ) && ( range % 4 == 3 ) ) { even ++ ; } else if ( ! ( L & 1 ) && ( range % 4 ) ) { even ++ ; } cout << " Even β = β " << even << " , β Odd β = β " << range - even ; } int main ( ) { int L = 2 , R = 7 ; countEvenOdd ( L , R ) ; return 0 ; } |
Minimize swaps of same | C ++ program for the above approach ; Function to count the number of swaps required to make the sum of ASCII values of the characters of both strings odd ; Initialize alphabets with value ; Initialize values for each alphabet ; Size of the string ; Sum of string S ; Sum of string T ; Stores whether there is any index i such that S [ i ] and T [ i ] have different parities ; Traverse the strings ; Update sum1 and sum2 ; If S [ i ] and T [ i ] have different parities ; If sum1 and sum2 are both odd ; If sum1 and sum2 are both even ; If exists print 1 ; Otherwise ; If sum1 and sum2 are of different parities ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void countSwaps ( string S , string T ) { int value [ 26 ] ; for ( int i = 0 ; i < 26 ; i ++ ) value [ i ] = i + 1 ; int N = S . size ( ) ; int sum1 = 0 ; int sum2 = 0 ; bool flag = false ; for ( int i = 0 ; i < N ; i ++ ) { sum1 += value [ S [ i ] - ' a ' ] ; sum2 += value [ T [ i ] - ' a ' ] ; if ( ( value [ S [ i ] - ' a ' ] % 2 == 0 && value [ T [ i ] - ' a ' ] % 2 == 1 ) || ( value [ S [ i ] - ' a ' ] % 2 == 1 && value [ T [ i ] - ' a ' ] % 2 == 0 ) ) flag = false ; } if ( sum1 % 2 == 1 && sum2 % 2 == 1 ) cout << "0 STRNEWLINE " ; else if ( sum1 % 2 == 0 && sum2 % 2 == 0 ) { if ( flag ) cout << "1" ; else cout << " - 1" ; } else { cout << " - 1" ; } } int main ( ) { string S = " acd " ; string T = " dbf " ; countSwaps ( S , T ) ; return 0 ; } |
Count distinct prime triplets up to N such that sum of two primes is equal to the third prime | C ++ program for the above approach ; Function to check if a number is a prime or not ; Function to count the number of valid prime triplets ; Stores the count of prime triplets ; Iterate from 2 to N and check for each p , whether p & ( p - 2 ) are prime or not ; Print the count obtained ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int N ) { if ( N <= 1 ) return false ; for ( int i = 2 ; i <= sqrt ( N ) ; i ++ ) { if ( N % i == 0 ) return false ; } return true ; } void countPrimeTuples ( int N ) { int count = 0 ; for ( int i = 2 ; i <= N ; i ++ ) { if ( isPrime ( i ) && isPrime ( i - 2 ) ) count ++ ; } cout << count ; } int main ( ) { int N = 6 ; countPrimeTuples ( N ) ; return 0 ; } |
Count pairs from an array whose Bitwise OR is greater than Bitwise AND | C ++ program for the above approach ; Function to count the number of pairs ( i , j ) their Bitwise OR is greater than Bitwise AND ; Store the required answer ; Check for all possible pairs ; If the condition satisfy then increment count by 1 ; Print the answer ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void countPairs ( int A [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) if ( ( A [ i ] A [ j ] ) > ( A [ i ] & A [ j ] ) ) { count ++ ; } } cout << count ; } int main ( ) { int A [ ] = { 1 , 4 , 7 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; countPairs ( A , N ) ; return 0 ; } |
Count maximum number of consumable candies | C ++ implememtation of the above approach ; Function to find the count of maximum consumable candies ; Store the count of total candies ; Stores the count of maximum consumable candies ; Checks if it is safe to counsume all candies ; Traverse the array arr [ ] ; If A [ i ] + M is greater than B [ i ] ; Mark all_safe as false ; Update ans ; Update ans ; Increment total by A [ i ] ; If all_safe is true ; Otherwise , ; Driver Code ; Function call to find maximum consumable candies | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumCandy ( int candies [ ] , int safety [ ] , int N , int M ) { int total = 0 ; int ans = INT_MAX ; bool all_safe = true ; for ( int i = 0 ; i < N ; i ++ ) { if ( candies [ i ] + M > safety [ i ] ) { all_safe = false ; ans = min ( ans , safety [ i ] ) ; } else { ans = min ( ans , candies [ i ] + M ) ; } total += candies [ i ] ; } if ( all_safe ) return total ; else return ans ; } int main ( ) { int A [ ] = { 2 , 4 , 1 , 9 , 6 } ; int B [ ] = { 8 , 7 , 3 , 12 , 7 } ; int M = 0 ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << maximumCandy ( A , B , N , M ) ; return 0 ; } |
Check if two arrays can be made equal by swapping pairs of one of the arrays | C ++ program for above approach ; Function to check if two arrays can be made equal or not by swapping pairs of only one of the arrays ; Stores elements required to be replaced ; To check if the arrays can be made equal or not ; Traverse the array ; If array elements are not equal ; Increment count by 1 ; Decrement count by 1 ; If flag is true and count is 0 , print " Yes " . Otherwise " No " ; Driver Code ; Given arrays ; Size of the array | #include <bits/stdc++.h> NEW_LINE using namespace std ; void checkArrays ( int arr1 [ ] , int arr2 [ ] , int N ) { int count = 0 ; bool flag = true ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr1 [ i ] != arr2 [ i ] ) { if ( arr1 [ i ] == 0 ) count ++ ; else { count -- ; if ( count < 0 ) { flag = 0 ; break ; } } } } if ( flag && count == 0 ) cout << " Yes " << endl ; else cout << " No " << endl ; } int main ( ) { int arr1 [ ] = { 0 , 0 , 1 , 1 } ; int arr2 [ ] = { 1 , 1 , 0 , 0 } ; int N = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; checkArrays ( arr1 , arr2 , N ) ; return 0 ; } |
Generate an N | C ++ program for the above approach ; Function to construct an array with sum of each subarray divisible by K ; Traverse a loop from 1 to N ; Print i - th multiple of K ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void construct_Array ( int N , int K ) { for ( int i = 1 ; i <= N ; i ++ ) { cout << K * i << " β " ; } } int main ( ) { int N = 3 , K = 3 ; construct_Array ( N , K ) ; return 0 ; } |
Generate an N | C ++ Program to implement the above approach ; Fun dtion to print the required sequence ; Stores count of even and odd elements ; Stores sum of even and odd elements ; Print N / 2 even elements ; Print N / 2 - 1 odd elements ; Print final odd element ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void Print ( int N ) { if ( ( N / 2 ) % 2 == 1 || ( N % 2 == 1 ) ) { cout << -1 << endl ; return ; } int CurEven = 2 , CurOdd = 1 ; int SumOdd = 0 , SumEven = 0 ; for ( int i = 0 ; i < ( N / 2 ) ; i ++ ) { cout << CurEven << " β " ; SumEven += CurEven ; CurEven += 2 ; } for ( int i = 0 ; i < N / 2 - 1 ; i ++ ) { cout << CurOdd << " β " ; SumOdd += CurOdd ; CurOdd += 2 ; } CurOdd = SumEven - SumOdd ; cout << CurOdd << ' ' ; } int main ( ) { int N = 12 ; Print ( N ) ; return 0 ; } |
Find the last remaining element after repeated removal of an element from pairs of increasing adjacent array elements | C ++ program for the above approach ; Function to print the last remaining array element after after performing given operations ; If size of the array is 1 ; Check for the condition ; If condition is not satisfied ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void canArrayBeReduced ( int arr [ ] , int N ) { if ( N == 1 ) { cout << arr [ 0 ] ; return ; } if ( arr [ 0 ] < arr [ N - 1 ] ) { cout << arr [ N - 1 ] ; } else cout << " Not β Possible " ; } int main ( ) { int arr [ ] = { 6 , 5 , 2 , 4 , 1 , 3 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; canArrayBeReduced ( arr , N ) ; return 0 ; } |
Minimum prefix increments required to make all elements of an array multiples of another array | C ++ program for the above approach ; Function to find minimum count of operations required to make A [ i ] multiple of B [ i ] by incrementing prefix subarray ; Stores minimum count of operations required to make A [ i ] multiple of B [ i ] by incrementing prefix subarray ; Stores the carry ; Stores minimum difference of correspoinding element in prefix subarray ; Traverse the array ; Stores the closest greater or equal number to A [ i ] which is a multiple of B [ i ] ; Stores minimum difference ; Update totalOperations ; Update carry ; Driver Code ; Input arrays A [ ] and B [ ] ; Length of arrays | #include <bits/stdc++.h> NEW_LINE using namespace std ; int MinimumMoves ( int A [ ] , int B [ ] , int N ) { int totalOperations = 0 ; int carry = 0 ; int K = 0 ; for ( int i = N - 1 ; i >= 0 ; i -- ) { int nearestMultiple = ceil ( ( double ) ( A [ i ] + carry ) / ( double ) ( B [ i ] ) ) * B [ i ] ; K = nearestMultiple - ( A [ i ] + carry ) ; totalOperations += K ; carry += K ; } return totalOperations ; } int main ( ) { int A [ ] = { 3 , 4 , 5 , 2 , 5 , 5 , 9 } ; int B [ ] = { 1 , 1 , 9 , 6 , 3 , 8 , 7 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << MinimumMoves ( A , B , N ) << endl ; return 0 ; } |
Minimize deviation of an array by given operations | C ++ implementation of the above approach ; Function to find the minimum deviation of the array A [ ] ; Store all array elements in sorted order ; Odd number are transformed using 2 nd operation ; ( Maximum - Minimum ) ; Check if the size of set is > 0 and the maximum element is divisible by 2 ; Maximum element of the set ; Erase the maximum element ; Using operation 1 ; ( Maximum - Minimum ) ; Print the Minimum Deviation Obtained ; Driver Code ; Function Call to find Minimum Deviation of A [ ] | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumDeviation ( int A [ ] , int N ) { set < int > s ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] % 2 == 0 ) s . insert ( A [ i ] ) ; else s . insert ( 2 * A [ i ] ) ; } int diff = * s . rbegin ( ) - * s . begin ( ) ; while ( ( int ) s . size ( ) && * s . rbegin ( ) % 2 == 0 ) { int maxEl = * s . rbegin ( ) ; s . erase ( maxEl ) ; s . insert ( maxEl / 2 ) ; diff = min ( diff , * s . rbegin ( ) - * s . begin ( ) ) ; } cout << diff ; } int main ( ) { int A [ ] = { 4 , 1 , 5 , 20 , 3 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; minimumDeviation ( A , N ) ; return 0 ; } |
Maximize given integer by swapping pairs of unequal bits | C ++ implementation of the above approach ; Function to return the maximum possible value that can be obtained from the given integer by performing given operations ; Convert to equivalent binary representation ; Stores binary representation of the maximized value ; Store the count of 0 ' s β and β 1' s ; Stores the total Number of Bits ; If current bit is set ; Increment Count1 ; Increment Count0 ; Shift all set bits to left to maximize the value ; Shift all unset bits to right to maximize the value ; Return the maximized value ; Driver code ; Given "Input ; Function call to find the Maximum Possible Number | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaxNum ( int num ) { bitset < 4 > b ( num ) ; string binaryNumber = b . to_string ( ) ; string maxBinaryNumber = " " ; int count0 = 0 , count1 = 0 ; int N = 4 ; for ( int i = 0 ; i < N ; i ++ ) { if ( binaryNumber [ i ] == '1' ) { count1 ++ ; } else { count0 ++ ; } } for ( int i = 0 ; i < count1 ; i ++ ) { maxBinaryNumber += '1' ; } for ( int i = 0 ; i < count0 ; i ++ ) { maxBinaryNumber += '0' ; } return stoi ( maxBinaryNumber , 0 , 2 ) ; } int main ( ) { int N = 11 ; cout << findMaxNum ( N ) ; return 0 ; } |
Minimum deletions to convert given integer to an odd number whose sum of digits is even | Set 2 | C ++ implementation of the above approach ; Function to find minimum count of digits required to be remove to make N odd and the sum of digits of N even ; Stores count of even digits ; Stores count of odd digits ; Iterate over the digits of N ; If current digit is even ; Update even ; Otherwise ; Update odd ; Base conditions ; Stores count of digits required to be removed to make N odd and the sum of digits of N even ; Iterate over the digits of N ; If current digit is even ; Update ans ; Otherwise , ; Update ans ; If count of odd digits is odd ; Update ans ; Finally print the ans ; Driver code ; Input string ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minOperations ( string & N ) { int even = 0 ; int odd = 0 ; for ( auto it : N ) { if ( ( it - '0' ) % 2 == 0 ) { even ++ ; } else { odd ++ ; } } if ( odd == 0 odd == 1 ) { cout << " Not β Possible " << " STRNEWLINE " ; } else { int ans = 0 ; for ( auto it : N ) { if ( ( it - '0' ) % 2 == 0 ) { ans ++ ; } else { ans = 0 ; } } if ( odd % 2 ) { ans ++ ; } cout << ans << endl ; } } int main ( ) { string N = "12345" ; minOperations ( N ) ; } |
Find the player with least 0 s after emptying a Binary String by removing non | C ++ program to implement the above approach ; Function to find the player who wins the game ; Stores total count of 0 s in the string ; Stores count of consecutive 1 s ; Stores Nim - Sum on count of consecutive 1 s ; Stores length of the string ; Traverse the string ; If the current character is 1 ; Update cntConOne ; Update nimSum ; Update cntConOne ; Update cntZero ; Update nimSum ; If countZero is an even number ; nimSum is not 0 ; If nimSum is zero ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void FindwinnerOfGame ( string & S ) { int cntZero = 0 ; int cntConOne = 0 ; int nimSum = 0 ; int N = S . length ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] == '1' ) { cntConOne += 1 ; } else { nimSum ^= cntConOne ; cntConOne = 0 ; cntZero ++ ; } } nimSum ^= cntConOne ; if ( cntZero % 2 == 0 ) { cout << " Tie " ; } else if ( nimSum ) { cout << " player β 1" ; } else { cout << " player β 2" ; } } int main ( ) { string S = "0110011" ; FindwinnerOfGame ( S ) ; } |
Place first N natural numbers at indices not equal to their values in an array | C ++ program for the above approach ; Function to place first N natural numbers in an array such that none of the values are equal to its indices ; Stores the required array ; Place N at the first position ; Iterate the range [ 1 , N ) ; Append elements to the sequence ; Print the sequence ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void generatepermutation ( int N ) { vector < int > answer ; answer . push_back ( N ) ; for ( int i = 1 ; i < N ; i ++ ) { answer . push_back ( i ) ; } for ( int i : answer ) cout << i << " β " ; } int main ( ) { int N = 4 ; generatepermutation ( N ) ; return 0 ; } |
Maximize element at index K in an array with at most sum M and difference between adjacent elements at most 1 | C ++ program for the above approach ; Function to calculate the maximum possible value at index K ; Stores the sum of elements in the left and right of index K ; Stores the maximum possible value at index K ; Print the answer ; Driver Code ; Given N , K & M | #include <bits/stdc++.h> NEW_LINE using namespace std ; void maxValueAtIndexK ( int N , int K , int M ) { int S1 = 0 , S2 = 0 ; S1 = K * ( K + 1 ) / 2 ; S2 = ( N - K - 1 ) * ( N - K ) / 2 ; int X = ( M + S1 + S2 ) / N ; cout << X ; } int main ( ) { int N = 3 , K = 1 , M = 7 ; maxValueAtIndexK ( N , K , M ) ; return 0 ; } |
Farthest cell from a given cell in a Matrix | C ++ program for the above approach ; Function to find the farthest cell distance from the given cell ; From cell ( N , M ) ; From Cell ( 1 , 1 ) ; From cell ( N , 1 ) ; From cell ( 1 , M ) ; Finding out maximum ; Print the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void farthestCellDistance ( int N , int M , int R , int C ) { int d1 = N + M - R - C ; int d2 = R + C - 2 ; int d3 = N - R + C - 1 ; int d4 = M - C + R - 1 ; int maxDistance = max ( d1 , max ( d2 , max ( d3 , d4 ) ) ) ; cout << maxDistance ; } int main ( ) { int N = 15 , M = 12 , R = 1 , C = 6 ; farthestCellDistance ( N , M , R , C ) ; return 0 ; } |
Maximize every array element by repeatedly adding all valid i + a [ i ] th array element | C ++ program for the above approach ; Function to maximize value at every array index by performing given operations ; Traverse the array in reverse ; If the current index is a valid index ; Print the array ; Driver Code ; Given array ; Size of the array | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSum ( int arr [ ] , int N ) { int ans = 0 ; for ( int i = N - 1 ; i >= 0 ; i -- ) { int t = i ; if ( t + arr [ i ] < N ) { arr [ i ] += arr [ t + arr [ i ] ] ; } } for ( int i = 0 ; i < N ; i ++ ) { cout << arr [ i ] << ' β ' ; } } int main ( ) { int arr [ ] = { 1 , 2 , 7 , 1 , 8 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maxSum ( arr , N ) ; return 0 ; } |
Path from the root node to a given node in an N | C ++ program for the above approach ; Function to find the path from root to N ; Stores the number of nodes at ( i + 1 ) - th level ; Stores the number of nodes ; Stores if the current level is even or odd ; If level is odd ; If level is even ; If level with node N is reached ; Push into vector ; Compute prefix sums of count of nodes in each level ; Stores the level in which node N s present ; Store path ; Insert temp into path ; Print path ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; typedef long long ll ; void PrintPathNodes ( ll N ) { vector < ll > arr ; arr . push_back ( 1 ) ; ll k = 1 ; bool flag = true ; while ( k < N ) { if ( flag == true ) { k *= 2 ; flag = false ; } else { k *= 4 ; flag = true ; } if ( k > N ) { break ; } arr . push_back ( k ) ; } ll len = arr . size ( ) ; vector < ll > prefix ( len ) ; prefix [ 0 ] = 1 ; for ( ll i = 1 ; i < len ; ++ i ) { prefix [ i ] = arr [ i ] + prefix [ i - 1 ] ; } vector < ll > :: iterator it = lower_bound ( prefix . begin ( ) , prefix . end ( ) , N ) ; ll ind = it - prefix . begin ( ) ; ll temp = N ; vector < int > path ; path . push_back ( N ) ; while ( ind > 1 ) { ll val = temp - prefix [ ind - 1 ] ; if ( ind % 2 != 0 ) { temp = prefix [ ind - 2 ] + ( val + 1 ) / 2 ; } else { temp = prefix [ ind - 2 ] + ( val + 3 ) / 4 ; } -- ind ; path . push_back ( temp ) ; } if ( N != 1 ) path . push_back ( 1 ) ; for ( int i = path . size ( ) - 1 ; i >= 0 ; i -- ) { cout << path [ i ] << " β " ; } } int main ( ) { ll N = 14 ; PrintPathNodes ( N ) ; return 0 ; } |
Generate an N | C ++ program for the above approach ; Function to construct an array with given conditions ; Traverse the array arr [ ] ; Stores closest power of 2 less than or equal to arr [ i ] ; Stores R into brr [ i ] ; Print array elements ; Driver Code ; Given array ; Size of the array ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void constructArray ( int arr [ ] , int N ) { int brr [ N ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { int K = log ( arr [ i ] ) / log ( 2 ) ; int R = pow ( 2 , K ) ; brr [ i ] = R ; } for ( int i = 0 ; i < N ; i ++ ) { cout << brr [ i ] << " β " ; } } int main ( ) { int arr [ ] = { 11 , 5 , 7 , 3 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; constructArray ( arr , N ) ; return 0 ; } |
Find the element at specified index in a Spiral Matrix | C ++ program for the above approach ; Function to the find element at ( i , j ) index ; Driver Code ; Function Call | #include <iostream> NEW_LINE using namespace std ; int findInGrid ( int i , int j ) { if ( i == j ) return ( i * i - ( i - 1 ) ) ; else if ( i > j ) { if ( i % 2 == 0 ) return i * i - ( j - 1 ) ; else return ( i - 1 ) * ( i - 1 ) + 1 + ( j - 1 ) ; } else { if ( j % 2 == 0 ) return ( j - 1 ) * ( j - 1 ) + 1 + ( i - 1 ) ; else return j * j - ( i - 1 ) ; } } int main ( ) { int i = 3 , j = 4 ; cout << findInGrid ( i , j ) ; return 0 ; } |
Make all array elements equal to 0 by replacing minimum subsequences consisting of equal elements | C ++ program for the above approach ; Function to find minimum count of operations required to convert all array elements to zero br replacing subsequence of equal elements to 0 ; Store distinct elements present in the array ; Traverse the array ; If arr [ i ] is already present in the Set or arr [ i ] is equal to 0 ; Otherwise , increment ans by 1 and insert current element ; Driver Code ; Given array ; Size of the given array | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minOpsToTurnArrToZero ( int arr [ ] , int N ) { unordered_set < int > st ; for ( int i = 0 ; i < N ; i ++ ) { if ( st . find ( arr [ i ] ) != st . end ( ) arr [ i ] == 0 ) { continue ; } else { st . insert ( arr [ i ] ) ; } } cout << st . size ( ) << endl ; } int main ( ) { int arr [ ] = { 3 , 7 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minOpsToTurnArrToZero ( arr , N ) ; return 0 ; } |
Split an array into equal length subsequences consisting of equal elements only | C ++ program for the above approach ; Function to find the GCD of two numbers a and b ; Function to check if it is possible to split the array into equal length subsequences such that all elements in the subsequence are equal ; Store frequencies of array elements ; Traverse the array ; Update frequency of arr [ i ] ; Store the GCD of frequencies of all array elements ; Traverse the map ; Update GCD ; If the GCD is greater than 1 , print YES otherwise print NO ; Driver Code ; Given array ; Store the size of the array | #include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } void splitArray ( int arr [ ] , int N ) { map < int , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { mp [ arr [ i ] ] ++ ; } int G = 0 ; for ( auto i : mp ) { G = gcd ( G , i . second ) ; } if ( G > 1 ) cout << " YES " ; else cout << " NO " ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 4 , 3 , 2 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; splitArray ( arr , n ) ; return 0 ; } |
Minimize count of given operations required to be performed to make all array elements equal to 1 | C ++ program to implement the above approach ; Function to check if all array elements are equal or not ; Traverse the array ; If all array elements are not equal ; Function to find minimum count of operation to make all the array elements equal to 1 ; Stores largest element of the array ; Check if a number is a power of 2 or not ; If Max is a power of 2 and all array elements are equal ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool CheckAllEqual ( int arr [ ] , int N ) { for ( int i = 1 ; i < N ; i ++ ) { if ( arr [ 0 ] != arr [ i ] ) { return false ; } } return true ; } int minCntOperations ( int arr [ ] , int N ) { int Max = * max_element ( arr , arr + N ) ; bool isPower2 = ! ( Max && ( Max & ( Max - 1 ) ) ) ; if ( isPower2 && CheckAllEqual ( arr , N ) ) { return log2 ( Max ) ; } else { return ceil ( log2 ( Max ) ) + 1 ; } } int main ( ) { int arr [ ] = { 2 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minCntOperations ( arr , N ) ; } |
Largest number not exceeding N that does not contain any of the digits of S | C ++ program to implement the above approach ; Function to obtain the largest number not exceeding num which does not contain any digits present in S ; Stores digits of S ; Traverse the string S ; Set occurrence as true ; Traverse the string n ; All digits of num are not present in string s ; Largest Digit not present in the string s ; Set all digits from positions in + 1 to n - 1 as LargestDig ; Counting leading zeroes ; Removing leading zeroes ; If the string becomes null ; Return the largest number ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string greatestReducedNumber ( string num , string s ) { vector < bool > vis_s ( 10 , false ) ; for ( int i = 0 ; i < ( int ) s . size ( ) ; i ++ ) { vis_s [ int ( s [ i ] ) - 48 ] = true ; } int n = num . size ( ) ; int in = -1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( vis_s [ ( int ) num [ i ] - '0' ] ) { in = i ; break ; } } if ( in == -1 ) { return num ; } for ( char dig = num [ in ] ; dig >= '0' ; dig -- ) { if ( vis_s [ ( int ) dig - '0' ] == 0 ) { num [ in ] = dig ; break ; } } char LargestDig = '0' ; for ( char dig = '9' ; dig >= '0' ; dig -- ) { if ( vis_s [ dig - '0' ] == false ) { LargestDig = dig ; break ; } } for ( int i = in + 1 ; i < n ; i ++ ) { num [ i ] = LargestDig ; } int Count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( num [ i ] == '0' ) Count ++ ; else break ; } num . erase ( 0 , Count ) ; if ( ( int ) num . size ( ) == 0 ) return "0" ; return num ; } int main ( ) { string N = "12345" ; string S = "23" ; cout << greatestReducedNumber ( N , S ) ; return 0 ; } |
Generate an array of minimum sum whose XOR of same | C ++ implementation of the above approach ; Function to generate an array whose XOR with same - indexed elements of the given array is always a prime ; Traverse the array ; If current array element is 2 ; Print its XOR with 3 ; Otherwise ; Print its XOR with 2 ; Driver Code ; Given array ; Size of the array ; Prints the required array | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minXOR ( vector < int > & Arr , int N ) { for ( int i = 0 ; i < N ; i ++ ) { if ( Arr [ i ] == 2 ) { cout << ( Arr [ i ] ^ 3 ) << " β " ; } else { cout << ( Arr [ i ] ^ 2 ) << " β " ; } } } int main ( ) { vector < int > Arr = { 5 , 4 , 7 , 6 } ; int N = Arr . size ( ) ; minXOR ( Arr , N ) ; return 0 ; } |
Find the largest element in an array generated using the given conditions | C ++ program to implement the above approach ; Function to generate the required array ; Stores the array ; Base case ; Iterate over the indices ; If current index is even ; Otherwise ; Function to find and return the maximum array element ; If n is 0 ; If n is 1 ; Generates the required array ; Return maximum element of Arr ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > findArray ( int n ) { vector < int > Arr ( n + 1 ) ; Arr [ 0 ] = 0 ; Arr [ 1 ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { if ( i % 2 == 0 ) { Arr [ i ] = Arr [ i / 2 ] ; } else { Arr [ i ] = Arr [ ( i - 1 ) / 2 ] + Arr [ ( i - 1 ) / 2 + 1 ] ; } } return Arr ; } int maxElement ( int n ) { if ( n == 0 ) return 0 ; if ( n == 1 ) return 1 ; vector < int > Arr = findArray ( n ) ; return * max_element ( Arr . begin ( ) , Arr . end ( ) ) ; } int main ( ) { int N = 7 ; cout << maxElement ( N ) ; return 0 ; } |
Construct a graph using N vertices whose shortest distance between K pair of vertices is 2 | C ++ program to implement the above approach ; Function to construct the simple and connected graph such that the distance between exactly K pairs of vertices is 2 ; Stores maximum possible count of edges in a graph ; Base Case ; Stores edges of a graph ; Connect all vertices of pairs ( i , j ) ; Print first ( ( N - 1 ) + Max - K ) elements of edges [ ] ; Driver Code | #include <iostream> NEW_LINE #include <vector> NEW_LINE using namespace std ; void constGraphWithCon ( int N , int K ) { int Max = ( ( N - 1 ) * ( N - 2 ) ) / 2 ; if ( K > Max ) { cout << -1 << endl ; return ; } vector < pair < int , int > > ans ; for ( int i = 1 ; i < N ; i ++ ) { for ( int j = i + 1 ; j <= N ; j ++ ) { ans . emplace_back ( make_pair ( i , j ) ) ; } } for ( int i = 0 ; i < ( N - 1 ) + Max - K ; i ++ ) { cout << ans [ i ] . first << " β " << ans [ i ] . second << endl ; } } int main ( ) { int N = 5 , K = 3 ; constGraphWithCon ( N , K ) ; return 0 ; } |
Minimum steps required to visit all corners of an N * M grid | C ++ program to implement the above approach ; Function to find the minimum count of steps required to visit all the corners of the grid ; Stores corner of the grid ; Stores minimum count of steps required to visit the first corner of the grid ; Checking for leftmost upper corner ; Checking for leftmost down corner ; Checking for rightmost upper corner ; Checking for rightmost down corner ; Stores minimum count of steps required to visit remaining three corners of the grid ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int min_steps_required ( int n , int m , int r , int c ) { int i , j ; int corner_steps_req = INT_MAX ; i = 1 ; j = 1 ; corner_steps_req = min ( corner_steps_req , abs ( r - i ) + abs ( j - c ) ) ; i = n ; j = 1 ; corner_steps_req = min ( corner_steps_req , abs ( r - i ) + abs ( j - c ) ) ; i = 1 ; j = m ; corner_steps_req = min ( corner_steps_req , abs ( r - i ) + abs ( j - c ) ) ; i = n ; j = m ; corner_steps_req = min ( corner_steps_req , abs ( r - i ) + abs ( j - c ) ) ; int minimum_steps = min ( 2 * ( n - 1 ) + m - 1 , 2 * ( m - 1 ) + n - 1 ) ; return minimum_steps + corner_steps_req ; } int main ( ) { int n = 3 ; int m = 2 ; int r = 1 ; int c = 1 ; cout << min_steps_required ( n , m , r , c ) ; return 0 ; } |
Minimum replacements required to have at most K distinct elements in the array | C ++ program to implement the above approach ; Function to find minimum count of array elements required to be replaced such that count of distinct elements is at most K ; Store the frequency of each distinct element of the array ; Traverse the array ; Update frequency of arr [ i ] ; Store frequency of each distinct element of the array ; Traverse the map ; Stores key of the map ; Insert mp [ i ] into Freq [ ] ; Sort Freq [ ] in descending order ; Stores size of Freq [ ] ; If len is less than or equal to K ; Stores minimum count of array elements required to be replaced such that count of distinct elements is at most K ; Iterate over the range [ K , len ] ; Update cntMin ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int min_elements ( int arr [ ] , int N , int K ) { map < int , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { mp [ arr [ i ] ] ++ ; } vector < int > Freq ; for ( auto it : mp ) { int i = it . first ; Freq . push_back ( mp [ i ] ) ; } sort ( Freq . rbegin ( ) , Freq . rend ( ) ) ; int len = Freq . size ( ) ; if ( len <= K ) { return 0 ; } int cntMin = 0 ; for ( int i = K ; i < len ; i ++ ) { cntMin += Freq [ i ] ; } return cntMin ; } int main ( ) { int arr [ ] = { 5 , 1 , 3 , 2 , 4 , 1 , 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; cout << min_elements ( arr , N , K ) ; return 0 ; } |
Check if sum of the given array can be reduced to 0 by reducing array elements by K | C ++ program for the above approach ; Function to check if the sum can be made 0 or not ; Stores sum of array elements ; Traverse the array ; Driver Code ; Given array arr [ ] | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sumzero ( int arr [ ] , int N , int K ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += arr [ i ] ; } if ( sum == 0 ) cout << " Yes " ; else if ( sum > 0 ) { if ( sum % K == 0 ) cout << " Yes " ; else cout << " No " ; } else cout << " No " ; return 0 ; } int main ( ) { int K , N ; int arr1 [ ] = { 1 , -6 , 2 , 2 } ; K = 1 ; N = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; sumzero ( arr1 , N , K ) ; return 0 ; } |
Counts 1 s that can be obtained in an Array by performing given operations | C ++ program to implement the above approach ; Function to count total number of 1 s in array by performing given operations ; Stores count of 1 s in the array by performing the operations ; Iterate over the range [ 1 , N ] ; Flip all array elements whose index is multiple of i ; Update arr [ i ] ; Traverse the array ; If current element is 1 ; Update cntOnes ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int cntOnesArrWithGivenOp ( int arr [ ] , int N ) { int cntOnes = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { for ( int j = i - 1 ; j < N ; j += i ) { arr [ j ] = ! ( arr [ j ] ) ; } } for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == 1 ) { cntOnes += 1 ; } } return cntOnes ; } int main ( ) { int arr [ ] = { 0 , 0 , 0 , 0 , 0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << cntOnesArrWithGivenOp ( arr , N ) ; return 0 ; } |
Counts 1 s that can be obtained in an Array by performing given operations | C ++ program to implement the above approach ; Function to count total number of 1 s in array by performing the given operations ; Stores count of 1 s in the array by performing the operations ; Update cntOnes ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int cntOnesArrWithGivenOp ( int arr [ ] , int N ) { int cntOnes = 0 ; cntOnes = sqrt ( N ) ; return cntOnes ; } int main ( ) { int arr [ ] = { 0 , 0 , 0 , 0 , 0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << cntOnesArrWithGivenOp ( arr , N ) ; return 0 ; } |
Count Knights that can attack a given pawn in an N * N board | C ++ program to implement the above approach ; Function to count the knights that are attacking the pawn in an M * M board ; Stores count of knights that are attacking the pawn ; Traverse the knights [ ] [ ] array ; Stores absolute difference of X co - ordinate of i - th knight and pawn ; Stores absolute difference of Y co - ordinate of i - th knight and pawn ; If X is 1 and Y is 2 or X is 2 and Y is 1 ; Update cntKnights ; Driver Code ; Stores total count of knights | #include <bits/stdc++.h> NEW_LINE using namespace std ; int cntKnightsAttackPawn ( int knights [ ] [ 2 ] , int pawn [ ] , int M ) { int cntKnights = 0 ; for ( int i = 0 ; i < M ; i ++ ) { int X = abs ( knights [ i ] [ 0 ] - pawn [ 0 ] ) ; int Y = abs ( knights [ i ] [ 1 ] - pawn [ 1 ] ) ; if ( ( X == 1 && Y == 2 ) || ( X == 2 && Y == 1 ) ) { cntKnights ++ ; } } return cntKnights ; } int main ( ) { int knights [ ] [ 2 ] = { { 0 , 4 } , { 4 , 5 } , { 1 , 4 } , { 3 , 1 } } ; int pawn [ ] = { 2 , 3 } ; int M = sizeof ( knights ) / sizeof ( knights [ 0 ] ) ; cout << cntKnightsAttackPawn ( knights , pawn , M ) ; return 0 ; } |
Find the winner of game of removing array elements having GCD equal to 1 | C ++ program to implement the above approach ; Function to find the winner of the game by removing array elements whose GCD is 1 ; mp [ i ] : Stores count of array elements whose prime factor is i ; Traverse the array ; Calculate the prime factors of arr [ i ] ; If arr [ i ] is divisible by j ; Update mp [ j ] ; Update arr [ i ] ; If arr [ i ] exceeds 1 ; Stores maximum value present in the Map ; Traverse the map ; Update maxCnt ; If n is an even number ; If maxCnt is greater than or equal to n - 1 ; Player 1 wins ; Player 2 wins ; If maxCnt equal to n ; Player 1 wins ; Player 2 wins ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findWinnerGameRemoveGCD ( int arr [ ] , int n ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 2 ; j * j <= arr [ i ] ; j ++ ) { if ( arr [ i ] % j == 0 ) { mp [ j ] ++ ; while ( arr [ i ] % j == 0 ) { arr [ i ] = arr [ i ] / j ; } } } if ( arr [ i ] > 1 ) { mp [ arr [ i ] ] ++ ; } } int maxCnt = 0 ; for ( auto i : mp ) { maxCnt = max ( maxCnt , i . second ) ; } if ( n % 2 == 0 ) { if ( maxCnt >= n - 1 ) { cout << " Player β 1" ; } else { cout << " Player β 2" ; } } else { if ( maxCnt == n ) { cout << " Player β 1" ; } else { cout << " Player β 2" ; } } } int main ( ) { int arr [ ] = { 2 , 4 , 8 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findWinnerGameRemoveGCD ( arr , N ) ; return 0 ; } |
Maximum possible sum of K even multiples of 5 in a given range | C ++ program to implement the above approach ; Function to find the maximum sum of K even multiples of 5 in the range [ L , R ] ; Store the total number of even multiples of 5 in the range [ L , R ] ; Check if K > N ; If true , print - 1 and return ; Otherwise , divide R by 10 ; Store the sum using the formula ; Print the sum ; Driver Code ; Given L , R and K ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void maxksum ( int L , int R , int K ) { int N = ( R / 10 - L / 10 ) + 1 ; if ( K > N ) { cout << -1 ; return ; } R = R / 10 ; int X = R - K ; int sum = 10 * ( ( R * ( R + 1 ) ) / 2 - ( X * ( X + 1 ) ) / 2 ) ; cout << sum ; } int main ( ) { int L = 16 , R = 60 , K = 4 ; maxksum ( L , R , K ) ; return 0 ; } |
Minimum swaps of same | C ++ program for the above approach ; Function to count the minimum swaps of same - indexed elements from arrays arr1 [ ] and arr2 [ ] required to make the sum of both the arrays even ; Store the sum of elements of the array arr1 and arr2 respectively ; Store the array sum of both the arrays ; If both sumArr1 and sumArr2 are even , print 0 and return ; If both sumArr1 and sumArr2 are odd and check for a pair with sum odd sum ; Stores if a pair with odd sum exists or not ; Traverse the array ; If a pair exists with odd sum , set flag = 1 ; Print the answer and return ; For all other cases , print - 1 ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumSwaps ( int arr1 [ ] , int arr2 [ ] , int n ) { int sumArr1 = 0 , sumArr2 = 0 ; for ( int i = 0 ; i < n ; ++ i ) { sumArr1 += arr1 [ i ] ; sumArr2 += arr2 [ i ] ; } if ( sumArr1 % 2 == 0 && sumArr2 % 2 == 0 ) { cout << 0 ; return ; } if ( sumArr1 % 2 != 0 && sumArr2 % 2 != 0 ) { int flag = -1 ; for ( int i = 0 ; i < n ; ++ i ) { if ( ( arr1 [ i ] + arr2 [ i ] ) % 2 == 1 ) { flag = 1 ; break ; } } cout << flag ; return ; } cout << -1 ; } int main ( ) { int arr1 [ ] = { 11 , 14 , 20 , 2 } ; int arr2 [ ] = { 5 , 9 , 6 , 3 } ; int N = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; minimumSwaps ( arr1 , arr2 , N ) ; return 0 ; } |
Count of seats booked on each of the given N flights | C ++ program for the above approach ; Function to find the total of the seats booked in each of the flights ; Stores the resultant sequence ; Traverse the array ; Store the first booked flight ; Store the last booked flight ; Store the total number of seats booked in flights [ l , r ] ; Add K to the flight L ; Subtract K from flight number R + 1 ; Find the prefix sum of the array ; Print the total number of seats booked in each flight ; Driver Code ; Given list of bookings ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void corpFlightBookings ( vector < vector < int > > & Bookings , int N ) { vector < int > res ( N , 0 ) ; for ( int i = 0 ; i < Bookings . size ( ) ; i ++ ) { int l = Bookings [ i ] [ 0 ] ; int r = Bookings [ i ] [ 1 ] ; int K = Bookings [ i ] [ 2 ] ; res [ l - 1 ] = res [ l - 1 ] + K ; if ( r <= res . size ( ) - 1 ) res [ r ] = ( - K ) + res [ r ] ; } for ( int i = 1 ; i < res . size ( ) ; i ++ ) res [ i ] = res [ i ] + res [ i - 1 ] ; for ( int i = 0 ; i < res . size ( ) ; i ++ ) { cout << res [ i ] << " β " ; } } int main ( ) { vector < vector < int > > bookings { { 1 , 3 , 100 } , { 2 , 6 , 100 } , { 3 , 4 , 100 } } ; int N = 6 ; corpFlightBookings ( bookings , N ) ; return 0 ; } |
Bitwise XOR of all odd numbers from a given range | C ++ program for the above approach ; Function to calculate Bitwise XOR of odd numbers in the range [ 1 , N ] ; N & 3 is equivalent to n % 4 ; If n is multiple of 4 ; If n % 4 gives remainder 1 ; If n % 4 gives remainder 2 ; If n % 4 gives remainder 3 ; Function to find the XOR of odd numbers less than or equal to N ; If number is even ; Print the answer ; If number is odd ; Print the answer ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findXOR ( int n ) { switch ( n & 3 ) { case 0 : return n ; case 1 : return 1 ; case 2 : return n + 1 ; case 3 : return 0 ; } } void findOddXOR ( int n ) { if ( n % 2 == 0 ) cout << ( ( findXOR ( n ) ) ^ ( 2 * findXOR ( n / 2 ) ) ) ; else cout << ( ( findXOR ( n ) ) ^ ( 2 * findXOR ( ( n - 1 ) / 2 ) ) ) ; } int main ( ) { int N = 11 ; findOddXOR ( N ) ; return 0 ; } |
Smallest number greater than or equal to N which is divisible by its non | C ++ program for the above approach ; Function to find the smallest number greater than or equal to N such that it is divisible by its non - zero digits ; Iterate in range [ N , N + 2520 ] ; To check if the current number satisfies the given condition ; Store the number in a temporary variable ; Loop until temp > 0 ; Check only for non zero digits ; Extract the current digit ; If number is divisible by current digit or not ; Otherwise , set possible to 0 ; Break out of the loop ; Divide by 10 ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findSmallestNumber ( int n ) { for ( int i = n ; i <= ( n + 2520 ) ; ++ i ) { bool possible = 1 ; int temp = i ; while ( temp ) { if ( temp % 10 != 0 ) { int digit = temp % 10 ; if ( i % digit != 0 ) { possible = 0 ; break ; } } temp /= 10 ; } if ( possible == 1 ) { cout << i ; return ; } } } int main ( ) { int N = 31 ; findSmallestNumber ( N ) ; return 0 ; } |
Print path from a node to root of given Complete Binary Tree | C ++ program for the above approach ; Function to print the path from node to root ; Iterate until root is reached ; Print the value of the current node ; Move to parent of the current node ; Driver Code | #include <iostream> NEW_LINE using namespace std ; void path_to_root ( int node ) { while ( node >= 1 ) { cout << node << ' β ' ; node /= 2 ; } } int main ( ) { int N = 7 ; path_to_root ( N ) ; return 0 ; } |
Smallest number whose sum of digits is N and every digit occurring at most K times | C ++ program for the above approach ; Function to find the smallest number whose sum of digits is N and each digit occurring at most K times ; Maximum sum possible using each digit at most K times ; Append smallest number into the resultant string ; Iterate over the range [ 9 , 1 ] ; If the count of the digit is K , then update count and check for the next digit ; If N is greater than current digit ; Subtract i from N ; Insert i as a digit ; Insert remaining N as a digit ; Increment count ; Reverse the string ; Print the answer ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findSmallestNumberPossible ( int N , int K ) { if ( N > 45 * K ) { cout << " - 1" ; return ; } string res = " " ; int count = 0 ; for ( int i = 9 ; i >= 1 ; ) { if ( count == K ) { i -- ; count = 0 ; } if ( N > i ) { N -= i ; res += ( char ) 48 + i ; } else { res += ( char ) N + 48 ; N = 0 ; break ; } count ++ ; } reverse ( res . begin ( ) , res . end ( ) ) ; cout << res ; } int main ( ) { int N = 25 , K = 3 ; findSmallestNumberPossible ( N , K ) ; return 0 ; } |
Minimum sum of values subtracted from array elements to make all array elements equal | C ++ program for the above approach ; Function to find the sum of values removed to make all array elements equal ; Stores the minimum of the array ; Stores required sum ; Traverse the array ; Add the value subtracted from the current element ; Return the total sum ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minValue ( int arr [ ] , int n ) { int minimum = * min_element ( arr , arr + n ) ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum = sum + ( arr [ i ] - minimum ) ; } return sum ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minValue ( arr , N ) ; return 0 ; } |
Smallest positive number made up of non | C ++ program for the above approach ; Function to find smallest positive number made up of non - repeating digits whose sum of its digits is equal to n ; No such number exists ; Stores the required answer ; Store the digit at unit 's place ; Iterate until n > digit ; Push digit at the start of res ; Decrement n by digit ; Decrement digit by 1 ; Push the remaining number as the starting digit ; Print the required number ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void result ( int n ) { if ( n > 45 ) { cout << -1 ; return ; } string res ; int digit = 9 ; while ( n > digit ) { res = char ( '0' + digit ) + res ; n -= digit ; digit -= 1 ; } if ( n > 0 ) { res = char ( '0' + n ) + res ; } cout << res ; } int main ( ) { int N = 19 ; result ( N ) ; return 0 ; } |
Count pair of integers having even sum | C ++ program for the above approach ; Function to count even pairs ; Stores count of pairs having even sum ; Stores count of even numbers up to N ; Stores count of odd numbers up to N ; Stores count of even numbers up to M ; Stores count of odd numbers up to M ; Return the count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countEvenPairs ( int N , int M ) { int count = 0 ; int nEven = floor ( N / 2 ) ; int nOdd = ceil ( N / 2 ) ; int mEven = floor ( M / 2 ) ; int mOdd = ceil ( M / 2 ) ; count = nEven * mEven + nOdd * mOdd ; return count ; } int main ( ) { int N = 4 ; int M = 6 ; cout << countEvenPairs ( N , M ) ; return 0 ; } |
Generate an N | C ++ program to implement the above approach ; Function to generate a string of length N having longest palindromic substring of length K ; Fill first K characters with ' a ' ; Stores a non - palindromic sequence to be repeated for N - k slots ; Print N - k remaining characters ; Driver Code ; Given N and K | #include <bits/stdc++.h> NEW_LINE using namespace std ; void string_palindrome ( int N , int K ) { for ( int i = 0 ; i < K ; i ++ ) cout << " a " ; string s = " bcd " ; for ( int i = 0 ; i < N - K ; i ++ ) cout << s [ i % 3 ] ; } int main ( ) { int N = 5 , K = 3 ; string_palindrome ( N , K ) ; return 0 ; } |
Last remaining character after repeated removal of the first character and flipping of characters of a Binary String | C ++ program to implement the above approach ; Function to find the last removed character from the string ; Stores length of the string ; Base Case : ; If the second last character is '0' ; If the second last character is '1' ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; char lastRemovedCharacter ( string str ) { int n = str . length ( ) ; if ( n == 1 ) return str [ 0 ] ; if ( str [ n - 2 ] == '0' ) { return ( '1' - str [ n - 1 ] + '0' ) ; } else return str [ n - 1 ] ; } int main ( ) { string str = "10010" ; cout << lastRemovedCharacter ( str ) ; } |
Find the triplet from given Bitwise XOR and Bitwise AND values of all its pairs | C ++ program to implement the above approach ; Function to find the triplet with given Bitwise XOR and Bitwise AND values of all possible pairs of the triplet ; Stores values of a triplet ; Stores a + b ; Stores a + c ; Stores b + c ; Calculate aSUMb ; Calculate aSUMc ; Calculate bSUMc ; Calculate a ; Calculate b ; Calculate c ; Print a ; Print b ; Print c ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findNumbers ( int aXORb , int aANDb , int aXORc , int aANDc , int bXORc , int bANDc ) { int a , b , c ; int aSUMb ; int aSUMc ; int bSUMc ; aSUMb = aXORb + aANDb * 2 ; aSUMc = aXORc + aANDc * 2 ; bSUMc = bXORc + bANDc * 2 ; a = ( aSUMb - bSUMc + aSUMc ) / 2 ; b = aSUMb - a ; c = aSUMc - a ; cout << " a β = β " << a ; cout << " , β b β = β " << b ; cout << " , β c β = β " << c ; } int main ( ) { int aXORb = 30 , aANDb = 0 , aXORc = 20 , aANDc = 10 , bXORc = 10 , bANDc = 20 ; findNumbers ( aXORb , aANDb , aXORc , aANDc , bXORc , bANDc ) ; } |
Find N distinct numbers whose Bitwise XOR is equal to K | C ++ program for the above approach ; Function to find N integers having Bitwise XOR equal to K ; Base Cases ; Assign values to P and Q ; Stores Bitwise XOR of the first ( N - 3 ) elements ; Print the first N - 3 elements ; Calculate Bitwise XOR of first ( N - 3 ) elements ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findArray ( int N , int K ) { if ( N == 1 ) { cout << " β " << K ; return ; } if ( N == 2 ) { cout << 0 << " β " << K ; return ; } int P = N - 2 ; int Q = N - 1 ; int VAL = 0 ; for ( int i = 1 ; i <= ( N - 3 ) ; i ++ ) { cout << " β " << i ; VAL ^= i ; } if ( VAL == K ) { cout << P << " β " << Q << " β " << ( P ^ Q ) ; } else { cout << 0 << " β " << P << " β " << ( P ^ K ^ VAL ) ; } } int main ( ) { int N = 4 , X = 6 ; findArray ( N , X ) ; return 0 ; } |
Flip consecutive set bits starting from LSB of a given number | C ++ program for the above approach ; Function to find the number after converting 1 s from end to 0 s ; Count of 1 s ; AND operation of N and 1 ; Left shift N by count ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findNumber ( int N ) { int count = 0 ; while ( ( N & 1 ) == 1 ) { N = N >> 1 ; count ++ ; } return N << count ; } int main ( ) { int N = 39 ; cout << findNumber ( N ) ; return 0 ; } |
Flip consecutive set bits starting from LSB of a given number | C ++ program for the above approach ; Function to find the number after converting 1 s from end to 0 s ; Return the logical AND of N and ( N + 1 ) ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findNumber ( int N ) { return N & ( N + 1 ) ; } int main ( ) { int N = 39 ; cout << findNumber ( N ) ; return 0 ; } |
Count of substrings of a string containing another given string as a substring | C ++ program for the above approach ; Function to store all substrings of S ; Stores the substrings of S ; Pick start point in outer loop and lengths of different strings for a given starting point ; Return the array containing substrings of S ; Function to check if a string is present in another string ; Check if target is in the string str or not ; Function to count the substring of S containing T in it as substring ; Store all substrings of S in the array v [ ] ; Store required count of substrings ; Iterate through all the substrings of S ; If string T is present in the current substring , then increment the ans ; Print the answer ; Driver code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < string > subString ( string s , int n ) { vector < string > v ; for ( int i = 0 ; i < n ; i ++ ) { for ( int len = 1 ; len <= n - i ; len ++ ) { string find = s . substr ( i , len ) ; v . push_back ( find ) ; } } return v ; } int IsPresent ( string & str , string & target ) { if ( str . find ( target ) != string :: npos ) { return 1 ; } return -1 ; } void countSubstrings ( string & S , string & T ) { vector < string > v = subString ( S , S . length ( ) ) ; int ans = 0 ; for ( auto it : v ) { if ( IsPresent ( it , T ) != -1 ) { ans ++ ; } } cout << ans ; } int main ( ) { string S = " dabc " ; string T = " ab " ; countSubstrings ( S , T ) ; return 0 ; } |
Minimum flips of odd indexed elements from odd length subarrays to make two given arrays equal | C ++ program for the above approach ; Function to find the minimum flip of subarrays required at alternate index to make binary arrays equals ; Stores count of total operations ; Stores count of consecutive unequal elements ; Loop to run on odd positions ; Incrementing the global counter ; Change count to 0 ; If all last elements are equal ; Loop to run on even positions ; Incrementing the global counter ; Change count to 0 ; Print the minimum operations ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minOperation ( int X [ ] , int Y [ ] , int n ) { int C = 0 ; int count = 0 ; for ( int i = 1 ; i < n ; i = i + 2 ) { if ( X [ i ] != Y [ i ] ) { count ++ ; } else { if ( count != 0 ) C ++ ; count = 0 ; } } if ( count != 0 ) C ++ ; count = 0 ; for ( int i = 0 ; i < n ; i = i + 2 ) { if ( X [ i ] != Y [ i ] ) { count ++ ; } else { if ( count != 0 ) C ++ ; count = 0 ; } } if ( count != 0 ) C ++ ; cout << C ; } int main ( ) { int X [ ] = { 1 , 0 , 0 , 0 , 0 , 1 } ; int Y [ ] = { 1 , 1 , 0 , 1 , 1 , 1 } ; int N = sizeof ( X ) / sizeof ( X [ 0 ] ) ; minOperation ( X , Y , N ) ; return 0 ; } |
Minimum subarray reversals required to make given binary array alternating | C ++ program to implement the above approach ; Function to count minimum subarray reversal operations required to make array alternating ; Stores minimum count of operations required to make array alternating ; Traverse the array ; If arr [ i ] is greater than arr [ i + 1 ] ; Update cntOp ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumcntOperationReq ( int arr [ ] , int N ) { int cntOp = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( arr [ i ] == arr [ i + 1 ] ) { cntOp ++ ; } } return ( cntOp + 1 ) / 2 ; } int main ( ) { int arr [ ] = { 1 , 1 , 1 , 0 , 1 , 0 , 0 , 0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minimumcntOperationReq ( arr , N ) ; return 0 ; } |
Modify sequence of first N natural numbers to a given array by replacing pairs with their GCD | C ++ program for the above approach ; Function to check if array arr [ ] can be obtained from first N natural numbers or not ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void isSequenceValid ( vector < int > & B , int N ) { for ( int i = 0 ; i < N ; i ++ ) { if ( ( i + 1 ) % B [ i ] != 0 ) { cout << " No " ; return ; } } cout << " Yes " ; } int main ( ) { int N = 4 ; vector < int > arr { 1 , 2 , 3 , 2 } ; isSequenceValid ( arr , N ) ; return 0 ; } |
Construct an array of first N natural numbers such that every adjacent pair is coprime | C ++ program to implement the above approach ; Function to construct an arrary with adjacent elements as co - prime numbers ; Iterate over the range [ 1 , N ] ; Print i ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void ConstArrayAdjacentCoprime ( int N ) { for ( int i = 1 ; i <= N ; i ++ ) { cout << i << " β " ; } } int main ( ) { int N = 6 ; ConstArrayAdjacentCoprime ( N ) ; return 0 ; } |
Maximize count of rows consisting of equal elements by flipping columns of a Matrix | C ++ program to implement the above approach ; Function to find the maximum number of rows containing all equal elements ; Store each row of the matrix ; Traverse each row of the matrix ; Update frequency of current row ; Stores maximum count of rows containing all equal elements ; Traverse each row of the matrix ; Stores 1 's complement of the current row ; Traverse current row of the given matrix ; Stores 1 s complement of mat [ i ] [ j ] ; Update cntMaxRows ; Driver Code ; Stores count of rows ; Stores count of columns | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxEqrows ( vector < vector < int > > & mat , int N , int M ) { map < vector < int > , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { mp [ mat [ i ] ] ++ ; } int cntMaxRows = 0 ; for ( int i = 0 ; i < N ; i ++ ) { vector < int > onesCompRow ( M , 0 ) ; for ( int j = 0 ; j < M ; j ++ ) { onesCompRow [ j ] = ( mat [ i ] [ j ] ^ 1 ) ; } cntMaxRows = max ( cntMaxRows , mp [ mat [ i ] ] + mp [ onesCompRow ] ) ; } return cntMaxRows ; } int main ( ) { vector < vector < int > > mat = { { 0 , 1 , 0 , 0 , 1 } , { 1 , 1 , 0 , 1 , 1 } , { 1 , 0 , 1 , 1 , 0 } } ; int N = mat . size ( ) ; int M = mat [ 0 ] . size ( ) ; cout << maxEqrows ( mat , N , M ) ; } |
Minimum cost to convert one given string to another using swap , insert or delete operations | C ++ program for the above approach ; Function to find the minimum cost to convert string a to b ; Stores the frequency of string a and b respectively ; Store the frequencies of characters in a ; Store the frequencies of characters in b ; Minimum cost to convert A to B ; Find the minimum cost ; Print the minimum cost ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumCost ( string a , string b ) { vector < int > fre1 ( 256 ) , fre2 ( 256 ) ; for ( char c : a ) fre1 [ ( int ) ( c ) ] ++ ; for ( char c : b ) fre2 [ ( int ) ( c ) ] ++ ; int mincost = 0 ; for ( int i = 0 ; i < 256 ; i ++ ) { mincost += abs ( fre1 [ i ] - fre2 [ i ] ) ; } cout << mincost << endl ; } int main ( ) { string A = "1AB + - " , B = " cc " ; minimumCost ( A , B ) ; return 0 ; } |
Minimum cost required to move all elements to the same position | C ++ program to implement the above approach ; Function to find the minimum cost required to place all elements in the same position ; Stores the count of even and odd elements ; Traverse the array arr [ ] ; Count even elements ; Count odd elements ; Print the minimum count ; Driver Code ; Given array ; Function Call | #include <iostream> NEW_LINE using namespace std ; int minCost ( int arr [ ] , int arr_size ) { int odd = 0 , even = 0 ; for ( int i = 0 ; i < arr_size ; i ++ ) { if ( arr [ i ] % 2 == 0 ) even ++ ; else odd ++ ; } cout << min ( even , odd ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minCost ( arr , arr_size ) ; } |
Maximize array sum by alternating the signs of adjacent elements | C ++ program to implement the above approach ; Function to find the maximum sum by alternating the signs of adjacent elements of the array ; Stores count of negative elements in the array ; Stores maximum sum by alternating the signs of adjacent elements ; Stores smallest absolute value of array elements ; Stores sum of absolute value of array elements ; Traverse the array ; If arr [ i ] is a negative number ; Update cntNeg ; Update sum ; Update SmValue ; Update MaxAltSum ; If cntNeg is an odd number ; Update MaxAltSum ; Drivers Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaxSumByAlternatingSign ( int arr [ ] , int N ) { int cntNeg = 0 ; int MaxAltSum = 0 ; int SmValue = 0 ; int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] < 0 ) { cntNeg += 1 ; } sum += abs ( arr [ i ] ) ; SmValue = min ( SmValue , abs ( arr [ i ] ) ) ; } MaxAltSum = sum ; if ( cntNeg & 1 ) { MaxAltSum -= 2 * SmValue ; } return MaxAltSum ; } int main ( ) { int arr [ ] = { 1 , 1 , -2 , -4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findMaxSumByAlternatingSign ( arr , N ) ; } |
Construct array with sum of product of same indexed elements in the given array equal to zero | C ++ program to implement the above approach ; Function to generate a new array with product of same indexed elements with arr [ ] equal to 0 ; Stores sum of same indexed array elements of arr and new array ; Traverse the array ; If i is an even number ; Insert arr [ i + 1 ] into the new array newArr [ ] ; Insert - arr [ i - 1 ] into the new array newArr [ ] ; Print new array elements ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void constructNewArraySumZero ( int arr [ ] , int N ) { int newArr [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { if ( i % 2 == 0 ) { newArr [ i ] = arr [ i + 1 ] ; } else { newArr [ i ] = - arr [ i - 1 ] ; } } for ( int i = 0 ; i < N ; i ++ ) { cout << newArr [ i ] << " β " ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , -5 , -6 , 8 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; constructNewArraySumZero ( arr , N ) ; return 0 ; } |
Generate Bitonic Sequence of length N from integers in a given range | C ++ program for the above approach ; Function to construct bitonic sequence of length N from integers in the range [ L , R ] ; If sequence is not possible ; Store the resultant list ; If size of deque < n ; Add elements from start ; Print the stored in the list ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void bitonicSequence ( int num , int lower , int upper ) { if ( num > ( upper - lower ) * 2 + 1 ) { cout << -1 ; return ; } deque < int > ans ; deque < int > :: iterator j = ans . begin ( ) ; for ( int i = 0 ; i < min ( upper - lower + 1 , num - 1 ) ; i ++ ) ans . push_back ( upper - i ) ; for ( int i = 0 ; i < num - ans . size ( ) ; i ++ ) ans . push_front ( upper - i - 1 ) ; cout << ' [ ' ; for ( j = ans . begin ( ) ; j != ans . end ( ) ; ++ j ) cout << ' β ' << * j ; cout << ' β ' << ' ] ' ; } int main ( ) { int N = 5 , L = 3 , R = 10 ; bitonicSequence ( N , L , R ) ; return 0 ; } |
Count substrings of same length differing by a single character from two given strings | C ++ pprogram for the above approach ; Function to count the number of substrings of equal length which differ by a single character ; Stores the count of pairs of substrings ; Traverse the string s ; Traverse the string t ; Different character ; Increment the answer ; Count equal substrings from next index ; Increment the count ; Increment q ; Check the condition ; Increment k ; Add q to count ; Decrement z ; Return the final count ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubstrings ( string s , string t ) { int answ = 0 ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { for ( int j = 0 ; j < t . size ( ) ; j ++ ) { if ( t [ j ] != s [ i ] ) { answ += 1 ; int k = 1 ; int z = -1 ; int q = 1 ; while ( j + z >= 0 && 0 <= i + z && s [ i + z ] == t [ j + z ] ) { z -= 1 ; answ += 1 ; q += 1 ; } while ( s . size ( ) > i + k && j + k < t . size ( ) && s [ i + k ] == t [ j + k ] ) { k += 1 ; answ += q ; z = -1 ; } } } } return answ ; } int main ( ) { string S = " aba " ; string T = " baba " ; cout << ( countSubstrings ( S , T ) ) ; } |
Minimum flips to make all 1 s in right and 0 s in left | C ++ program to implement the above approach ; Function to find the minimum count of flips required to make all 1 s on the right and all 0 s on the left of the given string ; Stores length of str ; Store count of 0 s in the string ; Traverse the string ; If current character is 0 ; Update zeros ; If count of 0 s in the string is 0 or n ; Store minimum count of flips required to make all 0 s on the left and all 1 s on the right ; Stores count of 1 s on the left of each index ; Stores count of flips required to make string monotonically increasing ; Traverse the string ; If current character is 1 ; Update currOnes ; Update flips ; Update the minimum count of flips ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumCntOfFlipsRequired ( string str ) { int n = str . length ( ) ; int zeros = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == '0' ) { zeros ++ ; } } if ( zeros == 0 zeros == n ) { return 0 ; } int minFlips = INT_MAX ; int currOnes = 0 ; int flips ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == '1' ) { currOnes ++ ; } flips = currOnes + ( zeros - ( i + 1 - currOnes ) ) ; minFlips = min ( minFlips , flips ) ; } return minFlips ; } int main ( ) { string str = "100101" ; cout << minimumCntOfFlipsRequired ( str ) ; return 0 ; } |
Maximize length of longest non | C ++ program to implement the above approach ; Function to find the length of the longest non - decreasing array that can be generated ; Stores the length of the longest non - decreasing array that can be generated from the array ; Stores index of start pointer ; Stores index of end pointer ; Stores previously inserted element into the new array ; Traverse the array ; If A [ start ] is less than or equal to A [ end ] ; If no element inserted into the newly generated array ; Update prev ; Update res ; Update start ; If A [ start ] is greater than or equal to prev ; Update res ; Update prev ; Update start ; If A [ end ] is greater than or equal to prev ; Update res ; Update prev ; Update end ; If A [ end ] is greater than A [ start ] ; If no element inserted into the newly generated array ; Update prev ; Update res ; Update end ; If A [ end ] is greater than or equal to prev ; Update res ; Update prev ; Update end ; If A [ start ] is greater than or equal to prev ; Update res ; Update prev ; Update start ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findLongestNonDecreasing ( int A [ ] , int N ) { int res = 0 ; int start = 0 ; int end = N - 1 ; int prev = -1 ; while ( start <= end ) { if ( A [ start ] <= A [ end ] ) { if ( prev == -1 ) { prev = A [ start ] ; res ++ ; start ++ ; } else { if ( A [ start ] >= prev ) { res ++ ; prev = A [ start ] ; start ++ ; } else if ( A [ end ] >= prev ) { res ++ ; prev = A [ end ] ; end -- ; } else { break ; } } } else { if ( prev == -1 ) { prev = A [ end ] ; res ++ ; end -- ; } else { if ( A [ end ] >= prev ) { res ++ ; prev = A [ end ] ; end -- ; } else if ( A [ start ] >= prev ) { res ++ ; prev = A [ start ] ; start ++ ; } else { break ; } } } } return res ; } int main ( ) { int A [ ] = { 1 , 1 , 3 , 5 , 4 , 3 , 6 , 2 , 1 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << findLongestNonDecreasing ( A , N ) ; return 0 ; } |
Non | C ++ program for the above approach ; Function to print all pairs whose sum of Bitwise OR and AND is N ; Iterate from i = 0 to N ; Print pairs ( i , N - i ) ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findPairs ( int N ) { for ( int i = 0 ; i <= N ; i ++ ) { cout << " ( " << i << " , β " << N - i << " ) , β " ; } } int main ( ) { int N = 5 ; findPairs ( N ) ; return 0 ; } |
Minimum index to split array into subarrays with co | C ++ program for the above approach ; Function to find the GCD of 2 numbers ; Base Case ; Find the GCD recursively ; Function to find the minimum partition index K s . t . product of both subarrays around that partition are co - prime ; Stores the prefix and suffix array product ; Update the prefix array ; Update the suffix array ; Iterate the given array ; Check if prefix [ k ] and suffix [ k + 1 ] are co - prime ; If no index for partition exists , then return - 1 ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int GCD ( int a , int b ) { if ( b == 0 ) return a ; return GCD ( b , a % b ) ; } int findPartition ( int nums [ ] , int N ) { int prefix [ N ] , suffix [ N ] , i , k ; prefix [ 0 ] = nums [ 0 ] ; for ( i = 1 ; i < N ; i ++ ) { prefix [ i ] = prefix [ i - 1 ] * nums [ i ] ; } suffix [ N - 1 ] = nums [ N - 1 ] ; for ( i = N - 2 ; i >= 0 ; i -- ) { suffix [ i ] = suffix [ i + 1 ] * nums [ i ] ; } for ( k = 0 ; k < N - 1 ; k ++ ) { if ( GCD ( prefix [ k ] , suffix [ k + 1 ] ) == 1 ) { return k ; } } return -1 ; } int main ( ) { int arr [ ] = { 2 , 3 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findPartition ( arr , N ) ; return 0 ; } |
Minimum subarray reversals required such that sum of all pairs of adjacent elements is odd | C ++ program for the above approach ; Function to count reversals to separate elements with same parity ; Traverse the given array ; Count size of subarray having integers with same parity only ; Otherwise ; Reversals required is equal to one less than subarray size ; Return the total reversals ; Function to print the array elements ; Function to count the minimum reversals required to make make sum of all adjacent elements odd ; Stores operations required for separating adjacent odd elements ; Stores operations required for separating adjacent even elements ; Maximum of two is the return ; Driver Code ; Given array arr [ ] ; Size of array ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int separate ( int arr [ ] , int n , int parity ) { int count = 1 , res = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( ( ( arr [ i ] + parity ) & 1 ) && ( ( arr [ i - 1 ] + parity ) & 1 ) ) count ++ ; else { if ( count > 1 ) res += count - 1 ; count = 1 ; } } return res ; } void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; } void requiredOps ( int arr [ ] , int N ) { int res1 = separate ( arr , N , 0 ) ; int res2 = separate ( arr , N , 1 ) ; cout << max ( res1 , res2 ) ; } int main ( ) { int arr [ ] = { 13 , 2 , 6 , 8 , 3 , 5 , 7 , 10 , 14 , 15 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; requiredOps ( arr , N ) ; return 0 ; } |
Count prime pairs whose difference is also a Prime Number | C ++ program to implement the above approach ; Function to find all prime numbers in the range [ 1 , N ] ; isPrime [ i ] : Stores if i is a prime number or not ; Calculate all prime numbers up to Max using Sieve of Eratosthenes ; If P is a prime number ; Set all multiple of P as non - prime ; Update isPrime ; Function to count pairs of prime numbers in the range [ 1 , N ] whose difference is prime ; Function to count pairs of prime numbers whose difference is also a prime number ; isPrime [ i ] : Stores if i is a prime number or not ; Iterate over the range [ 2 , N ] ; If i and i - 2 is a prime number ; Update cntPairs ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < bool > SieveOfEratosthenes ( int N ) { vector < bool > isPrime ( N , true ) ; isPrime [ 0 ] = false ; isPrime [ 1 ] = false ; for ( int p = 2 ; p * p <= N ; p ++ ) { if ( isPrime [ p ] ) { for ( int i = p * p ; i <= N ; i += p ) { isPrime [ i ] = false ; } } } return isPrime ; } int cntPairsdiffOfPrimeisPrime ( int N ) { int cntPairs = 0 ; vector < bool > isPrime = SieveOfEratosthenes ( N ) ; for ( int i = 2 ; i <= N ; i ++ ) { if ( isPrime [ i ] && isPrime [ i - 2 ] ) { cntPairs += 2 ; } } return cntPairs ; } int main ( ) { int N = 5 ; cout << cntPairsdiffOfPrimeisPrime ( N ) ; return 0 ; } |
Length of longest subsequence consisting of distinct adjacent elements | C ++ program for the above approach ; Function that finds the length of longest subsequence having different adjacent elements ; Stores the length of the longest subsequence ; Traverse the array ; If previous and current element are not same ; Increment the count ; Print the maximum length ; Driver Code ; Size of Array ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void longestSubsequence ( int arr [ ] , int N ) { int count = 1 ; for ( int i = 1 ; i < N ; i ++ ) { if ( arr [ i ] != arr [ i - 1 ] ) { count ++ ; } } cout << count << endl ; } int main ( ) { int arr [ ] = { 7 , 8 , 1 , 2 , 2 , 5 , 5 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; longestSubsequence ( arr , N ) ; return 0 ; } |
Count of substrings having the most frequent character in the string as first character | C ++ program for the above approach ; Function to find all substrings whose first character occurs maximum number of times ; Stores frequency of characters ; Stores character that appears maximum number of times ; Stores max frequency of character ; Updates frequency of characters ; Update maxfreq ; Character that occures maximum number of times ; Update the maximum frequency character ; Stores all count of substrings ; Traverse over string ; Get the current character ; Update count of substrings ; Return the count of all valid substrings ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int substringCount ( string s ) { vector < int > freq ( 26 , 0 ) ; char max_char = ' # ' ; int maxfreq = INT_MIN ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { freq [ s [ i ] - ' a ' ] ++ ; if ( maxfreq < freq [ s [ i ] - ' a ' ] ) maxfreq = freq [ s [ i ] - ' a ' ] ; } for ( int i = 0 ; i < 26 ; i ++ ) { if ( maxfreq == freq [ i ] ) { max_char = ( char ) ( i + ' a ' ) ; break ; } } int ans = 0 ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { char ch = s [ i ] ; if ( max_char == ch ) { ans += ( s . size ( ) - i ) ; } } return ans ; } int main ( ) { string S = " abcab " ; cout << ( substringCount ( S ) ) ; } |
Minimum sum possible by assigning every increasing / decreasing consecutive pair with values in that order | C ++ program for the above approach ; Function to print the minimum sum of values assigned to each element of the array as per given conditions ; Initialize vectors with value 1 ; Traverse from left to right ; Update if ans [ i ] > ans [ i - 1 ] ; Traverse from right to left ; Update as ans [ i ] > ans [ i + 1 ] if arr [ i ] > arr [ i + 1 ] ; Find the minimum sum ; Print the sum ; Driver Code ; Given array arr [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minSum ( int * arr , int n ) { vector < int > ans ( n , 1 ) ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] > arr [ i - 1 ] ) { ans [ i ] = max ( ans [ i ] , ans [ i - 1 ] + 1 ) ; } } for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] > arr [ i + 1 ] ) { ans [ i ] = max ( ans [ i ] , ans [ i + 1 ] + 1 ) ; } } int s = 0 ; for ( auto x : ans ) { s = s + x ; } cout << s << endl ; } int main ( ) { int arr [ ] = { 1 , 2 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minSum ( arr , N ) ; return 0 ; } |
Maximize sum of assigned weights by flipping at most K bits in given Binary String | C ++ program of the above approach ; Function to find maximum sum of weights of binary string after at most K flips ; Stores lengths of substrings of the form 1. . 00. . 1 s ; Stores the index of last 1 encountered in the string ; Stores the index of first 1 encountered ; Stores lengths of all substrings having of 0 s enclosed by 1 s at both ends ; Traverse the string ; If character is 0 ; If character is 1 First Priority ; Second Priority ; Add according to the first priority ; Stores length of the shortest substring of 0 s ; Convert shortest substrings of 0 s to 1 s ; Add according to the first priority ; Add according to the third priority ; If more 0 s can be made into 1 , then check for 0 s at ends ; Update the ans ; If K is non - zero , then flip 0 s at the beginning ; Return the final weights ; Driver Code ; Given string str ; Given K flips ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMax ( string s , int n , int k ) { int ans = 0 ; int l = 0 ; int ind = -1 ; int indf = -1 ; multiset < int > ls ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == '0' ) l ++ ; else if ( s [ i ] == '1' && l > 0 && ans != 0 ) { ls . insert ( l ) ; l = 0 ; } if ( s [ i ] == '1' ) { ind = i ; l = 0 ; if ( indf == -1 ) indf = i ; if ( i > 0 && s [ i - 1 ] == '1' ) ans += 2 ; else ans += 1 ; } } int curr ; while ( k > 0 && ! ls . empty ( ) ) { curr = * ls . begin ( ) ; if ( k >= curr ) { ans += ( 2 * curr + 1 ) ; k -= curr ; } else { ans += ( 2 * k ) ; k = 0 ; } ls . erase ( ls . begin ( ) ) ; } if ( k > 0 ) { ans += ( 2 * min ( k , n - ( ind + 1 ) ) - 1 ) ; k -= min ( k , n - ( ind + 1 ) ) ; if ( ind > -1 ) ans ++ ; } if ( k > 0 ) { ans += ( min ( indf , k ) * 2 - 1 ) ; if ( indf > -1 ) ans ++ ; } return ans ; } int main ( ) { string str = "1110000101" ; int N = str . length ( ) ; int K = 3 ; cout << findMax ( str , N , K ) ; return 0 ; } |
Minimum removal of consecutive similar characters required to empty a Binary String | C ++ program for the above approach ; Function to find minimum steps to make the string empty ; Stores the modified string ; Size of string ; Removing substring of same character from modified string ; Print the minimum steps required ; Driver Code ; Given string S ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minSteps ( string S ) { string new_str ; int N = S . length ( ) ; int i = 0 ; while ( i < N ) { new_str += S [ i ] ; int j = i ; while ( i < N && S [ i ] == S [ j ] ) ++ i ; } cout << ceil ( ( new_str . size ( ) + 1 ) / 2.0 ) ; } int main ( ) { string S = "0010100" ; minSteps ( S ) ; return 0 ; } |
Count pairs with equal Bitwise AND and Bitwise OR value | C ++ program to implement the above approach ; Function to count pairs in an array whose bitwise AND equal to bitwise OR ; Store count of pairs whose bitwise AND equal to bitwise OR ; Stores frequency of distinct elements of array ; Traverse the array ; Increment the frequency of arr [ i ] ; Traverse map ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int arr [ ] , int N ) { int cntPairs = 0 ; map < int , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { mp [ arr [ i ] ] ++ ; } for ( auto freq : mp ) { cntPairs += ( freq . second * ( freq . second - 1 ) ) / 2 ; } return cntPairs ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 1 , 2 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , N ) ; } |
Minimum increments required to make given matrix palindromic | C ++ program for the above approach ; Function to evaluate minimum number of operation required to convert the matrix to a palindrome matrix ; Variable to store number of operations required ; Iterate over the first quadrant of the matrix ; Store positions of all four values from four quadrants ; Store the values having unique indexes ; Largest value in the values vector ; Evaluate minimum increments required to make all vector elements equal ; Print the answer ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int palindromeMatrix ( int N , int M , vector < vector < int > > arr ) { int ans = 0 ; for ( int i = 0 ; i < ( N + 1 ) / 2 ; i ++ ) { for ( int j = 0 ; j < ( M + 1 ) / 2 ; j ++ ) { set < pair < int , int > > s ; s . insert ( { i , j } ) ; s . insert ( { i , M - j - 1 } ) ; s . insert ( { N - i - 1 , j } ) ; s . insert ( { N - i - 1 , M - j - 1 } ) ; vector < int > values ; for ( pair < int , int > p : s ) { values . push_back ( arr [ p . first ] [ p . second ] ) ; } int max = * max_element ( values . begin ( ) , values . end ( ) ) ; for ( int k = 0 ; k < values . size ( ) ; k ++ ) { ans += max - values [ k ] ; } } } cout << ans ; } int main ( ) { int N = 3 , M = 3 ; vector < vector < int > > arr = { { 1 , 2 , 1 } , { 3 , 4 , 1 } , { 1 , 2 , 1 } } ; palindromeMatrix ( N , M , arr ) ; return 0 ; } |
Minimum division by 10 and multiplication by 2 required to reduce given number to 1 | C ++ program for the above approach ; Function to find the minimum number operations required to reduce N to 1 ; Stores count of powers of 2 and 5 ; Calculating the primefactors 2 ; Calculating the primefactors 5 ; If n is 1 and cnt2 <= cnt5 ; Return the minimum operations ; Otherwise , n can 't be reduced ; Driver Code ; Given Number N ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumMoves ( int n ) { int cnt2 = 0 , cnt5 = 0 ; while ( n % 2 == 0 ) { n /= 2 ; cnt2 ++ ; } while ( n % 5 == 0 ) { n /= 5 ; cnt5 ++ ; } if ( n == 1 && cnt2 <= cnt5 ) { return 2 * cnt5 - cnt2 ; } else return -1 ; } int main ( ) { int N = 25 ; cout << minimumMoves ( N ) ; return 0 ; } |
Check if permutation of first N natural numbers exists having Bitwise AND of adjacent elements non | C ++ Program to implement the above approach ; Function to check if a permutation of first N natural numbers exist with Bitwise AND of adjacent elements not equal to 0 ; If n is a power of 2 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void check ( int n ) { if ( ( n & n - 1 ) != 0 ) cout << " YES " << endl ; else cout << " NO " << endl ; } int main ( ) { int n = 5 ; check ( n ) ; return 0 ; } |
Minimize adding odd and subtracting even numbers to make all array elements equal to K | C ++ program to implement the above approach ; Function to find the minimum operations required to make array elements equal to K ; Stores minimum count of operations ; Traverse the given array ; If K is greater than arr [ i ] ; If ( K - arr [ i ] ) is even ; Update cntOpe ; Update cntOpe ; If K is less than arr [ i ] ; If ( arr [ i ] - K ) is even ; Update cntOpe ; Update cntOpe ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int MinOperation ( int arr [ ] , int N , int K ) { int cntOpe = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( K > arr [ i ] ) { if ( ( K - arr [ i ] ) % 2 == 0 ) { cntOpe += 2 ; } else { cntOpe += 1 ; } } else if ( K < arr [ i ] ) { if ( ( K - arr [ i ] ) % 2 == 0 ) { cntOpe += 1 ; } else { cntOpe += 2 ; } } } return cntOpe ; } int main ( ) { int arr [ ] = { 8 , 7 , 2 , 1 , 3 } ; int K = 5 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << MinOperation ( arr , N , K ) ; return 0 ; } |
Rearrange array to make Bitwise XOR of similar indexed elements of two arrays is same | C ++ program for the above approach ; Function to rearrange the array B [ ] such that A [ i ] ^ B [ i ] is same for each element ; Store frequency of elements ; Stores xor value ; Taking xor of all the values of both arrays ; Store frequency of B [ ] ; Find the array B [ ] after rearrangement ; If the updated value is present then decrement its frequency ; Otherwise return empty vector ; Utility function to rearrange the array B [ ] such that A [ i ] ^ B [ i ] is same for each element ; Store rearranged array B ; If rearrangement possible ; Otherwise return - 1 ; Driver Code ; Given vector A ; Given vector B ; Size of the vector ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > rearrangeArray ( vector < int > & A , vector < int > & B , int N ) { map < int , int > m ; int xor_value = 0 ; for ( int i = 0 ; i < N ; i ++ ) { xor_value ^= A [ i ] ; xor_value ^= B [ i ] ; m [ B [ i ] ] ++ ; } for ( int i = 0 ; i < N ; i ++ ) { B [ i ] = A [ i ] ^ xor_value ; if ( m [ B [ i ] ] ) { m [ B [ i ] ] -- ; } else return vector < int > { } ; } return B ; } void rearrangeArrayUtil ( vector < int > & A , vector < int > & B , int N ) { vector < int > ans = rearrangeArray ( A , B , N ) ; if ( ans . size ( ) ) { for ( auto x : ans ) { cout << x << " β " ; } } else { cout << " - 1" ; } } int main ( ) { vector < int > A = { 13 , 21 , 33 , 49 , 53 } ; vector < int > B = { 54 , 50 , 34 , 22 , 14 } ; int N = ( int ) A . size ( ) ; rearrangeArrayUtil ( A , B , N ) ; return 0 ; } |
Count sequences of given length having non | C ++ program for the above approach ; Function to find the Binomial Coefficient C ( n , r ) ; Stores the value C ( n , r ) ; Update C ( n , r ) = C ( n , n - r ) ; Find C ( n , r ) iteratively ; Return the final value ; Function to find number of sequence whose prefix sum at each index is always non - negative ; Find n ; Value of C ( 2 n , n ) ; Catalan number ; Print the answer ; Driver Code ; Given M and X ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned long int binCoff ( unsigned int n , unsigned int r ) { unsigned long int val = 1 ; int i ; if ( r > ( n - r ) ) r = ( n - r ) ; for ( i = 0 ; i < r ; i ++ ) { val *= ( n - i ) ; val /= ( i + 1 ) ; } return val ; } void findWays ( int M ) { int n = M / 2 ; unsigned long int a , b , ans ; a = binCoff ( 2 * n , n ) ; b = a / ( n + 1 ) ; cout << b ; } int main ( ) { int M = 4 , X = 5 ; findWays ( M ) ; return 0 ; } |
XOR of array elements whose modular inverse with a given number exists | C ++ program for the above approach ; Function to return the gcd of a & b ; Base Case ; Recursively calculate GCD ; Function to print the Bitwise XOR of elements of arr [ ] if gcd ( arr [ i ] , M ) is 1 ; Initialize xor ; Traversing the array ; GCD of M and arr [ i ] ; If GCD is 1 , update xor ; Print xor ; Drive Code ; Given array arr [ ] ; Given number M ; Size of the array ; 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 ) ; } void countInverse ( int arr [ ] , int N , int M ) { int XOR = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int gcdOfMandelement = gcd ( M , arr [ i ] ) ; if ( gcdOfMandelement == 1 ) { XOR ^= arr [ i ] ; } } cout << XOR << ' β ' ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 } ; int M = 4 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countInverse ( arr , N , M ) ; 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.