text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Icosihexagonal Number | C ++ program for above approach ; Finding the nth Icosihexagonal Number ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int IcosihexagonalNum ( int n ) { return ( 24 * n * n - 22 * n ) / 2 ; } int main ( ) { int n = 3 ; cout << "3rd ▁ Icosihexagonal ▁ Number ▁ is ▁ = ▁ " << IcosihexagonalNum ( n ) ; return 0 ; }
Icosikaioctagon or Icosioctagon Number | C ++ program for above approach ; Finding the nth icosikaioctagonal number ; Driver code
#include <iostream> NEW_LINE using namespace std ; int icosikaioctagonalNum ( int n ) { return ( 26 * n * n - 24 * n ) / 2 ; } int main ( ) { int n = 3 ; cout << "3rd ▁ icosikaioctagonal ▁ Number ▁ is ▁ = ▁ " << icosikaioctagonalNum ( n ) ; return 0 ; }
Octacontagon Number | C ++ program for above approach ; Finding the nth octacontagon Number ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int octacontagonNum ( int n ) { return ( 78 * n * n - 76 * n ) / 2 ; } int main ( ) { int n = 3 ; cout << "3rd ▁ octacontagon ▁ Number ▁ is ▁ = ▁ " << octacontagonNum ( n ) ; return 0 ; }
Hectagon Number | C ++ program for above approach ; Finding the nth hectagon Number ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int hectagonNum ( int n ) { return ( 98 * n * n - 96 * n ) / 2 ; } int main ( ) { int n = 3 ; cout << "3rd ▁ hectagon ▁ Number ▁ is ▁ = ▁ " << hectagonNum ( n ) ; return 0 ; }
Tetracontagon Number | C ++ program for above approach ; Finding the nth tetracontagon Number ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int tetracontagonNum ( int n ) { return ( 38 * n * n - 36 * n ) / 2 ; } int main ( ) { int n = 3 ; cout << "3rd ▁ tetracontagon ▁ Number ▁ is ▁ = ▁ " << tetracontagonNum ( n ) ; return 0 ; }
Perimeter of an Ellipse | C ++ program to find perimeter of an Ellipse ; Function to find the perimeter of an Ellipse ; Compute perimeter ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void Perimeter ( int a , int b ) { float perimeter ; perimeter = 2 * 3.14 * sqrt ( ( a * a + b * b ) / ( 2 * 1.0 ) ) ; cout << perimeter ; } int main ( ) { int a = 3 , b = 2 ; Perimeter ( a , b ) ; return 0 ; }
Biggest Reuleaux Triangle within A Square | C ++ Program to find the area of the biggest Reuleaux triangle that can be inscribed within a square ; Function to find the Area of the Reuleaux triangle ; Side cannot be negative ; Area of the Reuleaux triangle ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; float ReuleauxArea ( float a ) { if ( a < 0 ) return -1 ; float A = 0.70477 * pow ( a , 2 ) ; return A ; } int main ( ) { float a = 6 ; cout << ReuleauxArea ( a ) << endl ; return 0 ; }
Largest hexagon that can be inscribed within a square | C ++ Program to find the biggest hexagon which can be inscribed within the given square ; Function to return the side of the hexagon ; Side cannot be negative ; Side of the hexagon ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; float hexagonside ( float a ) { if ( a < 0 ) return -1 ; float x = 0.5176 * a ; return x ; } int main ( ) { float a = 6 ; cout << hexagonside ( a ) << endl ; return 0 ; }
Largest hexagon that can be inscribed within an equilateral triangle | C ++ program to find the side of the largest hexagon which can be inscribed within an equilateral triangle ; Function to find the side of the hexagon ; Side cannot be negative ; Side of the hexagon ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; float hexagonside ( float a ) { if ( a < 0 ) return -1 ; float x = a / 3 ; return x ; } int main ( ) { float a = 6 ; cout << hexagonside ( a ) << endl ; return 0 ; }
Find middle point segment from given segment lengths | C / C ++ implementation of the approach ; Function that returns the segment for the middle point ; the middle point ; stores the segment index ; increment sum by length of the segment ; if the middle is in between two segments ; if sum is greater than middle point ; Driver code
#include <iostream> NEW_LINE using namespace std ; int findSegment ( int n , int m , int segment_length [ ] ) { double meet_point = ( 1.0 * n ) / 2.0 ; int sum = 0 ; int segment_number = 0 ; for ( int i = 0 ; i < m ; i ++ ) { sum += segment_length [ i ] ; if ( ( double ) sum == meet_point ) { segment_number = -1 ; break ; } if ( sum > meet_point ) { segment_number = i + 1 ; break ; } } return segment_number ; } int main ( ) { int n = 13 ; int m = 3 ; int segment_length [ ] = { 3 , 2 , 8 } ; int ans = findSegment ( n , m , segment_length ) ; cout << ( ans ) ; return 0 ; }
Maximum points of intersection n lines | CPP program to find maximum intersecting points ; nC2 = ( n ) * ( n - 1 ) / 2 ; ; Driver code ; n is number of line
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long int NEW_LINE ll countMaxIntersect ( ll n ) { return ( n ) * ( n - 1 ) / 2 ; } int main ( ) { ll n = 8 ; cout << countMaxIntersect ( n ) << endl ; return 0 ; }
Program to find volume and surface area of pentagonal prism | CPP program to find surface area and volume of the Pentagonal Prism ; function for surface area ; function for VOlume ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; float surfaceArea ( float a , float b , float h ) { return 5 * a * b + 5 * b * h ; } float volume ( float b , float h ) { return ( 5 * b * h ) / 2 ; } int main ( ) { float a = 5 ; float b = 3 ; float h = 7 ; cout << " surface ▁ area = ▁ " << surfaceArea ( a , b , h ) << " , ▁ " ; cout << " volume = ▁ " << volume ( b , h ) ; }
Check if a point is inside , outside or on the parabola | C ++ Program to check if the point lies within the parabola or not ; Function to check the point ; checking the equation of parabola with the given point ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int checkpoint ( int h , int k , int x , int y , int a ) { int p = pow ( ( y - k ) , 2 ) - 4 * a * ( x - h ) ; return p ; } int main ( ) { int h = 0 , k = 0 , x = 2 , y = 1 , a = 4 ; if ( checkpoint ( h , k , x , y , a ) > 0 ) cout << " Outside " << endl ; else if ( checkpoint ( h , k , x , y , a ) == 0 ) cout << " On ▁ the ▁ parabola " << endl ; else cout << " Inside " << endl ; return 0 ; }
Check if a point is inside , outside or on the ellipse | C ++ Program to check if the point lies within the ellipse or not ; Function to check the point ; checking the equation of ellipse with the given point ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int checkpoint ( int h , int k , int x , int y , int a , int b ) { int p = ( pow ( ( x - h ) , 2 ) / pow ( a , 2 ) ) + ( pow ( ( y - k ) , 2 ) / pow ( b , 2 ) ) ; return p ; } int main ( ) { int h = 0 , k = 0 , x = 2 , y = 1 , a = 4 , b = 5 ; if ( checkpoint ( h , k , x , y , a , b ) > 1 ) cout << " Outside " << endl ; else if ( checkpoint ( h , k , x , y , a , b ) == 1 ) cout << " On ▁ the ▁ ellipse " << endl ; else cout << " Inside " << endl ; return 0 ; }
Area of circle inscribed within rhombus | C ++ Program to find the area of the circle which can be inscribed within the rhombus ; Function to find the area of the inscribed circle ; the diagonals cannot be negative ; area of the circle ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; float circlearea ( float a , float b ) { if ( a < 0 b < 0 ) return -1 ; float A = ( 3.14 * pow ( a , 2 ) * pow ( b , 2 ) ) / ( 4 * ( pow ( a , 2 ) + pow ( b , 2 ) ) ) ; return A ; } int main ( ) { float a = 8 , b = 10 ; cout << circlearea ( a , b ) << endl ; return 0 ; }
The biggest possible circle that can be inscribed in a rectangle | C ++ Program to find the biggest circle which can be inscribed within the rectangle ; Function to find the area of the biggest circle ; the length and breadth cannot be negative ; area of the circle ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; float circlearea ( float l , float b ) { if ( l < 0 b < 0 ) return -1 ; if ( l < b ) return 3.14 * pow ( l / 2 , 2 ) ; else return 3.14 * pow ( b / 2 , 2 ) ; } int main ( ) { float l = 4 , b = 8 ; cout << circlearea ( l , b ) << endl ; return 0 ; }
Centered cube number | Program to find nth Centered cube number ; Function to find Centered cube number ; Formula to calculate nth Centered cube number & return it into main function . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int centered_cube ( int n ) { return ( 2 * n + 1 ) * ( n * n + n + 1 ) ; } int main ( ) { int n = 3 ; cout << n << " th ▁ Centered ▁ cube ▁ number : ▁ " ; cout << centered_cube ( n ) ; cout << endl ; n = 10 ; cout << n << " th ▁ Centered ▁ cube ▁ number : ▁ " ; cout << centered_cube ( n ) ; return 0 ; }
Find the center of the circle using endpoints of diameter | C ++ program to find the center of the circle ; function to find the center of the circle ; Driven Program
#include <iostream> NEW_LINE using namespace std ; void center ( int x1 , int x2 , int y1 , int y2 ) { cout << ( float ) ( x1 + x2 ) / 2 << " , ▁ " << ( float ) ( y1 + y2 ) / 2 ; } int main ( ) { int x1 = -9 , y1 = 3 , x2 = 5 , y2 = -7 ; center ( x1 , x2 , y1 , y2 ) ; return 0 ; }
Program to calculate volume of Octahedron | CPP Program to calculate volume of Octahedron ; utility Function ; Driver Function
#include <bits/stdc++.h> NEW_LINE using namespace std ; double vol_of_octahedron ( double side ) { return ( ( side * side * side ) * ( sqrt ( 2 ) / 3 ) ) ; } int main ( ) { double side = 3 ; cout << " Volume ▁ of ▁ octahedron ▁ = " << vol_of_octahedron ( side ) << endl ; }
Program to calculate volume of Ellipsoid | CPP program to find the volume of Ellipsoid . ; Function to find the volume ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; float volumeOfEllipsoid ( float r1 , float r2 , float r3 ) { float pi = 3.14 ; return 1.33 * pi * r1 * r2 * r3 ; } int main ( ) { float r1 = 2.3 , r2 = 3.4 , r3 = 5.7 ; cout << " volume ▁ of ▁ ellipsoid ▁ is ▁ : ▁ " << volumeOfEllipsoid ( r1 , r2 , r3 ) ; return 0 ; }
Program to calculate Area Of Octagon | CPP program to find area of octagon ; Utility function ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; double areaOctagon ( double side ) { return ( float ) ( 2 * ( 1 + sqrt ( 2 ) ) * side * side ) ; } int main ( ) { double side = 4 ; cout << " Area ▁ of ▁ Regular ▁ Octagon ▁ = ▁ " << areaOctagon ( side ) << endl ; return 0 ; }
Program for Volume and Surface Area of Cube | CPP program to find area and total surface area of cube ; utility function ; driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; double areaCube ( double a ) { return ( a * a * a ) ; } double surfaceCube ( double a ) { return ( 6 * a * a ) ; } int main ( ) { double a = 5 ; cout << " Area ▁ = ▁ " << areaCube ( a ) << endl ; cout << " Total ▁ surface ▁ area ▁ = ▁ " << surfaceCube ( a ) ; return 0 ; }
Find mirror image of a point in 2 | C ++ code to find mirror image ; C ++ function which finds coordinates of mirror image . This function return a pair of double ; Driver code to test above function
#include <iostream> NEW_LINE using namespace std ; pair < double , double > mirrorImage ( double a , double b , double c , double x1 , double y1 ) { double temp = -2 * ( a * x1 + b * y1 + c ) / ( a * a + b * b ) ; double x = temp * a + x1 ; double y = temp * b + y1 ; return make_pair ( x , y ) ; } int main ( ) { double a = -1.0 ; double b = 1.0 ; double c = 0.0 ; double x1 = 1.0 ; double y1 = 0.0 ; pair < double , double > image = mirrorImage ( a , b , c , x1 , y1 ) ; cout << " Image ▁ of ▁ point ▁ ( " << x1 << " , ▁ " << y1 << " ) ▁ " ; cout << " by ▁ mirror ▁ ( " << a << " ) x ▁ + ▁ ( " << b << " ) y ▁ + ▁ ( " << c << " ) ▁ = ▁ 0 , ▁ is ▁ : " ; cout << " ( " << image . first << " , ▁ " << image . second << " ) " << endl ; return 0 ; }
Program for Point of Intersection of Two Lines | C ++ Implementation . To find the point of intersection of two lines ; This pair is used to store the X and Y coordinates of a point respectively ; Function used to display X and Y coordinates of a point ; Line AB represented as a1x + b1y = c1 ; Line CD represented as a2x + b2y = c2 ; The lines are parallel . This is simplified by returning a pair of FLT_MAX ; Driver code ; NOTE : Further check can be applied in case of line segments . Here , we have considered AB and CD as lines
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define pdd pair<double, double> NEW_LINE void displayPoint ( pdd P ) { cout << " ( " << P . first << " , ▁ " << P . second << " ) " << endl ; } pdd lineLineIntersection ( pdd A , pdd B , pdd C , pdd D ) { double a1 = B . second - A . second ; double b1 = A . first - B . first ; double c1 = a1 * ( A . first ) + b1 * ( A . second ) ; double a2 = D . second - C . second ; double b2 = C . first - D . first ; double c2 = a2 * ( C . first ) + b2 * ( C . second ) ; double determinant = a1 * b2 - a2 * b1 ; if ( determinant == 0 ) { return make_pair ( FLT_MAX , FLT_MAX ) ; } else { double x = ( b2 * c1 - b1 * c2 ) / determinant ; double y = ( a1 * c2 - a2 * c1 ) / determinant ; return make_pair ( x , y ) ; } } int main ( ) { pdd A = make_pair ( 1 , 1 ) ; pdd B = make_pair ( 4 , 4 ) ; pdd C = make_pair ( 1 , 8 ) ; pdd D = make_pair ( 2 , 4 ) ; pdd intersection = lineLineIntersection ( A , B , C , D ) ; if ( intersection . first == FLT_MAX && intersection . second == FLT_MAX ) { cout << " The ▁ given ▁ lines ▁ AB ▁ and ▁ CD ▁ are ▁ parallel . STRNEWLINE " ; } else { cout << " The ▁ intersection ▁ of ▁ the ▁ given ▁ lines ▁ AB ▁ " " and ▁ CD ▁ is : ▁ " ; displayPoint ( intersection ) ; } return 0 ; }
Minimum revolutions to move center of a circle to a target | C ++ program to find minimum number of revolutions to reach a target center ; Minimum revolutions to move center from ( x1 , y1 ) to ( x2 , y2 ) ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minRevolutions ( double r , int x1 , int y1 , int x2 , int y2 ) { double d = sqrt ( ( x1 - x2 ) * ( x1 - x2 ) + ( y1 - y2 ) * ( y1 - y2 ) ) ; return ceil ( d / ( 2 * r ) ) ; } int main ( ) { int r = 2 , x1 = 0 , y1 = 0 , x2 = 0 , y2 = 4 ; cout << minRevolutions ( r , x1 , y1 , x2 , y2 ) ; return 0 ; }
Find all sides of a right angled triangle from given hypotenuse and area | Set 1 | C ++ program to get right angle triangle , given hypotenuse and area of triangle ; limit for float comparison ; Utility method to get area of right angle triangle , given base and hypotenuse ; Prints base and height of triangle using hypotenuse and area information ; maximum area will be obtained when base and height are equal ( = sqrt ( h * h / 2 ) ) ; if given area itself is larger than maxArea then no solution is possible ; binary search for base ; get height by pythagorean rule ; Driver code to test above methods
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define eps 1e-6 NEW_LINE double getArea ( double base , double hypotenuse ) { double height = sqrt ( hypotenuse * hypotenuse - base * base ) ; return 0.5 * base * height ; } void printRightAngleTriangle ( int hypotenuse , int area ) { int hsquare = hypotenuse * hypotenuse ; double sideForMaxArea = sqrt ( hsquare / 2.0 ) ; double maxArea = getArea ( sideForMaxArea , hypotenuse ) ; if ( area > maxArea ) { cout << " Not ▁ possiblen " ; return ; } double low = 0.0 ; double high = sideForMaxArea ; double base ; while ( abs ( high - low ) > eps ) { base = ( low + high ) / 2.0 ; if ( getArea ( base , hypotenuse ) >= area ) high = base ; else low = base ; } double height = sqrt ( hsquare - base * base ) ; cout << base << " ▁ " << height << endl ; } int main ( ) { int hypotenuse = 5 ; int area = 6 ; printRightAngleTriangle ( hypotenuse , area ) ; return 0 ; }
Circle and Lattice Points | C ++ program to find countLattice points on a circle ; Function to count Lattice points on a circle ; Initialize result as 4 for ( r , 0 ) , ( - r . 0 ) , ( 0 , r ) and ( 0 , - r ) ; Check every value that can be potential x ; Find a potential y ; checking whether square root is an integer or not . Count increments by 4 for four different quadrant values ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countLattice ( int r ) { if ( r <= 0 ) return 0 ; int result = 4 ; for ( int x = 1 ; x < r ; x ++ ) { int ySquare = r * r - x * x ; int y = sqrt ( ySquare ) ; if ( y * y == ySquare ) result += 4 ; } return result ; } int main ( ) { int r = 5 ; cout << countLattice ( r ) ; return 0 ; }
Count of subarrays of size K with average at least M | C ++ program for the above approach ; Function to count the subarrays of size K having average at least M ; Stores the resultant count of subarray ; Stores the sum of subarrays of size K ; Add the values of first K elements to the sum ; Increment the count if the current subarray is valid ; Traverse the given array ; Find the updated sum ; Check if current subarray is valid or not ; Return the count of subarrays ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int countSubArrays ( int arr [ ] , int N , int K , int M ) { int count = 0 ; int sum = 0 ; for ( int i = 0 ; i < K ; i ++ ) { sum += arr [ i ] ; } if ( sum >= K * M ) count ++ ; for ( int i = K ; i < N ; i ++ ) { sum += ( arr [ i ] - arr [ i - K ] ) ; if ( sum >= K * M ) count ++ ; } return count ; } int main ( ) { int arr [ ] = { 3 , 6 , 3 , 2 , 1 , 3 , 9 } ; int K = 2 , M = 4 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countSubArrays ( arr , N , K , M ) ; return 0 ; }
Count of Ks in the Array for a given range of indices after array updates for Q queries | C ++ program for the above approach ; Function to perform all the queries ; Stores the count of 0 s ; Count the number of 0 s for query of type 1 ; Update the array element for query of type 2 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void performQueries ( int n , int q , int k , vector < int > & arr , vector < vector < int > > & query ) { for ( int i = 1 ; i <= q ; i ++ ) { int count = 0 ; if ( query [ i - 1 ] [ 0 ] == 1 ) { for ( int j = query [ i - 1 ] [ 1 ] ; j <= query [ i - 1 ] [ 2 ] ; j ++ ) { if ( arr [ j ] == k ) count ++ ; } cout << count << endl ; } else { = arr [ query [ i - 1 ] [ 1 ] ] = query [ i - 1 ] [ 2 ] ; } } } int main ( ) { vector < int > arr = { 9 , 5 , 7 , 6 , 9 , 0 , 0 , 0 , 0 , 5 , 6 , 7 , 3 , 9 , 0 , 7 , 0 , 9 , 0 } ; int Q = 5 ; vector < vector < int > > query = { { 1 , 5 , 14 } , { 2 , 6 , 1 } , { 1 , 0 , 8 } , { 2 , 13 , 0 } , { 1 , 6 , 18 } } ; int N = arr . size ( ) ; int K = 0 ; performQueries ( N , Q , K , arr , query ) ; return 0 ; }
Find smallest value of K such that bitwise AND of numbers in range [ N , N | C ++ program to find smallest value of K such that bitwise AND of numbers in range [ N , N - K ] is 0 ; Function is to find the largest no which gives the sequence n & ( n - 1 ) & ( n - 2 ) & ... . . & ( n - k ) = 0. ; Since , we need the largest no , we start from n itself , till 0 ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int findSmallestNumK ( int n ) { int cummAnd = n ; int i = n - 1 ; while ( cummAnd != 0 ) { cummAnd = cummAnd & i ; if ( cummAnd == 0 ) { return i ; } i -- ; } return -1 ; } int main ( ) { int N = 17 ; int lastNum = findSmallestNumK ( N ) ; int K = lastNum == -1 ? lastNum : N - lastNum ; cout << K << " STRNEWLINE " ; return 0 ; }
Program to find the value of P ( N + r ) for a polynomial of a degree N such that P ( i ) = 1 for 1 Γƒ Β’ Γ’ €°€ i Γƒ Β’ Γ’ €°€ N and P ( N + 1 ) = a | C ++ program for the above approach ; Function to calculate factorial of N ; Base Case ; Otherwise , recursively calculate the factorial ; Function to find the value of P ( n + r ) for polynomial P ( X ) ; Stores the value of k ; Store the required answer ; Iterate in the range [ 1 , N ] and multiply ( n + r - i ) with answer ; Add the constant value C as 1 ; Return the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int fact ( int n ) { if ( n == 1 n == 0 ) return 1 ; else return n * fact ( n - 1 ) ; } int findValue ( int n , int r , int a ) { int k = ( a - 1 ) / fact ( n ) ; int answer = k ; for ( int i = 1 ; i < n + 1 ; i ++ ) answer = answer * ( n + r - i ) ; answer = answer + 1 ; return answer ; } int main ( ) { int N = 1 ; int A = 2 ; int R = 3 ; cout << ( findValue ( N , R , A ) ) ; return 0 ; }
Find winner in game of N balls , in which a player can remove any balls in range [ A , B ] in a single move | C ++ program of the above approach ; Function to find the winner of the game ; Stores sum of A and B ; If N is of the form m * ( A + B ) + y ; Otherwise , ; Driver code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string NimGame ( int N , int A , int B ) { int sum = A + B ; if ( N % sum <= A - 1 ) return " Bob " ; else return " Alice " ; } int main ( ) { int N = 3 , A = 1 , B = 2 ; cout << NimGame ( N , A , B ) << endl ; return 0 ; }
Find Nth number in a sequence which is not a multiple of a given number | C ++ program for the above approach ; Function to find Nth number not a multiple of A in range [ L , R ] ; Calculate the Nth no ; Check for the edge case ; Driver Code ; Input parameters ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countNo ( int A , int N , int L , int R ) { int ans = L - 1 + N + floor ( ( N - 1 ) / ( A - 1 ) ) ; if ( ans % A == 0 ) { ans = ans + 1 ; } cout << ans << endl ; } int main ( ) { int A = 5 , N = 10 , L = 4 , R = 20 ; countNo ( A , N , L , R ) ; return 0 ; }
Count of paths in given Binary Tree with odd bitwise AND for Q queries | C ++ implementation to count paths in Binary Tree with odd bitwise AND ; Function to count number of paths in binary tree such that bitwise AND of all nodes is Odd ; vector dp to store the count of bitwise odd paths till that vertex ; Precomputing for each value ; check for odd value ; Number of odd elements will be + 1 till the parent node ; For even case ; Since node is even Number of odd elements will be 0 ; Even value node will not contribute in answer hence dp [ i ] = previous answer ; Printing the answer for each query ; Driver code ; vector to store queries
#include <bits/stdc++.h> NEW_LINE using namespace std ; void compute ( vector < int > query ) { vector < int > v ( 100001 ) , dp ( 100001 ) ; v [ 1 ] = 1 , v [ 2 ] = 0 ; dp [ 1 ] = 0 , dp [ 2 ] = 0 ; for ( int i = 3 ; i < 100001 ; i ++ ) { if ( i % 2 != 0 ) { if ( ( i / 2 ) % 2 == 0 ) { v [ i ] = 1 ; dp [ i ] = dp [ i - 1 ] ; } else { v [ i ] = v [ i / 2 ] + 1 ; dp [ i ] = dp [ i - 1 ] + v [ i ] - 1 ; } } else { v [ i ] = 0 ; dp [ i ] = dp [ i - 1 ] ; } } for ( auto x : query ) cout << dp [ x ] << endl ; } int main ( ) { vector < int > query = { 5 , 2 } ; compute ( query ) ; return 0 ; }
Number of cycles formed by joining vertices of n sided polygon at the center | C ++ program for the above approach ; Function to calculate number of cycles ; BigInteger is used here if N = 10 ^ 9 then multiply will result into value greater than 10 ^ 18 ; BigInteger multiply function ; Return the final result ; Driver code ; Given N ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findCycles ( int N ) { int res = 0 ; int finalResult = 0 ; int val = 2 * N - 1 ; int s = val ; res = ( N - 1 ) * ( N - 2 ) ; finalResult = res + s ; return finalResult ; } int main ( ) { int N = 5 ; cout << findCycles ( N ) << endl ; return 0 ; }
Split a given array into K subarrays minimizing the difference between their maximum and minimum | C ++ program for the above approach ; Function to find the subarray ; Add the difference to vectors ; Sort vector to find minimum k ; Initialize result ; Adding first k - 1 values ; Return the minimized sum ; Driver Code ; Given array arr [ ] ; Given K ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find ( int a [ ] , int n , int k ) { vector < int > v ; for ( int i = 1 ; i < n ; ++ i ) { v . push_back ( a [ i - 1 ] - a [ i ] ) ; } sort ( v . begin ( ) , v . end ( ) ) ; int res = a [ n - 1 ] - a [ 0 ] ; for ( int i = 0 ; i < k - 1 ; ++ i ) { res += v [ i ] ; } return res ; } int main ( ) { int arr [ ] = { 4 , 8 , 15 , 16 , 23 , 42 } ; int N = sizeof ( arr ) / sizeof ( int ) ; int K = 3 ; cout << find ( arr , N , K ) << endl ; return 0 ; }
Last digit of a number raised to last digit of N factorial | C ++ program for the above approach ; Function to find a ^ b using binary exponentiation ; Initialise result ; If b is odd then , multiply result by a ; b must be even now Change b to b / 2 ; Change a = a ^ 2 ; Function to find the last digit of the given equation ; To store cyclicity ; Store cyclicity from 1 - 10 ; Observation 1 ; Observation 3 ; To store the last digits of factorial 2 , 3 , and 4 ; Find the last digit of X ; Step 1 ; Divide a [ N ] by cyclicity of v ; If remainder is 0 ; Step 1.1 ; Step 1.2 ; Step 1.3 ; If r is non - zero , then return ( l ^ r ) % 10 ; Else return 0 ; Else return 1 ; Driver Code ; Given Numbers ; Function Call ; Print the result
#include <bits/stdc++.h> NEW_LINE using namespace std ; long power ( long a , long b , long c ) { long result = 1 ; while ( b > 0 ) { if ( ( b & 1 ) == 1 ) { result = ( result * a ) % c ; } b /= 2 ; a = ( a * a ) % c ; } return result ; } long calculate ( long X , long N ) { int a [ 10 ] ; int cyclicity [ 11 ] ; cyclicity [ 1 ] = 1 ; cyclicity [ 2 ] = 4 ; cyclicity [ 3 ] = 4 ; cyclicity [ 4 ] = 2 ; cyclicity [ 5 ] = 1 ; cyclicity [ 6 ] = 1 ; cyclicity [ 7 ] = 4 ; cyclicity [ 8 ] = 4 ; cyclicity [ 9 ] = 2 ; cyclicity [ 10 ] = 1 ; if ( N == 0 N == 1 ) { return ( X % 10 ) ; } else if ( N == 2 N == 3 N == 4 ) { long temp = ( long ) 1e18 ; a [ 2 ] = 2 ; a [ 3 ] = 6 ; a [ 4 ] = 4 ; long v = X % 10 ; if ( v != 0 ) { int u = cyclicity [ ( int ) v ] ; int r = a [ ( int ) N ] % u ; if ( r == 0 ) { if ( v == 2 v == 4 v == 6 v == 8 ) { return 6 ; } else if ( v == 5 ) { return 5 ; } else if ( v == 1 v == 3 v == 7 v == 9 ) { return 1 ; } } else { return ( power ( v , r , temp ) % 10 ) ; } } else { return 0 ; } } return 1 ; } int main ( ) { int X = 18 ; int N = 4 ; long result = calculate ( X , N ) ; cout << result ; }
Maximize 3 rd element sum in quadruplet sets formed from given Array | C ++ code to Maximize 3 rd element sum in quadruplet sets formed from given Array ; Function to find the maximum possible value of Y ; pairs contain count of minimum elements that will be utilized at place of Z . it is equal to count of possible pairs that is size of array divided by 4 ; sorting the array in descending order so as to bring values with minimal difference closer to arr [ i ] ; here , i + 2 acts as a pointer that points to the third value of every possible quadruplet ; returning the optimally maximum possible value ; Driver code ; array declaration ; size of array
#include <bits/stdc++.h> NEW_LINE using namespace std ; int formQuadruplets ( int arr [ ] , int n ) { int ans = 0 , pairs = 0 ; pairs = n / 4 ; sort ( arr , arr + n , greater < int > ( ) ) ; for ( int i = 0 ; i < n - pairs ; i += 3 ) { ans += arr [ i + 2 ] ; } return ans ; } int main ( ) { int arr [ ] = { 2 , 1 , 7 , 5 , 5 , 4 , 1 , 1 , 3 , 3 , 2 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << formQuadruplets ( arr , n ) << endl ; return 0 ; }
Minimum concatenation required to get strictly LIS for array with repetitive elements | Set | C ++ implementation to Find the minimum concatenation required to get strictly Longest Increasing Subsequence for the given array with repetitive elements ; ordered map containing value and a vector containing index of it 's occurrences ; Mapping index with their values in ordered map ; k refers to present minimum index ; Stores the number of concatenation required ; Iterate over map m ; it . second . back refers to the last element of corresponding vector ; find the index of next minimum element in the sequence ; Return the final answer ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int LIS ( int arr [ ] , int n ) { map < int , vector < int > > m ; for ( int i = 0 ; i < n ; i ++ ) m [ arr [ i ] ] . push_back ( i ) ; int k = n ; int ans = 0 ; for ( auto it = m . begin ( ) ; it != m . end ( ) ; it ++ ) { if ( it -> second . back ( ) < k ) { k = it -> second [ 0 ] ; ans += 1 ; } else k = * lower_bound ( it -> second . begin ( ) , it -> second . end ( ) , k ) ; } cout << ans << endl ; } int main ( ) { int arr [ ] = { 1 , 3 , 2 , 1 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; LIS ( arr , n ) ; return 0 ; }
Two Balls Reachability Game | C ++ program to Find is it possible to have X white and Y black balls at the end . ; Recursive function to return gcd of a and b ; Function returns if it 's possible to have X white and Y black balls or not. ; Finding gcd of ( x , y ) and ( a , b ) ; If gcd is same , it 's always possible to reach (x, y) ; Here it 's never possible if gcd is not same ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } void IsPossible ( int a , int b , int x , int y ) { int final = gcd ( x , y ) ; int initial = gcd ( a , b ) ; if ( initial == final ) { cout << " POSSIBLE STRNEWLINE " ; } else { cout << " NOT ▁ POSSIBLE STRNEWLINE " ; } } int main ( ) { int A = 1 , B = 2 , X = 4 , Y = 11 ; IsPossible ( A , B , X , Y ) ; A = 2 , B = 2 , X = 3 , Y = 6 ; IsPossible ( A , B , X , Y ) ; return 0 ; }
Number of ways to color N | C ++ program for the above approach ; Function to count the ways to color block ; For storing powers of 2 ; For storing binomial coefficient values ; Calculating binomial coefficient using DP ; Calculating powers of 2 ; Sort the indices to calculate length of each section ; Initialise answer to 1 ; Find the length of each section ; Merge this section ; Return the final count ; Driver Code ; Number of blocks ; Number of colored blocks ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int mod = 1000000007 ; int waysToColor ( int arr [ ] , int n , int k ) { int powOf2 [ 500 ] = { 0 } ; int c [ 500 ] [ 500 ] ; for ( int i = 0 ; i <= n ; i ++ ) { c [ i ] [ 0 ] = 1 ; for ( int j = 1 ; j <= i ; j ++ ) { c [ i ] [ j ] = ( c [ i - 1 ] [ j ] + c [ i - 1 ] [ j - 1 ] ) % mod ; } } powOf2 [ 0 ] = powOf2 [ 1 ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { powOf2 [ i ] = powOf2 [ i - 1 ] * 2 % mod ; } int rem = n - k ; arr [ k ++ ] = n + 1 ; sort ( arr , arr + k ) ; int answer = 1 ; for ( int i = 0 ; i < k ; i ++ ) { int x = arr [ i ] - ( i - 1 >= 0 ? arr [ i - 1 ] : 0 ) - 1 ; answer *= c [ rem ] [ x ] % mod * ( i != 0 && i != k - 1 ? powOf2 [ x ] : 1 ) % mod ; rem -= x ; } return answer ; } int main ( ) { int N = 6 ; int K = 3 ; int arr [ K ] = { 1 , 2 , 6 } ; cout << waysToColor ( arr , N , K ) ; return 0 ; }
Rearrange array such that difference of adjacent elements is in descending order | C ++ implementation to Rearrange array such that difference of adjacent elements is in descending order ; Function to print array in given order ; Sort the array ; Check elements till the middle index ; check if length is odd print the middle index at last ; Print the remaining elements in the described order ; Driver code ; array declaration ; size of array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printArray ( int * a , int n ) { sort ( a , a + n ) ; int i = 0 ; int j = n - 1 ; while ( i <= j ) { if ( i == j ) { cout << a [ i ] << " ▁ " ; } else { cout << a [ j ] << " ▁ " ; cout << a [ i ] << " ▁ " ; } i = i + 1 ; j = j - 1 ; } cout << endl ; } int main ( ) { int arr1 [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int n1 = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; printArray ( arr1 , n1 ) ; }
Find the Smallest number that divides X ^ X | C ++ implementation of above approach ; Function to find the required smallest number ; Finding smallest number that divides n ; i divides n and return this value immediately ; If n is a prime number then answer should be n , As we can 't take 1 as our answer. ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int SmallestDiv ( int n ) { for ( int i = 2 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { return i ; } } return n ; } int main ( ) { int X = 385 ; int ans = SmallestDiv ( X ) ; cout << ans << " STRNEWLINE " ; return 0 ; }
Find an array of size N that satisfies the given conditions | C ++ implementation of the approach ; Utility function to print the contents of an array ; Function to generate and print the required array ; Initially all the positions are empty ; To store the count of positions i such that arr [ i ] = s ; To store the final array elements ; Set arr [ i ] = s and the gap between them is exactly 2 so in for loop we use i += 2 ; Mark the i 'th position as visited as we put arr[i] = s ; Increment the count ; Finding the next odd number after s ; If the i 'th position is not visited it means we did not put any value at position i so we put 1 now ; Print the final array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; } void findArray ( int n , int k , int s ) { int vis [ n ] = { 0 } ; int cnt = 0 ; int arr [ n ] ; for ( int i = 0 ; i < n && cnt < k ; i += 2 ) { arr [ i ] = s ; vis [ i ] = 1 ; cnt ++ ; } int val = s ; if ( s % 2 == 0 ) val ++ ; else val = val + 2 ; for ( int i = 0 ; i < n ; i ++ ) { if ( vis [ i ] == 0 ) { arr [ i ] = val ; } } printArr ( arr , n ) ; } int main ( ) { int n = 8 , k = 3 , s = 12 ; findArray ( n , k , s ) ; return 0 ; }
Sum of numbers in a range [ L , R ] whose count of divisors is prime | C ++ implementation of the approach ; prime [ i ] stores 1 if i is prime ; divi [ i ] stores the count of divisors of i ; sum [ i ] will store the sum of all the integers from 0 to i whose count of divisors is prime ; Function for Sieve of Eratosthenes ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be 0 if i is Not a prime , else true . ; 0 and 1 is not prime ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked . ; Function to count the divisors ; For each number i we will go to each of the multiple of i and update the count of divisor of its multiple j as i is one of the factor of j ; Function for pre - computation ; If count of divisors of i is prime ; taking prefix sum ; Driver code ; Find all the prime numbers till N ; Update the count of divisors of all the numbers till N ; Precomputation for the prefix sum array ; Perform query
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 100000 ; int prime [ N ] ; int divi [ N ] ; int sum [ N ] ; void SieveOfEratosthenes ( ) { for ( int i = 0 ; i < N ; i ++ ) prime [ i ] = 1 ; prime [ 0 ] = prime [ 1 ] = 0 ; for ( int p = 2 ; p * p < N ; p ++ ) { if ( prime [ p ] == 1 ) { for ( int i = p * p ; i < N ; i += p ) prime [ i ] = 0 ; } } } void DivisorCount ( ) { for ( int i = 1 ; i < N ; i ++ ) { for ( int j = i ; j < N ; j += i ) { divi [ j ] ++ ; } } } void pre ( ) { for ( int i = 1 ; i < N ; i ++ ) { if ( prime [ divi [ i ] ] == 1 ) { sum [ i ] = i ; } } for ( int i = 1 ; i < N ; i ++ ) sum [ i ] += sum [ i - 1 ] ; } int main ( ) { int l = 5 , r = 8 ; SieveOfEratosthenes ( ) ; DivisorCount ( ) ; pre ( ) ; cout << sum [ r ] - sum [ l - 1 ] ; return 0 ; }
Count total number of even sum sequences | C ++ implementation of the approach ; Iterative function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize result ; Update x if it is greater than or equal to p ; If y is odd then multiply x with the result ; y must be even now y = y >> 1 ; y = y / 2 ; Function to return n ^ ( - 1 ) mod p ; Function to return ( nCr % p ) using Fermat 's little theorem ; Base case ; Fill factorial array so that we can find all factorial of r , n and n - r ; Function to return the count of odd numbers from 1 to n ; Function to return the count of even numbers from 1 to n ; Function to return the count of the required sequences ; Take i even and n - i odd numbers ; Number of odd numbers must be even ; Total ways of placing n - i odd numbers in the sequence of n numbers ; Add this number to the final answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define M 1000000007 NEW_LINE #define ll long long int NEW_LINE ll power ( ll x , ll y , ll p ) { ll res = 1 ; x = x % p ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return res ; } ll modInverse ( ll n , ll p ) { return power ( n , p - 2 , p ) ; } ll nCrModPFermat ( ll n , ll r , ll p ) { if ( r == 0 ) return 1 ; ll fac [ n + 1 ] ; fac [ 0 ] = 1 ; for ( ll i = 1 ; i <= n ; i ++ ) fac [ i ] = fac [ i - 1 ] * i % p ; return ( fac [ n ] * modInverse ( fac [ r ] , p ) % p * modInverse ( fac [ n - r ] , p ) % p ) % p ; } ll countOdd ( ll n ) { ll x = n / 2 ; if ( n % 2 == 1 ) x ++ ; return x ; } ll counteEven ( ll n ) { ll x = n / 2 ; return x ; } ll CountEvenSumSequences ( ll n ) { ll count = 0 ; for ( ll i = 0 ; i <= n ; i ++ ) { ll even = i , odd = n - i ; if ( odd % 2 == 1 ) continue ; ll tot = ( power ( countOdd ( n ) , odd , M ) * nCrModPFermat ( n , odd , M ) ) % M ; tot = ( tot * power ( counteEven ( n ) , i , M ) ) % M ; count += tot ; count %= M ; } return count ; } int main ( ) { ll n = 5 ; cout << CountEvenSumSequences ( n ) ; return 0 ; }
Find the sum of prime numbers in the Kth array | C ++ implementation of the approach ; To store whether a number is prime or not ; Function for Sieve of Eratosthenes ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked . ; Function to return the sum of primes in the Kth array ; Update vector v to store all the prime numbers upto MAX ; To store the sum of primes in the kth array ; Count of primes which are in the arrays from 1 to k - 1 ; k is the number of primes in the kth array ; A prime has been added to the sum ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1000000 NEW_LINE bool prime [ MAX ] ; void SieveOfEratosthenes ( ) { for ( int i = 0 ; i < MAX ; i ++ ) prime [ i ] = true ; for ( int p = 2 ; p * p < MAX ; p ++ ) { if ( prime [ p ] ) { for ( int i = p * p ; i < MAX ; i += p ) prime [ i ] = false ; } } } int sumPrime ( int k ) { SieveOfEratosthenes ( ) ; vector < int > v ; for ( int i = 2 ; i < MAX ; i ++ ) { if ( prime [ i ] ) v . push_back ( i ) ; } int sum = 0 ; int skip = ( k * ( k - 1 ) ) / 2 ; while ( k > 0 ) { sum += v [ skip ] ; skip ++ ; k -- ; } return sum ; } int main ( ) { int k = 3 ; cout << sumPrime ( k ) ; return 0 ; }
Count all substrings having character K | C ++ implementation of the approach ; Function to return the index of the next occurrence of character ch in str starting from the given index ; Return the index of the first occurrence of ch ; No occurrence found ; Function to return the count of all the substrings of str which contain the character ch at least one ; To store the count of valid substrings ; Index of the first occurrence of ch in str ; No occurrence of ch after index i in str ; Substrings starting at index i and ending at indices j , j + 1 , ... , n - 1 are all valid substring ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int nextOccurrence ( string str , int n , int start , char ch ) { for ( int i = start ; i < n ; i ++ ) { if ( str [ i ] == ch ) return i ; } return -1 ; } int countSubStr ( string str , int n , char ch ) { int cnt = 0 ; int j = nextOccurrence ( str , n , 0 , ch ) ; for ( int i = 0 ; i < n ; i ++ ) { while ( j != -1 && j < i ) { j = nextOccurrence ( str , n , j + 1 , ch ) ; } if ( j == -1 ) break ; cnt += ( n - j ) ; } return cnt ; } int main ( ) { string str = " geeksforgeeks " ; int n = str . length ( ) ; char ch = ' k ' ; cout << countSubStr ( str , n , ch ) ; return 0 ; }
Check whether bitwise AND of N numbers is Even or Odd | C ++ implementation of the approach ; Function to check if the bitwise AND of the array elements is even or odd ; If at least an even element is present then the bitwise AND of the array elements will be even ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void checkEvenOdd ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % 2 == 0 ) { cout << " Even " ; return ; } } cout << " Odd " ; } int main ( ) { int arr [ ] = { 2 , 12 , 20 , 36 , 38 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; checkEvenOdd ( arr , n ) ; return 0 ; }
Find number of magical pairs of string of length L | C ++ implementation of the approach ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize result ; Update x if it is >= p ; If y is odd , multiply x with result ; Y must be even now y = y >> 1 ; y = y / 2 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int power ( int x , unsigned int y , int p ) { int res = 1 ; x = x % p ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return res ; } int main ( ) { int L = 2 , P = pow ( 10 , 9 ) ; int ans = power ( 325 , L , P ) ; cout << ans << " STRNEWLINE " ; return 0 ; }
Longest substring of only 4 's from the first N characters of the infinite string | C ++ implementation of the approach ; Function to return the length of longest contiguous string containing only 4 aTMs from the first N characters of the string ; Initialize result ; Initialize prefix sum array of characters and product variable ; Preprocessing of prefix sum array ; Initialize variable to store the string length where N belongs to ; Finding the string length where N belongs to ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAXN 30 NEW_LINE int countMaxLength ( int N ) { int res ; int pre [ MAXN ] , p = 1 ; pre [ 0 ] = 0 ; for ( int i = 1 ; i < MAXN ; i ++ ) { p *= 2 ; pre [ i ] = pre [ i - 1 ] + i * p ; } int ind ; for ( int i = 1 ; i < MAXN ; i ++ ) { if ( pre [ i ] >= N ) { ind = i ; break ; } } int x = N - pre [ ind - 1 ] ; int y = 2 * ind - 1 ; if ( x >= y ) res = min ( x , y ) ; else res = max ( x , 2 * ( ind - 2 ) + 1 ) ; return res ; } int main ( ) { int N = 25 ; cout << countMaxLength ( N ) ; return 0 ; }
Difference between Recursion and Iteration | C ++ program to find factorial of given number ; -- -- - Recursion -- -- - method to find factorial of given number ; recursion call ; -- -- - Iteration -- -- - Method to find the factorial of a given number ; using iteration ; Driver method
#include <bits/stdc++.h> NEW_LINE using namespace std ; int factorialUsingRecursion ( int n ) { if ( n == 0 ) return 1 ; return n * factorialUsingRecursion ( n - 1 ) ; } int factorialUsingIteration ( int n ) { int res = 1 , i ; for ( i = 2 ; i <= n ; i ++ ) res *= i ; return res ; } int main ( ) { int num = 5 ; cout << " Factorial ▁ of ▁ " << num << " ▁ using ▁ Recursion ▁ is : ▁ " << factorialUsingRecursion ( 5 ) << endl ; cout << " Factorial ▁ of ▁ " << num << " ▁ using ▁ Iteration ▁ is : ▁ " << factorialUsingIteration ( 5 ) ; return 0 ; }
Jump Pointer Algorithm | C ++ program to implement Jump pointer algorithm ; n -> it represent total number of nodes len -> it is the maximum length of array to hold parent of each node . In worst case , the highest value of parent a node can have is n - 1. 2 ^ len <= n - 1 len = O ( log2n ) ; jump represent 2D matrix to hold parent of node in jump matrix here we pass reference of 2D matrix so that the change made occur directly to the original matrix len is same as defined above n is total nodes in graph ; c -> it represent child p -> it represent parent i -> it represent node number p = 0 means the node is root node here also we pass reference of 2D matrix and depth vector so that the change made occur directly to the original matrix and original vector ; enter the node in node array it stores all the nodes in the graph ; to confirm that no child node have 2 parents ; make parent of x as y ; function to jump to Lth parent of any node ; to check if node is present in graph or not ; in this loop we decrease the value of L by L / 2 and increment j by 1 after each iteration , and check for set bit if we get set bit then we update x with jth parent of x as L becomes less than or equal to zero means we have jumped to Lth parent of node x ; to check if last bit is 1 or not ; use of shift operator to make L = L / 2 after every iteration ; Driver code ; n represent number of nodes ; initialization of parent matrix suppose max range of a node is up to 1000 if there are 1000 nodes than also length of jump matrix will not exceed 10 ; node array is used to store all nodes ; isNode is an array to check whether a node is present in graph or not ; memset function to initialize isNode array with 0 ; function to calculate len len -> it is the maximum length of array to hold parent of each node . ; R stores root node ; construction of graph here 0 represent that the node is root node ; function to pre compute jump matrix ; query to jump to parent using jump pointers query to jump to 1 st parent of node 2 ; query to jump to 2 nd parent of node 4 ; query to jump to 3 rd parent of node 8 ; query to jump to 5 th parent of node 20
#include <bits/stdc++.h> NEW_LINE using namespace std ; int R = 0 ; int getLen ( int n ) { int len = ( int ) ( log ( n ) / log ( 2 ) ) + 1 ; return len ; } void set_jump_pointer ( vector < vector < int > > & jump , int * node , int len , int n ) { for ( int j = 1 ; j <= len ; j ++ ) for ( int i = 0 ; i < n ; i ++ ) jump [ node [ i ] ] [ j ] = jump [ jump [ node [ i ] ] [ j - 1 ] ] [ j - 1 ] ; } void constructGraph ( vector < vector < int > > & jump , int * node , int * isNode , int c , int p , int i ) { node [ i ] = c ; if ( isNode == 0 ) { isNode = 1 ; jump [ 0 ] = p ; } return ; } void jumpPointer ( vector < vector < int > > & jump , int * isNode , int x , int L ) { int j = 0 , n = x , k = L ; if ( isNode [ x ] == 0 ) { cout << " Node ▁ is ▁ not ▁ present ▁ in ▁ graph ▁ " << endl ; return ; } while ( L > 0 ) { if ( L & 1 ) x = jump [ x ] [ j ] ; L = L >> 1 ; j ++ ; } cout << k << " th ▁ parent ▁ of ▁ node ▁ " << n << " ▁ is ▁ = ▁ " << x << endl ; return ; } int main ( ) { int n = 11 ; vector < vector < int > > jump ( 1000 , vector < int > ( 10 ) ) ; int * node = new int [ 1000 ] ; int * isNode = new int [ 1000 ] ; memset ( isNode , 0 , 1000 * sizeof ( int ) ) ; int len = getLen ( n ) ; R = 2 ; constructGraph ( jump , node , isNode , 2 , 0 , 0 ) ; constructGraph ( jump , node , isNode , 5 , 2 , 1 ) ; constructGraph ( jump , node , isNode , 3 , 5 , 2 ) ; constructGraph ( jump , node , isNode , 4 , 5 , 3 ) ; constructGraph ( jump , node , isNode , 1 , 5 , 4 ) ; constructGraph ( jump , node , isNode , 7 , 1 , 5 ) ; constructGraph ( jump , node , isNode , 9 , 1 , 6 ) ; constructGraph ( jump , node , isNode , 10 , 9 , 7 ) ; constructGraph ( jump , node , isNode , 11 , 10 , 8 ) ; constructGraph ( jump , node , isNode , 6 , 10 , 9 ) ; constructGraph ( jump , node , isNode , 8 , 10 , 10 ) ; set_jump_pointer ( jump , node , len , n ) ; jumpPointer ( jump , isNode , 2 , 0 ) ; jumpPointer ( jump , isNode , 4 , 2 ) ; jumpPointer ( jump , isNode , 8 , 3 ) ; jumpPointer ( jump , isNode , 20 , 5 ) ; return 0 ; }
In | An Not in - place C ++ program to reverse an array ; Function to reverse arr [ ] from start to end ; Create a copy array and store reversed elements ; Now copy reversed elements back to arr [ ] ; Utility function to print an array ; Driver function to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; void revereseArray ( int arr [ ] , int n ) { int rev [ n ] ; for ( int i = 0 ; i < n ; i ++ ) rev [ n - i - 1 ] = arr [ i ] ; for ( int i = 0 ; i < n ; i ++ ) arr [ i ] = rev [ i ] ; } void printArray ( int arr [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) cout << arr [ i ] << " ▁ " ; cout << endl ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printArray ( arr , n ) ; revereseArray ( arr , n ) ; cout << " Reversed ▁ array ▁ is " << endl ; printArray ( arr , n ) ; return 0 ; }
In | An in - place C ++ program to reverse an array ; Function to reverse arr [ ] from start to end ; Utility function to print an array ; Driver function to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; void revereseArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n / 2 ; i ++ ) swap ( arr [ i ] , arr [ n - i - 1 ] ) ; } void printArray ( int arr [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) cout << arr [ i ] << " ▁ " ; cout << endl ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printArray ( arr , n ) ; revereseArray ( arr , n ) ; cout << " Reversed ▁ array ▁ is " << endl ; printArray ( arr , n ) ; return 0 ; }
Find Binary string by converting all 01 or 10 to 11 after M iterations | C ++ program for the above approach . ; Function to find the modified binary string after M iterations ; Set the value of M to the minimum of N or M . ; Declaration of current string state ; Loop over M iterations ; Set the current state as null before each iteration ; Check if this zero has exactly one 1 as neighbour ; Flip the zero ; If there is no change , then no need for further iterations . ; Set the current state as the new previous state ; Driver Code ; Given String ; Number of Iterations ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findString ( string str , int M ) { int N = str . length ( ) ; M = min ( M , N ) ; string s1 = " " ; while ( M != 0 ) { s1 = " " ; for ( int i = 0 ; i < N ; i ++ ) { if ( str [ i ] == '0' ) { if ( ( str [ i - 1 ] == '1' && str [ i + 1 ] != '1' ) || ( str [ i - 1 ] != '1' && str [ i + 1 ] == '1' ) ) s1 += '1' ; else s1 += '0' ; } else s1 += '1' ; } if ( str == s1 ) break ; str = s1 ; M -- ; } cout << s1 ; } int main ( ) { string str = "0110100" ; int M = 3 ; findString ( str , M ) ; return 0 ; }
Count of subsequences with a sum in range [ L , R ] and difference between max and min element at least X | C ++ program for the above approach ; Function to find the number of subsequences of the given array with a sum in range [ L , R ] and the difference between the maximum and minimum element is at least X ; Initialize answer as 0 ; Creating mask from [ 0 , 2 ^ n - 1 ] ; Stores the count and sum of selected elements respectively ; Variables to store the value of Minimum and maximum element ; Traverse the array ; If the jth bit of the ith mask is on ; Add the selected element ; Update maxVal and minVal value ; Check if the given conditions are true , increment ans by 1. ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int numberofSubsequences ( int a [ ] , int L , int R , int X , int n ) { int ans = 0 ; for ( int i = 0 ; i < ( 1 << n ) ; i ++ ) { int cnt = 0 , sum = 0 ; int minVal = INT_MAX , maxVal = INT_MIN ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( i & ( 1 << j ) ) ) { cnt += 1 ; sum += a [ j ] ; maxVal = max ( maxVal , a [ j ] ) ; minVal = min ( minVal , a [ j ] ) ; } } if ( cnt >= 2 && sum >= L && sum <= R && ( maxVal - minVal >= X ) ) { ans += 1 ; } } return ans ; } int main ( ) { int a [ ] = { 10 , 20 , 30 , 25 } ; int L = 40 , R = 50 , X = 10 ; int N = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << numberofSubsequences ( a , L , R , X , N ) << endl ; return 0 ; }
Minimum count of numbers needed from 1 to N that yields the sum as K | C ++ program for the above approach ; Function to find minimum number of elements required to obtain sum K ; Stores the maximum sum that can be obtained ; If K is greater than the Maximum sum ; If K is less than or equal to to N ; Stores the sum ; Stores the count of numbers needed ; Iterate until N is greater than or equal to 1 and sum is less than K ; Increment count by 1 ; Increment sum by N ; Update the sum ; Finally , return the count ; Driver Code ; Given Input ; Function Call
#include <iostream> NEW_LINE using namespace std ; int Minimum ( int N , int K ) { int sum = N * ( N + 1 ) / 2 ; if ( K > sum ) return -1 ; if ( K <= N ) return 1 ; sum = 0 ; int count = 0 ; while ( N >= 1 && sum < K ) { count += 1 ; sum += N ; N -= 1 ; } return count ; } int main ( ) { int N = 5 , K = 10 ; cout << ( Minimum ( N , K ) ) ; return 0 ; }
Maximize X such that sum of numbers in range [ 1 , X ] is at most K | C ++ program for the above approach ; Function to count the elements with sum of the first that many natural numbers less than or equal to K ; If K equals to 0 ; Stores the result ; Iterate until low is less than or equal to high ; Stores the sum of first mid natural numbers ; If sum is less than or equal to K ; Update res and low ; Otherwise , ; Update ; Return res ; Driver Code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Count ( int N , int K ) { if ( K == 0 ) return 0 ; int res = 0 ; int low = 1 , high = N ; while ( low <= high ) { int mid = ( low + high ) / 2 ; int sum = ( mid * mid + mid ) / 2 ; if ( sum <= K ) { res = max ( res , mid ) ; low = mid + 1 ; } else { high = mid - 1 ; } } return res ; } int main ( ) { int N = 6 , K = 14 ; cout << Count ( N , K ) ; return 0 ; }
Largest number having both positive and negative values present in the array | C ++ program for the above approach ; Function to find the largest number k such that both k and - k are present in the array ; Stores the array elements ; Initialize a variable res as 0 to store maximum element while traversing the array ; Iterate through array arr ; Add the current element into the st ; Check if the negative of this element is also present in the st or not ; Return the resultant element ; Drive Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int largestNum ( int arr [ ] , int n ) { set < int > st ; int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { st . insert ( arr [ i ] ) ; if ( st . find ( -1 * arr [ i ] ) != st . end ( ) ) { res = max ( res , abs ( arr [ i ] ) ) ; } } return res ; } int main ( ) { int arr [ ] = { 3 , 2 , -2 , 5 , -3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << largestNum ( arr , n ) ; }
Check if an element is present in an array using at most floor ( N / 2 ) + 2 comparisons | C ++ program for the above approach ; Function to check whether X is present in the array A [ ] ; Initialise a pointer ; Store the number of comparisons ; Variable to store product ; Check is N is odd ; Update i and T ; Traverse the array ; Check if i < N ; Update T ; Check if T is equal to 0 ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findElement ( int A [ ] , int N , int X ) { int i = 0 ; int Comparisons = 0 ; int T = 1 ; string Found = " No " ; Comparisons ++ ; if ( N % 2 == 1 ) { i = 1 ; T *= ( A [ 0 ] - X ) ; } for ( ; i < N ; i += 2 ) { Comparisons += 1 ; T *= ( A [ i ] - X ) ; T *= ( A [ i + 1 ] - X ) ; } Comparisons += 1 ; if ( T == 0 ) { cout << " Yes ▁ " << Comparisons ; } else { cout << " No " ; } } int main ( ) { int A [ ] = { -3 , 5 , 11 , 3 , 100 , 2 , 88 , 22 , 7 , 900 , 23 , 4 , 1 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int X = 1 ; findElement ( A , N , X ) ; return 0 ; }
Search an element in a sorted array formed by reversing subarrays from a random index | C ++ program for the above approach ; Function to search an element in a sorted array formed by reversing subarrays from a random index ; Set the boundaries for binary search ; Apply binary search ; Initialize the middle element ; If element found ; Random point is on right side of mid ; From l to mid arr is reverse sorted ; Random point is on the left side of mid ; From mid to h arr is reverse sorted ; Return Not Found ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find ( vector < int > arr , int N , int key ) { int l = 0 ; int h = N - 1 ; while ( l <= h ) { int mid = ( l + h ) / 2 ; if ( arr [ mid ] == key ) return mid ; if ( arr [ l ] >= arr [ mid ] ) { if ( arr [ l ] >= key && key >= arr [ mid ] ) h = mid - 1 ; else l = mid + 1 ; } else { if ( arr [ mid ] >= key && key >= arr [ h ] ) l = mid + 1 ; else h = mid - 1 ; } } return -1 ; } int main ( ) { vector < int > arr = { 10 , 8 , 6 , 5 , 2 , 1 , 13 , 12 } ; int N = arr . size ( ) ; int key = 8 ; int ans = find ( arr , N , key ) ; cout << ans ; }
Maximum elements that can be removed from front of two arrays such that their sum is at most K | C ++ program for the above approach ; Function to find the maximum number of items that can be removed from both the arrays ; Stores the maximum item count ; Stores the prefix sum of the cost of items ; Insert the item cost 0 at the front of the arrays ; Build the prefix sum for the array A [ ] ; Update the value of A [ i ] ; Build the prefix sum for the array B [ ] ; Update the value of B [ i ] ; Iterate through each item of the array A [ ] ; If A [ i ] exceeds K ; Store the remaining amount after taking top i elements from the array A ; Store the number of items possible to take from the array B [ ] ; Store low and high bounds for binary search ; Binary search to find number of item that can be taken from stack B in rem amount ; Calculate the mid value ; Update the value of j and lo ; Update the value of the hi ; Store the maximum of total item count ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxItems ( int n , int m , int a [ ] , int b [ ] , int K ) { int count = 0 ; int A [ n + 1 ] ; int B [ m + 1 ] ; A [ 0 ] = 0 ; B [ 0 ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { A [ i ] = a [ i - 1 ] + A [ i - 1 ] ; } for ( int i = 1 ; i <= m ; i ++ ) { B [ i ] = b [ i - 1 ] + B [ i - 1 ] ; } for ( int i = 0 ; i <= n ; i ++ ) { if ( A [ i ] > K ) break ; int rem = K - A [ i ] ; int j = 0 ; int lo = 0 , hi = m ; while ( lo <= hi ) { int mid = ( lo + hi ) / 2 ; if ( B [ mid ] <= rem ) { j = mid ; lo = mid + 1 ; } else { hi = mid - 1 ; } } count = max ( j + i , count ) ; } cout << count ; } int main ( ) { int n = 4 , m = 5 , K = 7 ; int A [ n ] = { 2 , 4 , 7 , 3 } ; int B [ m ] = { 1 , 9 , 3 , 4 , 5 } ; maxItems ( n , m , A , B , K ) ; return 0 ; }
Numbers of pairs from an array whose average is also present in the array | CPP program for the above approach ; Function to count the total count of pairs having sum S ; Store the total count of all elements in map mp ; Initialize value to 0 , if key not found ; Stores the total count of total pairs ; Iterate through each element and increment the count ; If the value ( S - arr [ i ] ) exists in the map hm ; Update the twice count ; Return the half of twice_count ; Function to count of pairs having whose average exists in the array ; Stores the total count of pairs ; Use set to remove duplicates ; Insert all the element in the set S ; For every sum find the getCountPairs ; Return the total count of pairs ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getCountPairs ( int arr [ ] , int N , int S ) { map < int , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { mp [ arr [ i ] ] ++ ; } int twice_count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( mp . find ( S - arr [ i ] ) != mp . end ( ) ) { twice_count += mp [ S - arr [ i ] ] ; } if ( S - arr [ i ] == arr [ i ] ) twice_count -- ; } return twice_count / 2 ; } int countPairs ( int arr [ ] , int N ) { int count = 0 ; set < int > S ; for ( int i = 0 ; i < N ; i ++ ) S . insert ( arr [ i ] ) ; for ( int ele : S ) { int sum = 2 * ele ; count += getCountPairs ( arr , N , sum ) ; } return count ; } int main ( ) { int N = 6 ; int arr [ ] = { 4 , 2 , 5 , 1 , 3 , 5 } ; cout << ( countPairs ( arr , N ) ) ; }
Number which is co | C ++ program for the above approach ; Function to check whether the given number N is prime or not ; Base Case ; If N has more than one factor , then return false ; Otherwise , return true ; Function to find X which is co - prime with the integers from the range [ L , R ] ; Store the resultant number ; Check for prime integers greater than R ; If the current number is prime , then update coPrime and break out of loop ; Print the resultant number ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int N ) { if ( N == 1 ) return false ; for ( int i = 2 ; i * i <= N ; i ++ ) { if ( N % i == 0 ) return false ; } return true ; } int findCoPrime ( int L , int R ) { int coPrime ; for ( int i = R + 1 ; ; i ++ ) { if ( isPrime ( i ) ) { coPrime = i ; break ; } } return coPrime ; } int main ( ) { int L = 16 , R = 17 ; cout << findCoPrime ( L , R ) ; return 0 ; }
Maximum value of arr [ i ] + arr [ j ] + i Γ’ β‚¬β€œ j for any pair of an array | C ++ program to for the above approach ; Function to find the maximum value of arr [ i ] + arr [ j ] + i - j over all pairs ; Stores the required result ; Traverse over all the pairs ( i , j ) ; Calculate the value of the expression and update the overall maximum value ; Print the result ; Driven Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maximumValue ( int arr [ ] , int n ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { ans = max ( ans , arr [ i ] + arr [ j ] + i - j ) ; } } cout << ans ; } int main ( ) { int arr [ ] = { 1 , 9 , 3 , 6 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maximumValue ( arr , N ) ; return 0 ; }
Maximum value of arr [ i ] + arr [ j ] + i Γ’ β‚¬β€œ j for any pair of an array | C ++ program for the above approach ; Function to find the maximum value of ( arr [ i ] + arr [ j ] + i - j ) possible for a pair in the array ; Stores the maximum value of ( arr [ i ] + i ) ; Stores the required result ; Traverse the array arr [ ] ; Calculate for current pair and update maximum value ; Update maxValue if ( arr [ i ] + I ) is greater than maxValue ; Print the result ; Driven Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maximumValue ( int arr [ ] , int n ) { int maxvalue = arr [ 0 ] ; int result = 0 ; for ( int i = 1 ; i < n ; i ++ ) { result = max ( result , maxvalue + arr [ i ] - i ) ; maxvalue = max ( maxvalue , arr [ i ] + i ) ; } cout << result ; } int main ( ) { int arr [ ] = { 1 , 9 , 3 , 6 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maximumValue ( arr , N ) ; return 0 ; }
Minimum sum of absolute differences of pairs in a triplet from three arrays | C ++ program for the above approach ; Function to find the value closest to K in the array A [ ] ; Initialize close value as the end element ; Find lower bound of the array ; If lower_bound is found ; If lower_bound is not the first array element ; If * ( it - 1 ) is closer to k ; Return closest value of k ; Function to find the minimum sum of abs ( arr [ i ] - brr [ j ] ) and abs ( brr [ j ] - crr [ k ] ) ; Sort the vectors arr and crr ; Initialize minimum as INT_MAX ; Traverse the array brr [ ] ; Stores the element closest to val from the array arr [ ] ; Stores the element closest to val from the array crr [ ] ; If sum of differences is minimum ; Update the minimum ; Print the minimum absolute difference possible ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int closestValue ( vector < int > A , int k ) { int close = A . back ( ) ; auto it = lower_bound ( A . begin ( ) , A . end ( ) , k ) ; if ( it != A . end ( ) ) { close = * it ; if ( it != A . begin ( ) ) { if ( ( k - * ( it - 1 ) ) < ( close - k ) ) { close = * ( it - 1 ) ; } } } return close ; } void minPossible ( vector < int > arr , vector < int > brr , vector < int > crr ) { sort ( arr . begin ( ) , arr . end ( ) ) ; sort ( crr . begin ( ) , crr . end ( ) ) ; int minimum = INT_MAX ; for ( int val : brr ) { int arr_close = closestValue ( arr , val ) ; int crr_close = closestValue ( crr , val ) ; if ( abs ( val - arr_close ) + abs ( val - crr_close ) < minimum ) minimum = abs ( val - arr_close ) + abs ( val - crr_close ) ; } cout << minimum ; } int main ( ) { vector < int > a = { 1 , 8 , 5 } ; vector < int > b = { 2 , 9 } ; vector < int > c = { 5 , 4 } ; minPossible ( a , b , c ) ; return 0 ; }
Maximum time required for all patients to get infected | C ++ program for the above approach ; Direction arrays ; Function to find the maximum time required for all patients to get infected ; Stores the number of rows ; Stores the number of columns ; Stores whether particular index ( i , j ) is visited or not ; Stores index and time of infection of infected persons ; Stores uninfected patients count ; Stores time at which last person got infected ; Traverse the matrix ; If the current patient is already infected ; Push the index of current patient and mark it as visited ; If current patient is uninfected increment uninfected count ; Iterate until queue becomes empty ; Stores the front element of queue ; Pop out the front element ; Check for all four adjacent indices ; Find the index of the adjacent cell ; If the current adjacent cell is invalid or it contains an infected patient ; Continue to the next neighbouring cell ; Push the infected neighbour into queue ; If an uninfected patient is present ; Return the final result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < pair < int , int > > direction = { { 1 , 0 } , { 0 , -1 } , { -1 , 0 } , { 0 , 1 } } ; int maximumTime ( vector < vector < int > > arr ) { int n = arr . size ( ) ; int m = arr [ 0 ] . size ( ) ; vector < vector < bool > > visited ( n , vector < bool > ( m , 0 ) ) ; queue < pair < pair < int , int > , int > > q ; int uninfected_count = 0 ; int time = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( arr [ i ] [ j ] == 2 ) { q . push ( { { i , j } , 0 } ) ; visited [ i ] [ j ] = 1 ; } if ( arr [ i ] [ j ] == 1 ) { uninfected_count ++ ; } } } while ( ! q . empty ( ) ) { pair < pair < int , int > , int > current = q . front ( ) ; time = current . second ; q . pop ( ) ; for ( auto it : direction ) { int i = current . first . first + it . first ; int j = current . first . second + it . second ; if ( i < 0 j < 0 i > = n j > = m arr [ i ] [ j ] != 1 visited [ i ] [ j ] != 0 ) { continue ; } q . push ( { { i , j } , time + 1 } ) ; visited [ i ] [ j ] = 1 ; uninfected_count -- ; } } if ( uninfected_count != 0 ) return -1 ; return time ; } int main ( ) { vector < vector < int > > arr = { { 2 , 1 , 0 , 2 , 1 } , { 1 , 0 , 1 , 2 , 1 } , { 1 , 0 , 0 , 2 , 1 } } ; cout << maximumTime ( arr ) ; return 0 ; }
Minimize swaps required to make the first and last elements the largest and smallest elements in the array respectively | C ++ program for the above approach ; Function to find the minimum number of swaps required to make the first and the last elements the largest and smallest element in the array ; Stores the count of swaps ; Stores the maximum element ; Stores the minimum element ; If the array contains a single distinct element ; Stores the indices of the maximum and minimum elements ; If the first index of the maximum element is found ; If current index has the minimum element ; Update the count of operations to place largest element at the first ; Update the count of operations to place largest element at the last ; If smallest element is present before the largest element initially ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimum_swaps ( int arr [ ] , int n ) { int count = 0 ; int max_el = * max_element ( arr , arr + n ) ; int min_el = * min_element ( arr , arr + n ) ; if ( min_el == max_el ) return 0 ; int index_max = -1 ; int index_min = -1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == max_el && index_max == -1 ) { index_max = i ; } if ( arr [ i ] == min_el ) { index_min = i ; } } count += index_max ; count += ( n - 1 - index_min ) ; if ( index_min < index_max ) count -= 1 ; return count ; } int main ( ) { int arr [ ] = { 2 , 4 , 1 , 6 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minimum_swaps ( arr , N ) ; return 0 ; }
Maximum difference between node and its ancestor in a Directed Acyclic Graph ( DAG ) | C ++ program for the above approach ; Function to perform DFS Traversal on the given graph ; Update the value of ans ; Update the currentMin and currentMax ; Traverse the adjacency list of the node src ; Recursively call for the child node ; Function to calculate maximum absolute difference between a node and its ancestor ; Stores the adjacency list of graph ; Create Adjacency list ; Add a directed edge ; Perform DFS Traversal ; Print the maximum absolute difference ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void DFS ( int src , vector < int > Adj [ ] , int & ans , int arr [ ] , int currentMin , int currentMax ) { ans = max ( ans , max ( abs ( currentMax - arr [ src - 1 ] ) , abs ( currentMin - arr [ src - 1 ] ) ) ) ; currentMin = min ( currentMin , arr [ src - 1 ] ) ; currentMax = min ( currentMax , arr [ src - 1 ] ) ; for ( auto & child : Adj [ src ] ) { DFS ( child , Adj , ans , arr , currentMin , currentMax ) ; } } void getMaximumDifference ( int Edges [ ] [ 2 ] , int arr [ ] , int N , int M ) { vector < int > Adj [ N + 1 ] ; for ( int i = 0 ; i < M ; i ++ ) { int u = Edges [ i ] [ 0 ] ; int v = Edges [ i ] [ 1 ] ; Adj [ u ] . push_back ( v ) ; } int ans = 0 ; DFS ( 1 , Adj , ans , arr , arr [ 0 ] , arr [ 0 ] ) ; cout << ans ; } int main ( ) { int N = 5 , M = 4 ; int Edges [ ] [ 2 ] = { { 1 , 2 } , { 2 , 3 } , { 4 , 5 } , { 1 , 3 } } ; int arr [ ] = { 13 , 8 , 3 , 15 , 18 } ; getMaximumDifference ( Edges , arr , N , M ) ; return 0 ; }
Minimum cost path from source node to destination node via K intermediate nodes | C ++ program for the above approach ; Function to find the minimum cost path from the source vertex to destination vertex via K intermediate vertices ; Initialize the adjacency list ; Generate the adjacency list ; Initialize the minimum priority queue ; Stores the minimum cost to travel between vertices via K intermediate nodes ; Push the starting vertex , cost to reach and the number of remaining vertices ; Pop the top element of the stack ; If destination is reached ; Return the cost ; If all stops are exhausted ; Find the neighbour with minimum cost ; Pruning ; Update cost ; Update priority queue ; If no path exists ; Driver Code ; Function Call to find the path from src to dist via k nodes having least sum of weights
#include <bits/stdc++.h> NEW_LINE using namespace std ; int leastWeightedSumPath ( int n , vector < vector < int > > & edges , int src , int dst , int K ) { unordered_map < int , vector < pair < int , int > > > graph ; for ( vector < int > & edge : edges ) { graph [ edge [ 0 ] ] . push_back ( make_pair ( edge [ 1 ] , edge [ 2 ] ) ) ; } priority_queue < vector < int > , vector < vector < int > > , greater < vector < int > > > pq ; vector < vector < int > > costs ( n , vector < int > ( K + 2 , INT_MAX ) ) ; costs [ src ] [ K + 1 ] = 0 ; pq . push ( { 0 , src , K + 1 } ) ; while ( ! pq . empty ( ) ) { auto top = pq . top ( ) ; pq . pop ( ) ; if ( top [ 1 ] == dst ) return top [ 0 ] ; if ( top [ 2 ] == 0 ) continue ; for ( auto neighbor : graph [ top [ 1 ] ] ) { if ( costs [ neighbor . first ] [ top [ 2 ] - 1 ] < neighbor . second + top [ 0 ] ) { continue ; } costs [ neighbor . first ] [ top [ 2 ] - 1 ] = neighbor . second + top [ 0 ] ; pq . push ( { neighbor . second + top [ 0 ] , neighbor . first , top [ 2 ] - 1 } ) ; } } return -1 ; } int main ( ) { int n = 3 , src = 0 , dst = 2 , k = 1 ; vector < vector < int > > edges = { { 0 , 1 , 100 } , { 1 , 2 , 100 } , { 0 , 2 , 500 } } ; cout << leastWeightedSumPath ( n , edges , src , dst , k ) ; return 0 ; }
Check if a given string is a comment or not | C ++ program for the above approach ; Function to check if the given string is a comment or not ; If two continuous slashes precedes the comment ; Driver Code ; Given string ; Function call to check whether then given string is a comment or not
#include <bits/stdc++.h> NEW_LINE using namespace std ; void isComment ( string line ) { if ( line [ 0 ] == ' / ' && line [ 1 ] == ' / ' && line [ 2 ] != ' / ' ) { cout << " It ▁ is ▁ a ▁ single - line ▁ comment " ; return ; } if ( line [ line . size ( ) - 2 ] == ' * ' && line [ line . size ( ) - 1 ] == ' / ' && line [ 0 ] == ' / ' && line [ 1 ] == ' * ' ) { cout << " It ▁ is ▁ a ▁ multi - line ▁ comment " ; return ; } cout << " It ▁ is ▁ not ▁ a ▁ comment " ; } int main ( ) { string line = " GeeksForGeeks ▁ GeeksForGeeks " ; isComment ( line ) ; return 0 ; }
Print digits for each array element that does not divide any digit of that element | C ++ program for the above approach ; Function to find digits for each array element that doesn 't divide any digit of the that element ; Traverse the array arr [ ] ; Iterate over the range [ 2 , 9 ] ; Stores if there exists any digit in arr [ i ] which is divisible by j ; If any digit of the number is divisible by j ; If the digit j doesn 't divide any digit of arr[i] ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void indivisibleDigits ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { int num = 0 ; cout << arr [ i ] << " : ▁ " ; for ( int j = 2 ; j < 10 ; j ++ ) { int temp = arr [ i ] ; bool flag = true ; while ( temp > 0 ) { if ( ( temp % 10 ) != 0 && ( temp % 10 ) % j == 0 ) { flag = false ; break ; } temp /= 10 ; } if ( flag ) { cout << j << ' ▁ ' ; } } cout << endl ; } } int main ( ) { int arr [ ] = { 4162 , 1152 , 99842 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; indivisibleDigits ( arr , N ) ; return 0 ; }
Length of longest non | C ++ program to implement the above approach ; Function to find the longest non - decreasing subsequence with difference between adjacent elements exactly equal to 1 ; Base case ; Sort the array in ascending order ; Stores the maximum length ; Traverse the array ; If difference between current pair of adjacent elements is 1 or 0 ; Extend the current sequence Update len and max_len ; Otherwise , start a new subsequence ; Print the maximum length ; Driver Code ; Given array ; Size of the array ; Function call to find the longest subsequence
#include <bits/stdc++.h> NEW_LINE using namespace std ; void longestSequence ( int arr [ ] , int N ) { if ( N == 0 ) { cout << 0 ; return ; } sort ( arr , arr + N ) ; int maxLen = 1 ; int len = 1 ; for ( int i = 1 ; i < N ; i ++ ) { if ( arr [ i ] == arr [ i - 1 ] arr [ i ] == arr [ i - 1 ] + 1 ) { len ++ ; maxLen = max ( maxLen , len ) ; } else { len = 1 ; } } cout << maxLen ; } int main ( ) { int arr [ ] = { 8 , 5 , 4 , 8 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; longestSequence ( arr , N ) ; return 0 ; }
Queries to find the minimum array sum possible by removing elements from either end | C ++ program for the above approach ; Function to find the minimum sum for each query after removing elements from either ends ; Traverse the query array ; Traverse the array from the front ; If element equals val , then break out of loop ; Traverse the array from rear ; If element equals val , break ; Print the minimum of the two as the answer ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minSum ( int arr [ ] , int N , int Q [ ] , int M ) { for ( int i = 0 ; i < M ; i ++ ) { int val = Q [ i ] ; int front = 0 , rear = 0 ; for ( int j = 0 ; j < N ; j ++ ) { front += arr [ j ] ; if ( arr [ j ] == val ) { break ; } } for ( int j = N - 1 ; j >= 0 ; j -- ) { rear += arr [ j ] ; if ( arr [ j ] == val ) { break ; } } cout << min ( front , rear ) << " ▁ " ; } } int main ( ) { int arr [ ] = { 2 , 3 , 6 , 7 , 4 , 5 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int Q [ ] = { 7 , 6 } ; int M = sizeof ( Q ) / sizeof ( Q [ 0 ] ) ; minSum ( arr , N , Q , M ) ; return 0 ; }
Frequency of lexicographically Kth smallest character in the a string | C ++ program for the above approach ; Function to find the frequency of the lexicographically Kth smallest character ; Convert the string to array of characters ; Sort the array in ascending order ; Store the Kth character ; Store the frequency of the K - th character ; Count the frequency of the K - th character ; Print the count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void KthCharacter ( string S , int N , int K ) { char strarray [ N + 1 ] ; strcpy ( strarray , S . c_str ( ) ) ; sort ( strarray , strarray + N ) ; char ch = strarray [ K - 1 ] ; int count = 0 ; for ( auto c : strarray ) { if ( c == ch ) count ++ ; } cout << count ; } int main ( ) { string S = " geeksforgeeks " ; int N = S . length ( ) ; int K = 3 ; KthCharacter ( S , N , K ) ; return 0 ; }
Longest substring with no pair of adjacent characters are adjacent English alphabets | C ++ program for the above approach ; Function to find the longest substring satisfying the given condition ; Stores all temporary substrings ; Stores the longest substring ; Stores the length of the substring T ; Stores the first character of string S ; Traverse the string ; If the absolute difference is 1 ; Update the length of substring T ; Update the longest substring ; Otherwise , stores the current character ; Again checking for longest substring and update accordingly ; Print the longest substring ; Driver Code ; Given string ; Function call to find the longest substring satisfying given condition
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findSubstring ( string S ) { string T = " " ; string ans = " " ; int l = 0 ; T += S [ 0 ] ; for ( int i = 1 ; i < S . length ( ) ; i ++ ) { if ( abs ( S [ i ] - S [ i - 1 ] ) == 1 ) { l = T . length ( ) ; if ( l > ans . length ( ) ) { ans = T ; } T = " " ; T += S [ i ] ; } else { T += S [ i ] ; } } l = ( int ) T . length ( ) ; if ( l > ( int ) ans . length ( ) ) { ans = T ; } cout << ans << endl ; } int main ( ) { string S = " aabdml " ; findSubstring ( S ) ; return 0 ; }
Minimize length of an array by removing similar subarrays from both ends | C ++ program for the above approach ; Function to minimize length of the array by removing similar subarrays from both ends of the array ; Initialize two pointers ; Stores the current integer ; Check if the elements at both ends are same or not ; Move the front pointer ; Move the rear pointer ; Print the minimized length of the array ; Driver Code ; Input ; Function call to find the minimized length of the array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMinLength ( int arr [ ] , int N ) { int front = 0 , back = N - 1 ; while ( front < back ) { int x = arr [ front ] ; if ( arr [ front ] != arr [ back ] ) break ; while ( arr [ front ] == x && front <= back ) front ++ ; while ( arr [ back ] == x && front <= back ) back -- ; } cout << back - front + 1 << endl ; } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 3 , 3 , 1 , 2 , 2 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findMinLength ( arr , N ) ; return 0 ; }
Queries to find the maximum and minimum array elements excluding elements from a given range | C ++ program for the above approach ; Function to find the maximum and minimum array elements up to the i - th index ; Traverse the array ; Compare current value with maximum and minimum values up to previous index ; Function to find the maximum and minimum array elements from i - th index ; Traverse the array in reverse ; Compare current value with maximum and minimum values in the next index ; Function to find the maximum and minimum array elements for each query ; If no index remains after excluding the elements in a given range ; Find maximum and minimum from from the range [ R + 1 , N - 1 ] ; Find maximum and minimum from from the range [ 0 , N - 1 ] ; Find maximum and minimum values from the ranges [ 0 , L - 1 ] and [ R + 1 , N - 1 ] ; Print the maximum and minimum value ; Function to perform queries to find the minimum and maximum array elements excluding elements from a given range ; Size of the array ; Size of query array ; prefix [ i ] [ 0 ] : Stores the maximum prefix [ i ] [ 1 ] : Stores the minimum value ; suffix [ i ] [ 0 ] : Stores the maximum suffix [ i ] [ 1 ] : Stores the minimum value ; Function calls to store maximum and minimum values for respective ranges ; Driver Code ; Given array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void prefixArr ( int arr [ ] , int prefix [ ] [ 2 ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { if ( i == 0 ) { prefix [ i ] [ 0 ] = arr [ i ] ; prefix [ i ] [ 1 ] = arr [ i ] ; } else { prefix [ i ] [ 0 ] = max ( prefix [ i - 1 ] [ 0 ] , arr [ i ] ) ; prefix [ i ] [ 1 ] = min ( prefix [ i - 1 ] [ 1 ] , arr [ i ] ) ; } } } void suffixArr ( int arr [ ] , int suffix [ ] [ 2 ] , int N ) { for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( i == N - 1 ) { suffix [ i ] [ 0 ] = arr [ i ] ; suffix [ i ] [ 1 ] = arr [ i ] ; } else { suffix [ i ] [ 0 ] = max ( suffix [ i + 1 ] [ 0 ] , arr [ i ] ) ; suffix [ i ] [ 1 ] = min ( suffix [ i + 1 ] [ 1 ] , arr [ i ] ) ; } } } void maxAndmin ( int prefix [ ] [ 2 ] , int suffix [ ] [ 2 ] , int N , int L , int R ) { int maximum , minimum ; if ( L == 0 && R == N - 1 ) { cout << " No ▁ maximum ▁ and ▁ minimum ▁ value " << endl ; return ; } else if ( L == 0 ) { maximum = suffix [ R + 1 ] [ 0 ] ; minimum = suffix [ R + 1 ] [ 1 ] ; } else if ( R == N - 1 ) { maximum = prefix [ L - 1 ] [ 0 ] ; minimum = prefix [ R - 1 ] [ 1 ] ; } else { maximum = max ( prefix [ L - 1 ] [ 0 ] , suffix [ R + 1 ] [ 0 ] ) ; minimum = min ( prefix [ L - 1 ] [ 1 ] , suffix [ R + 1 ] [ 1 ] ) ; } cout << maximum << " ▁ " << minimum << endl ; } void MinMaxQueries ( int a [ ] , int Q [ ] [ ] ) { int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int q = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; int prefix [ N ] [ 2 ] ; int suffix [ N ] [ 2 ] ; prefixArr ( arr , prefix , N ) ; suffixArr ( arr , suffix , N ) ; for ( int i = 0 ; i < q ; i ++ ) { int L = queries [ i ] [ 0 ] ; int R = queries [ i ] [ 1 ] ; maxAndmin ( prefix , suffix , N , L , R ) ; } } int main ( ) { int arr [ ] = { 2 , 3 , 1 , 8 , 3 , 5 , 7 , 4 } ; int queries [ ] [ 2 ] = { { 4 , 6 } , { 0 , 4 } , { 3 , 7 } , { 2 , 5 } } ; MinMaxQueries ( arr , Q ) ; return 0 ; }
Digits whose alphabetic representations are jumbled in a given string | C ++ program for the above approach ; Function to convert the jumbled string into digits ; Strings of digits 0 - 9 ; Initialize vector ; Initialize answer ; Size of the string ; Traverse the string ; Update the elements of the vector ; Print the digits into their original format ; Return answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string finddigits ( string s ) { string num [ ] = { " zero " , " one " , " two " , " three " , " four " , " five " , " six " , " seven " , " eight " , " nine " } ; vector < int > arr ( 10 ) ; string ans = " " ; int n = s . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ' z ' ) arr [ 0 ] ++ ; if ( s [ i ] == ' w ' ) arr [ 2 ] ++ ; if ( s [ i ] == ' g ' ) arr [ 8 ] ++ ; if ( s [ i ] == ' x ' ) arr [ 6 ] ++ ; if ( s [ i ] == ' v ' ) arr [ 5 ] ++ ; if ( s [ i ] == ' o ' ) arr [ 1 ] ++ ; if ( s [ i ] == ' s ' ) arr [ 7 ] ++ ; if ( s [ i ] == ' f ' ) arr [ 4 ] ++ ; if ( s [ i ] == ' h ' ) arr [ 3 ] ++ ; if ( s [ i ] == ' i ' ) arr [ 9 ] ++ ; } arr [ 7 ] -= arr [ 6 ] ; arr [ 5 ] -= arr [ 7 ] ; arr [ 4 ] -= arr [ 5 ] ; arr [ 1 ] -= ( arr [ 2 ] + arr [ 4 ] + arr [ 0 ] ) ; arr [ 3 ] -= arr [ 8 ] ; arr [ 9 ] -= ( arr [ 5 ] + arr [ 6 ] + arr [ 8 ] ) ; for ( int i = 0 ; i < 10 ; i ++ ) { for ( int j = 0 ; j < arr [ i ] ; j ++ ) { ans += ( char ) ( i + '0' ) ; } } return ans ; } int main ( ) { string s = " owoftnuoer " ; cout << finddigits ( s ) << endl ; }
Check if two binary strings can be made equal by swapping pairs of unequal characters | C ++ Program to implement of above approach ; Function to check if a string s1 can be converted into s2 ; Count of '0' in strings in s1 and s2 ; Iterate both the strings and count the number of occurrences of ; Count is not equal ; Iterating over both the arrays and count the number of occurrences of '0' ; If the count of occurrences of '0' in S2 exceeds that in S1 ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void check ( string s1 , string s2 ) { int s1_0 = 0 , s2_0 = 0 ; for ( int i = 0 ; i < s1 . size ( ) ; i ++ ) { if ( s1 [ i ] == '0' ) { s1_0 ++ ; } if ( s2 [ i ] == '0' ) { s2_0 ++ ; } } if ( s1_0 != s2_0 ) { cout << " NO " << endl ; return ; } else { int Count1 = 0 , Count2 = 0 ; for ( int i = 0 ; i < s1 . size ( ) ; i ++ ) { if ( s1 [ i ] == '0' ) { Count1 ++ ; } if ( s2 [ i ] == '0' ) { Count2 ++ ; } if ( Count1 < Count2 ) { cout << " NO " << endl ; return ; } } cout << " YES " << endl ; } } int main ( ) { string s1 = "100111" ; string s2 = "111010" ; check ( s1 , s2 ) ; s1 = "110100" ; s2 = "010101" ; check ( s1 , s2 ) ; return 0 ; }
Check if two binary strings can be made equal by swapping 1 s occurring before 0 s | C ++ program for the above approach ; Function to check if it is possible to make two binary strings equal by given operations ; Stores count of 1 ' s ▁ and ▁ 0' s of the string str1 ; Stores count of 1 ' s ▁ and ▁ 0' s of the string str2 ; Stores current count of 1 's presenty in the string str1 ; Count the number of 1 ' s ▁ and ▁ 0' s present in the strings str1 and str2 ; If the number of 1 ' s ▁ and ▁ 0' s are not same of the strings str1 and str2 then print not possible ; Traversing through the strings str1 and str2 ; If the str1 character not equals to str2 character ; Swaps 0 with 1 of the string str1 ; Breaks the loop as the count of 1 's is zero. Hence, no swaps possible ; Swaps 1 with 0 in the string str1 ; Print not possible ; Driver Code ; Given Strings ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void isBinaryStringsEqual ( string str1 , string str2 ) { int str1Zeros = 0 , str1Ones = 0 ; int str2Zeros = 0 , str2Ones = 0 ; int flag = 0 ; int curStr1Ones = 0 ; for ( int i = 0 ; i < str1 . length ( ) ; i ++ ) { if ( str1 [ i ] == '1' ) { str1Ones ++ ; } else if ( str1 [ i ] == '0' ) { str1Zeros ++ ; } if ( str2 [ i ] == '1' ) { str2Ones ++ ; } else if ( str2 [ i ] == '0' ) { str2Zeros ++ ; } } if ( str1Zeros != str2Zeros && str1Ones != str2Ones ) { cout << " Not ▁ Possible " ; } else { for ( int i = 0 ; i < str1 . length ( ) ; i ++ ) { if ( str1 [ i ] != str2 [ i ] ) { if ( str1 [ i ] == '0' && curStr1Ones > 0 ) { str1 [ i ] = '1' ; curStr1Ones -- ; } if ( str1 [ i ] == '0' && curStr1Ones == 0 ) { flag ++ ; break ; } if ( str1 [ i ] == '1' && str2 [ i ] == '0' ) { str1 [ i ] = '0' ; curStr1Ones ++ ; } } } if ( flag == 0 ) { cout << " Possible " ; } else { cout << " Not ▁ Possible " ; } } } int main ( ) { string str1 = "0110" ; string str2 = "0011" ; isBinaryStringsEqual ( str1 , str2 ) ; return 0 ; }
Count array elements whose all distinct digits appear in K | C ++ program to implement the above approach ; Function to the count of array elements whose distinct digits are a subset of the digits of K ; Stores distinct digits of K ; Iterate over all the digits of K ; Insert current digit into set ; Update K ; Stores the count of array elements whose distinct digits are a subset of the digits of K ; Traverse the array , arr [ ] ; Stores current element ; Check if all the digits of arr [ i ] are present in K or not ; Iterate over all the digits of arr [ i ] ; Stores current digit ; If digit not present in the set ; Update flag ; Update no ; If all the digits of arr [ i ] present in set ; Update count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; static int noOfValidKbers ( int K , vector < int > arr ) { map < int , int > set ; while ( K != 0 ) { set [ K % 10 ] = 1 ; K = K / 10 ; } int count = 0 ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { int no = arr [ i ] ; bool flag = true ; while ( no != 0 ) { int digit = no % 10 ; if ( set . find ( digit ) == set . end ( ) ) { flag = false ; break ; } no = no / 10 ; } if ( flag == true ) { count ++ ; } } return count ; } int main ( ) { int K = 12 ; vector < int > arr = { 1 , 12 , 1222 , 13 , 2 } ; cout << ( noOfValidKbers ( K , arr ) ) ; }
Queries to find the minimum index in a range [ L , R ] having at least value X with updates | C ++ program for the above approach ; Stores nodes value of the Tree ; Function to build segment tree ; Base Case ; Find the value of mid ; Update for left subtree ; Update for right subtree ; Update the value at the current index ; Function for finding the index of the first element at least x ; If current range does not lie in query range ; If current range is inside of query range ; Maximum value in this range is less than x ; Finding index of first value in this range ; Update the value of the minimum index ; Find mid of the current range ; Left subtree ; If it does not lie in left subtree ; Function for updating segment tree ; Update the value , we reached leaf node ; Find the mid ; If pos lies in the left subtree ; pos lies in the right subtree ; Update the maximum value in the range ; Function to print the answer for the given queries ; Build segment tree ; Find index of first value atleast 2 in range [ 0 , n - 1 ] ; Update value at index 2 to 5 ; Find index of first value atleast 4 in range [ 0 , n - 1 ] ; Find index of first value atleast 0 in range [ 0 , n - 1 ] ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE #define maxN 100 NEW_LINE using namespace std ; int Tree [ 4 * maxN ] ; void build ( int arr [ ] , int index , int s , int e ) { if ( s == e ) Tree [ index ] = arr [ s ] ; else { int m = ( s + e ) / 2 ; build ( arr , 2 * index , s , m ) ; build ( arr , 2 * index + 1 , m + 1 , e ) ; Tree [ index ] = max ( Tree [ 2 * index ] , Tree [ 2 * index + 1 ] ) ; } } int atleast_x ( int index , int s , int e , int ql , int qr , int x ) { if ( ql > e qr < s ) return -1 ; if ( s <= ql && e <= qr ) { if ( Tree [ index ] < x ) return -1 ; while ( s != e ) { int m = ( s + e ) / 2 ; if ( Tree [ 2 * index ] >= x ) { e = m ; index = 2 * index ; } else { s = m + 1 ; index = 2 * index + 1 ; } } return s ; } int m = ( s + e ) / 2 ; int val = atleast_x ( 2 * index , s , m , ql , qr , x ) ; if ( val != -1 ) return val ; return atleast_x ( 2 * index + 1 , m + 1 , e , ql , qr , x ) ; } void update ( int index , int s , int e , int new_val , int pos ) { if ( s == e ) Tree [ index ] = new_val ; else { int m = ( s + e ) / 2 ; if ( pos <= m ) { update ( 2 * index , s , m , new_val , pos ) ; } else { update ( 2 * index + 1 , m + 1 , e , new_val , pos ) ; } Tree [ index ] = max ( Tree [ 2 * index ] , Tree [ 2 * index + 1 ] ) ; } } void printAnswer ( int * arr , int n ) { build ( arr , 1 , 0 , n - 1 ) ; cout << atleast_x ( 1 , 0 , n - 1 , 0 , n - 1 , 2 ) << " STRNEWLINE " ; arr [ 2 ] = 5 ; update ( 1 , 0 , n - 1 , 5 , 2 ) ; cout << atleast_x ( 1 , 0 , n - 1 , 0 , n - 1 , 4 ) << " STRNEWLINE " ; cout << atleast_x ( 1 , 0 , n - 1 , 0 , n - 1 , 0 ) << " STRNEWLINE " ; } int main ( ) { int arr [ ] = { 1 , 3 , 2 , 4 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printAnswer ( arr , N ) ; return 0 ; }
Smallest Subtree with all the Deepest Nodes | C ++ program to implement the above approach ; Structure of a Node ; Function to return depth of the Tree from root ; If current node is a leaf node ; Function to find the root of the smallest subtree consisting of all deepest nodes ; Stores height of left subtree ; Stores height of right subtree ; If height of left subtree exceeds that of the right subtree ; Traverse left subtree ; If height of right subtree exceeds that of the left subtree ; Otherwise ; Return current node ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct TreeNode { int val ; TreeNode * left ; TreeNode * right ; TreeNode ( int data ) { this -> val = data ; left = NULL ; right = NULL ; } } ; int find_ht ( TreeNode * root ) { if ( ! root ) return 0 ; if ( root -> left == NULL && root -> right == NULL ) return 1 ; return max ( find_ht ( root -> left ) , find_ht ( root -> right ) ) + 1 ; } void find_node ( TreeNode * root , TreeNode * & req_node ) { if ( ! root ) return ; int left_ht = find_ht ( root -> left ) ; int right_ht = find_ht ( root -> right ) ; if ( left_ht > right_ht ) { find_node ( root -> left , req_node ) ; } else if ( right_ht > left_ht ) { find_node ( root -> right , req_node ) ; } else { req_node = root ; return ; } } int main ( ) { struct TreeNode * root = new TreeNode ( 1 ) ; root -> left = new TreeNode ( 2 ) ; root -> right = new TreeNode ( 3 ) ; TreeNode * req_node = NULL ; find_node ( root , req_node ) ; cout << req_node -> val ; return 0 ; }
Maximum even numbers present in any subarray of size K | C ++ program to implement the above approach ; Function to find the maximum count of even numbers from all the subarrays of size K ; Stores the maximum count of even numbers from all the subarrays of size K ; Generate all subarrays of size K ; Store count of even numbers in current subarray of size K ; Traverse the current subarray ; If current element is an even number ; Update the answer ; Return answer ; Driver Code ; Size of the input array
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxEvenIntegers ( int arr [ ] , int N , int M ) { int ans = 0 ; for ( int i = 0 ; i <= N - M ; i ++ ) { int cnt = 0 ; for ( int j = 0 ; j < M ; j ++ ) { if ( arr [ i + j ] % 2 == 0 ) cnt ++ ; } ans = max ( ans , cnt ) ; } return ans ; } int main ( ) { int arr [ ] = { 2 , 3 , 5 , 4 , 7 , 6 } ; int K = 3 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxEvenIntegers ( arr , N , K ) << endl ; return 0 ; }
Count maximum concatenation of pairs from given array that are divisible by 3 | C ++ program to implement the above approach ; Function to count pairs whose concatenation is divisible by 3 and each element can be present in at most one pair ; Stores count of array elements whose remainder is 0 by taking modulo by 3 ; Stores count of array elements whose remainder is 1 by taking modulo by 3 ; Stores count of array elements whose remainder is 2 by taking modulo by 3 ; Traverse the array ; Stores sum of digits of arr [ i ] ; Update digitSum ; If remainder of digitSum by by taking modulo 3 is 0 ; Update rem0 ; If remainder of digitSum by by taking modulo 3 is 1 ; Update rem1 ; Update rem2 ; Driver code ; To display the result
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countDiv ( int arr [ ] , int n ) { int rem0 = 0 ; int rem1 = 0 ; int rem2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int digitSum = 0 ; digitSum += arr [ i ] ; if ( digitSum % 3 == 0 ) { rem0 += 1 ; } else if ( digitSum % 3 == 1 ) { rem1 += 1 ; } else { rem2 += 1 ; } } return ( rem0 / 2 + min ( rem1 , rem2 ) ) ; } int main ( ) { int arr [ ] = { 5 , 3 , 2 , 8 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ( countDiv ( arr , n ) ) ; }
Maximum Sum Subsequence | C ++ program to implement the above approach ; Function to print the maximum non - emepty subsequence sum ; Stores the maximum non - emepty subsequence sum in an array ; Stores the largest element in the array ; Traverse the array ; If a [ i ] is greater than 0 ; Update sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MaxNonEmpSubSeq ( int a [ ] , int n ) { int sum = 0 ; int max = * max_element ( a , a + n ) ; if ( max <= 0 ) { return max ; } for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] > 0 ) { sum += a [ i ] ; } } return sum ; } int main ( ) { int arr [ ] = { -2 , 11 , -4 , 2 , -3 , -10 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << MaxNonEmpSubSeq ( arr , N ) ; return 0 ; }
Count numbers up to N having Kth bit set | C ++ program for above approach ; Function to return the count of number of 1 's at ith bit in a range [1, n - 1] ; Store count till nearest power of 2 less than N ; If K - th bit is set in N ; Add to result the nearest power of 2 less than N ; Return result ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long getcount ( long long n , int k ) { long long res = ( n >> ( k + 1 ) ) << k ; if ( ( n >> k ) & 1 ) res += n & ( ( 1ll << k ) - 1 ) ; return res ; } int main ( ) { long long int N = 14 ; int K = 2 ; cout << getcount ( N + 1 , K ) << endl ; return 0 ; }
Check if a string can be split into two substrings such that one substring is a substring of the other | C ++ program to implement the above approach ; Function to check if a string can be divided into two substrings such that one substring is substring of the other ; Store the last character of S ; Traverse the characters at indices [ 0 , N - 2 ] ; Check if the current character is equal to the last character ; If true , set f = 1 ; Break out of the loop ; Driver Code ; Given string , S ; Store the size of S ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void splitString ( string S , int N ) { char c = S [ N - 1 ] ; int f = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( S [ i ] == c ) { f = 1 ; break ; } } if ( f ) cout << " Yes " ; else cout << " No " ; } int main ( ) { string S = " abcdab " ; int N = S . size ( ) ; splitString ( S , N ) ; return 0 ; }
Find the light bulb with maximum glowing time | C ++ program for the above approach ; Function to find the bulb having maximum glow ; Initialize variables ; Traverse the array consisting of glowing time of the bulbs ; For 1 st bulb ; Calculate the glowing time ; Update the maximum glow ; Find lexicographically largest bulb ; Bulb with maximum time ; Return the resultant bulb ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; char longestLastingBulb ( vector < int > onTime , string s ) { char ans ; int n = onTime . size ( ) ; int maxDur = INT_MIN ; int maxPos = INT_MIN ; int currentDiff = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i == 0 ) { currentDiff = onTime [ i ] ; maxDur = currentDiff ; maxPos = i ; } else { currentDiff = onTime [ i ] - onTime [ i - 1 ] ; if ( maxDur < currentDiff ) { maxDur = currentDiff ; maxPos = i ; } else { if ( maxDur == currentDiff ) { char one = s [ i ] ; char two = s [ maxPos ] ; if ( one > two ) { maxDur = currentDiff ; maxPos = i ; } } } } } ans = s [ maxPos ] ; return ans ; } int main ( ) { string S = " spuda " ; vector < int > arr = { 12 , 23 , 36 , 46 , 62 } ; cout << longestLastingBulb ( arr , S ) ; return 0 ; }
Find a pair of intersecting ranges from a given array | C ++ program for the above approach ; Store ranges and their corresponding array indices ; Function to find a pair of intersecting ranges ; Stores ending point of every range ; Stores the maximum ending point obtained ; Iterate from 0 to N - 1 ; Starting point of the current range ; End point of the current range ; Push pairs into tup ; Sort the tup vector ; Iterate over the ranges ; If starting points are equal ; Print the indices of the intersecting ranges ; If no such pair of segments exist ; Driver Code ; Given N ; Given 2d ranges [ ] [ ] array ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < pair < pair < int , int > , int > > tup ; void findIntersectingRange ( int N , int ranges [ ] [ 2 ] ) { int curr ; int currPos ; for ( int i = 0 ; i < N ; i ++ ) { int x , y ; x = ranges [ i ] [ 0 ] ; y = ranges [ i ] [ 1 ] ; tup . push_back ( { { x , y } , i + 1 } ) ; } sort ( tup . begin ( ) , tup . end ( ) ) ; curr = tup [ 0 ] . first . second ; currPos = tup [ 0 ] . second ; for ( int i = 1 ; i < N ; i ++ ) { int Q = tup [ i - 1 ] . first . first ; int R = tup [ i ] . first . first ; if ( Q == R ) { if ( tup [ i - 1 ] . first . second < tup [ i ] . first . second ) cout << tup [ i - 1 ] . second << ' ▁ ' << tup [ i ] . second ; else cout << tup [ i ] . second << ' ▁ ' << tup [ i - 1 ] . second ; return ; } int T = tup [ i ] . first . second ; if ( T <= curr ) { cout << tup [ i ] . second << ' ▁ ' << currPos ; return ; } else { curr = T ; currPos = tup [ i ] . second ; } } cout << " - 1 ▁ - 1" ; } int main ( ) { int N = 5 ; int ranges [ ] [ 2 ] = { { 1 , 5 } , { 2 , 10 } , { 3 , 10 } , { 2 , 2 } , { 2 , 15 } } ; findIntersectingRange ( N , ranges ) ; }
Find the next greater element in a Circular Array | Set 2 | C ++ program for the above approach ; Function to find the NGE for the given circular array arr [ ] ; Initialize stack and nge [ ] array ; Initialize nge [ ] array to - 1 ; Traverse the array ; If stack is not empty and current element is greater than top element of the stack ; Assign next greater element for the top element of the stack ; Pop the top element of the stack ; Print the nge [ ] array ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printNGE ( int * arr , int n ) { stack < int > s ; int nge [ n ] , i = 0 ; for ( i = 0 ; i < n ; i ++ ) { nge [ i ] = -1 ; } i = 0 ; while ( i < 2 * n ) { while ( ! s . empty ( ) && arr [ i % n ] > arr [ s . top ( ) ] ) { nge [ s . top ( ) ] = arr [ i % n ] ; s . pop ( ) ; } s . push ( i % n ) ; i ++ ; } for ( i = 0 ; i < n ; i ++ ) { cout << nge [ i ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 4 , -2 , 5 , 8 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printNGE ( arr , N ) ; return 0 ; }
Count array elements whose product of digits is a Composite Number | C ++ program for the above approach ; Function to generate prime numbers using Sieve of Eratosthenes ; Set 0 and 1 as non - prime ; If p is a prime ; Set all multiples of p as non - prime ; Function to calculate the product of digits of the given number ; Stores the product of digits ; Extract digits and add to the sum ; Return the product of its digits ; Function to print number of distinct values with digit product as composite ; Initialize set ; Initialize boolean array ; Pre - compute primes ; Traverse array ; Stores the product of digits of the current array element ; If Product of digits is less than or equal to 1 ; If Product of digits is not a prime ; Print the answer ; Driver Code ; Given array ; Given size ; Function call
#include <bits/stdc++.h> NEW_LINE #include <set> NEW_LINE using namespace std ; #define N 100005 NEW_LINE void SieveOfEratosthenes ( bool prime [ ] , int p_size ) { prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= p_size ; p ++ ) { if ( prime [ p ] ) { for ( int i = p * 2 ; i <= p_size ; i += p ) prime [ i ] = false ; } } } long long int digitProduct ( int number ) { long long int res = 1 ; while ( number > 0 ) { res *= ( number % 10 ) ; number /= 10 ; } return res ; } void DistinctCompositeDigitProduct ( int arr [ ] , int n ) { set < int > output ; bool prime [ N + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; SieveOfEratosthenes ( prime , N ) ; for ( int i = 0 ; i < n ; i ++ ) { long long int ans = digitProduct ( arr [ i ] ) ; if ( ans <= 1 ) { continue ; } if ( ! prime [ ans ] ) { output . insert ( ans ) ; } } cout << output . size ( ) << endl ; } int main ( ) { int arr [ ] = { 13 , 55 , 7 , 13 , 11 , 71 , 233 , 233 , 144 , 89 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; DistinctCompositeDigitProduct ( arr , n ) ; return 0 ; }
Count pairs from a given range whose sum is a Prime Number in that range | C ++ program to implement the above approach ; Function to find all prime numbers in range [ 1 , lmt ] using sieve of Eratosthenes ; segmentedSieve [ i ] : Stores if i is a prime number ( True ) or not ( False ) ; Initialize all elements of segmentedSieve [ ] to false ; Set 0 and 1 as non - prime ; Iterate over the range [ 2 , lmt ] ; If i is a prime number ; Append i into prime ; Set all multiple of i non - prime ; Update Sieve [ j ] ; Function to find all the prime numbers in the range [ low , high ] ; Stores square root of high + 1 ; Stores all the prime numbers in the range [ 1 , lmt ] ; Find all the prime numbers in the range [ 1 , lmt ] ; Stores count of elements in the range [ low , high ] ; segmentedSieve [ i ] : Check if ( i - low ) is a prime number or not ; Traverse the array prime [ ] ; Store smallest multiple of prime [ i ] in the range [ low , high ] ; If lowLim is less than low ; Update lowLim ; Iterate over all multiples of prime [ i ] ; If j not equal to prime [ i ] ; Update segmentedSieve [ j - low ] ; Function to count the number of pairs in the range [ L , R ] whose sum is a prime number in the range [ L , R ] ; segmentedSieve [ i ] : Check if ( i - L ) is a prime number or not ; Stores count of pairs whose sum of elements is a prime and in range [ L , R ] ; Iterate over [ L , R ] ; If ( i - L ) is a prime ; Update cntPairs ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void simpleSieve ( int lmt , vector < int > & prime ) { bool Sieve [ lmt + 1 ] ; memset ( Sieve , true , sizeof ( Sieve ) ) ; Sieve [ 0 ] = Sieve [ 1 ] = false ; for ( int i = 2 ; i <= lmt ; ++ i ) { if ( Sieve [ i ] == true ) { prime . push_back ( i ) ; for ( int j = i * i ; j <= lmt ; j += i ) { Sieve [ j ] = false ; } } } } vector < bool > SegmentedSieveFn ( int low , int high ) { int lmt = floor ( sqrt ( high ) ) + 1 ; vector < int > prime ; simpleSieve ( lmt , prime ) ; int n = high - low + 1 ; vector < bool > segmentedSieve ( n + 1 , true ) ; for ( int i = 0 ; i < prime . size ( ) ; i ++ ) { int lowLim = floor ( low / prime [ i ] ) * prime [ i ] ; if ( lowLim < low ) { lowLim += prime [ i ] ; } for ( int j = lowLim ; j <= high ; j += prime [ i ] ) { if ( j != prime [ i ] ) { segmentedSieve [ j - low ] = false ; } } } return segmentedSieve ; } int countPairsWhoseSumPrimeL_R ( int L , int R ) { vector < bool > segmentedSieve = SegmentedSieveFn ( L , R ) ; int cntPairs = 0 ; for ( int i = L ; i <= R ; i ++ ) { if ( segmentedSieve [ i - L ] ) { cntPairs += i / 2 ; } } return cntPairs ; } int main ( ) { int L = 1 , R = 5 ; cout << countPairsWhoseSumPrimeL_R ( L , R ) ; return 0 ; }
Lexicographically smallest permutation of a string that can be reduced to length K by removing K | C ++ program for the above approach ; Function to count the number of zeroes present in the string ; Traverse the string ; Return the count ; Function to rearrange the string s . t the string can be reduced to a length K as per the given rules ; Distribute the count of 0 s and 1 s in segment of length 2 k ; Store string that are initially have formed lexicographically smallest 2 k length substring ; Store the lexicographically smallest string of length n that satisfy the condition ; Insert temp_str into final_str ( n / 2 k ) times and add ( n % 2 k ) characters of temp_str at end ; Return the final string ; Function to reduce the string to length K that follows the given conditions ; If the string contains either 0 s or 1 s then it always be reduced into a K length string ; If the string contains only 0 s 1 s then it always reduces to a K length string ; If K = 1 ; Check whether the given string is K reducing string or not ; Otherwise recursively find the string ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count_zeroes ( int n , string str ) { int cnt = 0 ; for ( int i = 0 ; i < str . size ( ) ; i ++ ) { if ( str [ i ] == '0' ) cnt ++ ; } return cnt ; } string kReducingStringUtil ( int n , int k , string str , int no_of_zeroes ) { int zeroes_in_2k = ( ( no_of_zeroes ) * ( 2 * k ) ) / n ; int ones_in_2k = 2 * k - zeroes_in_2k ; string temp_str = " " ; for ( int i = 0 ; i < ( zeroes_in_2k ) / 2 ; i ++ ) { temp_str . push_back ( '0' ) ; } for ( int i = 0 ; i < ones_in_2k ; i ++ ) { temp_str . push_back ( '1' ) ; } for ( int i = 0 ; i < ( zeroes_in_2k ) / 2 ; i ++ ) { temp_str . push_back ( '0' ) ; } string final_str = " " ; for ( int i = 0 ; i < n / ( 2 * k ) ; i ++ ) { final_str += ( temp_str ) ; } for ( int i = 0 ; i < n % ( 2 * k ) ; i ++ ) { final_str . push_back ( temp_str [ i ] ) ; } return final_str ; } string kReducingString ( int n , int k , string str ) { int no_of_zeroes = count_zeroes ( n , str ) ; int no_of_ones = n - no_of_zeroes ; if ( no_of_zeroes == 0 no_of_zeroes == n ) { return str ; } if ( k == 1 ) { if ( no_of_zeroes == 0 no_of_zeroes == n ) { return str ; } else { return " Not ▁ Possible " ; } } bool check = 0 ; for ( int i = ( n / k ) ; i < n ; i += ( n / k ) ) { if ( no_of_zeroes == i no_of_ones == i ) { check = 1 ; break ; } } if ( check == 0 ) { return " Not ▁ Possible " ; } return kReducingStringUtil ( n , k , str , no_of_zeroes ) ; } int main ( ) { string str = "0000100001100001" ; int K = 4 ; int N = str . length ( ) ; cout << kReducingString ( N , K , str ) ; return 0 ; }
Count quadruplets with sum K from given array | C ++ program for the above approach ; Function to return the number of quadruplets having the given sum ; Initialize variables ; Initialize answer ; Store the frequency of sum of first two elements ; Traverse from 0 to N - 1 , where arr [ i ] is the 3 rd element ; All possible 4 th elements ; Sum of last two element ; Frequency of sum of first two elements ; Store frequency of all possible sums of first two elements ; Return the answer ; Driver Code ; Given array arr [ ] ; Given sum S ; Function Call
#include <iostream> NEW_LINE #include <unordered_map> NEW_LINE using namespace std ; int countSum ( int a [ ] , int n , int sum ) { int i , j , k ; int count = 0 ; unordered_map < int , int > m ; for ( i = 0 ; i < n - 1 ; i ++ ) { for ( j = i + 1 ; j < n ; j ++ ) { int temp = a [ i ] + a [ j ] ; if ( temp < sum ) count += m [ sum - temp ] ; } for ( j = 0 ; j < i ; j ++ ) { int temp = a [ i ] + a [ j ] ; if ( temp < sum ) m [ temp ] ++ ; } } return count ; } int main ( ) { int arr [ ] = { 4 , 5 , 3 , 1 , 2 , 4 } ; int S = 13 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countSum ( arr , N , S ) ; return 0 ; }
Count pairs whose product modulo 10 ^ 9 + 7 is equal to 1 | C ++ program to implement the above approach ; Iterative Function to calculate ( x ^ y ) % MOD ; Initialize result ; Update x if it exceeds MOD ; If x is divisible by MOD ; If y is odd ; Multiply x with res ; y must be even now ; Function to count number of pairs whose product modulo 1000000007 is 1 ; Stores the count of desired pairs ; Stores the frequencies of each array element ; Traverse the array and update frequencies in hash ; Calculate modular inverse of arr [ i ] under modulo 1000000007 ; Update desired count of pairs ; If arr [ i ] and its modular inverse is equal under modulo MOD ; Updating count of desired pairs ; Return the final count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MOD 1000000007 NEW_LINE long long int modPower ( long long int x , long long int y ) { long long int res = 1 ; x = x % MOD ; if ( x == 0 ) return 0 ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % MOD ; y = y / 2 ; x = ( x * x ) % MOD ; } return res ; } int countPairs ( long long int arr [ ] , int N ) { int pairCount = 0 ; map < long long int , int > hash ; for ( int i = 0 ; i < N ; i ++ ) { hash [ arr [ i ] ] ++ ; } for ( int i = 0 ; i < N ; i ++ ) { long long int modularInverse = modPower ( arr [ i ] , MOD - 2 ) ; pairCount += hash [ modularInverse ] ; if ( arr [ i ] == modularInverse ) { pairCount -- ; } } return pairCount / 2 ; } int main ( ) { long long int arr [ ] = { 2 , 236426 , 280311812 , 500000004 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , N ) ; return 0 ; }
Check if all subarrays contains at least one unique element | C ++ program for above approach ; Function to check if all subarrays of array have at least one unique element ; Stores frequency of subarray elements ; Generate all subarrays ; Insert first element in map ; Update frequency of current subarray in the HashMap ; Check if at least one element occurs once in current subarray ; If any subarray doesn 't have unique element ; Clear map for next subarray ; Return Yes if all subarray having at least 1 unique element ; Driver Code ; Given array arr [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string check ( int arr [ ] , int n ) { map < int , int > hm ; for ( int i = 0 ; i < n ; i ++ ) { hm [ arr [ i ] ] = 1 ; for ( int j = i + 1 ; j < n ; j ++ ) { hm [ arr [ j ] ] ++ ; bool flag = false ; for ( auto x : hm ) { if ( x . second == 1 ) { flag = true ; break ; } } if ( ! flag ) return " No " ; } hm . clear ( ) ; } return " Yes " ; } int main ( ) { int arr [ ] = { 1 , 2 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << check ( arr , N ) ; }