text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Lexicographically Kth smallest way to reach given coordinate from origin | CPP Program to find Lexicographically Kth smallest way to reach given coordinate from origin ; Return ( a + b ) ! / a ! b ! ; finding ( a + b ) ! ; finding ( a + b ) ! / a ! ; finding ( a + b ) ! / b ! ; Return the Kth smallest way to reach given coordinate from origin ; if at origin ; if on y - axis ; decrement y . ; Move vertical ; recursive call to take next step . ; If on x - axis ; decrement x . ; Move horizontal . ; recursive call to take next step . ; If x + y C x is greater than K ; Move Horizontal ; recursive call to take next step . ; Move vertical ; recursive call to take next step . ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int factorial ( int a , int b ) { int res = 1 ; for ( int i = 1 ; i <= ( a + b ) ; i ++ ) res = res * i ; for ( int i = 1 ; i <= a ; i ++ ) res = res / i ; for ( int i = 1 ; i <= b ; i ++ ) res = res / i ; return res ; } void Ksmallest ( int x , int y , int k ) { if ( x == 0 && y == 0 ) return ; else if ( x == 0 ) { y -- ; cout << " V " ; Ksmallest ( x , y , k ) ; } else if ( y == 0 ) { x -- ; cout << " H " ; Ksmallest ( x , y , k ) ; } else { if ( factorial ( x - 1 , y ) > k ) { cout << " H " ; Ksmallest ( x - 1 , y , k ) ; } else { cout << " V " ; Ksmallest ( x , y - 1 , k - factorial ( x - 1 , y ) ) ; } } } int main ( ) { int x = 2 , y = 2 , k = 2 ; Ksmallest ( x , y , k ) ; return 0 ; }
Centered pentagonal number | Program to find nth Centered pentagonal number . ; centered pentagonal number function ; Formula to calculate nth Centered pentagonal number and return it into main function . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int centered_pentagonal_Num ( int n ) { return ( 5 * n * n - 5 * n + 2 ) / 2 ; } int main ( ) { int n = 7 ; cout << n << " th ▁ Centered ▁ pentagonal ▁ number : ▁ " ; cout << centered_pentagonal_Num ( n ) ; return 0 ; }
Find maximum and minimum distance between magnets | C ++ program for max and min distance ; Function for finding distance between pivots ; Function for minimum distance ; Function for maximum distance ; Drivers code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int pivotDis ( int x0 , int y0 , int x1 , int y1 ) { return sqrt ( ( x1 - x0 ) * ( x1 - x0 ) + ( y1 - y0 ) * ( y1 - y0 ) ) ; } int minDis ( int D , int r1 , int r2 ) { return max ( ( D - r1 - r2 ) , 0 ) ; } int maxDis ( int D , int r1 , int r2 ) { return D + r1 + r2 ; } int main ( ) { int x0 = 0 , y0 = 0 , x1 = 8 , y1 = 0 , r1 = 4 , r2 = 5 ; int D = pivotDis ( x0 , y0 , x1 , y1 ) ; cout << " Distance ▁ while ▁ repulsion ▁ = ▁ " << maxDis ( D , r1 , r2 ) ; cout << " Distance while attraction = " return 0 ; }
Maximize a value for a semicircle of given radius | C ++ program to find the maximum value of F ; Function to find the maximum value of F ; using the formula derived for getting the maximum value of F ; Drivers code
#include <bits/stdc++.h> NEW_LINE using namespace std ; double maximumValueOfF ( int R ) { return 4 * R * R + 0.25 ; } int main ( ) { int R = 3 ; printf ( " % .2f " , maximumValueOfF ( R ) ) ; return 0 ; }
Find the other end point of a line with given one end and mid | CPP program to find the end point of a line ; CPP function to find the end point of a line ; find end point for x coordinates ; find end point for y coordinates ; Driven Program
#include <iostream> NEW_LINE using namespace std ; void otherEndPoint ( int x1 , int y1 , int m1 , int m2 ) { float x2 = ( float ) ( 2 * m1 - x1 ) ; float y2 = ( float ) ( 2 * m2 - y1 ) ; cout << " x2 ▁ = ▁ " << x2 << " , ▁ " << " y2 ▁ = ▁ " << y2 ; } int main ( ) { int x1 = -4 , y1 = -1 , m1 = 3 , m2 = 5 ; otherEndPoint ( x1 , y1 , m1 , m2 ) ; return 0 ; }
Coordinates of rectangle with given points lie inside | Program to find smallest rectangle to conquer all points ; function to print coordinate of smallest rectangle ; find Xmax and Xmin ; find Ymax and Ymin ; print all four coordinates ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printRect ( int X [ ] , int Y [ ] , int n ) { int Xmax = * max_element ( X , X + n ) ; int Xmin = * min_element ( X , X + n ) ; int Ymax = * max_element ( Y , Y + n ) ; int Ymin = * min_element ( Y , Y + n ) ; cout << " { " << Xmin << " , ▁ " << Ymin << " } " << endl ; cout << " { " << Xmin << " , ▁ " << Ymax << " } " << endl ; cout << " { " << Xmax << " , ▁ " << Ymax << " } " << endl ; cout << " { " << Xmax << " , ▁ " << Ymin << " } " << endl ; } int main ( ) { int X [ ] = { 4 , 3 , 6 , 1 , -1 , 12 } ; int Y [ ] = { 4 , 1 , 10 , 3 , 7 , -1 } ; int n = sizeof ( X ) / sizeof ( X [ 0 ] ) ; printRect ( X , Y , n ) ; return 0 ; }
Check if a line passes through the origin | C ++ program to find if line passing through two coordinates also passes through origin or not ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkOrigin ( int x1 , int y1 , int x2 , int y2 ) { return ( x1 * ( y2 - y1 ) == y1 * ( x2 - x1 ) ) ; } int main ( ) { if ( checkOrigin ( 1 , 28 , 2 , 56 ) == true ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Number of horizontal or vertical line segments to connect 3 points | CPP program to find number of horizontal ( or vertical line segments needed to connect three points . ; Function to check if the third point forms a rectangle with other two points at corners ; Returns true if point k can be used as a joining point to connect using two line segments ; Check for the valid polyline with two segments ; Check whether the X - coordinates or Y - cocordinates are same . ; Iterate over all pairs to check for two line segments ; Otherwise answer is three . ; Driver code
#include <iostream> NEW_LINE using namespace std ; bool isBetween ( int a , int b , int c ) { return min ( a , b ) <= c && c <= max ( a , b ) ; } bool canJoin ( int x [ ] , int y [ ] , int i , int j , int k ) { return ( x [ k ] == x [ i ] x [ k ] == x [ j ] ) && isBetween ( y [ i ] , y [ j ] , y [ k ] ) || ( y [ k ] == y [ i ] y [ k ] == y [ j ] ) && isBetween ( x [ i ] , x [ j ] , x [ k ] ) ; } int countLineSegments ( int x [ ] , int y [ ] ) { if ( ( x [ 0 ] == x [ 1 ] && x [ 1 ] == x [ 2 ] ) || ( y [ 0 ] == y [ 1 ] && y [ 1 ] == y [ 2 ] ) ) return 1 ; else if ( canJoin ( x , y , 0 , 1 , 2 ) || canJoin ( x , y , 0 , 2 , 1 ) || canJoin ( x , y , 1 , 2 , 0 ) ) return 2 ; else return 3 ; } int main ( ) { int x [ 3 ] , y [ 3 ] ; x [ 0 ] = -1 ; y [ 0 ] = -1 ; x [ 1 ] = -1 ; y [ 1 ] = 3 ; x [ 2 ] = 4 ; y [ 2 ] = 3 ; cout << countLineSegments ( x , y ) ; return 0 ; }
Pythagorean Quadruple | C ++ code to detect Pythagorean Quadruples . ; function for checking ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool pythagorean_quadruple ( int a , int b , int c , int d ) { int sum = a * a + b * b + c * c ; if ( d * d == sum ) return true ; else return false ; } int main ( ) { int a = 1 , b = 2 , c = 2 , d = 3 ; if ( pythagorean_quadruple ( a , b , c , d ) ) cout << " Yes " << endl ; else cout << " No " << endl ; }
Program for Volume and Surface area of Frustum of Cone | CPP program to calculate Volume and Surface area of frustum of cone ; Function to calculate Volume of frustum of cone ; Function to calculate Curved Surface area of frustum of cone ; Function to calculate Total Surface area of frustum of cone ; Driver function ; Printing value of volume and surface area
#include <iostream> NEW_LINE using namespace std ; float pi = 3.14159 ; float volume ( float r , float R , float h ) { return ( float ( 1 ) / float ( 3 ) ) * pi * h * ( r * r + R * R + r * R ) ; } float curved_surface_area ( float r , float R , float l ) { return pi * l * ( R + r ) ; } float total_surface_area ( float r , float R , float l , float h ) { return pi * l * ( R + r ) + pi * ( r * r + R * R ) ; } int main ( ) { float small_radius = 3 ; float big_radius = 8 ; float slant_height = 13 ; float height = 12 ; cout << " Volume ▁ Of ▁ Frustum ▁ of ▁ Cone ▁ : ▁ " << volume ( small_radius , big_radius , height ) << endl ; cout << " Curved ▁ Surface ▁ Area ▁ Of ▁ Frustum ▁ of ▁ Cone ▁ : ▁ " << curved_surface_area ( small_radius , big_radius , slant_height ) << endl ; cout << " Total ▁ Surface ▁ Area ▁ Of ▁ Frustum ▁ of ▁ Cone ▁ : ▁ " << total_surface_area ( small_radius , big_radius , slant_height , height ) ; return 0 ; }
Program to find Perimeter / Circumference of Square and Rectangle | CPP program to find Circumference of a square ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Circumference ( int a ) { return 4 * a ; } int main ( ) { int a = 5 ; cout << " Circumference ▁ of " << " ▁ a ▁ square ▁ is ▁ " << Circumference ( a ) ; return 0 ; }
Maximum area of quadrilateral | CPP program to find maximum are of a quadrilateral ; Calculating the semi - perimeter of the given quadrilateral ; Applying Brahmagupta 's formula to get maximum area of quadrilateral ; Driver code
#include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; double maxArea ( double a , double b , double c , double d ) { double semiperimeter = ( a + b + c + d ) / 2 ; return sqrt ( ( semiperimeter - a ) * ( semiperimeter - b ) * ( semiperimeter - c ) * ( semiperimeter - d ) ) ; } int main ( ) { double a = 1 , b = 2 , c = 1 , d = 2 ; cout << maxArea ( a , b , c , d ) ; return 0 ; }
Direction of a Point from a Line Segment | C ++ Program to Determine Direction of Point from line segment ; structure for point in cartesian plane . ; constant integers for directions ; subtracting co - ordinates of point A from B and P , to make A as origin ; Determining cross Product ; return RIGHT if cross product is positive ; return LEFT if cross product is negative ; return ZERO if cross product is zero . ; Driver code ; A . y = 10 ; A ( - 30 , 10 ) ; B . y = - 15 ; B ( 29 , - 15 ) ; P . y = 28 ; P ( 15 , 28 )
#include <iostream> NEW_LINE using namespace std ; struct point { int x , y ; } ; const int RIGHT = 1 , LEFT = -1 , ZERO = 0 ; int directionOfPoint ( point A , point B , point P ) { B . x -= A . x ; B . y -= A . y ; P . x -= A . x ; P . y -= A . y ; int cross_product = B . x * P . y - B . y * P . x ; if ( cross_product > 0 ) return RIGHT ; if ( cross_product < 0 ) return LEFT ; return ZERO ; } int main ( ) { point A , B , P ; A . x = -30 ; B . x = 29 ; P . x = 15 ; int direction = directionOfPoint ( A , B , P ) ; if ( direction == 1 ) cout << " Right ▁ Direction " << endl ; else if ( direction == -1 ) cout << " Left ▁ Direction " << endl ; else cout << " Point ▁ is ▁ on ▁ the ▁ Line " << endl ; return 0 ; }
Find minimum radius such that atleast k point lie inside the circle | C ++ program to find minimum radius such that atleast k point lie inside the circle ; Return minimum distance required so that aleast k point lie inside the circle . ; Finding distance between of each point from origin ; Sorting the distance ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minRadius ( int k , int x [ ] , int y [ ] , int n ) { int dis [ n ] ; for ( int i = 0 ; i < n ; i ++ ) dis [ i ] = x [ i ] * x [ i ] + y [ i ] * y [ i ] ; sort ( dis , dis + n ) ; return dis [ k - 1 ] ; } int main ( ) { int k = 3 ; int x [ ] = { 1 , -1 , 1 } ; int y [ ] = { 1 , -1 , -1 } ; int n = sizeof ( x ) / sizeof ( x [ 0 ] ) ; cout << minRadius ( k , x , y , n ) << endl ; return 0 ; }
Program for Area And Perimeter Of Rectangle | CPP program to find area and perimeter of rectangle ; Utility function ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int areaRectangle ( int a , int b ) { int area = a * b ; return area ; } int perimeterRectangle ( int a , int b ) { int perimeter = 2 * ( a + b ) ; return perimeter ; } int main ( ) { int a = 5 ; int b = 6 ; cout << " Area ▁ = ▁ " << areaRectangle ( a , b ) << endl ; cout << " Perimeter ▁ = ▁ " << perimeterRectangle ( a , b ) ; return 0 ; }
Program for Area Of Square | CPP program to find the area of the square ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int areaSquare ( int side ) { int area = side * side ; return area ; } int main ( ) { int side = 4 ; cout << areaSquare ( side ) ; return 0 ; }
Minimum Perimeter of n blocks | CPP program to find minimum perimeter using n blocks . ; if n is a perfect square ; Number of rows ; perimeter of the rectangular grid ; if there are blocks left ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minPerimeter ( int n ) { int l = sqrt ( n ) ; int sq = l * l ; if ( sq == n ) return l * 4 ; else { long long int row = n / l ; long long int perimeter = 2 * ( l + row ) ; if ( n % l != 0 ) perimeter += 2 ; return perimeter ; } } int main ( ) { int n = 10 ; cout << minPerimeter ( n ) ; return 0 ; }
Find if it 's possible to rotate the page by an angle or not. | C ++ program to find if its possible to rotate page or not ; function to find if it 's possible to rotate page or not ; Calculating distance b / w points ; If distance is not equal ; If the points are in same line ; Driver Code ; Points a , b , and c
#include <bits/stdc++.h> NEW_LINE using namespace std ; void possibleOrNot ( long long a1 , long long a2 , long long b1 , long long b2 , long long c1 , long long c2 ) { long long dis1 = pow ( b1 - a1 , 2 ) + pow ( b2 - a2 , 2 ) ; long long dis2 = pow ( c1 - b1 , 2 ) + pow ( c2 - b2 , 2 ) ; if ( dis1 != dis2 ) cout << " No " ; else if ( b1 == ( ( a1 + c1 ) / 2.0 ) && b2 == ( ( a2 + c2 ) / 2.0 ) ) cout << " No " ; else cout << " Yes " ; } int main ( ) { ios_base :: sync_with_stdio ( false ) ; cin . tie ( NULL ) ; long long a1 = 1 , a2 = 0 , b1 = 2 , b2 = 0 , c1 = 3 , c2 = 0 ; possibleOrNot ( a1 , a2 , b1 , b2 , c1 , c2 ) ; return 0 ; }
Check if two given circles touch or intersect each other | C ++ program to check if two circles touch each other or not . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int circle ( int x1 , int y1 , int x2 , int y2 , int r1 , int r2 ) { int distSq = ( x1 - x2 ) * ( x1 - x2 ) + ( y1 - y2 ) * ( y1 - y2 ) ; int radSumSq = ( r1 + r2 ) * ( r1 + r2 ) ; if ( distSq == radSumSq ) return 1 ; else if ( distSq > radSumSq ) return -1 ; else return 0 ; } int main ( ) { int x1 = -10 , y1 = 8 ; int x2 = 14 , y2 = -24 ; int r1 = 30 , r2 = 10 ; int t = circle ( x1 , y1 , x2 , y2 , r1 , r2 ) ; if ( t == 1 ) cout << " Circle ▁ touch ▁ to " << " ▁ each ▁ other . " ; else if ( t < 0 ) cout << " Circle ▁ not ▁ touch " << " ▁ to ▁ each ▁ other . " ; else cout << " Circle ▁ intersect " << " ▁ to ▁ each ▁ other . " ; return 0 ; }
Count of obtuse angles in a circle with ' k ' equidistant points between 2 given points | C ++ program to count number of obtuse angles for given two points . ; There are two arcs connecting a and b . Let us count points on both arcs . ; Both arcs have same number of points ; Points on smaller arc is answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countObtuseAngles ( int a , int b , int k ) { int c1 = ( b - a ) - 1 ; int c2 = ( k - b ) + ( a - 1 ) ; if ( c1 == c2 ) return 0 ; return min ( c1 , c2 ) ; } int main ( ) { int k = 6 , a = 1 , b = 3 ; cout << countObtuseAngles ( a , b , k ) ; return 0 ; }
Find points at a given distance on a line of given slope | C ++ program to find the points on a line of slope M at distance L ; structure to represent a co - ordinate point ; Function to print pair of points at distance ' l ' and having a slope ' m ' from the source ; m is the slope of line , and the required Point lies distance l away from the source Point ; slope is 0 ; if slope is infinite ; print the first Point ; print the second Point ; driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Point { float x , y ; Point ( ) { x = y = 0 ; } Point ( float a , float b ) { x = a , y = b ; } } ; void printPoints ( Point source , float l , int m ) { Point a , b ; if ( m == 0 ) { a . x = source . x + l ; a . y = source . y ; b . x = source . x - l ; b . y = source . y ; } else if ( m == std :: numeric_limits < float > :: max ( ) ) { a . x = source . x ; a . y = source . y + l ; b . x = source . x ; b . y = source . y - l ; } else { float dx = ( l / sqrt ( 1 + ( m * m ) ) ) ; float dy = m * dx ; a . x = source . x + dx ; a . y = source . y + dy ; b . x = source . x - dx ; b . y = source . y - dy ; } cout << a . x << " , ▁ " << a . y << endl ; cout << b . x << " , ▁ " << b . y << endl ; } int main ( ) { Point p ( 2 , 1 ) , q ( 1 , 0 ) ; printPoints ( p , sqrt ( 2 ) , 1 ) ; cout << endl ; printPoints ( q , 5 , 0 ) ; return 0 ; }
Minimum block jumps to reach destination | C ++ program to find minimum jumps to reach a given destination from a given source ; To represent point in 2D space ; To represent line of ( ax + by + c ) format ; Returns 1 if evaluation is greater > 0 , else returns - 1 ; Returns minimum jumps to reach dest point from start point ; get sign of evaluation from point co - ordinate and line equation ; if both evaluation are of opposite sign , increase jump by 1 ; Driver code to test above methods
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct point { int x , y ; point ( int x , int y ) : x ( x ) , y ( y ) { } } ; struct line { int a , b , c ; line ( int a , int b , int c ) : a ( a ) , b ( b ) , c ( c ) { } line ( ) { } } ; int evalPointOnLine ( point p , line curLine ) { int eval = curLine . a * p . x + curLine . b * p . y + curLine . c ; if ( eval > 0 ) return 1 ; return -1 ; } int minJumpToReachDestination ( point start , point dest , line lines [ ] , int N ) { int jumps = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int signStart = evalPointOnLine ( start , lines [ i ] ) ; int signDest = evalPointOnLine ( dest , lines [ i ] ) ; if ( signStart * signDest < 0 ) jumps ++ ; } return jumps ; } int main ( ) { point start ( 1 , 1 ) ; point dest ( -2 , -1 ) ; line lines [ 3 ] ; lines [ 0 ] = line ( 1 , 0 , 0 ) ; lines [ 1 ] = line ( 0 , 1 , 0 ) ; lines [ 2 ] = line ( 1 , 1 , -2 ) ; cout << minJumpToReachDestination ( start , dest , lines , 3 ) ; return 0 ; }
Minimum distance to travel to cover all intervals | C ++ program to find minimum distance to travel to cover all intervals ; structure to store an interval ; Method returns minimum distance to travel to cover all intervals ; looping over all intervals to get right most start and left most end ; if rightmost start > leftmost end then all intervals are not aligned and it is not possible to cover all of them ; if x is in between rightmoststart and leftmostend then no need to travel any distance ; choose minimum according to current position x ; Driver code to test above methods
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Interval { int start , end ; Interval ( int start , int end ) : start ( start ) , end ( end ) { } } ; int minDistanceToCoverIntervals ( Interval intervals [ ] , int N , int x ) { int rightMostStart = INT_MIN ; int leftMostEnd = INT_MAX ; for ( int i = 0 ; i < N ; i ++ ) { if ( rightMostStart < intervals [ i ] . start ) rightMostStart = intervals [ i ] . start ; if ( leftMostEnd > intervals [ i ] . end ) leftMostEnd = intervals [ i ] . end ; } int res ; if ( rightMostStart > leftMostEnd ) res = -1 ; else if ( rightMostStart <= x && x <= leftMostEnd ) res = 0 ; else res = ( x < rightMostStart ) ? ( rightMostStart - x ) : ( x - leftMostEnd ) ; return res ; } int main ( ) { int x = 3 ; Interval intervals [ ] = { { 0 , 7 } , { 2 , 14 } , { 4 , 6 } } ; int N = sizeof ( intervals ) / sizeof ( intervals [ 0 ] ) ; int res = minDistanceToCoverIntervals ( intervals , N , x ) ; if ( res == -1 ) cout << " Not ▁ Possible ▁ to ▁ cover ▁ all ▁ intervals STRNEWLINE " ; else cout << res << endl ; }
Count of acute , obtuse and right triangles with given sides | C ++ program to count of acute , obtuse and right triangles in an array ; Find the number of acute , right , obtuse triangle that can be formed from given array . ; Finding the square of each element of array . ; Sort the sides of array and their squares . ; x for acute triangles y for right triangles z for obtuse triangles ; Finding the farthest point p where a ^ 2 + b ^ 2 >= c ^ 2. ; Finding the farthest point q where a + b > c . ; If point p make right triangle . ; All triangle between j and p are acute triangles . So add p - j - 1 in x . ; Increment y by 1. ; All triangle between q and p are acute triangles . So add q - p in z . ; If no right triangle ; All triangle between j and p are acute triangles . So add p - j in x . ; All triangle between q and p are acute triangles . So add q - p in z . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findTriangle ( int a [ ] , int n ) { int b [ n + 2 ] ; for ( int i = 0 ; i < n ; i ++ ) b [ i ] = a [ i ] * a [ i ] ; sort ( a , a + n ) ; sort ( b , b + n ) ; int x = 0 , y = 0 , z = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int p = i + 1 ; int q = i + 1 ; for ( int j = i + 1 ; j < n ; j ++ ) { while ( p < n - 1 && b [ i ] + b [ j ] >= b [ p + 1 ] ) p ++ ; q = max ( q , p ) ; while ( q < n - 1 && a [ i ] + a [ j ] > a [ q + 1 ] ) q ++ ; if ( b [ i ] + b [ j ] == b [ p ] ) { x += max ( p - j - 1 , 0 ) ; y ++ ; z += q - p ; } else { x += max ( p - j , 0 ) ; z += q - p ; } } } cout << " Acute ▁ Triangle : ▁ " << x << endl ; cout << " Right ▁ Triangle : ▁ " << y << endl ; cout << " Obtuse ▁ Triangle : ▁ " << z << endl ; } int main ( ) { int arr [ ] = { 2 , 3 , 9 , 10 , 12 , 15 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findTriangle ( arr , n ) ; return 0 ; }
Check whether a point exists in circle sector or not . | C ++ program to check if a point lies inside a circle sector . ; calculate endAngle ; Calculate polar co - ordinates ; Check whether polarradius is less then radius of circle or not and Angle is between startAngle and endAngle or not ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void checkPoint ( int radius , int x , int y , float percent , float startAngle ) { float endAngle = 360 / percent + startAngle ; float polarradius = sqrt ( x * x + y * y ) ; float Angle = atan ( y / x ) ; if ( Angle >= startAngle && Angle <= endAngle && polarradius < radius ) printf ( " Point ▁ ( % d , ▁ % d ) ▁ exist ▁ in ▁ the ▁ circle ▁ sector STRNEWLINE " , x , y ) ; else printf ( " Point ▁ ( % d , ▁ % d ) ▁ does ▁ not ▁ exist ▁ in ▁ the ▁ circle ▁ sector STRNEWLINE " , x , y ) ; } int main ( ) { int radius = 8 , x = 3 , y = 4 ; float percent = 12 , startAngle = 0 ; checkPoint ( radius , x , y , percent , startAngle ) ; return 0 ; }
Program to find the Type of Triangle from the given Coordinates | C / C ++ program to classify a given triangle ; Utility method to return square of x ; Utility method to sort a , b , c ; after this method a <= b <= c ; Utility method to return Square of distance between two points ; Method to classify side ; if all sides are equal ; if any two sides are equal ; Method to classify angle ; If addition of sum of square of two side is less , then acute ; by pythagoras theorem ; Method to classify the triangle by sides and angles ; Find squares of distances between points ; Sort all squares of distances in increasing order ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct point { int x , y ; point ( ) { } point ( int x , int y ) : x ( x ) , y ( y ) { } } ; int square ( int x ) { return x * x ; } void order ( int & a , int & b , int & c ) { int copy [ 3 ] ; copy [ 0 ] = a ; copy [ 1 ] = b ; copy [ 2 ] = c ; sort ( copy , copy + 3 ) ; a = copy [ 0 ] ; b = copy [ 1 ] ; c = copy [ 2 ] ; } int euclidDistSquare ( point p1 , point p2 ) { return square ( p1 . x - p2 . x ) + square ( p1 . y - p2 . y ) ; } string getSideClassification ( int a , int b , int c ) { if ( a == b && b == c ) return " Equilateral " ; else if ( a == b b == c ) return " Isosceles " ; else return " Scalene " ; } string getAngleClassification ( int a , int b , int c ) { if ( a + b > c ) return " acute " ; else if ( a + b == c ) return " right " ; else return " obtuse " ; } void classifyTriangle ( point p1 , point p2 , point p3 ) { int a = euclidDistSquare ( p1 , p2 ) ; int b = euclidDistSquare ( p1 , p3 ) ; int c = euclidDistSquare ( p2 , p3 ) ; order ( a , b , c ) ; cout << " Triangle ▁ is ▁ " + getAngleClassification ( a , b , c ) + " ▁ and ▁ " + getSideClassification ( a , b , c ) << endl ; } int main ( ) { point p1 , p2 , p3 ; p1 = point ( 3 , 0 ) ; p2 = point ( 0 , 4 ) ; p3 = point ( 4 , 7 ) ; classifyTriangle ( p1 , p2 , p3 ) ; p1 = point ( 0 , 0 ) ; p2 = point ( 1 , 1 ) ; p3 = point ( 1 , 2 ) ; classifyTriangle ( p1 , p2 , p3 ) ; return 0 ; }
Area of a polygon with given n ordered vertices | C ++ program to evaluate area of a polygon using shoelace formula ; ( X [ i ] , Y [ i ] ) are coordinates of i 'th point. ; Initialize area ; Calculate value of shoelace formula ; j = i ; j is previous vertex to i ; Return absolute value ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; double polygonArea ( double X [ ] , double Y [ ] , int n ) { double area = 0.0 ; int j = n - 1 ; for ( int i = 0 ; i < n ; i ++ ) { area += ( X [ j ] + X [ i ] ) * ( Y [ j ] - Y [ i ] ) ; } return abs ( area / 2.0 ) ; } int main ( ) { double X [ ] = { 0 , 2 , 4 } ; double Y [ ] = { 1 , 3 , 7 } ; int n = sizeof ( X ) / sizeof ( X [ 0 ] ) ; cout << polygonArea ( X , Y , n ) ; }
Difference of count of distinct elements present to left and right for each array element | C ++ program for the above approach ; Function to find the difference of count of distince elements to the left and right for each array elements ; Stores distinct array element in the left and right ; Traverse the array ; Insert all element to the left in the set S1 ; Insert all element to the right in the set S2 ; Print the difference ; Driver Code
#include " bits / stdc + + . h " NEW_LINE using namespace std ; void findDifferenceArray ( int arr [ ] , int N ) { set < int > S1 ; set < int > S2 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { S1 . insert ( arr [ j ] ) ; } for ( int j = i + 1 ; j < N ; j ++ ) { S2 . insert ( arr [ j ] ) ; } cout << abs ( ( int ) S1 . size ( ) - ( int ) S2 . size ( ) ) << ' ▁ ' ; S1 . clear ( ) ; S2 . clear ( ) ; } } int main ( ) { int arr [ ] = { 7 , 7 , 3 , 2 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findDifferenceArray ( arr , N ) ; return 0 ; }
Maximum subarray sum with same first and last element formed by removing elements | C ++ program for the above approach ; Function to find the maximum sum of sub - array ; Initialize the variables ; Traverse over the range ; Add the current value to the variable currsum for prefix sum ; Calculate the result ; Return the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumSubarraySum ( vector < int > & arr ) { int N = arr . size ( ) ; unordered_map < int , int > memo ; int res = INT_MIN ; int currsum = 0 , currval = 0 ; for ( int i = 0 ; i < N ; ++ i ) { currval = arr [ i ] ; currsum = currsum + currval ; if ( memo . count ( currval ) != 0 ) { if ( currval > 0 ) res = max ( res , currsum - memo [ currval ] + currval ) ; else res = max ( res , currsum - memo [ currval ] + 2 * currval ) ; } else memo [ currval ] = currsum ; if ( currval < 0 ) currsum = currsum - currval ; } return res ; } int main ( ) { vector < int > arr = { -1 , -3 , 4 , 0 , -1 , -2 } ; cout << maximumSubarraySum ( arr ) ; return 0 ; }
Find Nth root of a number using Bisection method | C ++ program for above approach ; Function that returns the value of the function at a given value of x ; calculating the value of the differential of the function ; The function that returns the root of given number ; Defining range on which answer can be found ; finding mid value ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; double f ( double x , int p , double num ) { return pow ( x , p ) - num ; } double f_prime ( double x , int p ) { return p * pow ( x , p - 1 ) ; } double root ( double num , int p ) { double left = - num ; double right = num ; double x ; while ( true ) { x = ( left + right ) / 2.0 ; double value = f ( x , p , num ) ; double prime = f_prime ( x , p ) ; if ( value * prime <= 0 ) left = x ; else right = x ; if ( value < 0.000001 && value >= 0 ) { return x ; } } } int main ( ) { double P = 1234321 ; int N = 2 ; double ans = root ( P , N ) ; cout << ans ; }
Count of permutations of an Array having maximum MEXs sum of prefix arrays | C ++ program for the above approach ; To calculate the factorial ; To return the number of permutations of an array with maximum MEXs sum of prefix array ; Map to store the frequency of each element ; Running a loop from i = 0 to i < n ; If continuity breaks , then break the loop ; Considering choices available to be filled at this position , i . e . mp [ i ] ; Decrement the count of remaining right elements ; Adding all permutations of the elements present to the right of the point where continuity breaks . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int factorial ( int n ) { int res = 1 , i ; for ( i = 2 ; i <= n ; i ++ ) { res *= i ; } return res ; } int countPermutations ( int ar [ ] , int n ) { unordered_map < int , int > mp ; int ans = 1 , cnt = n ; for ( int i = 0 ; i < n ; i ++ ) { mp [ ar [ i ] ] ++ ; } for ( int i = 0 ; i < n ; i ++ ) { if ( mp [ i ] == 0 ) { break ; } ans = ( ans * mp [ i ] ) ; cnt -- ; } ans = ans * factorial ( cnt ) ; return ans ; } int main ( ) { int arr [ ] = { 1 , 0 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPermutations ( arr , N ) ; }
Convert 0 to N by adding 1 or multiplying by 2 in minimum steps | C ++ program for above approach ; Function to count number of set bits in N ; Stores the count of set bits ; If N is odd , then it a set bit ; Return the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumAdditionOperation ( unsigned long long int N ) { int count = 0 ; while ( N ) { if ( N & 1 == 1 ) { count ++ ; } N = N >> 1 ; } return count ; } int main ( ) { int N = 6 ; cout << minimumAdditionOperation ( N ) ; return 0 ; }
Count of unordered pairs of semi | C ++ program of the above approach ; Stores the count of distinct prime number in factor of current number ; Function to return the vector of semi prime numbers in range [ 1 , N ] ; Count of distinct prime number in the factor of current number using Sieve of Eratosthenes ; If current number is prime ; Stores the semi prime numbers ; If p has 2 distinct prime factors ; Return vector ; Function to count unordered pairs of semi prime numbers with prime sum ; Stores the final count ; Loop to iterate over al the l unordered pairs ; If sum of current semi prime numbers is a prime number ; Return answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int maxn = 100000 ; int prime [ maxn ] = { } ; vector < int > semiPrimes ( int N ) { for ( int p = 2 ; p <= maxn ; p ++ ) { if ( prime [ p ] == 0 ) { for ( int i = 2 * p ; i <= maxn ; i += p ) prime [ i ] ++ ; } } vector < int > sPrimes ; for ( int p = 2 ; p <= N ; p ++ ) if ( prime [ p ] == 2 ) sPrimes . push_back ( p ) ; return sPrimes ; } int countPairs ( vector < int > semiPrimes ) { int cnt = 0 ; for ( int i = 0 ; i < semiPrimes . size ( ) ; i ++ ) { for ( int j = i + 1 ; j < semiPrimes . size ( ) ; j ++ ) { if ( prime [ semiPrimes [ i ] + semiPrimes [ j ] ] == 0 ) { cnt ++ ; } } } return cnt ; } int main ( ) { int N = 100 ; cout << countPairs ( semiPrimes ( N ) ) ; return 0 ; }
Minimum divide by 2 operations required to make GCD odd for given Array | C ++ program for the above approach ; Function to find the minimum number of operations to make the GCD of the array odd ; Stores the minimum operations required ; Stores the powers of two for the current array element ; Dividing by 2 ; Increment the count ; Update the minimum operation required ; Return the result required ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumOperations ( int arr [ ] , int N ) { int mini = INT_MAX ; for ( int i = 0 ; i < N ; i ++ ) { int count = 0 ; while ( arr [ i ] % 2 == 0 ) { arr [ i ] = arr [ i ] / 2 ; count ++ ; } if ( mini > count ) { mini = count ; } } return mini ; } int main ( ) { int arr [ ] = { 4 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minimumOperations ( arr , N ) ; return 0 ; }
Minimum size of the array with MEX as A and XOR of the array elements as B | C ++ program for the above approach ; Function to find the minimum size of array with given MEX and XOR ; Find the XOR of values from 0 to A - 1 ; If A is a multiple of 4 ; If A % 4 gives remainder 1 ; If A % 4 gives remainder 2 ; Initializing array size by A ; If XOR of all values of array is equal to B ; If the required integer to be added is equal to A ; Else any integer can be added ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumSizeArr ( int A , int B ) { int currXor = 0 ; int reminder = ( A - 1 ) % 4 ; if ( reminder == 0 ) currXor = A - 1 ; else if ( reminder == 1 ) currXor = 1 ; else if ( reminder == 2 ) currXor = A ; int minSize = A ; if ( currXor == B ) return minSize ; else if ( currXor ^ B == A ) return minSize + 2 ; else return minSize + 1 ; } int main ( ) { int A = 1 ; int B = 999 ; cout << minimumSizeArr ( A , B ) ; return 0 ; }
Count of triplets till N whose product is at most N | C ++ program for the above approach ; Function to find number of triplets ( A , B , C ) having A * B * C <= N ; Stores the count of triplets ; Iterate a loop fixing the value of A ; Iterate a loop fixing the value of A ; Find the total count of triplets and add it to cnt ; Return the total triplets formed ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countTriplets ( int N ) { int cnt = 0 ; for ( int A = 1 ; A <= N ; ++ A ) { for ( int B = 1 ; B <= N / A ; ++ B ) { cnt += N / ( A * B ) ; } } return cnt ; } int main ( ) { int N = 2 ; cout << countTriplets ( N ) ; return 0 ; }
Largest integer upto N having greatest prime factor greater than its square root | C ++ program for the above approach ; Stores the Greatest Prime Factor ; Modified Sieve to find the Greatest Prime Factor of all integers in the range [ 1 , maxn ] ; Initialize the array with 0 ; Iterate through all values of i ; If i is not a prime number ; Update the multiples of i ; Function to find integer in the range [ 1 , N ] such that its Greatest Prime factor is greater than its square root ; Iterate through all values of i in the range [ N , 1 ] ; If greatest prime factor of i is greater than its sqare root ; Return answer ; If no valid integer exist ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int maxn = 100001 ; int gpf [ maxn ] ; void modifiedSieve ( ) { memset ( gpf , 0 , sizeof ( gpf ) ) ; gpf [ 0 ] = 0 ; gpf [ 1 ] = 1 ; for ( int i = 2 ; i < maxn ; i ++ ) { if ( gpf [ i ] > 0 ) continue ; for ( int j = i ; j < maxn ; j += i ) { gpf [ j ] = max ( i , gpf [ j ] ) ; } } } int greatestValidInt ( int N ) { modifiedSieve ( ) ; for ( int i = N ; i > 0 ; i -- ) { if ( gpf [ i ] > sqrt ( i ) ) { return i ; } } return -1 ; } int main ( ) { int N = 25 ; cout << greatestValidInt ( N ) ; return 0 ; }
Count of pass required to visit same index again by moving arr [ i ] to index arr [ i ] | C ++ program for the above approach ; Function to find the number of moves required to visit the same index again for every array element ; Make given array 0 index based ; Stores the number of moves ; Store index value ; Update the value of cnt ; Make a pass ; Print the value of cnt ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void numberOfPasses ( vector < int > arr , int N ) { for ( int i = 0 ; i < N ; ++ i ) { -- arr [ i ] ; } for ( int i = 0 ; i < N ; ++ i ) { int cnt = 0 ; int k = i ; do { ++ cnt ; k = arr [ k ] ; } while ( k != i ) ; cout << cnt << " ▁ " ; } } int main ( ) { vector < int > arr { 4 , 6 , 2 , 1 , 5 , 3 } ; int N = arr . size ( ) ; numberOfPasses ( arr , N ) ; return 0 ; }
Find subfactorial of a number | / C ++ program for the above approach ; Function to find the subfactorial of the number ; Initialize variables ; Iterating over range N ; Fact variable store factorial of the i ; If count is even ; Increase the value of count by 1 ; Driver Code
#include <iostream> NEW_LINE using namespace std ; double subfactorial ( int N ) { double res = 0 , fact = 1 ; int count = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { fact = fact * i ; if ( count % 2 == 0 ) res = res - ( 1 / fact ) ; else res = res + ( 1 / fact ) ; count ++ ; } return fact * ( 1 + res ) ; } int main ( ) { int N = 4 ; cout << subfactorial ( N ) ; return 0 ; }
Minimize operations to delete all elements of permutation A by removing a subsequence having order as array B | C ++ program for the above approach ; Function to find the minimum number of operations to delete all elements of permutation A in order described by B ; Stores the count of operations ; Stores the index of current integer in B to be deleted ; Loop to iterate over all values of B ; Stores the current index in A ; Iterate over all values A ; If current integer of B and A equal , increment the index of the current integer of B ; As the permutation A has been traversed completelly , increment the count of operations by 1 ; Return Answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperations ( int A [ ] , int B [ ] , int N ) { int cnt = 0 ; int i = 0 ; while ( i < N ) { int j = 0 ; while ( j < N && i < N ) { if ( B [ i ] == A [ j ] ) { i ++ ; } j ++ ; } cnt ++ ; } return cnt ; } int main ( ) { int A [ ] = { 2 , 4 , 6 , 1 , 5 , 3 } ; int B [ ] = { 6 , 5 , 4 , 2 , 3 , 1 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << minOperations ( A , B , N ) ; return 0 ; }
Count of pair of integers ( x , y ) such that difference between square of x and y is a perfect square | C ++ program for the above approach ; Function to find number of pairs ( x , y ) such that x ^ 2 - y is a square number ; Stores the count of total pairs ; Iterate q value 1 to sqrt ( N ) ; Maximum possible value of p is min ( 2 * N - q , N / q ) ; P must be greater than or equal to q ; Total number of pairs are ; Adding all valid pairs to res ; Return total no of pairs ( x , y ) ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int N ) { int res = 0 ; for ( int q = 1 ; q * q <= N ; q ++ ) { int maxP = min ( 2 * N - q , N / q ) ; if ( maxP < q ) continue ; int cnt = maxP - q + 1 ; res += ( cnt / 2 + ( cnt & 1 ) ) ; } return res ; } int main ( ) { int N = 3 ; cout << countPairs ( N ) ; return 0 ; }
Maximum size of subset such that product of all subset elements is a factor of N | C ++ program for the above approach ; Function to find the maximum size of the subset such that the product of subset elements is a factor of N ; Base Case ; Stores maximum size of valid subset ; Traverse the given array ; If N % arr [ i ] = 0 , include arr [ i ] in a subset and recursively call for the remaining array integers ; Return Answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximizeSubset ( int N , int arr [ ] , int M , int x = 0 ) { if ( x == M ) { return 0 ; } int ans = 0 ; for ( int i = x ; i < M ; i ++ ) { if ( N % arr [ i ] == 0 ) { ans = max ( ans , maximizeSubset ( N / arr [ i ] , arr , M , x + 1 ) + 1 ) ; } } return ans ; } int main ( ) { int N = 64 ; int arr [ ] = { 1 , 2 , 4 , 8 , 16 , 32 } ; int M = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maximizeSubset ( N , arr , M ) ; return 0 ; }
Count of distinct sums formed by N numbers taken form range [ L , R ] | C ++ program for the above approach ; Function to find total number of different sums of N numbers in the range [ L , R ] ; To store minimum possible sum with N numbers with all as L ; To store maximum possible sum with N numbers with all as R ; All other numbers in between maxSum and minSum can also be formed so numbers in this range is the final answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countDistinctSums ( int N , int L , int R ) { int minSum = L * N ; int maxSum = R * N ; return maxSum - minSum + 1 ; } int main ( ) { int N = 2 , L = 1 , R = 3 ; cout << countDistinctSums ( N , L , R ) ; return 0 ; }
Make the Array sum 0 by using either ceil or floor on each element | C ++ program for the above approach ; Function to modify the array element such that the sum is close to 0 ; Stores the modified elements ; Stores the sum of array element ; Stores minimum size of the array ; Traverse the array and find the sum ; If sum is positive ; Find the minimum number of elements that must be changed ; Iterate until M elements are modified or the array end ; Update the current array elements to its floor ; Print the resultant array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void setSumtoZero ( double arr [ ] , int N ) { int A [ N ] ; int sum = 0 ; int m = INT_MIN ; for ( int i = 0 ; i < N ; i ++ ) { sum += ceil ( arr [ i ] ) ; A [ i ] = ceil ( arr [ i ] ) ; } if ( sum > 0 ) { m = min ( sum , N ) ; for ( int i = 0 ; i < N && m > 0 ; i ++ ) { A [ i ] = floor ( arr [ i ] ) ; if ( A [ i ] != floor ( arr [ i ] ) ) m -- ; } } for ( int i = 0 ; i < N ; i ++ ) { cout << A [ i ] << " ▁ " ; } } int main ( ) { double arr [ ] = { -2 , -2 , 4.5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; setSumtoZero ( arr , N ) ; return 0 ; }
Find first undeleted integer from K to N in given unconnected Graph after performing Q queries | C ++ program for the above approach ; Function to perform th Get operation of disjoint set union ; Function to perform the union operation of dijoint set union ; Update the graph [ a ] as b ; Function to perform given queries on set of vertices initially not connected ; Stores the vertices ; Mark every vertices rightmost vertex as i ; Traverse the queries array ; Check if it is first type of the givan query ; Get the parent of a ; Print the answer for the second query ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Get ( vector < int > & graph , int a ) { return graph [ a ] = ( graph [ a ] == a ? a : Get ( graph , graph [ a ] ) ) ; } void Union ( vector < int > & graph , int a , int b ) { a = Get ( graph , a ) ; b = Get ( graph , b ) ; graph [ a ] = b ; } void Queries ( vector < pair < int , int > > & queries , int N , int M ) { vector < int > graph ( N + 2 ) ; for ( int i = 1 ; i <= N + 1 ; i ++ ) { graph [ i ] = i ; } for ( auto query : queries ) { if ( query . first == 1 ) { Union ( graph , query . second , query . second + 1 ) ; } else { int a = Get ( graph , query . second ) ; if ( a == N + 1 ) cout << -1 << " ▁ " ; else cout << graph [ a ] << " ▁ " ; } } } int main ( ) { int N = 5 ; vector < pair < int , int > > queries { { 2 , 1 } , { 1 , 1 } , { 2 , 1 } , { 2 , 3 } } ; int Q = queries . size ( ) ; Queries ( queries , N , Q ) ; return 0 ; }
Finding the Nth term in a sequence formed by removing digit K from natural numbers | C ++ implementation for the above approach ; Denotes the digit place ; Method to convert any number to binary equivalent ; denotes the current digits place ; If current digit is >= K increment its value by 1 ; Else add the digit as it is ; Move to the next digit ; Driver code
#include <iostream> NEW_LINE using namespace std ; long long convertToBase9 ( long long n ) { long long ans = 0 ; long long a = 1 ; while ( n > 0 ) { ans += ( a * ( n % 9 ) ) ; a *= 10 ; n /= 9 ; } return ans ; } long long getNthnumber ( long long base9 , long long K ) { long long ans = 0 ; long long a = 1 ; while ( base9 > 0 ) { int cur = base9 % 10 ; if ( cur >= K ) { ans += a * ( cur + 1 ) ; } else { ans += a * cur ; } base9 /= 10 ; a *= 10 ; } return ans ; } int main ( ) { long long N = 10 , K = 1 ; long long base9 = convertToBase9 ( N ) ; cout << getNthnumber ( base9 , K ) ; return 0 ; }
Check if given array can be rearranged such that mean is equal to median | C ++ program for the above approach ; Function to return true or false if size of array is odd ; To prevent overflow ; If element is greater than mid , then it can only be present in right subarray ; If element is smaller than mid , then it can only be present in left subarray ; Else the element is present at the middle then return 1 ; when element is not present in array then return 0 ; Function to return true or false if size of array is even ; Calculating Candidate Median ; If Candidate Median if greater than Mean then decrement j ; If Candidate Median if less than Mean then increment i ; If Candidate Median if equal to Mean then return 1 ; when No candidate found for mean ; Function to return true if Mean can be equal to any candidate median otherwise return false ; Calculating Mean ; If N is Odd ; If N is even ; Driver Code
#include <iostream> NEW_LINE using namespace std ; bool binarySearch ( float arr [ ] , int size , float key ) { int low = 0 , high = size - 1 , mid ; while ( low <= high ) { mid = low + ( high - low ) / 2 ; if ( key > arr [ mid ] ) low = mid + 1 ; else if ( key < arr [ mid ] ) high = mid - 1 ; else return 1 ; } return 0 ; } bool twoPointers ( float arr [ ] , int N , float mean ) { int i = 0 , j = N - 1 ; while ( i < j ) { float temp = ( arr [ i ] + arr [ j ] ) / 2 ; if ( temp > mean ) j -- ; else if ( temp < mean ) i ++ ; else return 1 ; } return 0 ; } bool checkArray ( float arr [ ] , int N ) { float sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) sum += arr [ i ] ; float mean = sum / N ; if ( N & 1 ) return binarySearch ( arr , N , mean ) ; else return twoPointers ( arr , N , mean ) ; } int main ( ) { float arr [ ] = { 1.0 , 3.0 , 6.0 , 9.0 , 12.0 , 32.0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( checkArray ( arr , N ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Count of distinct integers belonging to first N terms of at least one of given GPs | C ++ program for the above approach ; Function to find the count of distinct integers that belong to the first N terms of at least one of them is GP ; Stores the integers that occur in GPs in a set data - structure ; Stores the current integer of the first GP ; Iterate first N terms of first GP ; Insert the ith term of GP in S ; Stores the current integer of the second GP ; Iterate first N terms of second GP ; Return Answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int UniqueGeometricTerms ( int N , int a1 , int r1 , int a2 , int r2 ) { set < int > S ; long long p1 = a1 ; for ( int i = 0 ; i < N ; i ++ ) { S . insert ( p1 ) ; p1 = ( long long ) ( p1 * r1 ) ; } long long p2 = a2 ; for ( int i = 0 ; i < N ; i ++ ) { S . insert ( p2 ) ; p2 = ( long long ) ( p2 * r2 ) ; } return S . size ( ) ; } int main ( ) { int N = 5 ; int a1 = 3 , r1 = 2 , a2 = 2 , r2 = 3 ; cout << UniqueGeometricTerms ( N , a1 , r1 , a2 , r2 ) ; return 0 ; }
Minimize operations to make all array elements | C ++ program for the above approach ; Function to find minimum the number of operations required to make all the array elements to - 1 ; Stores the array elements with their corresponding indices ; Push the array element and it 's index ; Sort the elements according to it 's first value ; Stores the minimum number of operations required ; Traverse until vp is not empty ; Stores the first value of vp ; Stores the second value of vp ; Update the minCnt ; Pop the back element from the vp until the first value is same as val and difference between indices is less than K ; Return the minCnt ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperations ( int arr [ ] , int N , int K ) { vector < pair < int , int > > vp ; for ( int i = 0 ; i < N ; i ++ ) { vp . push_back ( { arr [ i ] , i } ) ; } sort ( vp . begin ( ) , vp . end ( ) ) ; int minCnt = 0 ; while ( ! vp . empty ( ) ) { int val , ind ; val = vp . back ( ) . first ; ind = vp . back ( ) . second ; minCnt ++ ; while ( ! vp . empty ( ) && vp . back ( ) . first == val && ind - vp . back ( ) . second + 1 <= K ) vp . pop_back ( ) ; } return minCnt ; } int main ( ) { int arr [ ] = { 18 , 11 , 18 , 11 , 18 } ; int K = 3 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minOperations ( arr , N , K ) ; return 0 ; }
Find array sum after incrementing by K adjacent elements of every positive element M times | C ++ program for the above approach ; Function to find the nearest non - zero element in the left direction ; Stores the index of the first element greater than 0 from the right side ; Traverse the array in the range [ 1 , N ] ; Check arr [ i ] is greater than 0 ; Update the value of L ; Traverse the array from the left side ; Check arr [ i ] is greater than 0 ; Update the value of L ; Update the value of steps [ i ] ; Function to find the nearest non - zero element in the right direction ; Stores the index of the first element greater than 0 from the left side ; Traverse the array from the left side ; Check arr [ i ] is greater than 0 ; Update the value of R ; Traverse the array from the right side ; Check arr [ i ] is greater than 0 ; Update the value of R ; Update the value of steps [ i ] ; Function to find the sum of the array after the given operation M times ; Stores the distance of the nearest non zero element . ; Stores sum of the initial array arr [ ] ; Traverse the array from the left side ; Update the value of sum ; Print the total sum of the array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void nearestLeft ( int arr [ ] , int N , vector < int > & steps ) { int L = - N ; for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( arr [ i ] > 0 ) { L = - ( N - i ) ; break ; } } for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] > 0 ) { L = i ; } steps [ i ] = i - L ; } } void nearestRight ( int arr [ ] , int N , vector < int > & steps ) { int R = 2 * N ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] > 0 ) { R = N + i ; break ; } } for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( arr [ i ] > 0 ) { R = i ; } steps [ i ] = min ( steps [ i ] , R - i ) ; } } int findSum ( int arr [ ] , int N , int M , int K ) { vector < int > steps ( N ) ; int sum = accumulate ( arr , arr + N , 0 ) ; if ( sum == 0 ) { return 0 ; } nearestLeft ( arr , N , steps ) ; nearestRight ( arr , N , steps ) ; for ( int i = 0 ; i < N ; i ++ ) sum += 2 * K * max ( 0 , M - steps [ i ] ) ; return sum ; } int main ( ) { int arr [ ] = { 0 , 1 , 0 , 1 , 0 , 0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int M = 2 ; int K = 1 ; cout << findSum ( arr , N , M , K ) ; return 0 ; }
Smallest vertex in the connected components of all the vertices in given undirect graph | C ++ program for the above approach ; Stores the parent and size of the set of the ith element ; Function to initialize the ith set ; Function to find set of ith vertex ; Base Case ; Recursive call to find set ; Function to unite the set that includes a and the set that includes b ; If a and b are not from same set ; Function to find the smallest vertex in the connected component of the ith vertex for all i in range [ 1 , N ] ; Loop to initialize the ith set ; Loop to unite all vertices connected by edges into the same set ; Stores the minimum vertex value for ith set ; Loop to iterate over all vertices ; If current vertex does not exist in minVal initialize it with i ; Update the minimum value of the set having the ith vertex ; Loop to print required answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int maxn = 100 ; int parent [ maxn ] , Size [ maxn ] ; void make_set ( int v ) { parent [ v ] = v ; Size [ v ] = 1 ; } int find_set ( int v ) { if ( v == parent [ v ] ) { return v ; } return parent [ v ] = find_set ( parent [ v ] ) ; } void union_sets ( int a , int b ) { a = find_set ( a ) ; b = find_set ( b ) ; if ( a != b ) { if ( Size [ a ] < Size [ b ] ) swap ( a , b ) ; parent [ b ] = a ; Size [ a ] += Size [ b ] ; } } void findMinVertex ( int N , vector < pair < int , int > > edges ) { for ( int i = 1 ; i <= N ; i ++ ) { make_set ( i ) ; } for ( int i = 0 ; i < edges . size ( ) ; i ++ ) { union_sets ( edges [ i ] . first , edges [ i ] . second ) ; } unordered_map < int , int > minVal ; for ( int i = 1 ; i <= N ; i ++ ) { if ( minVal [ find_set ( i ) ] == 0 ) { minVal [ find_set ( i ) ] = i ; } else { minVal [ find_set ( i ) ] = min ( minVal [ find_set ( i ) ] , i ) ; } } for ( int i = 1 ; i <= N ; i ++ ) { cout << minVal [ find_set ( i ) ] << " ▁ " ; } } int main ( ) { int N = 6 ; vector < pair < int , int > > edges = { { 1 , 3 } , { 2 , 4 } } ; findMinVertex ( N , edges ) ; return 0 ; }
Count of pairs in given range having their ratio equal to ratio of product of their digits | C ++ program for the above approach ; Function to find the product of digits of the given number ; Function to find the count of pairs ( a , b ) such that a : b = ( product ofdigits of a ) : ( product of digits of b ) ; Stores the count of the valid pairs ; Loop to iterate over all unordered pairs ( a , b ) ; Stores the product of digits of a ; Stores the product of digits of b ; If x != 0 and y != 0 and a : b is equivalent to x : y ; Increment valid pair count ; Return Answer ; Driver code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getProduct ( int n ) { int product = 1 ; while ( n != 0 ) { product = product * ( n % 10 ) ; n = n / 10 ; } return product ; } int countPairs ( int L , int R ) { int cntPair = 0 ; for ( int a = L ; a <= R ; a ++ ) { for ( int b = a + 1 ; b <= R ; b ++ ) { int x = getProduct ( a ) ; int y = getProduct ( b ) ; if ( x && y && ( a * y ) == ( b * x ) ) { cntPair ++ ; } } } return cntPair ; } int main ( ) { int L = 1 ; int R = 100 ; cout << countPairs ( 1 , 100 ) ; return 0 ; }
Find numbers in range [ L , R ] that are coprime with given Array elements | C ++ program for the above approach ; Function to find all the elements in the range [ L , R ] which are co prime with all array elements ; Store all the divisors of array element in S ; Find the divisors ; Stores all possible required number satisfying the given criteria ; Insert all element [ L , R ] ; Traverse the set ; Remove the multiples of ele ; Print the resultant numbers ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void elementsCoprimeWithArr ( int A [ ] , int N , int L , int R ) { unordered_set < int > S ; for ( int i = 0 ; i < N ; i ++ ) { int curr_ele = A [ i ] ; for ( int j = 1 ; j <= sqrt ( curr_ele ) + 1 ; j ++ ) { if ( curr_ele % j == 0 ) { S . insert ( j ) ; S . insert ( curr_ele / j ) ; } } } unordered_set < int > store ; for ( int i = L ; i <= R ; i ++ ) store . insert ( i ) ; S . erase ( 1 ) ; for ( auto it : S ) { int ele = it ; int index = 1 ; while ( index * ele <= R ) { store . erase ( index * ele ) ; index ++ ; } } for ( auto i : store ) { cout << i << " ▁ " ; } } int main ( ) { int arr [ ] = { 3 , 5 } ; int L = 1 , R = 10 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; elementsCoprimeWithArr ( arr , N , L , R ) ; return 0 ; }
Maximize matrix sum by flipping the sign of any adjacent pairs | C ++ program for the above approach ; Function to find the maximum sum of matrix element after flipping the signs of adjacent matrix elements ; Initialize row and column ; Stores the sum of absolute matrix element ; Find the minimum absolute value in the matrix ; Store count of negatives ; Find the smallest absolute value in the matrix ; Increment the count of negative numbers ; Find the absolute sum ; If the count of negatives is even then print the sum ; Subtract minimum absolute element ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSum ( vector < vector < int > > & matrix ) { int r = matrix . size ( ) ; int c = matrix [ 0 ] . size ( ) ; int sum = 0 ; int mini = INT_MAX ; int count = 0 ; for ( int i = 0 ; i < r ; i ++ ) { for ( int j = 0 ; j < c ; j ++ ) { int k = matrix [ i ] [ j ] ; mini = min ( mini , abs ( k ) ) ; if ( k < 0 ) count ++ ; sum += abs ( k ) ; } } if ( count % 2 == 0 ) { return sum ; } else { return ( sum - 2 * mini ) ; } } int main ( ) { vector < vector < int > > matrix = { { 2 , -2 } , { -2 , 2 } } ; cout << maxSum ( matrix ) ; return 0 ; }
Find the last positive element remaining after repeated subtractions of smallest positive element from all Array elements | C ++ program for the above approach ; Function to calculate last positive element of the array ; Return the first element if N = 1 ; Stores the greatest and the second greatest element ; Traverse the array A [ ] ; If current element is greater than the greatest element ; If current element is greater than second greatest element ; Return the final answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int lastPositiveElement ( vector < int > arr ) { int N = arr . size ( ) ; if ( N == 1 ) return arr [ 0 ] ; int greatest = -1 , secondGreatest = -1 ; for ( int x : arr ) { if ( x >= greatest ) { secondGreatest = greatest ; greatest = x ; } else if ( x >= secondGreatest ) { secondGreatest = x ; } } return greatest - secondGreatest ; } int main ( ) { vector < int > arr = { 3 , 5 , 4 , 7 } ; cout << lastPositiveElement ( arr ) ; return 0 ; }
Reduce given array by replacing subarrays with values less than K with their sum | C ++ program for the above approach ; Function to replace all the subarray having values < K with their sum ; Stores the sum of subarray having elements less than K ; Stores the updated array ; Traverse the array ; Update the sum ; Otherwise , update the vector ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void updateArray ( vector < int > & arr , int K ) { int sum = 0 ; vector < int > res ; for ( int i = 0 ; i < ( int ) arr . size ( ) ; i ++ ) { if ( arr [ i ] < K ) { sum += arr [ i ] ; } else { if ( sum != 0 ) { res . push_back ( sum ) ; } sum = 0 ; res . push_back ( arr [ i ] ) ; } } if ( sum != 0 ) res . push_back ( sum ) ; for ( auto & it : res ) cout << it << ' ▁ ' ; } int main ( ) { vector < int > arr = { 200 , 6 , 36 , 612 , 121 , 66 , 63 , 39 , 668 , 108 } ; int K = 100 ; updateArray ( arr , K ) ; return 0 ; }
Find if path length is even or odd between given Tree nodes for Q queries | C ++ program for the above approach ; Stores the input tree ; Stores the set number of all nodes ; Function to add an edge in the tree ; Function to convert the given tree into a bipartite graph using BFS ; Set the set number to - 1 for all node of the given tree ; Stores the current node during the BFS traversal of the tree ; Initialize the set number of 1 st node and enqueue it ; BFS traversal of the given tree ; Current node ; Traverse over all neighbours of the current node ; If the set is not assigned ; Assign set number to node u ; Function to find if the path length between node A and B is even or odd ; If the set number of both nodes is same , path length is odd else even ; Driver Code ; Function to convert tree into bipartite
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < vector < int > > adj ( 100000 ) ; vector < int > setNum ( 100000 ) ; void addEdge ( int a1 , int a2 ) { adj [ a1 ] . push_back ( a2 ) ; adj [ a2 ] . push_back ( a1 ) ; } void toBipartite ( int N ) { setNum . assign ( N , -1 ) ; queue < int > q ; q . push ( 0 ) ; setNum [ 0 ] = 0 ; while ( ! q . empty ( ) ) { int v = q . front ( ) ; q . pop ( ) ; for ( int u : adj [ v ] ) { if ( setNum [ u ] == -1 ) { setNum [ u ] = setNum [ v ] ^ 1 ; q . push ( u ) ; } } } } void pathLengthQuery ( int A , int B ) { if ( setNum [ A ] == setNum [ B ] ) { cout << " Odd " << endl ; } else { cout << " Even " << endl ; } } int main ( ) { int N = 7 ; addEdge ( 0 , 1 ) ; addEdge ( 0 , 2 ) ; addEdge ( 1 , 3 ) ; addEdge ( 3 , 4 ) ; addEdge ( 3 , 5 ) ; addEdge ( 2 , 6 ) ; toBipartite ( N ) ; pathLengthQuery ( 4 , 2 ) ; pathLengthQuery ( 0 , 4 ) ; return 0 ; }
Minimum size of set having either element in range [ 0 , X ] or an odd power of 2 with sum N | CPP program for the above approach ; Function to find the highest odd power of 2 in the range [ 0 , N ] ; If P is even , subtract 1 ; Function to find the minimum operations to make N ; If N is odd and X = 0 , then no valid set exist ; Stores the minimum possible size of the valid set ; Loop to subtract highest odd power of 2 while X < N , step 2 ; If N > 0 , then increment the value of answer by 1 ; Return the resultant size of set ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int highestPowerof2 ( int n ) { int p = int ( log2 ( n ) ) ; if ( p % 2 == 0 ) p -= 1 ; return int ( pow ( 2 , p ) ) ; } int minStep ( int N , int X ) { if ( N % 2 and X == 0 ) return -1 ; int size = 0 ; while ( X < N ) { N -= highestPowerof2 ( N ) ; size += 1 ; } if ( N ) size += 1 ; return size ; } int main ( ) { int N = 11 ; int X = 2 ; cout << ( minStep ( N , X ) ) ; }
Check if all the digits of the given number are same | C ++ Program to implement the above approach ; Function to check if all the digits in the number N is the same or not ; Find the last digit ; Find the current last digit ; Update the value of N ; If there exists any distinct digit , then return No ; Otherwise , return Yes ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string checkSameDigits ( int N ) { int digit = N % 10 ; while ( N != 0 ) { int current_digit = N % 10 ; N = N / 10 ; if ( current_digit != digit ) { return " No " ; } } return " Yes " ; } int main ( ) { int N = 222 ; cout << ( checkSameDigits ( N ) ) ; return 0 ; }
Find number formed by K times alternatively reducing X and adding Y to 0 | C ++ program for the above approach ; Function to find the value obtained after alternatively reducing X and adding Y to 0 total K number of times ; Stores the final result after adding only Y to 0 ; Stores the final number after reducing only X from 0 ; Return the result obtained ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int positionAfterKJumps ( int X , int Y , int K ) { int addY = Y * ( K / 2 ) ; int reduceX = -1 * X * ( K / 2 + K % 2 ) ; return addY + reduceX ; } int main ( ) { int X = 2 , Y = 5 , K = 3 ; cout << positionAfterKJumps ( X , Y , K ) ; return 0 ; }
Maximize the largest number K such that bitwise and of K till N is 0 | C ++ program for above approach ; Function to find maximum value of k which makes bitwise AND zero . ; Take k = N initially ; Start traversing from N - 1 till 0 ; Whenever we get AND as 0 we stop and return ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaxK ( int N ) { int K = N ; for ( int i = N - 1 ; i >= 0 ; i -- ) { K &= i ; if ( K == 0 ) { return i ; } } return 0 ; } int main ( ) { int N = 5 ; cout << findMaxK ( N ) ; }
Count of unordered pair of indices such that ratio of elements at these indices is same as ratio of indices | C ++ program of the above approach ; Function of find the count of unordered pairs ( i , j ) in the array such that arr [ j ] / arr [ i ] = j / i . ; Stores the count of valid pairs ; Iterating over all possible pairs ; Check if the pair is valid ; Return answer ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int arr [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( ( arr [ j ] % arr [ i ] == 0 ) && ( j + 1 ) % ( i + 1 ) == 0 && ( arr [ j ] / arr [ i ] == ( j + 1 ) / ( i + 1 ) ) ) { count ++ ; } } } return count ; } int main ( ) { int arr [ ] = { 5 , -2 , 4 , 20 , 25 , -6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , n ) ; return 0 ; }
Count of unordered pair of indices such that ratio of elements at these indices is same as ratio of indices | C ++ program of the above approach ; Function of find the count of unordered pairs ( i , j ) in the array such that arr [ j ] / arr [ i ] = j / i . ; Stores the count of valid pairs ; Iterating over all values of x in range [ 1 , N ] . ; Iterating over all values of y that are divisible by x in the range [ 1 , N ] . ; Check if the pair is valid ; Return answer ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int arr [ ] , int n ) { int count = 0 ; for ( int x = 1 ; x <= n ; x ++ ) { for ( int y = 2 * x ; y <= n ; y += x ) { if ( ( arr [ y - 1 ] % arr [ x - 1 ] == 0 ) && ( arr [ y - 1 ] / arr [ x - 1 ] == y / x ) ) { count ++ ; } } } return count ; } int main ( ) { int arr [ ] = { 5 , -2 , 4 , 20 , 25 , -6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , n ) ; return 0 ; }
Number of minimum length paths between 1 to N including each node | C ++ program for the above approach ; Function to calculate the distances from node 1 to N ; Stores the number of edges ; Storing the edges in vector ; Initialize queue ; BFS from 1 st node using queue ; Pop from queue ; Traversing the adjacency list ; Initialize queue ; BFS from last node ; Pop from queue ; Traverse the adjacency list ; Print the count of minimum distance ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE void countMinDistance ( int n , int m , int edges [ ] [ 2 ] ) { vector < ll > g [ 10005 ] ; for ( int i = 0 ; i < m ; i ++ ) { int a = edges [ i ] [ 0 ] - 1 ; int b = edges [ i ] [ 1 ] - 1 ; g [ a ] . push_back ( b ) ; g [ b ] . push_back ( a ) ; } queue < pair < ll , ll > > queue1 ; queue1 . push ( { 0 , 0 } ) ; vector < int > dist ( n , 1e9 ) ; vector < int > ways1 ( n , 0 ) ; dist [ 0 ] = 0 ; ways1 [ 0 ] = 1 ; while ( ! queue1 . empty ( ) ) { auto up = queue1 . front ( ) ; queue1 . pop ( ) ; int x = up . first ; int dis = up . second ; if ( dis > dist [ x ] ) continue ; if ( x == n - 1 ) continue ; for ( ll y : g [ x ] ) { if ( dist [ y ] > dis + 1 ) { dist [ y ] = dis + 1 ; ways1 [ y ] = ways1 [ x ] ; queue1 . push ( { y , dis + 1 } ) ; } else if ( dist [ y ] == dis + 1 ) { ways1 [ y ] += ways1 [ x ] ; } } } queue < pair < ll , ll > > queue2 ; queue2 . push ( { n - 1 , 0 } ) ; vector < int > dist1 ( n , 1e9 ) ; vector < int > ways2 ( n , 0 ) ; dist1 [ n - 1 ] = 0 ; ways2 [ n - 1 ] = 1 ; while ( ! queue2 . empty ( ) ) { auto up = queue2 . front ( ) ; queue2 . pop ( ) ; int x = up . first ; int dis = up . second ; if ( dis > dist1 [ x ] ) continue ; if ( x == 0 ) continue ; for ( ll y : g [ x ] ) { if ( dist1 [ y ] > dis + 1 ) { dist1 [ y ] = dis + 1 ; ways2 [ y ] = ways2 [ x ] ; queue2 . push ( { y , dis + 1 } ) ; } else if ( dist1 [ y ] == 1 + dis ) { ways2 [ y ] += ways2 [ x ] ; } } } for ( int i = 0 ; i < n ; i ++ ) { cout << ways1 [ i ] * ways2 [ i ] << " ▁ " ; } } int main ( ) { int N = 5 , M = 5 ; int edges [ M ] [ 2 ] = { { 1 , 2 } , { 1 , 4 } , { 1 , 3 } , { 2 , 5 } , { 2 , 4 } } ; countMinDistance ( N , M , edges ) ; return 0 ; }
Count of N | C ++ program for the above approach ; Function to find the count of odd and even integers having N bits and K set bits ; Find the count of even integers ; Find the count of odd integers ; Print the total count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long factorial ( int n ) { long long ans = 1 ; while ( n >= 1 ) { ans *= n ; n -- ; } return ans ; } void Binary_Num ( int n , int k ) { long long num_even , num_odd ; if ( n - k - 1 >= 0 && k - 1 >= 0 ) { num_even = factorial ( n - 2 ) / ( factorial ( k - 1 ) * factorial ( n - k - 1 ) ) ; } else { num_even = 0 ; } if ( k - 2 >= 0 ) { num_odd = factorial ( n - 2 ) / ( factorial ( k - 2 ) * factorial ( n - k ) ) ; } else { num_odd = 0 ; } cout << num_even << " ▁ " << num_odd << endl ; } int main ( ) { int N = 9 , K = 6 ; Binary_Num ( N , K ) ; return 0 ; }
Sum of all subsets of a given size ( = K ) | C ++ program for the above approach ; Function to find the sum of all sub - sets of size K ; Frequency of each array element in summation equation . ; calculate factorial of n - 1 ; calculate factorial of k - 1 ; calculate factorial of n - k ; Calculate sum of array . ; Sum of all subsets of size k . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findSumOfAllSubsets ( int arr [ ] , int n , int k ) { int factorial_N = 1 , factorial_d = 1 , factorial_D = 1 ; for ( int i = 1 ; i <= n - 1 ; i ++ ) factorial_N *= i ; for ( int i = 1 ; i <= k - 1 ; i ++ ) factorial_d *= i ; for ( int i = 1 ; i <= n - k ; i ++ ) factorial_D *= i ; int freq = factorial_N / ( factorial_d * factorial_D ) ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; sum = sum * freq ; cout << " Sum ▁ of ▁ all ▁ subsets ▁ of ▁ size ▁ = ▁ " << k << " ▁ is ▁ = > ▁ " << sum << endl ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 5 } ; int n = 4 , k = 2 ; findSumOfAllSubsets ( arr , n , k ) ; return 0 ; }
Maximize XOR by selecting 3 numbers in range [ 0 , A ] , [ 0 , B ] , and [ 0 , C ] respectively | C ++ Program to implement the above approach ; Function to calculate maximum triplet XOR form 3 ranges ; Initialize a variable to store the answer ; create minimum number that have a set bit at ith position ; Check for each number and try to greedily choose the bit if possible If A >= cur then A also have a set bit at ith position ; Increment the answer ; Subtract this value from A ; Check for B ; Increment the answer ; Subtract this value from B ; Check for C ; Increment the answer ; Subtract this value from C ; If any of the above conditions is not satisfied then there is no way to turn that bit ON . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumTripletXOR ( int A , int B , int C ) { int ans = 0 ; for ( int i = 30 ; i >= 0 ; i -- ) { int cur = 1 << i ; if ( A >= cur ) { ans += cur ; A -= cur ; } else if ( B >= cur ) { ans += cur ; B -= cur ; } else if ( C >= cur ) { ans += cur ; C -= cur ; } } return ans ; } int main ( ) { int A = 6 ; int B = 2 ; int C = 10 ; cout << maximumTripletXOR ( A , B , C ) ; }
Count of integers in given range having their last K digits are equal | C ++ Program of the above approach ; Function to return the count of integers from 1 to X having the last K digits as equal ; Stores the total count of integers ; Loop to iterate over all possible values of z ; Terminate the loop when z > X ; Add count of integers with last K digits equal to z ; Return count ; Function to return the count of integers from L to R having the last K digits as equal ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int intCount ( int X , int K ) { int ans = 0 ; for ( int z = 0 ; z < pow ( 10 , K ) ; z += ( pow ( 10 , K ) - 1 ) / 9 ) { if ( z > X ) break ; ans += ( ( X - z ) / pow ( 10 , K ) + 1 ) ; } return ans ; } int intCountInRange ( int L , int R , int K ) { return ( intCount ( R , K ) - intCount ( L - 1 , K ) ) ; } int main ( ) { int L = 49 ; int R = 101 ; int K = 2 ; cout << intCountInRange ( L , R , K ) ; return 0 ; }
Count subsequence of length 4 having product of the first three elements equal to the fourth element | C ++ program for the above approach ; Function to find the total number of subsequences satisfying the given criteria ; Stores the count of quadruplets ; Stores the frequency of product of the triplet ; Traverse the given array arr [ ] ; Consider arr [ i ] as fourth element of subsequences ; Generate all possible pairs of the array [ 0 , i - 1 ] ; Increment the frequency of the triplet ; Return the total count obtained ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countQuadruples ( int A [ ] , int N ) { int ans = 0 ; unordered_map < int , int > freq ; for ( int i = 0 ; i < N ; i ++ ) { ans += freq [ A [ i ] ] ; for ( int j = 0 ; j < i ; j ++ ) { for ( int k = 0 ; k < j ; k ++ ) { freq [ A [ i ] * A [ j ] * A [ k ] ] ++ ; } } } return ans ; } int main ( ) { int arr [ ] = { 10 , 2 , 2 , 7 , 40 , 160 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countQuadruples ( arr , N ) ; return 0 ; }
Maximum times X and Y can be reduced to near 0 using numbers A or B | C ++ Program to implement the above approach ; Helper function to check if we can perform Mid number of moves # define MAXN 10000000 MAXN = 1e7 ; Remove atleast Mid * B from both X and Y ; If any value is negative return false . ; Calculate remaining values ; If val >= Mid then it is possible to perform this much moves ; else return false ; Initialize a variable to store the answer ; Fix the left and right range ; Binary Search over the answer ; Check for the middle value as the answer ; It is possible to perform this much moves ; Maximise the answer ; Return answer ; Driver Code ; Generalise that A >= B
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool can ( int Mid , int X , int Y , int A , int B ) { int p1 = X - Mid * B ; int p2 = Y - Mid * B ; if ( p1 < 0 p2 < 0 ) { return false ; } int k = A - B ; if ( k == 0 ) { return true ; } int val = p1 / k + p2 / k ; if ( val >= Mid ) { return true ; } return false ; } int maxPossibleMoves ( int X , int Y , int A , int B ) { int ans = 0 ; int L = 1 , R = MAXN ; while ( L <= R ) { int Mid = ( L + R ) / 2 ; if ( can ( Mid , X , Y , A , B ) ) { L = Mid + 1 ; ans = max ( ans , Mid ) ; } else { R = Mid - 1 ; } } return ans ; } int main ( ) { int X = 10 , Y = 12 , A = 2 , B = 5 ; if ( A < B ) { swap ( A , B ) ; } cout << maxPossibleMoves ( X , Y , A , B ) ; }
Find two proper factors of N such that their sum is coprime with N | C ++ Program for the above approach ; Function to find two proper factors of N such that their sum is coprime with N ; Find factors in sorted order ; Find largest value of d2 such that d1 and d2 are co - prime ; Check if d1 and d2 are proper factors of N ; Print answer ; No such factors exist ; Driver code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printFactors ( int n ) { for ( int i = 2 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { int d1 = i , d2 = n ; while ( d2 % d1 == 0 ) { d2 = d2 / d1 ; } if ( d1 > 1 && d2 > 1 ) { cout << d1 << " , ▁ " << d2 ; return ; } } } cout << -1 ; } int main ( ) { int N = 10 ; printFactors ( N ) ; return 0 ; }
Sum of product of all unordered pairs in given range with update queries | C ++ Program for the above approach ; Vector to store fenwick tree of the 1 st type ; Vector to store fenwick tree of the 2 nd type ; Function to update the value at idx index in fenwick tree ; Function to return the sum of values stored from O to idx index in the array using Fenwick Tree ; Function to build the Fenwick tree from the a [ ] Array ; Function call to update the ith element in the first Fenwick Tree ; Function call to update the ith element in the first Fenwick Tree ; Function to find the Pairwise Product Sum in the range L to R ; Function call to calculate E in the given range ; Function call to calculate E in the given range ; Print Answer ; Function to update the Fenwick tree and the array element at index P to the new value X ; Function call to update the value in 1 st Fenwick Tree ; Function call to update the value in 2 nd Fenwick Tree ; Function to solve Q queries ; Function Call to build the Fenwick Tree ; If Query is of type 1 ; If Query is of type 2 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAXN 100000 NEW_LINE vector < int > bit1 ( MAXN , 0 ) ; vector < int > bit2 ( MAXN , 0 ) ; void update ( int idx , int val , vector < int > & bit ) { while ( idx < bit . size ( ) ) { bit [ idx ] += val ; idx += idx & ( - idx ) ; } } int query ( int idx , vector < int > & bit ) { int res = 0 ; while ( idx > 0 ) { res += bit [ idx ] ; idx -= idx & ( - idx ) ; } return res ; } void buildFenwickTree ( int a [ ] , int n ) { for ( int i = 1 ; i <= n ; i ++ ) { update ( i , a [ i - 1 ] , bit1 ) ; update ( i , a [ i - 1 ] * a [ i - 1 ] , bit2 ) ; } } void pairwiseProductSum ( int a [ ] , int l , int r ) { int sum , e , q ; e = query ( r , bit1 ) - query ( l - 1 , bit1 ) ; e = e * e ; q = query ( r , bit2 ) - query ( l - 1 , bit2 ) ; sum = ( e - q ) / 2 ; cout << sum << endl ; } void updateArray ( int * a , int p , int x ) { update ( p , - a [ p - 1 ] , bit1 ) ; update ( p , x , bit1 ) ; update ( p , - a [ p - 1 ] * a [ p - 1 ] , bit2 ) ; update ( p , x * x , bit2 ) ; a [ p - 1 ] = x ; } void solveQueries ( int * a , int n , int Q , int query [ ] [ 3 ] ) { buildFenwickTree ( a , n ) ; for ( int i = 0 ; i < Q ; i ++ ) { if ( query [ i ] [ 0 ] == 1 ) pairwiseProductSum ( a , query [ i ] [ 1 ] , query [ i ] [ 2 ] ) ; else updateArray ( a , query [ i ] [ 1 ] , query [ i ] [ 2 ] ) ; } } int main ( ) { int A [ ] = { 5 , 7 , 2 , 3 , 1 } ; int N = sizeof ( A ) / sizeof ( int ) ; int Q = 3 ; int query [ Q ] [ 3 ] = { { 1 , 1 , 3 } , { 2 , 2 , 5 } , { 1 , 2 , 5 } } ; solveQueries ( A , N , Q , query ) ; return 0 ; }
Count of triplets in an Array with odd sum | C ++ Program for the above approach ; Function to count the number of unordered triplets such that their sum is an odd integer ; Count the number of odd and even integers in the array ; Number of ways to create triplets using one odd and two even integers ; Number of ways to create triplets using three odd integers ; Return answer ; Driver Code ; Function Call ; Print Answer
#include <iostream> NEW_LINE using namespace std ; int countTriplets ( int arr [ ] , int n ) { int odd = 0 , even = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] & 1 ) odd ++ ; else even ++ ; } int c1 = odd * ( even * ( even - 1 ) ) / 2 ; int c2 = ( odd * ( odd - 1 ) * ( odd - 2 ) ) / 6 ; return c1 + c2 ; } int main ( ) { int arr [ ] = { 4 , 5 , 6 , 4 , 5 , 10 , 1 , 7 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int ans = countTriplets ( arr , n ) ; cout << ans ; return 0 ; }
Longest remaining array of distinct elements possible after repeated removal of maximum and minimum elements of triplets | C ++ Program to implement the above approach ; Function to return length of longest remaining array of pairwise distinct array possible by removing triplets ; Stores the frequency of array elements ; Traverse the array ; Iterate through the map ; If frequency of current element is even ; Stores the required count of unique elements remaining ; If count is odd ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxUniqueElements ( int A [ ] , int N ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { mp [ A [ i ] ] ++ ; } int cnt = 0 ; for ( auto x : mp ) { if ( x . second % 2 == 0 ) { cnt ++ ; } } int ans = mp . size ( ) ; if ( cnt % 2 == 1 ) { ans -- ; } return ans ; } int main ( ) { int N = 5 ; int A [ ] = { 1 , 2 , 1 , 3 , 7 } ; cout << maxUniqueElements ( A , N ) ; }
Count cells in a grid from which maximum number of cells can be reached by K vertical or horizontal jumps | C ++ program for the above approach ; Function to count the number of cells in the grid such that maximum cell is reachable with a jump of K ; Maximum reachable rows from the current row ; Stores the count of cell that are reachable from the current row ; Count of reachable rows ; Update the maximum value ; Add it to the count ; Maximum reachable columns from the current column ; Stores the count of cell that are reachable from the current column ; Count of rechable columns ; Update the maximum value ; Add it to the count ; Return the total count of cells ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long countCells ( int n , int m , int s ) { int mx1 = -1 ; int cont1 = 0 ; for ( int i = 0 ; i < s && i < n ; ++ i ) { int aux = ( n - ( i + 1 ) ) / s + 1 ; if ( aux > mx1 ) { mx1 = cont1 = aux ; } else if ( aux == mx1 ) cont1 += aux ; } int mx2 = -1 ; int cont2 = 0 ; for ( int i = 0 ; i < s && i < m ; ++ i ) { int aux = ( m - ( i + 1 ) ) / s + 1 ; if ( aux > mx2 ) mx2 = cont2 = aux ; else if ( aux == mx2 ) cont2 += aux ; } return ( long long ) ( cont1 * cont2 ) ; } int main ( ) { int N = 5 , M = 5 , K = 2 ; cout << countCells ( N , M , K ) ; return 0 ; }
Count of pairs from first N natural numbers with remainder at least K | C ++ program for the above approach ; Function to count the number of pairs ( a , b ) such that a % b is at least K ; Base Case ; Stores resultant count of pairs ; Iterate over the range [ K + 1 , N ] ; Find the cycled elements ; Find the remaining elements ; Return the resultant possible count of pairs ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countTotalPairs ( int N , int K ) { if ( K == 0 ) { return N * N ; } int ans = 0 ; for ( int b = K + 1 ; b <= N ; b ++ ) { ans += ( N / b ) * ( b - K ) ; ans += max ( N % b - K + 1 , 0 ) ; } return ans ; } int main ( ) { int N = 5 , K = 2 ; cout << countTotalPairs ( N , K ) ; return 0 ; }
Maximum number of pairs of distinct array elements possible by including each element in only one pair | ; stores the frequency array ; maxi stores the maximum frequency of an element ; it stores the sum of all the frequency other than the element which has maximum frequency ; there will be always zero or more element which will not participate in making pairs ; if n is odd then except one element we can always form pair for every element if n is even then all the elements can form pair
#include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { int arr [ ] = { 4 , 2 , 4 , 1 , 4 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int maxi = 0 , remain , ans ; map < int , int > freq ; for ( int i = 0 ; i < n ; i ++ ) { freq [ arr [ i ] ] ++ ; } for ( auto it : freq ) { maxi = max ( maxi , it . second ) ; } remain = n - maxi ; if ( maxi >= remain ) { ans = remain ; } else { ans = n / 2 ; } cout << ans ; freq . clear ( ) ; return 0 ; }
Minimize sum of absolute difference between all pairs of array elements by decrementing and incrementing pairs by 1 | C ++ program for the above approach ; Function to find the minimum value of the sum of absolute difference between all pairs of arrays ; Stores the sum of array elements ; Find the sum of array element ; Store the value of sum % N ; Return the resultant value ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minSumDifference ( int ar [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += ar [ i ] ; int rem = sum % n ; return rem * ( n - rem ) ; } int main ( ) { int arr [ ] = { 3 , 6 , 8 , 5 , 2 , 1 , 11 , 7 , 10 , 4 } ; int N = sizeof ( arr ) / sizeof ( int ) ; cout << minSumDifference ( arr , N ) ; return 0 ; }
Count N | C ++ program for the above approache ; Function to find the value of x ^ y ; Stores the value of x ^ y ; Iterate until y is positive ; If y is odd ; Divide y by 2 ; Return the value of x ^ y ; Function to find the number of N - digit integers satisfying the given criteria ; Count of even positions ; Count of odd positions ; Return the resultant count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int m = 1000000007 ; int power ( int x , int y ) { int res = 1 ; while ( y > 0 ) { if ( ( y & 1 ) != 0 ) res = ( res * x ) % m ; y = y >> 1 ; x = ( x * x ) % m ; } return res ; } int countNDigitNumber ( int N ) { int ne = N / 2 + N % 2 ; int no = floor ( N / 2 ) ; return power ( 4 , ne ) * power ( 5 , no ) ; } int main ( ) { int N = 5 ; cout << countNDigitNumber ( N ) % m << endl ; }
Minimum jumps to traverse all integers in range [ 1 , N ] such that integer i can jump i steps | C ++ implementation of the above approach ; Utility function to find minimum steps ; Initialize count and result ; Traverse over the range [ 1 , N ] ; Update res ; Increment count ; Return res ; Driver Code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minSteps ( int N ) { int count = 1 , res = 0 ; for ( int i = 1 ; i <= N ; i += count ) { res = max ( res , count ) ; count ++ ; } return res ; } int main ( ) { int N = 6 ; cout << minSteps ( N ) << " STRNEWLINE " ; }
Minimum jumps to traverse all integers in range [ 1 , N ] such that integer i can jump i steps | C ++ implementation of the above approach ; Utility function to find minimum steps ; Driver code ; Input integer ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minSteps ( int N ) { int res = ( sqrt ( 1 + 8 * N ) - 1 ) / 2 ; return res ; } int main ( ) { int N = 6 ; cout << minSteps ( N ) << " STRNEWLINE " ; }
The dice problem | C ++ program for the above approach ; Function to find number written on the opposite face of the dice ; Stores number on opposite face of dice ; Print the answer ; Driver Code ; Given value of N ; Function call to find number written on the opposite face of the dice
#include <bits/stdc++.h> NEW_LINE using namespace std ; int oppositeFaceOfDice ( int N ) { int ans = 7 - N ; cout << ans ; } int main ( ) { int N = 2 ; oppositeFaceOfDice ( N ) ; return 0 ; }
Count numbers from a given range that can be visited moving any number of steps from the range [ L , R ] | C ++ code for above approach ; Function to count points from the range [ X , Y ] that can be reached by moving by L or R steps ; Initialize difference array ; Initialize Count ; Marking starting point ; Iterating from X to Y ; Accumulate difference array ; If diff_arr [ i ] is greater than 1 ; Updating difference array ; Visited point found ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countReachablePoints ( int X , int Y , int L , int R ) { int diff_arr [ 100000 ] = { 0 } ; int count = 0 ; diff_arr [ X ] = 1 ; diff_arr [ X + 1 ] = -1 ; for ( int i = X ; i <= Y ; i ++ ) { diff_arr [ i ] += diff_arr [ i - 1 ] ; if ( diff_arr [ i ] >= 1 ) { diff_arr [ i + L ] += 1 ; diff_arr [ i + R + 1 ] -= 1 ; count ++ ; } } return count ; } int main ( ) { int X = 3 , Y = 12 , L = 2 , R = 3 ; cout << countReachablePoints ( X , Y , L , R ) ; return 0 ; }
Multiply a single digit number in place to a number represented as a Linked List | C ++ program for the above approach ; Node of a Linked List ; Function to create a new node with given data ; Initialize new node ; Set the data field of the node ; Return the new node ; Function to reverse the linked list ; Traverse until curr != null ; Return the head of the reversed linked list ; Utility function to multiply a single digit to a linked list ; Store the head of list ; Stores the address of previous node ; Initially set carry as 0 and product as 1 ; Multiply M with each digit ; Add carry to product if carry exist ; Update carry for next calculation ; Update the value of each nodes ; Move head and temp pointers to next nodes ; If some carry is still there , add a new node to list ; Return head of the resultant list ; Function to multiply a single digit to a linked list ; Reverse linked list ; Multiply M from left to right of reversed list ; Reverse the modified list and return its head ; Function to print the linked list ; Driver Code ; Given Input list : 1 -> 2 -> 7 -> 3 ; Function Call ; Print resultant list
#include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * next ; } ; Node * newNode ( int data ) { Node * new_node = new Node ; new_node -> data = data ; new_node -> next = NULL ; return new_node ; } Node * reverse ( Node * head ) { Node * prev = NULL ; Node * current = head ; Node * next ; while ( current != NULL ) { next = current -> next ; current -> next = prev ; prev = current ; current = next ; } return prev ; } Node * multiplyHelp ( Node * head , int M ) { Node * res = head ; Node * prev = NULL ; int carry = 0 , product = 1 ; while ( head != NULL ) { product = head -> data * M ; product += carry ; carry = product / 10 ; head -> data = product % 10 ; prev = head ; head = head -> next ; } if ( carry > 0 ) prev -> next = newNode ( carry ) ; return res ; } Node * multiply ( Node * head , int M ) { head = reverse ( head ) ; head = multiplyHelp ( head , M ) ; return reverse ( head ) ; } void printList ( Node * node ) { while ( node != NULL ) { cout << node -> data ; node = node -> next ; } } int main ( ) { Node * head = newNode ( 1 ) ; head -> next = newNode ( 2 ) ; head -> next -> next = newNode ( 7 ) ; head -> next -> next -> next = newNode ( 3 ) ; int M = 3 ; head = multiply ( head , M ) ; printList ( head ) ; return 0 ; }
Count of triplets having sum of product of any two numbers with the third number equal to N | C ++ program for the above approach ; Function to find the SPF [ i ] using the Sieve Of Erastothenes ; Stores whether i is prime or not ; Initializing smallest factor as 2 for all even numbers ; Iterate for all odd numbers < N ; SPF of i for a prime is the number itself ; Iterate for all the multiples of the current prime number ; The value i is smallest prime factor for i * j ; Function to generate prime factors and its power ; Current prime factor of N ; Stores the powers of the current prime factor ; Find all the prime factors and their powers ; Return the total count of factors ; Function to count the number of triplets satisfying the given criteria ; Stores the count of resultant triplets ; Add the count all factors of N - z to the variable CountTriplet ; Return total count of triplets ; Driver Code ; Find the SPF [ i ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > s ( 11 , 0 ) ; void sieveOfEratosthenes ( int N ) { bool prime [ N + 1 ] ; memset ( prime , false , sizeof ( false ) ) ; for ( int i = 2 ; i < N + 1 ; i += 2 ) s [ i ] = 2 ; for ( int i = 3 ; i < N + 1 ; i += 2 ) { if ( prime [ i ] == false ) { s [ i ] = i ; for ( int j = i ; j < N / i + 1 ; j += 2 ) { if ( prime [ i * j ] == false ) { prime [ i * j ] = true ; s [ i * j ] = i ; } } } } } int generatePrimeFactors ( int N ) { int curr = s [ N ] ; map < int , int > cnt ; cnt [ s [ N ] ] = 1 ; while ( N > 1 ) { N /= s [ N ] ; if ( N and s [ N ] ) if ( cnt . find ( s [ N ] ) == cnt . end ( ) ) cnt [ s [ N ] ] = 1 ; else cnt [ s [ N ] ] += 1 ; } if ( cnt . find ( 0 ) != cnt . end ( ) ) cnt . erase ( 0 ) ; int totfactor = 1 ; for ( auto i : cnt ) totfactor *= i . second + 1 ; return totfactor ; } int countTriplets ( int N ) { int CountTriplet = 0 ; for ( int z = 1 ; z < N + 1 ; z ++ ) { int p = generatePrimeFactors ( N - z ) ; if ( p > 1 ) CountTriplet += p ; } return CountTriplet + 1 ; } int main ( ) { int N = 10 ; sieveOfEratosthenes ( N ) ; cout << countTriplets ( N ) ; }
Minimum length of the subarray required to be replaced to make frequency of array elements equal to N / M | C ++ program for the above approach ; Function to find the minimum length of the subarray to be changed . ; Stores the frequencies of array elements ; Stores the number of array elements that are present more than N / M times ; Iterate over the range ; Increment the frequency ; If the frequency of all array elements are already N / M ; Stores the resultant length of the subarray ; The left and right pointers ; Iterate over the range ; If the current element is ; If the value of c is 0 , then find the possible answer ; Iterate over the range ; If the element at left is making it extra ; Update the left pointer ; Update the right pointer ; Return the resultant length ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumSubarray ( vector < int > arr , int n , int m ) { vector < int > mapu ( m + 1 , 0 ) ; int c = 0 ; for ( int i = 0 ; i < n ; i ++ ) { mapu [ arr [ i ] ] ++ ; if ( mapu [ arr [ i ] ] == ( n / m ) + 1 ) c ++ ; } if ( c == 0 ) return 0 ; int ans = n ; int l = 0 , r = 0 ; while ( r < n ) { if ( -- mapu [ arr [ r ] ] == ( n / m ) ) c -- ; if ( c == 0 ) { while ( l <= r && c == 0 ) { ans = min ( ans , r - l + 1 ) ; if ( ++ mapu [ arr [ l ] ] > ( n / m ) ) c ++ ; l ++ ; } } r ++ ; } return ans ; } int main ( ) { vector < int > arr = { 1 , 1 , 2 , 1 , 1 , 2 } ; int M = 2 ; int N = arr . size ( ) ; cout << minimumSubarray ( arr , N , M ) ; return 0 ; }
Check if the sum of K least and most frequent array elements are equal or not | C ++ program for the above approach ; Function to compare the sum of K most and least occurrences ; Stores frequency of array element ; Stores the frequencies as indexes and putelements with the frequency in a vector ; Find the frequency ; Insert in the vector ; Stores the count of elements ; Traverse the frequency array ; Find the kleastfreqsum ; If the count is K , break ; Reinitialize the count to zero ; Traverse the frequency ; Find the kmostfreqsum ; If the count is K , break ; Comparing the sum ; Otherwise , return No ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string checkSum ( int arr [ ] , int n , int k ) { unordered_map < int , int > m ; for ( int i = 0 ; i < n ; i ++ ) m [ arr [ i ] ] ++ ; vector < int > freq [ n + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) { int f = m [ arr [ i ] ] ; if ( f != -1 ) { freq [ f ] . push_back ( arr [ i ] ) ; m [ arr [ i ] ] = -1 ; } } int count = 0 ; int kleastfreqsum = 0 ; for ( int i = 0 ; i <= n ; i ++ ) { for ( int x : freq [ i ] ) { kleastfreqsum += x ; count ++ ; if ( count == k ) break ; } if ( count == k ) break ; } count = 0 ; int kmostfreqsum = 0 ; for ( int i = n ; i >= 0 ; i -- ) { for ( int x : freq [ i ] ) { kmostfreqsum += x ; count ++ ; if ( count == k ) break ; } if ( count == k ) break ; } if ( kleastfreqsum == kmostfreqsum ) return " Yes " ; return " No " ; } int main ( ) { int arr [ ] = { 3 , 2 , 1 , 2 , 3 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 2 ; cout << checkSum ( arr , N , K ) ; return 0 ; }
Print all numbers from a given range that are made up of consecutive digits | C ++ program for the above approach ; Function to find the consecutive digit numbers in the given range ; Initialize num as empty string ; Stores the resultant number ; Iterate over the range [ 1 , 9 ] ; Check if the current number is within range ; Iterate on the digits starting from i ; Checking the consecutive digits numbers starting from i and ending at j is within range or not ; Sort the numbers in the increasing order ; Driver Code ; Print the required numbers
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > solve ( int start , int end ) { string num = " " ; vector < int > ans ; for ( int i = 1 ; i <= 9 ; i ++ ) { num = to_string ( i ) ; int value = stoi ( num ) ; if ( value >= start and value <= end ) { ans . push_back ( value ) ; } for ( int j = i + 1 ; j <= 9 ; j ++ ) { num += to_string ( j ) ; value = stoi ( num ) ; if ( value >= start and value <= end ) { ans . push_back ( value ) ; } } } sort ( ans . begin ( ) , ans . end ( ) ) ; return ans ; } int main ( ) { int L = 12 , R = 87 ; vector < int > ans = solve ( 12 , 87 ) ; for ( auto & it : ans ) cout << it << ' ▁ ' ; return 0 ; }
Minimum distance a person has to move in order to take a picture of every racer | C ++ implementation of the approach ; Function to return the minimum distance the person has to move int order to get the pictures ; To store the minimum ending point ; To store the maximum starting point ; Find the values of minSeg and maxSeg ; Impossible ; The person doesn 't need to move ; Get closer to the left point ; Get closer to the right point ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minDistance ( int start [ ] , int end [ ] , int n , int d ) { int left = INT_MIN ; int right = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { left = max ( left , start [ i ] ) ; right = min ( right , end [ i ] ) ; } if ( left > right ) return -1 ; if ( d >= left && d <= right ) return 0 ; if ( d < left ) return ( left - d ) ; if ( d > right ) return ( d - right ) ; } int main ( ) { int start [ ] = { 0 , 2 , 4 } ; int end [ ] = { 7 , 14 , 6 } ; int n = sizeof ( start ) / sizeof ( int ) ; int d = 3 ; cout << minDistance ( start , end , n , d ) ; return 0 ; }
Maximum number of Armstrong Numbers present in a subarray of size K | C ++ program for the above approach ; Function to calculate the value of x raised to the power y in O ( log y ) ; Base Case ; If the power y is even ; Otherwise ; Function to calculate the order of the number , i . e . count of digits ; Stores the total count of digits ; Iterate until num is 0 ; Function to check a number is an Armstrong Number or not ; Find the order of the number ; Check for Armstrong Number ; If Armstrong number condition is satisfied ; Utility function to find the maximum sum of a subarray of size K ; If k is greater than N ; Find the sum of first subarray of size K ; Find the sum of the remaining subarray ; Return the maximum sum of subarray of size K ; Function to find all the Armstrong Numbers in the array ; Traverse the array arr [ ] ; If arr [ i ] is an Armstrong Number , then replace it by 1. Otherwise , 0 ; Return the resultant count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int power ( int x , unsigned int y ) { if ( y == 0 ) return 1 ; if ( y % 2 == 0 ) return power ( x , y / 2 ) * power ( x , y / 2 ) ; return x * power ( x , y / 2 ) * power ( x , y / 2 ) ; } int order ( int num ) { int count = 0 ; while ( num ) { count ++ ; num = num / 10 ; } return count ; } int isArmstrong ( int N ) { int r = order ( N ) ; int temp = N , sum = 0 ; while ( temp ) { int d = temp % 10 ; sum += power ( d , r ) ; temp = temp / 10 ; } return ( sum == N ) ; } int maxSum ( int arr [ ] , int N , int K ) { if ( N < K ) { return -1 ; } int res = 0 ; for ( int i = 0 ; i < K ; i ++ ) { res += arr [ i ] ; } int curr_sum = res ; for ( int i = K ; i < N ; i ++ ) { curr_sum += arr [ i ] - arr [ i - K ] ; res = max ( res , curr_sum ) ; } return res ; } int maxArmstrong ( int arr [ ] , int N , int K ) { for ( int i = 0 ; i < N ; i ++ ) { arr [ i ] = isArmstrong ( arr [ i ] ) ; } return maxSum ( arr , N , K ) ; } int main ( ) { int arr [ ] = { 28 , 2 , 3 , 6 , 153 , 99 , 828 , 24 } ; int K = 6 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxArmstrong ( arr , N , K ) ; return 0 ; }
Count N | C ++ program for the above approach ; Function to calculate the power of n ^ k % p ; Update x if it is more than or equal to p ; In case x is divisible by p ; ; If y is odd , multiply x with result ; y must be even now y = y >> 1 ; y = y / 2 ; Function to count the number of arrays satisfying required conditions ; Calculating N ^ K ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int power ( long long x , unsigned int y , int p ) { int res = 1 ; x = x % p ; if ( x == 0 ) return 0 ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return res ; } int countArrays ( int n , int k ) { int mod = 1000000007 ; int ans = power ( n , k , mod ) ; return ans ; } int main ( ) { int n = 3 , k = 5 ; int ans = countArrays ( n , k ) ; cout << ans << endl ; return 0 ; }
Count ways to replace ' ? ' in a Binary String to make the count of 0 s and 1 s same as that of another string | C ++ program for the above approach ; Function to find the factorial of the given number N ; Stores the factorial ; Iterate over the range [ 2 , N ] ; Return the resultant result ; Function to find the number of ways of choosing r objects from n distinct objects ; Function to find the number of ways to replace ' ? ' in string t to get the same count of 0 s and 1 s in the string S and T ; Traverse the string s ; If the current character is 1 ; Update the value of the sum1 ; Otherwise ; Traverse the string t ; If the current character is 1 , then update the value of sum2 ; If the current character is 0 ; Otherwise , update the value of K ; Check if P is greater than K or if K - P is odd ; Print the count of ways ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int fact ( int n ) { int res = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { res = res * i ; } return res ; } int nCr ( int n , int r ) { return fact ( n ) / ( fact ( r ) * fact ( n - r ) ) ; } void countWays ( string s , string t ) { int n = s . length ( ) ; int sum1 = 0 , sum2 = 0 , K = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == '1' ) { sum1 ++ ; } else sum1 -- ; } int m = t . length ( ) ; for ( int i = 0 ; i < m ; i ++ ) { if ( t [ i ] == '1' ) { sum2 ++ ; } else if ( t [ i ] == '0' ) { sum2 -- ; } else K ++ ; } int P = abs ( sum1 - sum2 ) ; if ( P > K or ( K - P ) % 2 ) { cout << 0 ; return ; } cout << nCr ( K , ( P + K ) / 2 ) ; } int main ( ) { string S1 = "1010" ; string S2 = "10 ? ? " ; countWays ( S1 , S2 ) ; return 0 ; }
Count pairs of indices having sum of indices same as the sum of elements at those indices | C ++ program for the above approach ; Function to find all possible pairs of the given array such that the sum of arr [ i ] + arr [ j ] is i + j ; Stores the total count of pairs ; Iterate over the range ; Iterate over the range ; Print the total count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countPairs ( int arr [ ] , int N ) { int answer = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { if ( arr [ i ] + arr [ j ] == i + j ) { answer ++ ; } } } cout << answer ; } int main ( ) { int arr [ ] = { 0 , 1 , 2 , 3 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countPairs ( arr , N ) ; return 0 ; }
Distribute R , B beans such that each packet has at least 1 R and 1 B bean with absolute difference at most D | C ++ program for the above approach ; Function to check if it is possible to distribute R red and B blue beans in packets such that the difference between the beans in each packet is atmost D ; Check for the condition to distributing beans ; Print the answer ; Distribution is not possible ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void checkDistribution ( int R , int B , int D ) { if ( max ( R , B ) <= min ( R , B ) * ( D + 1 ) ) { cout << " Yes " ; } else { cout << " No " ; } } int main ( ) { int R = 1 , B = 1 , D = 0 ; checkDistribution ( R , B , D ) ; return 0 ; }
Generate a sequence with product N such that for every pair of indices ( i , j ) and i < j , arr [ j ] is divisible by arr [ i ] | C ++ program for the above approach ; Function to calculate the prime factors of N with their count ; Initialize a vector , say v ; Initialize the count ; Count the number of divisors ; Divide the value of N by 2 ; For factor 2 divides it ; Find all prime factors ; Count their frequency ; Push it to the vector ; Push N if it is not 1 ; Function to print the array that have the maximum size ; Stores the all prime factor and their powers ; Traverse the vector and find the maximum power of prime factor ; If max size is less than 2 ; Otherwise ; Print the maximum size of sequence ; Print the final sequence ; Print the prime factor ; Print the last value of the sequence ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < pair < int , int > > primeFactor ( int N ) { vector < pair < int , int > > v ; int count = 0 ; while ( ! ( N % 2 ) ) { N >>= 1 ; count ++ ; } if ( count ) v . push_back ( { 2 , count } ) ; for ( int i = 3 ; i <= sqrt ( N ) ; i += 2 ) { count = 0 ; while ( N % i == 0 ) { count ++ ; N = N / i ; } if ( count ) { v . push_back ( { i , count } ) ; } } if ( N > 2 ) v . push_back ( { N , 1 } ) ; return v ; } void printAnswer ( int n ) { vector < pair < int , int > > v = primeFactor ( n ) ; int maxi_size = 0 , prime_factor = 0 ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { if ( maxi_size < v [ i ] . second ) { maxi_size = v [ i ] . second ; prime_factor = v [ i ] . first ; } } if ( maxi_size < 2 ) { cout << 1 << ' ▁ ' << n ; } else { int product = 1 ; cout << maxi_size << endl ; for ( int i = 0 ; i < maxi_size - 1 ; i ++ ) { cout << prime_factor << " ▁ " ; product *= prime_factor ; } cout << ( n / product ) ; } } int main ( ) { int N = 360 ; printAnswer ( N ) ; return 0 ; }
Check if it is possible to reach destination in even number of steps in an Infinite Matrix | C ++ Program for the above approach ; Function to check destination can be reached from source in even number of steps ; Coordinates differences ; minimum number of steps required ; Minsteps is even ; Minsteps is odd ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void IsEvenPath ( int Source [ ] , int Destination [ ] ) { int x_dif = abs ( Source [ 0 ] - Destination [ 0 ] ) ; int y_dif = abs ( Source [ 1 ] - Destination [ 1 ] ) ; int minsteps = x_dif + y_dif ; if ( minsteps % 2 == 0 ) cout << " Yes " ; else cout << " No " ; } int main ( ) { int Source [ ] = { 2 , 1 } ; int Destination [ ] = { 1 , 4 } ; IsEvenPath ( Source , Destination ) ; return 0 ; }
Find the closest Fraction to given fraction having minimum absolute difference | C ++ program for the above approach ; Function to find the absolute value of x ; Function to find the fraction with minimum absolute difference ; Initialize the answer variables ; Iterate over the range ; Nearest fraction ; x / y - d / i < x / y - A / B ( B * x - y * A ) * ( i * y ) > ( i * x - y * d ) * ( B * y ) ; Check for d + 1 ; Print the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long ABS ( long long x ) { return max ( x , - x ) ; } void findFraction ( long long x , long long y , long long n ) { long long A = -1 , B = -1 ; for ( long long i = 1 ; i <= n ; i ++ ) { long long d = ( i * x ) / y ; if ( d >= 0 && ( A == -1 || ABS ( B * x - y * A ) * ABS ( i * y ) > ABS ( i * x - y * d ) * ABS ( B * y ) ) ) A = d , B = i ; d ++ ; if ( d >= 0 && ( A == -1 || ABS ( B * x - y * A ) * ABS ( i * y ) > ABS ( i * x - y * d ) * ABS ( B * y ) ) ) A = d , B = i ; } cout << A << " / " << B << endl ; } int main ( ) { long long x = 3 , y = 7 , n = 6 ; findFraction ( x , y , n ) ; return 0 ; }
Represent a number N in base | C ++ Program for above approach ; Function to convert N to equivalent representation in base - 2 ; Stores the required answer ; Iterate until N is not equal to zero ; If N is Even ; Add char '0' in front of string ; Add char '1' in front of string ; Decrement N by 1 ; Divide N by - 2 ; If string is empty , that means N is zero ; Put '0' in string s ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string BaseConversion ( int N ) { string s = " " ; while ( N != 0 ) { if ( N % 2 == 0 ) { s = "0" + s ; } else { s = "1" + s ; N -- ; } N /= -2 ; } if ( s == " " ) { s = "0" ; } return s ; } int main ( ) { int N = -9 ; cout << BaseConversion ( N ) ; return 0 ; }
Find instances at end of time frame after auto scaling | C ++ program for the above approach ; Function to find the number of instances after compintion ; Traverse the array , arr [ ] ; If current element is less than 25 ; Divide instances by 2 and take ceil value ; If the current element is greater than 60 ; Double the instances ; Print the instances at the end of the traversal ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void finalInstances ( int instances , int arr [ ] , int N ) { int i = 0 ; while ( i < N ) { if ( arr [ i ] < 25 && instances > 1 ) { double temp = ( instances / 2.0 ) ; instances = ( int ) ( ceil ( temp ) ) ; i = i + 10 ; } else if ( arr [ i ] > 60 && instances <= ( 2 * pow ( 10 , 8 ) ) ) { instances = instances * 2 ; i = i + 10 ; } i = i + 1 ; } cout << instances ; } int main ( ) { int instances = 2 ; int arr [ ] = { 25 , 23 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 76 , 80 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; finalInstances ( instances , arr , N ) ; }
Modify array by making all array elements equal to 0 by subtracting K ^ i from an array element in every i | C ++ program for the above approach ; Function to check whether all array elements can be made zero or not ; Stores if a power of K has already been subtracted or not ; Stores all the Kth power ; Iterate until X is less than INT_MAX ; Traverse the array arr [ ] ; Iterate over the range [ 0 , M ] ; If MP [ V [ j ] ] is 0 and V [ j ] is less than or equal to arr [ i ] ; If arr [ i ] is not 0 ; If i is less than N ; Otherwise , ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string isMakeZero ( int arr [ ] , int N , int K ) { map < int , int > MP ; vector < int > V ; int X = 1 ; int i ; while ( X > 0 && X < INT_MAX ) { V . push_back ( X ) ; X *= K ; } for ( i = 0 ; i < N ; i ++ ) { for ( int j = V . size ( ) - 1 ; j >= 0 ; j -- ) { if ( MP [ V [ j ] ] == 0 && V [ j ] <= arr [ i ] ) { arr [ i ] -= V [ j ] ; MP [ V [ j ] ] = 1 ; } } if ( arr [ i ] != 0 ) break ; } if ( i < N ) return " No " ; else return " Yes " ; } int main ( ) { int arr [ ] = { 8 , 0 , 3 , 4 , 80 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 2 ; cout << isMakeZero ( arr , N , K ) ; return 0 ; }