text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Check whether Quadrilateral is valid or not if angles are given | C ++ program to check if a given quadrilateral is valid or not ; Function to check if a given quadrilateral is valid or not ; Check condition ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool Valid ( int a , int b , int c , int d ) { if ( a + b + c + d == 360 ) return true ; return false ; } int main ( ) { int a = 80 , b = 70 , c = 100 , d = 110 ; if ( Valid ( a , b , c , d ) ) cout << " Valid β quadrilateral " ; else cout << " Invalid β quadrilateral " ; return 0 ; } |
Central angle of a N sided Regular Polygon | C ++ program for the above approach ; Function to calculate central angle of a polygon ; Calculate the angle ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; double calculate_angle ( double n ) { double total_angle = 360 ; return total_angle / n ; } int main ( ) { double N = 5 ; cout << calculate_angle ( N ) ; return 0 ; } |
Program to calculate the area of Kite | C ++ implementation of the approach ; Function to return the area of kite ; use above formula ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; float areaOfKite ( int d1 , int d2 ) { float area = ( d1 * d2 ) / 2 ; return area ; } int main ( ) { int d1 = 4 , d2 = 6 ; cout << " Area β of β Kite β = β " << areaOfKite ( d1 , d2 ) ; return 0 ; } |
Program to calculate the area of Kite | C ++ implementation of the approach ; Function to return the area of the kite ; convert angle degree to radians ; use above formula ; Driver code | #include <bits/stdc++.h> NEW_LINE #define PI 3.14159 / 180 NEW_LINE using namespace std ; float areaOfKite ( int a , int b , double angle ) { angle = angle * PI ; double area = a * b * sin ( angle ) ; return area ; } int main ( ) { int a = 4 , b = 7 , angle = 78 ; cout << " Area β of β Kite β = β " << areaOfKite ( a , b , angle ) ; return 0 ; } |
Program to calculate angle on circumference subtended by the chord when the central angle subtended by the chord is given | C ++ Program to calculate angle on the circumference subtended by the chord when the central angle subtended by the chord is given ; Driver code ; Angle on center | #include <iostream> NEW_LINE using namespace std ; float angleOncirCumference ( float z ) { return ( z / 2 ) ; } int main ( ) { float angle = 65 ; float z = angleOncirCumference ( angle ) ; cout << " The β angle β is β " << ( z ) << " β degrees " ; return 0 ; } |
Maximum and Minimum value of a quadratic function | C ++ implementation of the above approach ; Function to print the Maximum and Minimum values of the quadratic function ; Calculate the value of second part ; Print the values ; Open upward parabola function ; Open downward parabola function ; If a = 0 then it is not a quadratic function ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void PrintMaxMinValue ( double a , double b , double c ) { double secondPart = c * 1.0 - ( b * b / ( 4.0 * a ) ) ; if ( a > 0 ) { cout << " Maxvalue β = β " << " Infinity STRNEWLINE " ; cout << " Minvalue β = β " << secondPart ; } else if ( a < 0 ) { cout << " Maxvalue β = β " << secondPart << " STRNEWLINE " ; cout << " Minvalue β = β " << " - Infinity " ; } else { cout << " Not β a β quadratic β function STRNEWLINE " ; } } int main ( ) { double a = -1 , b = 3 , c = -2 ; PrintMaxMinValue ( a , b , c ) ; return 0 ; } |
Percentage increase in the cylinder if the height is increased by given percentage but radius remains constant | C ++ program to find percentage increase in the cylinder if the height is increased by given percentage but radius remains constant ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void newvol ( double x ) { cout << " percentage β increase β " << " in β the β volume β of β the β cylinder β is β " << x << " % " << endl ; } int main ( ) { double x = 10 ; newvol ( x ) ; return 0 ; } |
Find the side of the squares which are inclined diagonally and lined in a row | C ++ program to find side of the squares inclined and touch each other externally at vertices and are lined in a row and distance between the centers of first and last squares is given ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void radius ( double n , double d ) { cout << " The β side β of β each β square β is β " << d / ( ( n - 1 ) * sqrt ( 2 ) ) << endl ; } int main ( ) { double d = 42 , n = 4 ; radius ( n , d ) ; return 0 ; } |
Program to calculate area of inner circle which passes through center of outer circle and touches its circumference | C ++ implementation of the above approach ; Function calculate the area of the inner circle ; the radius cannot be negative ; area of the circle ; Driver Code | #include <bits/stdc++.h> NEW_LINE #include <iostream> NEW_LINE using namespace std ; double innerCirclearea ( double radius ) { if ( radius < 0 ) { return -1 ; } double r = radius / 2 ; double Area = ( 3.14 * pow ( r , 2 ) ) ; return Area ; } int main ( ) { double radius = 4 ; cout << ( " Area β of β circle β c2 β = β " , innerCirclearea ( radius ) ) ; return 0 ; } |
Angle subtended by the chord when the angle subtended by another chord of same length is given | C ++ program to find the angle subtended at the center by the chord when the angle subtended at center by another chord of equal length is given ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void angleequichord ( int z ) { cout << " The β angle β subtended β at β the β center β is β " << z << " β degrees " << endl ; } int main ( ) { int z = 48 ; angleequichord ( z ) ; return 0 ; } |
Distance of chord from center when distance between center and another equal length chord is given | C ++ program to find the distance of chord from center when distance between center and another equal length chord is given ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void lengequichord ( int z ) { cout << " The β distance β between β the β " << " chord β and β the β center β is β " << z << endl ; } int main ( ) { int z = 48 ; lengequichord ( z ) ; return 0 ; } |
Length of the perpendicular bisector of the line joining the centers of two circles | C ++ program to find the Length of the perpendicular bisector of the line joining the centers of two circles in which one lies completely inside touching the bigger circle at one point ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void lengperpbisect ( double r1 , double r2 ) { double z = 2 * sqrt ( ( r1 * r1 ) - ( ( r1 - r2 ) * ( r1 - r2 ) / 4 ) ) ; cout << " The β length β of β the β " << " perpendicular β bisector β is β " << z << endl ; } int main ( ) { double r1 = 5 , r2 = 3 ; lengperpbisect ( r1 , r2 ) ; return 0 ; } |
Length of the chord the circle if length of the another chord which is equally inclined through the diameter is given | C ++ program to find the length of the chord the circle if length of the another chord which is equally inclined through the diameter is given ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void lengchord ( int z ) { cout << " The β length β is β " << z << endl ; } int main ( ) { int z = 48 ; lengchord ( z ) ; return 0 ; } |
Distance between centers of two intersecting circles if the radii and common chord length is given | C ++ program to find the distance between centers of two intersecting circles if the radii and common chord length is given ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void distcenter ( int r1 , int r2 , int x ) { int z = sqrt ( ( r1 * r1 ) - ( x / 2 * x / 2 ) ) + sqrt ( ( r2 * r2 ) - ( x / 2 * x / 2 ) ) ; cout << " distance β between β the " << " β centers β is β " << z << endl ; } int main ( ) { int r1 = 24 , r2 = 37 , x = 40 ; distcenter ( r1 , r2 , x ) ; return 0 ; } |
Exterior angle of a cyclic quadrilateral when the opposite interior angle is given | C ++ program to find the exterior angle of a cyclic quadrilateral when the opposite interior angle is given ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void angleextcycquad ( int z ) { cout << " The β exterior β angle β of β the " << " β cyclic β quadrilateral β is β " << z << " β degrees " << endl ; } int main ( ) { int z = 48 ; angleextcycquad ( z ) ; return 0 ; } |
Angle between a chord and a tangent when angle in the alternate segment is given | C ++ program to find the angle between a chord and a tangent when angle in the alternate segment is given ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void anglechordtang ( int z ) { cout << " The β angle β between β tangent " << " β and β the β chord β is β " << z << " β degrees " << endl ; } int main ( ) { int z = 48 ; anglechordtang ( z ) ; return 0 ; } |
Print all Perfect Numbers from an array whose sum of digits is also a Perfect Number | C ++ program for the above approach ; Function to check if a number is perfect number or not ; Stores sum of proper divisors ; If sum of digits is equal to N , then it 's a perfect number ; Otherwise , not a perfect number ; Function to find the sum of digits of a number ; Stores sum of digits ; Return sum of digits ; Function to count perfect numbers from an array whose sum of digits is also perfect ; Traverse the array ; If number is perfect ; Stores sum of digits of the number ; If that is also perfect number ; Print that number ; Driver Code ; Given array ; Size of the array ; Function call to count perfect numbers having sum of digits also perfect | #include <bits/stdc++.h> NEW_LINE using namespace std ; int isPerfect ( int N ) { int sumOfDivisors = 1 ; for ( int i = 2 ; i <= N / 2 ; ++ i ) { if ( N % i == 0 ) { sumOfDivisors += i ; } } if ( sumOfDivisors == N ) { return 1 ; } else return 0 ; } int sumOfDigits ( int N ) { int sum = 0 ; while ( N != 0 ) { sum += ( N % 10 ) ; N = N / 10 ; } return sum ; } void countPerfectNumbers ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; ++ i ) { if ( isPerfect ( arr [ i ] ) ) { int sum = sumOfDigits ( arr [ i ] ) ; if ( isPerfect ( sum ) ) { cout << arr [ i ] << " β " ; } } } } int main ( ) { int arr [ ] = { 3 , 8 , 12 , 28 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countPerfectNumbers ( arr , N ) ; return 0 ; } |
Maximum Prefix Sum possible by merging two given arrays | C ++ implementation of above approach ; Stores the dp states ; Recursive Function to calculate the maximum prefix sum ontained by merging two arrays ; If subproblem is already computed ; If x >= N or y >= M ; If x < N ; If y < M ; Otherwise ; Driver Code | #include <bits/stdc++.h> NEW_LINE #define int long long NEW_LINE using namespace std ; map < pair < int , int > , int > dp ; int maxPreSum ( vector < int > a , vector < int > b , int x , int y ) { if ( dp . find ( { x , y } ) != dp . end ( ) ) return dp [ { x , y } ] ; if ( x == a . size ( ) && y == b . size ( ) ) return 0 ; int curr = dp [ { x , y } ] ; if ( x == a . size ( ) ) { curr = max ( curr , b [ y ] + maxPreSum ( a , b , x , y + 1 ) ) ; } else if ( y == b . size ( ) ) { curr = max ( curr , a [ x ] + maxPreSum ( a , b , x + 1 , y ) ) ; } else { curr = max ( { curr , a [ x ] + maxPreSum ( a , b , x + 1 , y ) , b [ y ] + maxPreSum ( a , b , x , y + 1 ) } ) ; } return dp [ { x , y } ] = curr ; } signed main ( ) { vector < int > A = { 2 , 1 , 13 , 5 , 14 } ; vector < int > B = { -1 , 4 , -13 } ; cout << maxPreSum ( A , B , 0 , 0 ) << endl ; return 0 ; } |
Sum of Bitwise AND of the sum of all leaf and non | C ++ program for given approach ; Structure of a Binary tree node ; Helper function to allocate a new node with the given data and left and right pointers as None ; Function to calculate the sum of bitwise AND of the sum of all leaf nodes and non - leaf nodes for each level ; Initialize a queue and append root to it ; Store the required answer ; Stores the sum of leaf nodes at the current level ; Stores the sum of non - leaf nodes at the current level ; Get the size of the queue ; Iterate for all the nodes in the queue currently ; Dequeue a node from queue ; Check if the node is a leaf node ; If true , update the leaf node sum ; Otherwise , update the non - leaf node sum ; Enqueue left and right children of removed node ; Update the answer ; Return the answer ; Driver Code ; Given Tree ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct TreeNode { int val ; TreeNode * left , * right ; TreeNode ( int x = 0 ) { val = x ; left = NULL ; right = NULL ; } } ; int findSum ( TreeNode * root ) { queue < TreeNode * > que ; que . push ( root ) ; int ans = 0 ; while ( que . size ( ) ) { int leaf = 0 ; int nonleaf = 0 ; int length = que . size ( ) ; while ( length ) { auto temp = que . front ( ) ; que . pop ( ) ; if ( ! temp -> left && ! temp -> right ) leaf += temp -> val ; else nonleaf += temp -> val ; if ( temp -> left ) que . push ( temp -> left ) ; if ( temp -> right ) que . push ( temp -> right ) ; length -= 1 ; } ans += leaf & nonleaf ; } return ans ; } int main ( ) { TreeNode * root = new TreeNode ( 5 ) ; root -> left = new TreeNode ( 3 ) ; root -> right = new TreeNode ( 9 ) ; root -> left -> left = new TreeNode ( 6 ) ; root -> left -> right = new TreeNode ( 4 ) ; root -> left -> left -> right = new TreeNode ( 7 ) ; cout << findSum ( root ) ; } |
Minimize replacements to make every element in an array exceed every element in another given array | C ++ program for the above approach ; Function to find the minimize replacements to make every element in the array A [ ] strictly greater than every element in B [ ] or vice - versa ; Store the final result ; Create two arrays and initialize with 0 s ; Traverse the array a [ ] ; Increment prefix_a [ a [ i ] ] by 1 ; Traverse the array b [ ] ; Increment prefix_b [ b [ i ] ] by 1 ; Calculate prefix sum of the array a [ ] ; Calculate prefix sum of the array b [ ] ; Iterate over the range [ 0 , 9 ] ; Make every element in array a [ ] strictly greater than digit i and make every element in the array b [ ] less than digit i ; Make every element in array b [ ] strictly greater than digit i and make every element in array a [ ] less than digit i ; Print the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void MinTime ( int * a , int * b , int n , int m ) { int ans = INT_MAX ; int prefix_a [ 10 ] = { 0 } ; int prefix_b [ 10 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { prefix_a [ a [ i ] ] ++ ; } for ( int i = 0 ; i < m ; i ++ ) { prefix_b [ b [ i ] ] ++ ; } for ( int i = 1 ; i <= 9 ; i ++ ) { prefix_a [ i ] += prefix_a [ i - 1 ] ; } for ( int i = 1 ; i <= 9 ; i ++ ) { prefix_b [ i ] += prefix_b [ i - 1 ] ; } for ( int i = 0 ; i <= 9 ; i ++ ) { ans = min ( ans , prefix_a [ i ] + m - prefix_b [ i ] ) ; ans = min ( ans , n - prefix_a [ i ] + prefix_b [ i ] ) ; } cout << ans ; } int main ( ) { int A [ ] = { 0 , 0 , 1 , 3 , 3 } ; int B [ ] = { 2 , 0 , 3 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int M = sizeof ( B ) / sizeof ( B [ 0 ] ) ; MinTime ( A , B , N , M ) ; return 0 ; } |
Count remaining array elements after reversing binary representation of each array element | C ++ program for the above approach ; Function to reverse the binary representation of a number ; Traverse bits of N from the right ; Bitwise left shift ' rev ' by 1 ; If current bit is '1' ; Bitwise right shift N by 1 ; Required number ; Function to count elements from the original array that are also present in the array formed by reversing the binary representation of each element ; Stores the reversed num ; Iterate from [ 0 , N ] ; Stores the presence of integer ; Stores count of elements present in original array ; Traverse the array ; If current number is present ; Print the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findReverse ( int N ) { int rev = 0 ; while ( N > 0 ) { rev <<= 1 ; if ( N & 1 == 1 ) rev ^= 1 ; N >>= 1 ; } return rev ; } void countElements ( int arr [ ] , int N ) { vector < int > ans ; for ( int i = 0 ; i < N ; i ++ ) { ans . push_back ( findReverse ( arr [ i ] ) ) ; } unordered_map < int , int > cnt ; for ( int i = 0 ; i < N ; i ++ ) { cnt [ arr [ i ] ] = 1 ; } int count = 0 ; for ( auto i : ans ) { if ( cnt [ i ] ) count ++ ; } cout << count << endl ; } int main ( ) { int arr [ ] = { 1 , 30 , 3 , 8 , 12 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countElements ( arr , N ) ; return 0 ; } |
Fizz Buzz Implementation | Set 2 | C ++ program for the above approach ; Function to generate FizzBuzz sequence ; Stores count of multiples of 3 and 5 respectively ; Iterate from 1 to N ; Increment count3 by 1 ; Increment count5 by 1 ; Initialize a boolean variable to check if none of the condition matches ; Check if the value of count3 is equal to 3 ; Reset count3 to 0 , and set flag as True ; Check if the value of count5 is equal to 5 ; Reset count5 to 0 , and set flag as True ; If none of the condition matches ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void fizzBuzz ( int N ) { int count3 = 0 ; int count5 = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { count3 ++ ; count5 ++ ; bool flag = false ; if ( count3 == 3 ) { cout << " Fizz " ; count3 = 0 ; flag = true ; } if ( count5 == 5 ) { cout << " Buzz " ; count5 = 0 ; flag = true ; } if ( ! flag ) { cout << i ; } cout << " β " ; } } int main ( ) { int N = 15 ; fizzBuzz ( N ) ; return 0 ; } |
Check if diagonal elements of a Matrix are Prime or not | C ++ program for the above approach ; Stores if a number is prime or not ; Function to generate and store primes using Sieve Of Eratosthenes ; Set all numbers as prime ; If p is a prime ; Set all its multiples as non - prime ; Function to check if all diagonal elements are prime or not ; Stores if all diagonal elements are prime or not ; Precompute primes ; Traverse the range [ 0 , N - 1 ] ; Check if numbers on the cross diagonal and main diagonal are primes or not ; If true , then print " Yes " ; Otherwise , print " No " ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool prime [ 1000005 ] ; void SieveOfEratosthenes ( int N ) { memset ( prime , true , sizeof ( prime ) ) ; prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= N ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= N ; i += p ) prime [ i ] = false ; } } } void checkElementsOnDiagonal ( vector < vector < int > > M , int N ) { int flag = 1 ; SieveOfEratosthenes ( 1000000 ) ; for ( int i = 0 ; i < N ; i ++ ) { flag &= ( prime [ M [ i ] [ i ] ] && prime [ M [ i ] [ N - 1 - i ] ] ) ; } if ( flag ) cout << " Yes " << endl ; else cout << " No " ; } int main ( ) { vector < vector < int > > M = { { 1 , 2 , 3 , 13 } , { 5 , 3 , 7 , 8 } , { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 7 } } ; int N = M . size ( ) ; checkElementsOnDiagonal ( M , N ) ; return 0 ; } |
Generate a circular permutation with number of mismatching bits between pairs of adjacent elements exactly 1 | C ++ program for the above approach ; Function to find the permutation of integers from a given range such that number of mismatching bits between pairs of adjacent elements is 1 ; Initialize an arrayList to store the resultant permutation ; Store the index of rotation ; Iterate over the range [ 0 , N - 1 ] ; Traverse all the array elements up to ( 2 ^ k ) - th index in reverse ; If current element is S ; Check if S is zero ; Rotate the array by index value to the left ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > circularPermutation ( int n , int start ) { vector < int > res = { 0 } ; vector < int > ret ; int index = -1 ; for ( int k = 0 , add = 1 << k ; k < n ; k ++ , add = 1 << k ) { for ( int i = res . size ( ) - 1 ; i >= 0 ; i -- ) { if ( res [ i ] + add == start ) index = res . size ( ) ; res . push_back ( res [ i ] + add ) ; } } if ( start == 0 ) return res ; while ( ret . size ( ) < res . size ( ) ) { ret . push_back ( res [ index ] ) ; index = ( index + 1 ) % res . size ( ) ; } return ret ; } int main ( ) { int N = 2 , S = 3 ; vector < int > print = circularPermutation ( N , S ) ; cout << " [ " ; for ( int i = 0 ; i < print . size ( ) - 1 ; i ++ ) { cout << print [ i ] << " , β " ; } cout << print [ print . size ( ) - 1 ] << " ] " ; return 0 ; } |
Count pairs from an array having equal sum and quotient | C ++ program for the above approach ; Function to count all pairs ( i , j ) such that a [ i ] + [ j ] = a [ i ] / a [ j ] ; Stores total count of pairs ; Generate all possible pairs ; If a valid pair is found ; Increment count ; Return the final count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int 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 [ j ] != 0 && a [ i ] % a [ j ] == 0 ) { if ( ( a [ i ] + a [ j ] ) == ( a [ i ] / a [ j ] ) ) count ++ ; } } } return count ; } int main ( ) { int arr [ ] = { -4 , -3 , 0 , 2 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , N ) ; return 0 ; } |
Count pairs from an array having equal sum and quotient | C ++ program for the above approach ; Function to find number of pairs with equal sum and quotient from a given array ; Store the count of pairs ; Stores frequencies ; Traverse the array ; If y is neither 1 or 0 ; Evaluate x ; Increment count by frequency of x ; Update map ; Print the final count ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int a [ ] , int n ) { int count = 0 ; map < double , int > mp ; for ( int i = 0 ; i < n ; i ++ ) { int y = a [ i ] ; if ( y != 0 && y != 1 ) { double x = ( ( y * 1.0 ) / ( 1 - y ) ) * y ; count += mp [ x ] ; } mp [ y ] ++ ; } return count ; } int main ( ) { int arr [ ] = { -4 , -3 , 0 , 2 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , N ) ; return 0 ; } |
Queries to count numbers from a range which does not contain digit K in their decimal or octal representation | C ++ program for the above approach ; Function to check if the given digit ' K ' is present in the decimal and octal representations of num or not ; Stores if the digit exists or not ; Iterate till nums is non - zero ; Find the remainder ; If the remainder is K ; Function to count the numbers in the range [ 1 , N ] such that it doesn ' t β contain β the β digit β ' K ' in its decimal and octal representation ; Stores count of numbers in the range [ 0 , i ] that contains the digit ' K ' in its octal or decimal representation ; Traverse the range [ 0 , 1e6 + 5 ] ; Check if i contains the digit ' K ' in its decimal or octal representation ; Update pref [ i ] ; Print the answer of queries ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool contains ( int num , int K , int base ) { bool isThere = 0 ; while ( num ) { int remainder = num % base ; if ( remainder == K ) { isThere = 1 ; } num /= base ; } return isThere ; } void count ( int n , int k , vector < vector < int > > v ) { int pref [ 1000005 ] = { 0 } ; for ( int i = 1 ; i < 1e6 + 5 ; i ++ ) { bool present = contains ( i , k , 10 ) || contains ( i , k , 8 ) ; pref [ i ] += pref [ i - 1 ] + present ; } for ( int i = 0 ; i < n ; ++ i ) { cout << v [ i ] [ 1 ] - v [ i ] [ 0 ] + 1 - ( pref [ v [ i ] [ 1 ] ] - pref [ v [ i ] [ 0 ] - 1 ] ) << ' β ' ; } } int main ( ) { int K = 7 ; vector < vector < int > > Q = { { 2 , 5 } , { 1 , 15 } } ; int N = Q . size ( ) ; count ( N , K , Q ) ; } |
Count tiles of dimensions 2 * 1 that can be placed in an M * N rectangular board that satisfies the given conditions | C ++ Program to implement the above approach ; Function to count tiles of dimensions 2 x 1 that can be placed in a grid of dimensions M * N as per given conditions ; Number of tiles required ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int numberOfTiles ( int N , int M ) { if ( N % 2 == 1 ) { return -1 ; } return ( N * 1LL * M ) / 2 ; } int main ( ) { int N = 2 , M = 4 ; cout << numberOfTiles ( N , M ) ; return 0 ; } |
Check if an array can be converted to another given array by swapping pairs of unequal elements | C ++ program for the above approach ; Function to check if arr1 [ ] can be converted to arr2 [ ] by swapping pair ( i , j ) such that i < j and arr [ i ] is 1 and arr [ j ] is 0 ; Stores the differences of prefix sum of arr1 and arr2 ; Stores the count of 1 and zero of arr1 ; Stores the count of 1 and zero of arr2 ; Iterate in the range [ 0 , N - 1 ] ; If arr1 [ i ] is 1 , then increment arr1_one by one ; Otherwise increment arr1_zero by one ; If arr2 [ i ] is 1 , then increment arr2_one by one ; Otherwise increment arr2_zero by one ; Check if number of 1 s and 0 s of arr1 is equal to number of 1 s and 0 s of arr2 respectievly ; Iterate over the range [ 0 , N - 1 ] ; Increment count by differences arr1 [ i ] and arr2 [ i ] ; Check if number of 1 's in arr2 are more than arr1 and then print "No" ; Finally , print " Yes " ; Driver Code ; Given input arrays ; Size of the array ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void canMakeEqual ( int arr1 [ ] , int arr2 [ ] , int N ) { int count = 0 ; int arr1_one = 0 , arr1_zero = 0 ; int arr2_one = 0 , arr2_zero = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr1 [ i ] == 1 ) { arr1_one ++ ; } else if ( arr1 [ i ] == 0 ) { arr1_zero ++ ; } if ( arr2 [ i ] == 1 ) { arr2_one ++ ; } else if ( arr2 [ i ] == 0 ) { arr2_zero ++ ; } } if ( arr1_one != arr2_one arr1_zero != arr2_zero ) { cout << " No " ; return ; } for ( int i = 0 ; i < N ; i ++ ) { count = count + ( arr1 [ i ] - arr2 [ i ] ) ; if ( count < 0 ) { cout << " No " ; return ; } } cout << " Yes " ; } int main ( ) { int arr1 [ ] = { 0 , 1 , 1 , 0 } ; int arr2 [ ] = { 0 , 0 , 1 , 1 } ; int N = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; canMakeEqual ( arr1 , arr2 , N ) ; return 0 ; } |
Check for each subarray whether it consists of all natural numbers up to its length or not | C ++ program to implement the above approach ; Function to check if a subarray of size i exists that contain all the numbers in the range [ 1 , i ] ; Store the position of each element of arr [ ] ; Traverse the array ; Insert the position of arr [ i ] ; Store position of each element from the range [ 1 , N ] ; Iterate over the range [ 1 , N ] ; Insert the index of i into st ; Find the smallest element of st ; Find the largest element of st ; If distance between the largest and smallest element of arr [ ] till i - th index is equal to i ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void checksubarrayExist1_N ( int arr [ ] , int N ) { unordered_map < int , int > pos ; for ( int i = 0 ; i < N ; i ++ ) { pos [ arr [ i ] ] = i ; } set < int > st ; for ( int i = 1 ; i <= N ; i ++ ) { st . insert ( pos [ i ] ) ; int Min = * ( st . begin ( ) ) ; int Max = * ( st . rbegin ( ) ) ; if ( Max - Min + 1 == i ) { cout << " True β " ; } else { cout << " False β " ; } } } int main ( ) { int arr [ ] = { 1 , 4 , 3 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; checksubarrayExist1_N ( arr , N ) ; } |
Check if a pair of integers A and B can coincide by shifting them by distances arr [ ( A % N + N ) % N ] and arr [ ( B % N + N ) % N ] | C ++ program for the above approach ; Function to check if two integers coincide at a point ; Store the final position of integers A and B ; Iterate over the range [ 0 , n ] ; Store the final position of the integer i ; If temp is present in the Map ; Print Yes and return ; Mark its final position as visited ; If every integer stored in the Map is unique ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void checkSamePosition ( int arr [ ] , int n ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) { int temp = ( ( i + arr [ i ] ) % n + n ) % n ; if ( mp . find ( temp ) != mp . end ( ) ) { cout << " Yes " ; return ; } mp [ temp ] ++ ; } cout << " No " ; } int main ( ) { int arr [ ] = { 5 , 4 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; checkSamePosition ( arr , N ) ; return 0 ; } |
Sum of Fibonacci Numbers | Set 2 | C ++ program for the above approach ; Function to find the sum of first N + 1 fibonacci numbers ; Apply the formula ; Print the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sumFib ( int N ) { long num = ( long ) round ( pow ( ( sqrt ( 5 ) + 1 ) / 2.0 , N + 2 ) / sqrt ( 5 ) ) ; cout << ( num - 1 ) ; } int main ( ) { int N = 3 ; sumFib ( N ) ; return 0 ; } |
Sum of Fibonacci Numbers | Set 2 | C ++ program for the above approach ; Function to find the sum of first N + 1 fibonacci numbers ; Apply the formula ; Print the result ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sumFib ( int N ) { double num = ( 1 - sqrt ( 5 ) ) / 2 ; long val = round ( abs ( 1 / ( pow ( num , N + 2 ) + pow ( num , N + 1 ) + pow ( num , N ) + pow ( num , N - 1 ) ) ) - 1 ) ; cout << val ; } int main ( ) { int N = 3 ; sumFib ( N ) ; } |
Make all array elements equal to K by repeatedly incrementing subsequences | C ++ program for the above approach ; Function to find the minimum number of operations required to make all elements equal to k ; Initialize a hashmap ; Store frequency of array elements ; Store the minimum number of operations required ; Iterate until all array elements becomes equal to K ; Iterate through range [ 1 , k - 1 ] since only one element can be increased from each group ; Check if the current number has frequency > 0 , i . e . , it is a part of a group ; If true , decrease the frequency of current group of element by 1 ; Increase the frequency of the next group of elements by 1 ; If the next element is not the part of any group , then skip it ; Increment count of operations ; Print the count of operations ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minOperations ( int arr [ ] , int n , int k ) { map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) { mp [ arr [ i ] ] ++ ; } int ans = 0 ; while ( mp [ k ] < n ) { for ( int i = 1 ; i <= k - 1 ; i ++ ) { if ( mp [ i ] ) { mp [ i ] -- ; mp [ i + 1 ] ++ ; if ( mp [ i + 1 ] == 1 ) { i ++ ; } } } ans ++ ; } cout << ans ; } int main ( ) { int arr [ ] = { 2 , 3 , 3 , 4 } ; int K = 5 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minOperations ( arr , N , K ) ; return 0 ; } |
Minimum number of pigs required to find the poisonous bucket | C ++ program for the above approach ; Function to find the minimum number of pigs required to find the poisonous bucket ; Print the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void poorPigs ( int buckets , int minutesToDie , int minutesToTest ) { cout << ceil ( log ( buckets ) / log ( ( minutesToTest / minutesToDie ) + 1 ) ) ; } int main ( ) { int N = 1000 , M = 15 , P = 60 ; poorPigs ( N , M , P ) ; return 0 ; } |
Maximum product of the remaining pair after repeatedly replacing pairs of adjacent array elements with their sum | C ++ program for the above approach ; Function to find the maximum product possible after repeatedly replacing pairs of adjacent array elements with their sum ; Store the maximum product ; Store the prefix sum ; Store the total sum of array ; Traverse the array to find the total sum ; Iterate in the range [ 0 , N - 2 ] ; Add arr [ i ] to prefix_sum ; Store the value of prefix_sum ; Store the value of ( total sum - prefix sum ) ; Update the maximum product ; Print the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void maxProduct ( int arr [ ] , int N ) { int max_product = INT_MIN ; int prefix_sum = 0 ; int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += arr [ i ] ; } for ( int i = 0 ; i < N - 1 ; i ++ ) { prefix_sum += arr [ i ] ; int X = prefix_sum ; int Y = sum - prefix_sum ; max_product = max ( max_product , X * Y ) ; } cout << max_product ; } int main ( ) { int arr [ ] = { 2 , 3 , 5 , 6 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maxProduct ( arr , N ) ; return 0 ; } |
Find array elements with rightmost set bit at the position of the rightmost set bit in K | C ++ program for the above approach ; Function to find the mask for finding rightmost set bit in K ; Function to find all array elements with rightmost set bit same as that in K ; Stores mask of K ; Store position of rightmost set bit ; Traverse the array ; Check if rightmost set bit of current array element is same as position of rightmost set bit in K ; Driver Code ; Input ; Function call to find the elements having same rightmost set bit as of K | #include " bits / stdc + + . h " NEW_LINE using namespace std ; int findMask ( int K ) { int mask = 1 ; while ( ( K & mask ) == 0 ) { mask = mask << 1 ; } return mask ; } void sameRightSetBitPos ( int arr [ ] , int N , int K ) { int mask = findMask ( K ) ; int pos = ( K & mask ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( ( arr [ i ] & mask ) == pos ) cout << arr [ i ] << " β " ; } } int main ( ) { int arr [ ] = { 3 , 4 , 6 , 7 , 9 , 12 , 15 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 7 ; sameRightSetBitPos ( arr , N , K ) ; return 0 ; } |
Generate an N | C ++ program for the above approach ; Utility function to find x ^ y in O ( log ( y ) ) ; Stores the result ; Update x if it is >= p ; If y is odd ; Multiply x with res ; y must be even now Set y = y / 2 ; Function to generate the N digit number satisfying the given conditions ; Find all possible integers upto 2 ^ N ; Generate binary representation of i ; Reduce the length of the string to N ; If current bit is '0' ; Convert string to equivalent integer ; If condition satisfies ; Print and break ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long int power ( long long int x , unsigned long long int y ) { long long int res = 1 ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) ; y = y >> 1 ; x = ( x * x ) ; } return res ; } void printNth ( int N ) { for ( long long int i = 1 ; i <= power ( 2 , N ) ; i ++ ) { string s = bitset < 64 > ( i ) . to_string ( ) ; string s1 = s . substr ( s . length ( ) - N , s . length ( ) ) ; for ( long long int j = 0 ; s1 [ j ] ; j ++ ) { if ( s1 [ j ] == '0' ) { s1 [ j ] = '2' ; } } long long int res = stoll ( s1 , nullptr , 10 ) ; if ( res % power ( 2 , N ) == 0 ) { cout << res << endl ; break ; } } } int main ( ) { int N = 15 ; printNth ( N ) ; } |
Maximum sum of K | C ++ program for the above approach ; Function to print the sum of subarray of length K having maximum distinct prime factors ; If K exceeds N ; Stores the count of distinct primes ; True , if index ' i ' is a prime ; Initialize the count of factors to 0 and set all indices as prime ; If i is prime ; Number is prime ; Count of factors of a prime number is 1 ; Increment CountDistinct as the factors of i ; Mark its multiple non - prime ; Compute sum of first K - length subarray ; Compute sums of remaining windows by removing first element of the previous window and adding last element of the current window ; Print the maximum sum ; Driver Code ; Given array ; Given size of subarray ; Size of the array | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100001 NEW_LINE int maxSum ( int arr [ ] , int N , int K ) { if ( N < K ) { cout << " Invalid " ; return -1 ; } int CountDistinct [ MAX + 1 ] ; 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 Maxarr_sum = 0 , DistPrimeSum = 0 ; for ( int i = 0 ; i < K ; i ++ ) { Maxarr_sum += arr [ i ] ; DistPrimeSum += CountDistinct [ arr [ i ] ] ; } int curr_sum = DistPrimeSum ; int curr_arrSum = Maxarr_sum ; for ( int i = K ; i < N ; i ++ ) { curr_sum += CountDistinct [ arr [ i ] ] - CountDistinct [ arr [ i - K ] ] ; curr_arrSum += arr [ i ] - arr [ i - K ] ; if ( curr_sum > DistPrimeSum ) { DistPrimeSum = curr_sum ; Maxarr_sum = curr_arrSum ; } else if ( curr_sum == DistPrimeSum ) { Maxarr_sum = max ( curr_arrSum , Maxarr_sum ) ; } } cout << Maxarr_sum ; } int main ( ) { int arr [ ] = { 1 , 4 , 2 , 10 , 3 } ; int K = 3 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maxSum ( arr , N , K ) ; return 0 ; } |
Count Pronic numbers from a given range | C ++ program for the above approach ; Function to check if x is a Pronic Number or not ; Check for Pronic Number by multiplying consecutive numbers ; Function to count pronic numbers in the range [ A , B ] ; Initialise count ; Iterate from A to B ; If i is pronic ; Increment count ; Print count ; Driver Code ; Function call to count pronic numbers in the range [ A , B ] | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkPronic ( int x ) { for ( int i = 0 ; i <= ( int ) ( sqrt ( x ) ) ; i ++ ) { if ( x == i * ( i + 1 ) ) { return true ; } } return false ; } void countPronic ( int A , int B ) { int count = 0 ; for ( int i = A ; i <= B ; i ++ ) { if ( checkPronic ( i ) ) { count ++ ; } } cout << count ; } int main ( ) { int A = 3 , B = 20 ; countPronic ( A , B ) ; return 0 ; } |
Count Pronic numbers from a given range | C ++ program for the above approach ; Function to count pronic numbers in the range [ A , B ] ; Check upto sqrt N ; If product of consecutive numbers are less than equal to num ; Return N - 1 ; Function to count pronic numbers in the range [ A , B ] ; Subtract the count of pronic numbers which are <= ( A - 1 ) from the count f pronic numbers which are <= B ; Driver Code ; Function call to count pronic numbers in the range [ A , B ] | #include <bits/stdc++.h> NEW_LINE using namespace std ; int pronic ( int num ) { int N = ( int ) sqrt ( num ) ; if ( N * ( N + 1 ) <= num ) { return N ; } return N - 1 ; } int countPronic ( int A , int B ) { return pronic ( B ) - pronic ( A - 1 ) ; } int main ( ) { int A = 3 ; int B = 20 ; cout << countPronic ( A , B ) ; return 0 ; } |
Count integers from a given range with no odd divisors | C ++ program for the above approach ; Function to count integers in the range 1 to N having no odd divisors ; Traverse the array ; Stores the nearest power of two less than arr [ i ] ; Stores the count of integers with no odd divisor for each query ; Iterate until powerOfTwo is less then or equal to arr [ i ] ; Print the answer for the current element ; Driver Code ; Given array ; Size of the array | #include <bits/stdc++.h> NEW_LINE using namespace std ; void oddDivisors ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { int powerOfTwo = 2 ; int count = 0 ; while ( powerOfTwo <= arr [ i ] ) { count ++ ; powerOfTwo = 2 * powerOfTwo ; } cout << count << " β " ; } return ; } int main ( ) { int arr [ ] = { 15 , 16 , 20 , 35 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; oddDivisors ( arr , N ) ; return 0 ; } |
Check if all array elements can be reduced to 0 by repeatedly reducing pairs of consecutive elements by their minimum | C ++ program for the above approach ; Function to check if it is possible to convert the array ; Traverse the array range [ 1 , N - 1 ] ; If arr [ i ] < arr [ i - 1 ] ; Otherwise ; Decrement arr [ i ] by arr [ i - 1 ] ; If arr [ n - 1 ] is not equal to zero ; Otherwise ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void checkPossible ( int * arr , int n ) { for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] < arr [ i - 1 ] ) { cout << " No STRNEWLINE " ; return ; } else { arr [ i ] -= arr [ i - 1 ] ; arr [ i - 1 ] = 0 ; } } if ( arr [ n - 1 ] == 0 ) { cout << " Yes STRNEWLINE " ; } else { cout << " No STRNEWLINE " ; } } int main ( ) { int arr [ ] = { 2 , 3 , 3 , 4 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; checkPossible ( arr , N ) ; return 0 ; } |
Nearest smaller power of 2 for every digit of a number | C ++ program to implement the above approach ; Function to find the nearest power of two for every digit of a given number ; Converting number to string ; Traverse the array ; Calculate log base 2 of the current digit s [ i ] ; Highest power of 2 <= s [ i ] ; ASCII conversion ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void highestPowerOfTwo ( int num ) { string s = to_string ( num ) ; for ( int i = 0 ; i < ( int ) s . size ( ) ; i ++ ) { if ( s [ i ] == '0' ) { cout << "0" ; continue ; } int lg = log2 ( int ( s [ i ] ) - 48 ) ; int p = pow ( 2 , lg ) ; cout << char ( p + 48 ) ; } } int main ( ) { int num = 4317 ; highestPowerOfTwo ( num ) ; return 0 ; } |
Maximum prefix sum after K reversals of a given array | C ++ program for the above approach ; Function to find the maximum prefix sum after K reversals of the array ; Stores the required sum ; If K is odd , reverse the array ; Store current prefix sum of array ; Traverse the array arr [ ] ; Add arr [ i ] to currsum ; Update maximum prefix sum till now ; Print the answer ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSumAfterKReverse ( int arr [ ] , int K , int N ) { int sum = INT_MIN ; if ( K & 1 ) reverse ( arr , arr + N ) ; int currsum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { currsum += arr [ i ] ; sum = max ( sum , currsum ) ; } cout << sum ; } int main ( ) { int arr [ ] = { 1 , 5 , 8 , 9 , 11 , 2 } ; int K = 1 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maxSumAfterKReverse ( arr , K , N ) ; return 0 ; } |
Print all submasks of a given mask | C ++ Program for above approach ; Function to print the submasks of N ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void SubMasks ( int N ) { for ( int S = N ; S ; S = ( S - 1 ) & N ) { cout << S << " β " ; } } int main ( ) { int N = 25 ; SubMasks ( N ) ; return 0 ; } |
Count pairs from a given range having equal Bitwise OR and XOR values | C ++ program for the above approach ; Function to calculate ( x ^ y ) % MOD ; Initialize result ; Update x if it is more than or equal to MOD ; If y is odd , multiply x with result ; y must be even now y = y / 2 ; Return ( x ^ y ) % MOD ; Function to count total pairs ; The upper bound is 2 ^ N ; Stores the count of pairs ; Generate all possible pairs ; Find XOR of both integers ; Find OR of both integers ; If both are equal ; Increment count ; Print count % MOD ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE #define MOD 1000000007 NEW_LINE using namespace std ; long long int power ( int x , int y ) { long long int res = 1 ; x = x % MOD ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % MOD ; y = y >> 1 ; x = ( x * x ) % MOD ; } return res ; } void countPairs ( int N ) { long long int high = power ( 2 , N ) ; int count = 0 ; for ( int i = 0 ; i < high ; i ++ ) { for ( int j = 0 ; j < high ; j ++ ) { int X = ( i ^ j ) ; int Y = ( i j ) ; if ( X == Y ) { count ++ ; } } } cout << count % MOD << endl ; } int main ( ) { int N = 10 ; countPairs ( N ) ; return 0 ; } |
Count pairs from a given range having equal Bitwise OR and XOR values | C ++ program for the above approach ; Function to find the value of ( x ^ y ) % MOD ; Initialize result ; Update x if it is more than or equal to MOD ; If y is odd , multiply x with result ; y must be even now , then update y / 2 ; Return ( x ^ y ) % MOD ; Function to count total pairs ; Finding 3 ^ N % 10 ^ 9 + 7 ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE #define MOD 1000000007 NEW_LINE using namespace std ; long long int power ( int x , int y ) { long long int res = 1 ; x = x % MOD ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % MOD ; y = y >> 1 ; x = ( x * x ) % MOD ; } return res ; } void countPairs ( int N ) { cout << power ( 3 , N ) ; } int main ( ) { int N = 10 ; countPairs ( N ) ; return 0 ; } |
Minimize swaps required to place largest and smallest array elements at first and last array indices | C ++ program for the above approach ; Function to find the minimum count of adjacent swaps to move largest and smallest element at the first and the last index of the array , respectively ; Stores the smallest array element ; Stores the smallest array element ; Stores the last occurrence of the smallest array element ; Stores the first occurrence of the largest array element ; Traverse the array arr [ ] ; If a [ i ] is less than min_element ; Update min_element ; Update min_ind ; If a [ i ] is greater than max_element ; Update max_element ; Update max_ind ; If max_ind is equal to min_ind ; Return 0 ; If max_ind is greater than min_ind ; Otherwise ; Driver Code ; Input ; Print the result | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumMoves ( int * a , int n ) { int min_element = INT_MAX ; int max_element = INT_MIN ; int min_ind = -1 ; int max_ind = -1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] <= min_element ) { min_element = a [ i ] ; min_ind = i ; } if ( a [ i ] > max_element ) { max_element = a [ i ] ; max_ind = i ; } } if ( max_ind == min_ind ) { return 0 ; } else if ( max_ind > min_ind ) { return max_ind + ( n - min_ind - 2 ) ; } else { return max_ind + n - min_ind - 1 ; } } int main ( ) { int arr [ ] = { 35 , 46 , 17 , 23 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minimumMoves ( arr , N ) << endl ; } |
Find the index of the smallest element to be removed to make sum of array divisible by K | C ++ program to implement the above approach ; Function to find index of the smallest array element required to be removed to make sum divisible by K ; Stores sum of array elements ; Stores index of the smallest element removed from the array to make sum divisible by K ; Stores the smallest element removed from the array to make sum divisible by K ; Traverse the array , arr [ ] ; Update sum ; Traverse the array arr [ ] ; Calculate remaining sum ; If sum is divisible by K ; If res == - 1 or mini is greater than arr [ i ] ; Update res and mini ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findIndex ( int arr [ ] , int n , int K ) { int sum = 0 ; int res = -1 ; int mini = 1e9 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; } for ( int i = 0 ; i < n ; i ++ ) { int temp = sum - arr [ i ] ; if ( temp % K == 0 ) { if ( res == -1 mini > arr [ i ] ) { res = i + 1 ; mini = arr [ i ] ; } } } return res ; } int main ( ) { int arr [ ] = { 14 , 7 , 8 , 2 , 4 } ; int K = 7 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findIndex ( arr , N , K ) ; return 0 ; } |
Count subarrays having a single distinct element that can be obtained from a given array | C ++ program for the above approach ; Function to count subarrays of single distinct element into which given array can be split ; Stores the count ; Stores frequency of array elements ; Traverse the array ; Traverse the map ; Increase count of subarrays by ( frequency - 1 ) ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void divisionalArrays ( int arr [ 3 ] , int N ) { int sum = N ; unordered_map < int , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { mp [ arr [ i ] ] ++ ; } for ( auto x : mp ) { if ( x . second > 1 ) { sum += x . second - 1 ; } } cout << sum << endl ; } int main ( ) { int arr [ ] = { 1 , 1 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; divisionalArrays ( arr , N ) ; } |
Count inversions in a sequence generated by appending given array K times | C ++ program for the above approach ; Function to count the number of inversions in K copies of given array ; Stores count of inversions in the given array ; Stores the count of pairs of distinct array elements ; Traverse the array ; Generate each pair ; Check for each pair , if the condition is satisfied or not ; If pairs consist of distinct elements ; Count inversiosn in the sequence ; Print the answer ; Driver Code ; Given array ; Given K ; Size of the array | #include <bits/stdc++.h> NEW_LINE using namespace std ; void totalInversions ( int arr [ ] , int K , int N ) { int inv = 0 ; int X = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( arr [ i ] > arr [ j ] and i < j ) inv ++ ; if ( arr [ i ] > arr [ j ] ) X ++ ; } } int totalInv = X * K * ( K - 1 ) / 2 + inv * K ; cout << totalInv << endl ; } int main ( ) { int arr [ ] = { 2 , 1 , 3 } ; int K = 3 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; totalInversions ( arr , K , N ) ; } |
Count ways to generate an array having distinct elements at M consecutive indices | C ++ program for the above approach ; Modular function to calculate factorial ; Stores factorial of N ; Iterate over the range [ 1 , N ] ; Update result ; Function to count ways to replace array elements having 0 s with non - zero elements such that any M consecutive elements are distinct ; Store m consecutive distinct elements such that arr [ i ] is equal to B [ i % M ] ; Stores frequency of array elements ; Traverse the array arr [ ] ; If arr [ i ] is non - zero ; If B [ i % M ] is equal to 0 ; Update B [ i % M ] ; Update frequency of arr [ i ] ; If a duplicate element found in M consecutive elements ; Handling the case of inequality ; Stores count of 0 s in B [ ] ; Traverse the array , B [ ] ; If B [ i ] is 0 ; Update cnt ; Calculate factorial ; Driver Code ; Given M ; Given array ; Size of the array ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long int Fact ( int N ) { long long int result = 1 ; for ( int i = 1 ; i <= N ; i ++ ) { result = ( result * i ) ; } return result ; } void numberOfWays ( int M , int arr [ ] , int N ) { int B [ M ] = { 0 } ; int counter [ M + 1 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] != 0 ) { if ( B [ i % M ] == 0 ) { B [ i % M ] = arr [ i ] ; counter [ arr [ i ] ] ++ ; if ( counter [ arr [ i ] ] > 1 ) { cout << 0 << endl ; return ; } } else if ( B [ i % M ] != arr [ i ] ) { cout << 0 << endl ; return ; } } } int cnt = 0 ; for ( int i = 0 ; i < M ; i ++ ) { if ( B [ i ] == 0 ) { cnt ++ ; } } cout << Fact ( cnt ) << endl ; } int main ( ) { int M = 4 ; int arr [ ] = { 1 , 0 , 3 , 0 , 0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; numberOfWays ( M , arr , N ) ; } |
Maximize sum by traversing diagonally from each cell of a given Matrix | C ++ program for the above approach ; Function to find the maximum sum ; Loop to traverse through the upper triangular matrix and update the maximum sum to ans ; Traverse through the lower triangular matrix ; Driver Code ; Given matrix ; Given dimension | #include <bits/stdc++.h> NEW_LINE using namespace std ; int MaximumSum ( vector < vector < int > > & arr , int n ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int x = 0 , y = i , sum = 0 ; for ( int j = i ; j < n ; j ++ ) { sum += arr [ x ++ ] [ y ++ ] ; } if ( sum > ans ) ans = sum ; } for ( int i = 1 ; i < n ; i ++ ) { int x = i , y = 0 , sum = 0 ; for ( int j = i ; j < n ; j ++ ) { sum += arr [ x ++ ] [ y ++ ] ; } if ( sum > ans ) ans = sum ; } return ans ; } int main ( ) { vector < vector < int > > arr ; arr = { { 1 , 2 , 3 } , { 3 , 5 , 10 } , { 1 , 3 , 5 } } ; int n = arr . size ( ) ; cout << MaximumSum ( arr , n ) ; return 0 ; } |
Count array elements exceeding all previous elements as well as the next array element | C ++ program for the above approach ; Function to count array elements satisfying the given condition ; If there is only one array element ; Traverse the array ; Update the maximum element encountered so far ; Count the number of array elements strictly greater than all previous and immediately next elements ; Print the count ; Driver Code ; Given array ; Size of the array | #include <bits/stdc++.h> NEW_LINE using namespace std ; int numberOfIntegers ( int arr [ ] , int N ) { int cur_max = 0 , count = 0 ; if ( N == 1 ) { count = 1 ; } else { for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( arr [ i ] > cur_max ) { cur_max = arr [ i ] ; if ( arr [ i ] > arr [ i + 1 ] ) { count ++ ; } } } if ( arr [ N - 1 ] > cur_max ) count ++ ; } cout << count ; } int main ( ) { int arr [ ] = { 1 , 2 , 0 , 7 , 2 , 0 , 2 , 0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; numberOfIntegers ( arr , N ) ; return 0 ; } |
Count ways to represent N as sum of powers of 2 | C ++ program for above implementation ; Base Cases ; Check if 2 ^ k can be used as one of the numbers or not ; Otherwise ; Count number of ways to N using 2 ^ k - 1 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int numberOfWays ( int n , int k ) { if ( n == 0 ) return 1 ; if ( k == 0 ) return 1 ; if ( n >= pow ( 2 , k ) ) { int curr_val = pow ( 2 , k ) ; return numberOfWays ( n - curr_val , k ) + numberOfWays ( n , k - 1 ) ; } else return numberOfWays ( n , k - 1 ) ; } int main ( ) { int n = 4 ; int k = log2 ( n ) ; cout << numberOfWays ( n , k ) << endl ; } |
Count ways to obtain triplets with positive product consisting of at most one negative element | C ++ Program to implement the above approach ; Function to calculate possible number of triplets ; counting frequency of positive numbers in array ; If current array element is positive ; Increment frequency ; Select a triplet from freq elements such that i < j < k . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long int possibleTriplets ( int arr [ ] , int N ) { int freq = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] > 0 ) { freq ++ ; } } return ( freq * 1LL * ( freq - 1 ) * ( freq - 2 ) ) / 6 ; } int main ( ) { int arr [ ] = { 2 , 5 , -9 , -3 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << possibleTriplets ( arr , N ) ; return 0 ; } |
Maximize difference between sum of even and odd | C ++ program to implement the above approach ; Function to find the maximum possible difference between sum of even and odd indices ; Convert arr [ ] into 1 - based indexing ; Reverse the array ; Convert arr [ ] into 1 based index ; Reverse the array ; Stores maximum difference between sum of even and odd indexed elements ; Traverse the array ; If arr [ i ] is local maxima ; Update maxDiff ; If arr [ i ] is local minima ; Update maxDiff ; Driver Code ; Size of array ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxPossibleDiff ( vector < int > & arr , int N ) { arr . push_back ( -1 ) ; reverse ( arr . begin ( ) , arr . end ( ) ) ; arr . push_back ( -1 ) ; reverse ( arr . begin ( ) , arr . end ( ) ) ; int maxDiff = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { if ( arr [ i ] > arr [ i - 1 ] && arr [ i ] > arr [ i + 1 ] ) { maxDiff += arr [ i ] ; } if ( arr [ i ] < arr [ i - 1 ] && arr [ i ] < arr [ i + 1 ] ) { maxDiff -= arr [ i ] ; } } cout << maxDiff ; } int main ( ) { vector < int > arr = { 3 , 2 , 1 , 4 , 5 , 2 , 1 , 7 , 8 , 9 } ; int N = arr . size ( ) ; maxPossibleDiff ( arr , N ) ; return 0 ; } |
Reverse all elements of given circular array starting from index K | C ++ program for the above approach ; Function to print the array arr [ ] ; Print the array ; Function to reverse elements of given circular array starting from index k ; Initialize two variables as start = k and end = k - 1 ; Initialize count = N / 2 ; Loop while count > 0 ; Swap the elements at index ( start % N ) and ( end % N ) ; Update the start and end ; If end equals to - 1 set end = N - 1 ; Print the circular array ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printArray ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { cout << arr [ i ] << " β " ; } } void reverseCircularArray ( int arr [ ] , int N , int K ) { int start = K , end = K - 1 ; int count = N / 2 ; while ( count -- ) { int temp = arr [ start % N ] ; arr [ start % N ] = arr [ end % N ] ; arr [ end % N ] = temp ; start ++ ; end -- ; if ( end == -1 ) { end = N - 1 ; } } printArray ( arr , N ) ; } int main ( ) { int arr [ ] = { 3 , 5 , 2 , 4 , 1 } ; int K = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; reverseCircularArray ( arr , N , K ) ; return 0 ; } |
Generate a Matrix such that given Matrix elements are equal to Bitwise OR of all corresponding row and column elements of generated Matrix | C ++ program for the above approach ; Function to find the matrix , A [ ] [ ] satisfying the given conditions ; Store the final matrix ; Initialize all the elements of the matrix A with 1 ; Traverse the matrix B [ ] [ ] row - wise ; If B [ i ] [ j ] is equal to 0 ; Mark all the elements of ith row of A [ ] [ ] as 0 ; Mark all the elements of jth column of A [ ] [ ] as 0 ; Check if the matrix B [ ] [ ] can be made using matrix A [ ] [ ] ; Store the bitwise OR of all elements of A [ ] [ ] in ith row and jth column ; Traverse through ith row ; Traverse through jth column ; If B [ i ] [ j ] is not equal to c , print " Not β Possible " ; Print the final matrix A [ ] [ ] ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findOriginalMatrix ( vector < vector < int > > B , int N , int M ) { int A [ N ] [ M ] ; for ( int i = 0 ; i < N ; ++ i ) { for ( int j = 0 ; j < M ; ++ j ) { A [ i ] [ j ] = 1 ; } } for ( int i = 0 ; i < N ; ++ i ) { for ( int j = 0 ; j < M ; ++ j ) { if ( B [ i ] [ j ] == 0 ) { for ( int k = 0 ; k < M ; ++ k ) { A [ i ] [ k ] = 0 ; } for ( int k = 0 ; k < N ; ++ k ) { A [ k ] [ j ] = 0 ; } } } } for ( int i = 0 ; i < N ; ++ i ) { for ( int j = 0 ; j < M ; ++ j ) { int c = 0 ; for ( int k = 0 ; k < M ; ++ k ) { if ( c == 1 ) break ; c += A [ i ] [ k ] ; } for ( int k = 0 ; k < N ; ++ k ) { if ( c == 1 ) break ; c += A [ k ] [ j ] ; } if ( c != B [ i ] [ j ] ) { cout << " Not β Possible " ; return ; } } } for ( int i = 0 ; i < N ; ++ i ) { for ( int j = 0 ; j < M ; ++ j ) { cout << A [ i ] [ j ] << " β " ; } cout << " STRNEWLINE " ; } } int main ( ) { vector < vector < int > > B { { 1 , 1 , 1 } , { 1 , 1 , 1 } } ; int N = B . size ( ) ; int M = B [ 0 ] . size ( ) ; findOriginalMatrix ( B , N , M ) ; return 0 ; } |
Minimize cost to make X and Y equal by given increments | C ++ program for the above approach ; Function to find gcd of x and y ; Function to find lcm of x and y ; Function to find minimum Cost ; Subtracted initial cost of x ; Subtracted initial cost of y ; Driver Code ; Returns the minimum cost required | #include <iostream> NEW_LINE using namespace std ; int gcd ( int x , int y ) { if ( y == 0 ) return x ; return gcd ( y , x % y ) ; } int lcm ( int x , int y ) { return ( x * y ) / gcd ( x , y ) ; } int minimumCost ( int x , int y ) { int lcm_ = lcm ( x , y ) ; int costx = ( lcm_ - x ) / x ; int costy = ( lcm_ - y ) / y ; return costx + costy ; } int main ( ) { int x = 5 , y = 17 ; cout << minimumCost ( x , y ) << endl ; } |
Find GCD between the sum of two given integers raised to the power of N and their difference | C ++ program for the above approach ; Function to find the value of ( a ^ n ) % d ; Stores the value of ( a ^ n ) % d ; Calculate the value of ( a ^ n ) % d ; If n is odd ; Update res ; Update a ; Update n ; Function to find the GCD of ( p ^ n + q ^ n ) and p - q mod d ; If p and q are equal ; Stores GCD of ( p ^ n + q ^ n ) and ( p - q ) mod d ; Stores the value of ( p - q ) ; Stores square root of num ; Find the divisors of num . ; If i divides num ; Stores power of ( p ^ n ) mod i ; Stores power of ( q ^ n ) mod i ; Stores power of ( p ^ n + q ^ n ) mod i ; If ( p ^ n + q ^ n ) is divisible by i ; Calculate the largest divisor . ; If i divides num , ( num / i ) also divides num . Hence , calculate temp . ; If ( p ^ n + q ^ n ) is divisible by ( num / i ) ; Calculate the largest divisor . ; Driver Code ; Given p , q and n ; Function Call | #include <bits/stdc++.h> NEW_LINE #define mod 1000000007 NEW_LINE using namespace std ; long long int power ( long long a , long long n , long long int d ) { long long int res = 1 ; while ( n ) { if ( n % 2 ) { res = ( ( res % d ) * ( a % d ) ) % d ; } a = ( ( a % d ) * ( a % d ) ) % d ; n /= 2 ; } return res ; } long long int gcd ( long long p , long long q , long long n ) { if ( p == q ) { return ( power ( p , n , mod ) + power ( q , n , mod ) ) % mod ; } long long int candidate = 1 ; long long int num = p - q ; long long int sq = sqrt ( num ) ; for ( long long i = 1 ; i <= sq ; ++ i ) { if ( num % i == 0 ) { long long int X = power ( p , n , i ) ; long long int Y = power ( q , n , i ) ; long long int temp = ( X + Y ) % i ; if ( temp == 0 ) { candidate = max ( candidate , i ) ; } temp = ( power ( p , n , num / i ) + power ( q , n , num / i ) ) % ( num / i ) ; if ( temp == 0 ) { candidate = max ( candidate , num / i ) ; } } } return candidate % mod ; } int main ( ) { long long int p , q , n ; p = 10 ; q = 6 ; n = 5 ; cout << gcd ( p , q , n ) ; return 0 ; } |
Split given isosceles triangle of height H into N equal parts | C ++ Code for above approach ; Function to divide the isosceles triangle in equal parts by making N - 1 cuts parallel to the base ; Iterate over the range [ 1 , n - 1 ] ; Driver code ; Given N ; Given H ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findPoint ( int n , int h ) { for ( int i = 1 ; i < n ; i ++ ) printf ( " % .2f β " , sqrt ( i / ( n * 1.0 ) ) * h ) ; } int main ( ) { int n = 3 ; int h = 2 ; findPoint ( n , h ) ; return 0 ; } |
Count all possible values of K less than Y such that GCD ( X , Y ) = GCD ( X + K , Y ) | C ++ program for the above approach ; Function to find the gcd of a and b ; Function to find the number of Ks ; Find gcd ; Calculating value of totient function for n ; Driver Code ; Given X and Y | #include <iostream> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } int calculateK ( int x , int y ) { int g = gcd ( x , y ) ; int n = y / g ; int res = n ; for ( int i = 2 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { res -= ( res / i ) ; while ( n % i == 0 ) n /= i ; } } if ( n != 1 ) res -= ( res / n ) ; return res ; } int main ( ) { int x = 3 , y = 15 ; cout << calculateK ( x , y ) << endl ; } |
Check if a Float value is equivalent to an Integer value | C ++ program to implement the above approach ; Function to check if N is equivalent to an integer ; Convert float value of N to integer ; If N is not equivalent to any integer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isInteger ( double N ) { int X = N ; double temp2 = N - X ; if ( temp2 > 0 ) { return false ; } return true ; } int main ( ) { double N = 1.5 ; if ( isInteger ( N ) ) { cout << " YES " ; } else { cout << " NO " ; } return 0 ; } |
Find the nearest power of 2 for every array element | C ++ program to implement the above approach ; Function to find nearest power of two for every element in the given array ; Traverse the array ; Calculate log of the current array element ; Find the nearest ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void nearestPowerOfTwo ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { int lg = log2 ( arr [ i ] ) ; int a = pow ( 2 , lg ) ; int b = pow ( 2 , lg + 1 ) ; if ( ( arr [ i ] - a ) < ( b - arr [ i ] ) ) cout << a << " β " ; else cout << b << " β " ; } } int main ( ) { int arr [ ] = { 5 , 2 , 7 , 12 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; nearestPowerOfTwo ( arr , N ) ; return 0 ; } |
Flip bits of the sum of count of set bits of two given numbers | C ++ program for the above approach ; Function to count number of set bits in integer ; Variable for counting set bits ; Function to invert bits of a number ; Calculate number of bits of N - 1 ; ; Function to invert the sum of set bits in A and B ; Stores sum of set bits ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSetBits ( int n ) { int count = 0 ; while ( n ) { n &= ( n - 1 ) ; count ++ ; } return count ; } int invertBits ( int n ) { int x = log2 ( n ) ; int m = 1 << x ; m = m | m - 1 ; n = n ^ m ; return n ; } void invertSum ( int A , int B ) { int temp = countSetBits ( A ) + countSetBits ( B ) ; cout << invertBits ( temp ) << endl ; } int main ( ) { int A = 5 ; int B = 7 ; invertSum ( A , B ) ; return 0 ; } |
Sum of Bitwise XOR of each array element with all other array elements | C ++ program for the above approach ; Function to calculate for each array element , sum of its Bitwise XOR with all other array elements ; Declare an array of size 64 to store count of each bit ; Traversing the array ; Check if bit is present of not ; Increase the bit position ; Reduce the number to half ; Traverse the array ; Stores the bit position ; Stores the sum of Bitwise XOR ; Check if bit is present of not ; Reduce the number to its half ; Print the sum for A [ i ] ; Driver Code ; Given array ; Given N ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void XOR_for_every_i ( int A [ ] , int N ) { int frequency_of_bits [ 32 ] { } ; for ( int i = 0 ; i < N ; i ++ ) { int bit_position = 0 ; int M = A [ i ] ; while ( M ) { if ( M & 1 ) { frequency_of_bits [ bit_position ] += 1 ; } bit_position += 1 ; M >>= 1 ; } } for ( int i = 0 ; i < N ; i ++ ) { int M = A [ i ] ; int value_at_that_bit = 1 ; int XOR_sum = 0 ; for ( int bit_position = 0 ; bit_position < 32 ; bit_position ++ ) { if ( M & 1 ) { XOR_sum += ( N - frequency_of_bits [ bit_position ] ) * value_at_that_bit ; } else { XOR_sum += ( frequency_of_bits [ bit_position ] ) * value_at_that_bit ; } M >>= 1 ; value_at_that_bit <<= 1 ; } cout << XOR_sum << ' β ' ; } return ; } int main ( ) { int A [ ] = { 1 , 2 , 3 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; XOR_for_every_i ( A , N ) ; return 0 ; } |
Minimize the maximum difference of any pair by doubling odd elements and reducing even elements by half | C ++ program for the above approach ; Function to minimize the maximum difference between any pair of elements of the array by the given operations ; Traverse the array ; If current element is even ; Insert it into even ; Otherwise ; Make it even by multiplying by 2 and insert it into set ; Calculate difference between first and the last element of the set ; Iterate until difference is minimized ; Erase the current element ; Reduce current element by half and insert it into the Set ; Update difference ; Return the resultant difference ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumMaxDiff ( vector < int > & nums ) { set < int > s ; for ( int i = 0 ; i < nums . size ( ) ; i ++ ) { if ( nums [ i ] % 2 == 0 ) s . insert ( nums [ i ] ) ; else s . insert ( nums [ i ] * 2 ) ; } int res = * s . rbegin ( ) - * s . begin ( ) ; while ( * s . rbegin ( ) % 2 == 0 ) { int x = * s . rbegin ( ) ; s . erase ( x ) ; s . insert ( x / 2 ) ; res = min ( res , * s . rbegin ( ) - * s . begin ( ) ) ; } return res ; } int main ( ) { vector < int > arr = { 1 , 2 , 5 , 9 } ; cout << minimumMaxDiff ( arr ) ; } |
XOR of all even numbers from a given range | C ++ Implementation of the above approach ; Function to calculate XOR of numbers in the range [ 1 , n ] ; If n is divisible by 4 ; If n mod 4 is equal to 1 ; If n mod 4 is equal to 2 ; Function to find XOR of even numbers in the range [ l , r ] ; Stores XOR of even numbers in the range [ 1 , l - 1 ] ; Stores XOR of even numbers in the range [ 1 , r ] ; Update xor_r ; Update xor_l ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int bitwiseXorRange ( int n ) { if ( n % 4 == 0 ) return n ; if ( n % 4 == 1 ) return 1 ; if ( n % 4 == 2 ) return n + 1 ; return 0 ; } int evenXorRange ( int l , int r ) { int xor_l ; int xor_r ; xor_r = 2 * bitwiseXorRange ( r / 2 ) ; xor_l = 2 * bitwiseXorRange ( ( l - 1 ) / 2 ) ; return xor_l ^ xor_r ; } int main ( ) { int l = 10 ; int r = 20 ; cout << evenXorRange ( l , r ) ; return 0 ; } |
Program to calculate Variance of first N Natural Numbers | C ++ Program to implement the above approach ; Function to calculate Variance of first N natural numbers ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long double find_Variance ( int n ) { long long int numerator = n * n - 1 ; long double ans = ( numerator * 1.0 ) / 12 ; return ans ; } int main ( ) { int N = 5 ; cout << fixed << setprecision ( 6 ) << find_Variance ( N ) ; } |
Count digits present in each element of a given Matrix | C ++ program for the above approach ; Function to count the number of digits in each element of the given matrix ; Traverse each row of arr [ ] [ ] ; Traverse each column of arr [ ] [ ] ; Store the current matrix element ; Count the number of digits ; Print the result ; Driver Code ; Given matrix | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int M = 3 ; const int N = 3 ; void countDigit ( int arr [ M ] [ N ] ) { for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { int X = arr [ i ] [ j ] ; int d = floor ( log10 ( X ) * 1.0 ) + 1 ; cout << d << " β " ; } cout << endl ; } } int main ( ) { int arr [ ] [ 3 ] = { { 27 , 173 , 5 } , { 21 , 6 , 624 } , { 5 , 321 , 49 } } ; countDigit ( arr ) ; return 0 ; } |
Difference between sum of odd and even frequent elements in an Array | C ++ program to find absolute difference between the sum of all odd frequenct and even frequent elements in an array ; Function to find the sum of all even and odd frequent elements in an array ; Stores the frequency of array elements ; Traverse the array ; Update frequency of current element ; Stores sum of odd and even frequent elements ; Traverse the map ; If frequency is odd ; Add sum of all occurrences of current element to sum_odd ; If frequency is even ; Add sum of all occurrences of current element to sum_even ; Calculate difference between their sum ; Return diff ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findSum ( int arr [ ] , int N ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { mp [ arr [ i ] ] ++ ; } int sum_odd = 0 , sum_even = 0 ; for ( auto itr = mp . begin ( ) ; itr != mp . end ( ) ; itr ++ ) { if ( itr -> second % 2 != 0 ) sum_odd += ( itr -> first ) * ( itr -> second ) ; if ( itr -> second % 2 == 0 ) sum_even += ( itr -> first ) * ( itr -> second ) ; } int diff = sum_even - sum_odd ; return diff ; } int main ( ) { int arr [ ] = { 1 , 5 , 5 , 2 , 4 , 3 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findSum ( arr , N ) ; return 0 ; } |
Count N | C ++ program for the above approach ; Function to find the number of arrays following the given condition ; Initialize answer ; Calculate nPm ; Print ans ; Driver Code ; Given N and M ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; typedef long long ll ; void noOfArraysPossible ( ll N , ll M ) { ll ans = 1 ; for ( ll i = 0 ; i < N ; ++ i ) { ans = ans * ( M - i ) ; } cout << ans ; } int main ( ) { ll N = 2 , M = 3 ; noOfArraysPossible ( N , M ) ; return 0 ; } |
Permutations of an array having sum of Bitwise AND of adjacent elements at least K | C ++ program for the above approach ; Function to print all permutations of arr [ ] such that the sum of Bitwise AND of all adjacent element is at least K ; To check if any permutation exists or not ; Sort the given array ; Find all possible permutations ; Stores the sum of bitwise AND of adjacent elements of the current permutation ; Traverse the current permutation of arr [ ] ; Update the sum ; If the sum is at least K , then print the current permutation ; Set the flag variable ; Print the current permutation ; If flag is unset , then print - 1 ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printPermutation ( int arr [ ] , int n , int k ) { bool flag = false ; sort ( arr , arr + n ) ; do { int sum = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { sum += arr [ i ] & arr [ i + 1 ] ; } if ( sum >= k ) { flag = true ; for ( int i = 0 ; i < n ; i ++ ) { cout << arr [ i ] << " β " ; } cout << " STRNEWLINE " ; } } while ( next_permutation ( arr , arr + n ) ) ; if ( flag == false ) { cout << " - 1" ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int K = 8 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printPermutation ( arr , N , K ) ; return 0 ; } |
Positive integers up to N that are not present in given Array | CPP program for the above approach ; Function to find positive integers from 1 to N that are not present in the array ; Declare bitset ; Iterate from 0 to M - 1 ; Iterate from 0 to len - 1 ; Iterate from bset . _Find_first ( ) to bset . size ( ) - 1 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findMissingNumbers ( int arr [ ] , int len ) { const int M = 15 ; bitset < M > bset ; for ( int i = 0 ; i < M ; i ++ ) { bset . set ( i ) ; } for ( int i = 0 ; i < len ; i ++ ) { bset . set ( arr [ i ] - 1 , 0 ) ; } for ( int i = bset . _Find_first ( ) ; i < bset . size ( ) ; i = bset . _Find_next ( i ) ) { if ( i + 1 > len ) break ; cout << i + 1 << endl ; } } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 6 , 8 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findMissingNumbers ( arr , n ) ; return 0 ; } |
Sum of the first N terms of XOR Fibonacci series | C ++ program for the above approach ; Function to calculate the sum of the first N terms of XOR Fibonacci Series ; Base Case ; Stores the sum of the first N terms ; Iterate from [ 0 , n - 3 ] ; Store XOR of last 2 elements ; Update sum ; Update the first element ; Update the second element ; Print the final sum ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findSum ( int a , int b , int n ) { if ( n == 1 ) { cout << a ; return ; } int s = a + b ; for ( int i = 0 ; i < n - 2 ; i ++ ) { int x = a xor b ; s += x ; a = b ; b = x ; } cout << s ; } int main ( ) { int a = 2 , b = 5 , N = 8 ; findSum ( a , b , N ) ; return 0 ; } |
Sum of the first N terms of XOR Fibonacci series | C ++ program for the above approach ; Function to calculate sum of the first N terms of XOR Fibonacci Series ; Store the sum of first n terms ; Store XOR of a and b ; Case 1 : If n is divisible by 3 ; Case 2 : If n % 3 leaves remainder 1 ; Case 3 : If n % 3 leaves remainder 2 on division by 3 ; Print the final sum ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findSum ( int a , int b , int n ) { int sum = 0 ; int x = a ^ b ; if ( n % 3 == 0 ) { sum = ( n / 3 ) * ( a + b + x ) ; } else if ( n % 3 == 1 ) { sum = ( n / 3 ) * ( a + b + x ) + a ; } else { sum = ( n / 3 ) * ( a + b + x ) + a + b ; } cout << sum ; } int main ( ) { int a = 2 , b = 5 , N = 8 ; findSum ( a , b , N ) ; return 0 ; } |
Length of the longest subarray whose Bitwise XOR is K | C ++ program to implement the above approach ; Function to find the length of the longest subarray whose bitwise XOR is equal to K ; Stores prefix XOR of the array ; Stores length of longest subarray having bitwise XOR equal to K ; Stores index of prefix XOR of the array ; Insert 0 into the map ; Traverse the array ; Update prefixXOR ; If ( prefixXOR ^ K ) present in the map ; Update maxLen ; If prefixXOR not present in the Map ; Insert prefixXOR into the map ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int LongestLenXORK ( int arr [ ] , int N , int K ) { int prefixXOR = 0 ; int maxLen = 0 ; map < int , int > mp ; mp [ 0 ] = -1 ; for ( int i = 0 ; i < N ; i ++ ) { prefixXOR ^= arr [ i ] ; if ( mp . count ( prefixXOR ^ K ) ) { maxLen = max ( maxLen , ( i - mp [ prefixXOR ^ K ] ) ) ; } if ( ! mp . count ( prefixXOR ) ) { mp [ prefixXOR ] = i ; } } return maxLen ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 7 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 1 ; cout << LongestLenXORK ( arr , N , K ) ; return 0 ; } |
Two Dimensional Difference Array | C ++ Program to implement the above approach ; Function to initialize the difference array ; Function to add k to the specified submatrix ( r1 , c1 ) to ( r2 , c2 ) ; Function to print the modified array ; Function to perform the given queries ; Difference array ; Function to initialize the difference array ; Count of queries ; Perform Queries ; Driver Code ; Given Matrix ; Given Queries | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 3 NEW_LINE #define M 3 NEW_LINE void intializeDiff ( int D [ N ] [ M + 1 ] , int A [ N ] [ M ] ) { for ( int i = 0 ; i < N ; i ++ ) { D [ i ] [ 0 ] = A [ i ] [ 0 ] ; D [ i ] [ M ] = 0 ; } for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 1 ; j < M ; j ++ ) D [ i ] [ j ] = A [ i ] [ j ] - A [ i ] [ j - 1 ] ; } } void update ( int D [ N ] [ M + 1 ] , int k , int r1 , int c1 , int r2 , int c2 ) { for ( int i = r1 ; i <= r2 ; i ++ ) { D [ i ] [ c1 ] += k ; D [ i ] [ c2 + 1 ] -= k ; } } void printArray ( int A [ N ] [ M ] , int D [ N ] [ M + 1 ] ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( j == 0 ) A [ i ] [ j ] = D [ i ] [ j ] ; else A [ i ] [ j ] = D [ i ] [ j ] + A [ i ] [ j - 1 ] ; cout << A [ i ] [ j ] << " β " ; } cout << endl ; } } void performQueries ( int A [ N ] [ M ] , vector < vector < int > > Queries ) { int D [ N ] [ M + 1 ] ; intializeDiff ( D , A ) ; int Q = Queries . size ( ) ; for ( int i = 0 ; i < Q ; i ++ ) { update ( D , Queries [ i ] [ 0 ] , Queries [ i ] [ 1 ] , Queries [ i ] [ 2 ] , Queries [ i ] [ 3 ] , Queries [ i ] [ 4 ] ) ; } printArray ( A , D ) ; } int main ( ) { int A [ N ] [ M ] = { { 1 , 2 , 3 } , { 1 , 1 , 0 } , { 4 , -2 , 2 } } ; vector < vector < int > > Queries = { { 2 , 0 , 0 , 1 , 1 } , { -1 , 1 , 0 , 2 , 2 } } ; performQueries ( A , Queries ) ; return 0 ; } |
Minimum value to be added to maximize Bitwise XOR of the given array | C ++ program for the above approach ; Function to find complement of an integer ; Count the number of bits of maxElement ; Return 1 's complement ; Function to find the value required to be added to maximize XOR of the given array ; Stores the required value to be added to the array ; Stores the maximum array element ; Traverse the array ; Update XOR of the array ; Find maximum element in array ; Calculate 1 s ' complement ; Return the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned int onesComplement ( unsigned int n , int maxElement ) { int bits = floor ( log2 ( maxElement ) ) + 1 ; return ( ( 1 << bits ) - 1 ) ^ n ; } int findNumber ( int arr [ ] , int n ) { unsigned int res = 0 ; int maxElement = 0 ; for ( int i = 0 ; i < n ; i ++ ) { res = res ^ arr [ i ] ; if ( maxElement < arr [ i ] ) maxElement = arr [ i ] ; } res = onesComplement ( res , maxElement ) ; return ( res ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findNumber ( arr , N ) ; return 0 ; } |
Count ways to select K array elements lying in a given range | C ++ program to implement the above approach ; Function to calculate factorial of all the numbers up to N ; Factorial of 0 is 1 ; Calculate factorial of all the numbers upto N ; Calculate factorial of i ; Function to find the count of ways to select at least K elements whose values in range [ L , R ] ; Stores count of ways to select at least K elements whose values in range [ L , R ] ; Stores count of numbers having value lies in the range [ L , R ] ; Traverse the array ; Checks if the array elements lie in the given range ; Update cntNum ; Stores factorial of numbers upto N ; Calculate total ways to select at least K elements whose values lies in [ L , R ] ; Update cntWays ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > calculateFactorial ( int N ) { vector < int > fact ( N + 1 ) ; fact [ 0 ] = 1 ; for ( int i = 1 ; i <= N ; i ++ ) { fact [ i ] = fact [ i - 1 ] * i ; } return fact ; } int cntWaysSelection ( int arr [ ] , int N , int K , int L , int R ) { int cntWays = 0 ; int cntNum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] >= L && arr [ i ] <= R ) { cntNum ++ ; } } vector < int > fact = calculateFactorial ( cntNum ) ; for ( int i = K ; i <= cntNum ; i ++ ) { cntWays += fact [ cntNum ] / ( fact [ i ] * fact [ cntNum - i ] ) ; } return cntWays ; } int main ( ) { int arr [ ] = { 12 , 4 , 6 , 13 , 5 , 10 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; int L = 4 ; int R = 10 ; cout << cntWaysSelection ( arr , N , K , L , R ) ; } |
Bitwise AND of all unordered pairs from a given array | C ++ program to implement the above approach ; Function to calculate bitwise AND of all pairs from the given array ; Stores bitwise AND of all possible pairs ; Generate all possible pairs ; Calculate bitwise AND of each pair ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int TotalAndPair ( int arr [ ] , int N ) { int totalAND = ( 1 << 30 ) - 1 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { totalAND &= arr [ i ] & arr [ j ] ; } } return totalAND ; } int main ( ) { int arr [ ] = { 4 , 5 , 12 , 15 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << TotalAndPair ( arr , N ) ; } |
Modify N by adding its smallest positive divisor exactly K times | C ++ program to implement the above approach ; Function to find the smallest divisor of N greater than 1 ; If i is a divisor of N ; If N is a prime number ; Function to find the value of N by performing the operations K times ; Iterate over the range [ 1 , K ] ; Update N ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int smallestDivisorGr1 ( int N ) { for ( int i = 2 ; i <= sqrt ( N ) ; i ++ ) { if ( N % i == 0 ) { return i ; } } return N ; } int findValOfNWithOperat ( int N , int K ) { for ( int i = 1 ; i <= K ; i ++ ) { N += smallestDivisorGr1 ( N ) ; } return N ; } int main ( ) { int N = 6 , K = 4 ; cout << findValOfNWithOperat ( N , K ) ; return 0 ; } |
Sum of all possible triplet products from given ranges | C ++ program to implement the above approach ; Function to find the sum of all possible triplet products ( i * j * k ) ; Stores sum required sum ; Iterate over all possible values of i ; Iterate over all possible values of j ; Iterate over all possible values of k ; Stores the product of ( i * j * k ) ; Update sum ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define M 1000000007 NEW_LINE long long findTripleSum ( long long A , long long B , long long C ) { long long sum = 0 ; for ( long long i = 1 ; i <= A ; i ++ ) { for ( long long j = 1 ; j <= B ; j ++ ) { for ( long long k = 1 ; k <= C ; k ++ ) { long long prod = ( ( ( i % M ) * ( j % M ) ) % M * ( k % M ) ) % M ; sum = ( sum + prod ) % M ; } } } return sum ; } int main ( ) { long long A = 10 ; long long B = 100 ; long long C = 1000 ; cout << findTripleSum ( A , B , C ) ; return 0 ; } |
Sum of all possible triplet products from given ranges | C ++ implementation to implement the above approach ; Function to find the value of power ( X , N ) % M ; Stores the value of ( X ^ N ) % M ; Calculate the value of power ( x , N ) % M ; If N is odd ; Update res ; Update x ; Update N ; Function to find modulo multiplicative inverse of X under modulo M ; Function to find the sum of all possible triplet products ( i * j * k ) ; Stores modulo multiplicative inverse of 8 ; Stores the sum of all possible values of ( i * j * k ) ; Update res ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define M 1000000007 NEW_LINE long long power ( long long x , long long N ) { long long res = 1 ; while ( N > 0 ) { if ( N & 1 ) { res = ( res * x ) % M ; } x = ( x * x ) % M ; N = N >> 1 ; } return res ; } long long modinv ( long long X ) { return power ( X , M - 2 ) ; } int findTripleSum ( long long A , long long B , long long C ) { long long MMI = modinv ( 8 ) ; long long res = 0 ; res = ( ( ( ( A % M * ( A + 1 ) % M ) % M * ( B % M * ( B + 1 ) % M ) % M ) % M * ( C % M * ( C + 1 ) % M ) % M ) % M * MMI ) % M ; return res ; } int main ( ) { long long A = 10 ; long long B = 100 ; long long C = 1000 ; cout << findTripleSum ( A , B , C ) ; return 0 ; } |
Maximize minimum of array generated by maximums of same indexed elements of two rows of a given Matrix | C ++ program for the above approach ; Function to find the maximum of minimum of array constructed from any two rows of the given matrix ; Initialize global max as INT_MIN ; Iterate through the rows ; Iterate through remaining rows ; Initialize row_min as INT_MAX ; Iterate through the column values of two rows ; Find max of two elements ; Update the row_min ; Update the global_max ; Print the global max ; Driver Code ; Given matrix mat [ ] [ ] ; Given number of rows and columns ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getMaximum ( int N , int M , vector < vector < int > > mat ) { int global_max = INT_MIN ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { int row_min = INT_MAX ; for ( int k = 0 ; k < M ; k ++ ) { int m = max ( mat [ i ] [ k ] , mat [ j ] [ k ] ) ; row_min = min ( row_min , m ) ; } global_max = max ( global_max , row_min ) ; } } return global_max ; } int main ( ) { vector < vector < int > > mat = { { 5 , 0 , 3 , 1 , 2 } , { 1 , 8 , 9 , 1 , 3 } , { 1 , 2 , 3 , 4 , 5 } , { 9 , 1 , 0 , 3 , 7 } , { 2 , 3 , 0 , 6 , 3 } , { 6 , 4 , 1 , 7 , 0 } } ; int N = 6 , M = 5 ; cout << getMaximum ( N , M , mat ) ; return 0 ; } |
Maximize sum of MEX values of each node in an N | C ++ program for the above approach ; Function to create an N - ary Tree ; Traverse the edges ; Add edges ; Function to get the maximum sum of MEX values of tree rooted at 1 ; Initialize mex ; Iterate through all children of node ; Recursively find maximum sum of MEX values of each node in tree rooted at u ; Store the maximum sum of MEX of among all subtrees ; Increase the size of tree rooted at current node ; Resulting MEX for the current node of the recursive call ; Driver Code ; Given N nodes ; Given N - 1 edges ; Stores the tree ; Generates the tree ; Returns maximum sum of MEX values of each node | #include <bits/stdc++.h> NEW_LINE using namespace std ; void makeTree ( vector < int > tree [ ] , pair < int , int > edges [ ] , int N ) { for ( int i = 0 ; i < N - 1 ; i ++ ) { int u = edges [ i ] . first ; int v = edges [ i ] . second ; tree [ u ] . push_back ( v ) ; } } pair < int , int > dfs ( int node , vector < int > tree [ ] ) { int mex = 0 ; int size = 1 ; for ( int u : tree [ node ] ) { pair < int , int > temp = dfs ( u , tree ) ; mex = max ( mex , temp . first ) ; size += temp . second ; } return { mex + size , size } ; } int main ( ) { int N = 7 ; pair < int , int > edges [ ] = { { 1 , 4 } , { 1 , 5 } , { 5 , 2 } , { 5 , 3 } , { 4 , 7 } , { 7 , 6 } } ; vector < int > tree [ N + 1 ] ; makeTree ( tree , edges , N ) ; cout << dfs ( 1 , tree ) . first ; return 0 ; } |
Minimum value exceeding X whose count of divisors has different parity with count of divisors of X | C ++ program for the above approach ; Function to count divisors of n ; Function to find the minimum value exceeding x whose count of divisors has different parity with count of divisors of X ; Divisor count of x ; Iterate from x + 1 and check for each element ; Driver Code ; Given X ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int divisorCount ( int n ) { int x = 0 ; for ( int i = 1 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( i == n / i ) x ++ ; else x += 2 ; } } return x ; } int minvalue_y ( int x ) { int a = divisorCount ( x ) ; int y = x + 1 ; while ( ( a & 1 ) == ( divisorCount ( y ) & 1 ) ) y ++ ; return y ; } int main ( ) { int x = 5 ; cout << minvalue_y ( x ) << endl ; return 0 ; } |
Minimum value exceeding X whose count of divisors has different parity with count of divisors of X | C ++ program for the above approach ; Function to find the minimum value exceeding x whose count of divisors has different parity with count of divisors of X ; Check if x is perfect square ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minvalue_y ( int x ) { int n = sqrt ( x ) ; if ( n * n == x ) return x + 1 ; return pow ( n + 1 , 2 ) ; } int main ( ) { int x = 5 ; cout << minvalue_y ( x ) << endl ; return 0 ; } |
Sum of first N natural numbers with alternate signs | C ++ program to implement the above approach ; Function to find the sum of first N natural numbers with alternate signs ; Stores sum of alternate sign of first N natural numbers ; If N is an even number ; Update alternateSum ; If N is an odd number ; Update alternateSum ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int alternatingSumOfFirst_N ( int N ) { int alternateSum = 0 ; if ( N % 2 == 0 ) { alternateSum = ( - N ) / 2 ; } else { alternateSum = ( N + 1 ) / 2 ; } return alternateSum ; } int main ( ) { int N = 6 ; cout << alternatingSumOfFirst_N ( N ) ; return 0 ; } |
Minimum value to be added to the prefix sums at each array indices to make them positive | C ++ program for the above approach ; Function to find minimum startValue for positive prefix sum at each index ; Store the minimum prefix sum ; Stores prefix sum at each index ; Traverse over the array ; Update the prefix sum ; Update the minValue ; Return the positive start value ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minStartValue ( vector < int > & nums ) { int minValue = 0 ; int sum = 0 ; for ( auto n : nums ) { sum += n ; minValue = min ( minValue , sum ) ; } int startValue = 1 - minValue ; return startValue ; } int main ( ) { vector < int > nums = { -3 , 2 , -3 , 4 , 2 } ; cout << minStartValue ( nums ) ; return 0 ; } |
Count ways to split array into two equal sum subarrays by replacing each array element to 0 once | C ++ program for the above approach ; Function to find number of ways to split array into 2 subarrays having equal sum by changing element to 0 once ; Stores the count of elements in prefix and suffix of array elements ; Stores the sum of array ; Traverse the array ; Increase the frequency of current element in suffix ; Stores prefix sum upto index i ; Stores sum of suffix of index i ; Stores the desired result ; Traverse the array ; Modify prefix sum ; Add arr [ i ] to prefix map ; Calculate suffix sum by subtracting prefix sum from total sum of elements ; Remove arr [ i ] from suffix map ; Store the difference between the subarrays ; Count number of ways to split the array at index i such that subarray sums are equal ; Update the final result ; Return the result ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubArrayRemove ( int arr [ ] , int N ) { unordered_map < int , int > prefix_element_count , suffix_element_count ; int total_sum_of_elements = 0 ; for ( int i = N - 1 ; i >= 0 ; i -- ) { total_sum_of_elements += arr [ i ] ; suffix_element_count [ arr [ i ] ] ++ ; } int prefix_sum = 0 ; int suffix_sum = 0 ; int count_subarray_equal_sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { prefix_sum += arr [ i ] ; prefix_element_count [ arr [ i ] ] ++ ; suffix_sum = total_sum_of_elements - prefix_sum ; suffix_element_count [ arr [ i ] ] -- ; int difference = prefix_sum - suffix_sum ; int number_of_subarray_at_i_split = prefix_element_count [ difference ] + suffix_element_count [ - difference ] ; count_subarray_equal_sum += number_of_subarray_at_i_split ; } return count_subarray_equal_sum ; } int main ( ) { int arr [ ] = { 1 , 2 , 1 , 1 , 3 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countSubArrayRemove ( arr , N ) ; return 0 ; } |
Count set bits in Bitwise XOR of all adjacent elements upto N | C ++ program to implement the above approach ; Function to count of set bits in Bitwise XOR of adjacent elements up to N ; Stores count of set bits by Bitwise XOR on adjacent elements of [ 0 , N ] ; Stores all possible values on right most set bit over [ 0 , N ] ; Iterate over the range [ 0 , N ] ; Update N ; Update bit_Position ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countXORSetBitsAdjElemRange1_N ( int N ) { int total_set_bits = 0 ; int bit_Position = 1 ; while ( N ) { total_set_bits += ( ( N + 1 ) / 2 * bit_Position ) ; N -= ( N + 1 ) / 2 ; bit_Position ++ ; } return total_set_bits ; } int main ( ) { int N = 4 ; cout << countXORSetBitsAdjElemRange1_N ( N ) ; return 0 ; } |
Check if a right | C ++ program to implement the above approach ; Function to check if N is a perfect square number or not ; If N is a non positive integer ; Stores square root of N ; Check for perfect square ; If N is not a perfect square number ; Function to check if given two sides of a triangle forms a right - angled triangle ; If the value of ( A * A + B * B ) is a perfect square number ; Update checkTriangle ; If the value of ( A * A - B * B ) is a perfect square number ; Update checkTriangle ; If the value of ( B * B - A * A ) is a perfect square number ; Update checkTriangle ; Driver Code ; If the given two sides of a triangle forms a right - angled triangle ; Otherwise | #include <bits/stdc++.h> NEW_LINE using namespace std ; int checkPerfectSquare ( int N ) { if ( N <= 0 ) { return 0 ; } double sq = sqrt ( N ) ; if ( floor ( sq ) == ceil ( sq ) ) { return 1 ; } return 0 ; } bool checktwoSidesareRighTriangle ( int A , int B ) { bool checkTriangle = false ; if ( checkPerfectSquare ( A * A + B * B ) ) { checkTriangle = true ; } if ( checkPerfectSquare ( A * A - B * B ) ) { checkTriangle = true ; } if ( checkPerfectSquare ( B * B - A * A ) ) { checkTriangle = true ; } return checkTriangle ; } int main ( ) { int A = 3 , B = 4 ; if ( checktwoSidesareRighTriangle ( A , B ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; } |
Minimize increments or decrements required to make sum and product of array elements non | C ++ program for the above approach ; Function to find the sum of array ; Return the sum ; Function that counts the minimum operations required to make the sum and product of array non - zero ; Stores count of zero elements ; Iterate over the array to count zero elements ; Sum of elements of the array ; Print the result ; Driver Code ; Given array arr [ ] ; Size of array ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int array_sum ( int arr [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; return sum ; } int countOperations ( int arr [ ] , int N ) { int count_zeros = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == 0 ) count_zeros ++ ; } int sum = array_sum ( arr , N ) ; if ( count_zeros ) return count_zeros ; if ( sum == 0 ) return 1 ; return 0 ; } int main ( ) { int arr [ ] = { -1 , -1 , 0 , 0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countOperations ( arr , N ) ; return 0 ; } |
Bitwise OR of all unordered pairs from a given array | C ++ program to implement the above approach ; Function to find the bitwise OR of all possible pairs of the array ; Stores bitwise OR of all possible pairs of arr [ ] ; Traverse the array arr [ ] ; Update totalOR ; Return bitwise OR of all possible pairs of arr [ ] ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int TotalBitwiseORPair ( int arr [ ] , int N ) { int totalOR = 0 ; for ( int i = 0 ; i < N ; i ++ ) { totalOR |= arr [ i ] ; } return totalOR ; } int main ( ) { int arr [ ] = { 4 , 5 , 12 , 15 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << TotalBitwiseORPair ( arr , N ) ; } |
Compute maximum of two integers in C / C ++ using Bitwise Operators | C ++ program for above approach ; Function to find the largest number ; Perform the subtraction ; Right shift and Bitwise AND ; Find the maximum number ; Return the maximum value ; Driver Code ; Function Call | #include <iostream> NEW_LINE using namespace std ; int findMax ( int a , int b ) { int z , i , max ; z = a - b ; i = ( z >> 31 ) & 1 ; max = a - ( i * z ) ; return max ; } int main ( ) { int A = 40 , B = 54 ; cout << findMax ( A , B ) ; return 0 ; } |
Difference between lexicographical ranks of two given permutations | C ++ program for the above approach ; Function the print the difference between the lexicographical ranks ; Store the permutations in lexicographic order ; Intital permutation ; Initial variables ; Check permutation ; Initialize second permutation ; Check permutation ; Print difference ; Driver Code ; Given array P [ ] ; Given array Q [ ] ; Given size ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findDifference ( vector < int > & p , vector < int > & q , int N ) { vector < int > A ( N ) ; for ( int i = 0 ; i < N ; i ++ ) A [ i ] = i + 1 ; bool IsCorrect ; int a = 1 , b = 1 ; do { IsCorrect = true ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] != p [ i ] ) { IsCorrect = false ; break ; } } if ( IsCorrect ) break ; a ++ ; } while ( next_permutation ( A . begin ( ) , A . end ( ) ) ) ; for ( int i = 0 ; i < N ; i ++ ) A [ i ] = i + 1 ; do { IsCorrect = true ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] != q [ i ] ) { IsCorrect = false ; break ; } } if ( IsCorrect ) break ; b ++ ; } while ( next_permutation ( A . begin ( ) , A . end ( ) ) ) ; cout << abs ( a - b ) << endl ; } int main ( ) { vector < int > p = { 1 , 3 , 2 } ; vector < int > q = { 3 , 1 , 2 } ; int n = p . size ( ) ; findDifference ( p , q , n ) ; return 0 ; } |
Count of packets placed in each box after performing given operations | C ++ program for the above approach ; Function to print final array after performing all the operations ; Initialize variables ; Traverse through all operations ; Operation Type ; Move left ; Move right ; Pick a packet ; Drop a packet ; Exit ; Print final array ; Driver Code ; Given capacity ; Given array with initial values ; Array size ; Operations ; Number of operations ; Function call | #include <iostream> NEW_LINE using namespace std ; #define ll long long int NEW_LINE int printFinalArray ( int * a , int n , int * operations , int p , int capacity ) { int i , curr = 0 ; bool picked = false ; for ( i = 0 ; i < p ; i ++ ) { int s = operations [ i ] ; bool flag = false ; switch ( s ) { case 1 : if ( curr != 0 ) curr -- ; break ; case 2 : if ( curr != n - 1 ) curr ++ ; break ; case 3 : if ( picked == false && a [ curr ] != 0 ) { picked = true ; a [ curr ] -- ; } break ; case 4 : if ( picked == true && a [ curr ] != capacity ) { picked = false ; a [ curr ] ++ ; } break ; default : flag = true ; } if ( flag == true ) break ; } for ( i = 0 ; i < n ; i ++ ) { cout << a [ i ] << " β " ; } } int main ( ) { int capacity = 5 ; int a [ ] = { 2 , 5 , 2 } ; int N = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int operations [ ] = { 3 , 2 , 4 , 1 , 4 , 5 } ; int M = sizeof ( operations ) / sizeof ( operations [ 0 ] ) ; printFinalArray ( a , N , operations , M , capacity ) ; return 0 ; } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.