text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Print the DFS traversal step | C ++ program to print the complete DFS - traversal of graph using back - tracking ; Function to print the complete DFS - traversal ; Check if all th node is visited or not and count unvisited nodes ; If all the node is visited return ; ; Mark not visited node as visited ; Track the current edge ; Print the node ; Check for not visited node and proceed with it . ; call the DFs function if not visited ; Backtrack through the last visited nodes ; Function to call the DFS function which prints the DFS - traversal stepwise ; Create a array of visited node ; Vector to track last visited road ; Initialize all the node with false ; call the function ; Function to insert edges in Graph ; Driver Code ; number of nodes and edges in the graph ; Function call to create the graph ; Call the function to print | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 1000 ; vector < int > adj [ N ] ; void dfsUtil ( int u , int node , bool visited [ ] , vector < pair < int , int > > road_used , int parent , int it ) { int c = 0 ; for ( int i = 0 ; i < node ; i ++ ) if ( visited [ i ] ) c ++ ; if ( c == node ) return ; visited [ u ] = true ; road_used . push_back ( { parent , u } ) ; cout << u << " β " ; for ( int x : adj [ u ] ) { if ( ! visited [ x ] ) dfsUtil ( x , node , visited , road_used , u , it + 1 ) ; } for ( auto y : road_used ) if ( y . second == u ) dfsUtil ( y . first , node , visited , road_used , u , it + 1 ) ; } void dfs ( int node ) { bool visited [ node ] ; vector < pair < int , int > > road_used ; for ( int i = 0 ; i < node ; i ++ ) visited [ i ] = false ; dfsUtil ( 0 , node , visited , road_used , -1 , 0 ) ; } void insertEdge ( int u , int v ) { adj [ u ] . push_back ( v ) ; adj [ v ] . push_back ( u ) ; } int main ( ) { int node = 11 , edge = 13 ; insertEdge ( 0 , 1 ) ; insertEdge ( 0 , 2 ) ; insertEdge ( 1 , 5 ) ; insertEdge ( 1 , 6 ) ; insertEdge ( 2 , 4 ) ; insertEdge ( 2 , 9 ) ; insertEdge ( 6 , 7 ) ; insertEdge ( 6 , 8 ) ; insertEdge ( 7 , 8 ) ; insertEdge ( 2 , 3 ) ; insertEdge ( 3 , 9 ) ; insertEdge ( 3 , 10 ) ; insertEdge ( 9 , 10 ) ; dfs ( node ) ; return 0 ; } |
Find Maximum number possible by doing at | C ++ program to find maximum integer possible by doing at - most K swap operations on its digits . ; Function to find maximum integer possible by doing at - most K swap operations on its digits ; Return if no swaps left ; Consider every digit ; Compare it with all digits after it ; if digit at position i is less than digit at position j , swap it and check for maximum number so far and recurse for remaining swaps ; swap str [ i ] with str [ j ] ; If current num is more than maximum so far ; recurse of the other k - 1 swaps ; Backtrack ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findMaximumNum ( string str , int k , string & max ) { if ( k == 0 ) return ; int n = str . length ( ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( str [ i ] < str [ j ] ) { swap ( str [ i ] , str [ j ] ) ; if ( str . compare ( max ) > 0 ) max = str ; findMaximumNum ( str , k - 1 , max ) ; swap ( str [ i ] , str [ j ] ) ; } } } } int main ( ) { string str = "129814999" ; int k = 4 ; string max = str ; findMaximumNum ( str , k , max ) ; cout << max << endl ; return 0 ; } |
Print all possible paths from top left to bottom right of a mXn matrix | C ++ program to Print all possible paths from top left to bottom right of a mXn matrix ; If we reach the bottom of maze , we can only move right ; path . append ( maze [ i ] [ k ] ) ; If we hit this block , it means one path is completed . Add it to paths list and print ; If we reach to the right most corner , we can only move down ; path . append ( maze [ j ] [ k ] ) If we hit this block , it means one path is completed . Add it to paths list and print ; Add current element to the path list path . append ( maze [ i ] [ j ] ) ; Move down in y direction and call findPathsUtil recursively ; Move down in y direction and call findPathsUtil recursively ; ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < vector < int > > allPaths ; void findPathsUtil ( vector < vector < int > > maze , int m , int n , int i , int j , vector < int > path , int indx ) { if ( i == m - 1 ) { for ( int k = j ; k < n ; k ++ ) { path [ indx + k - j ] = maze [ i ] [ k ] ; } cout << " [ " << path [ 0 ] << " , β " ; for ( int z = 1 ; z < path . size ( ) - 1 ; z ++ ) { cout << path [ z ] << " , β " ; } cout << path [ path . size ( ) - 1 ] << " ] " << endl ; allPaths . push_back ( path ) ; return ; } if ( j == n - 1 ) { for ( int k = i ; k < m ; k ++ ) { path [ indx + k - i ] = maze [ k ] [ j ] ; } cout << " [ " << path [ 0 ] << " , β " ; for ( int z = 1 ; z < path . size ( ) - 1 ; z ++ ) { cout << path [ z ] << " , β " ; } cout << path [ path . size ( ) - 1 ] << " ] " << endl ; allPaths . push_back ( path ) ; return ; } path [ indx ] = maze [ i ] [ j ] ; findPathsUtil ( maze , m , n , i + 1 , j , path , indx + 1 ) ; findPathsUtil ( maze , m , n , i , j + 1 , path , indx + 1 ) ; } void findPaths ( vector < vector < int > > maze , int m , int n ) { vector < int > path ( m + n - 1 , 0 ) ; findPathsUtil ( maze , m , n , 0 , 0 , path , 0 ) ; } int main ( ) { vector < vector < int > > maze { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; findPaths ( maze , 3 , 3 ) ; return 0 ; } |
Given an array A [ ] and a number x , check for pair in A [ ] with sum as x | * This C ++ program tells if there exists a pair in array whose sum results in x . ; Function to find and print pair ; Driver code | #include <iostream> NEW_LINE using namespace std ; bool chkPair ( int A [ ] , int size , int x ) { for ( int i = 0 ; i < ( size - 1 ) ; i ++ ) { for ( int j = ( i + 1 ) ; j < size ; j ++ ) { if ( A [ i ] + A [ j ] == x ) { cout << " Pair β with β a β given β sum β " << x << " β is β ( " << A [ i ] << " , β " << A [ j ] << " ) " << endl ; return 1 ; } } } return 0 ; } int main ( void ) { int A [ ] = { 0 , -1 , 2 , -3 , 1 } ; int x = -2 ; int size = sizeof ( A ) / sizeof ( A [ 0 ] ) ; if ( chkPair ( A , size , x ) ) { cout << " Valid β pair β exists " << endl ; } else { cout << " No β valid β pair β exists β for β " << x << endl ; } return 0 ; } |
Reduce the array by deleting elements which are greater than all elements to its left | C ++ program for the above approach ; Function to implement merging of arr [ ] ; Function to delete all elements which satisfy the condition A [ i ] > A [ i - 1 ] ; Divide array into its subarray ; Getting back merged array with all its right element greater than left one . ; Driver Code ; Given array arr [ ] | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > merge ( vector < int > x , vector < int > y ) { for ( auto i : y ) { if ( x [ x . size ( ) - 1 ] > i ) x . push_back ( i ) ; } return x ; } vector < int > mergeDel ( vector < int > l ) { if ( l . size ( ) == 1 ) return l ; int m = l . size ( ) / 2 ; vector < int > temp1 = { l . begin ( ) + 0 , l . begin ( ) + m } ; vector < int > temp2 = { l . begin ( ) + m , l . end ( ) } ; return merge ( mergeDel ( temp1 ) , mergeDel ( temp2 ) ) ; } int main ( ) { vector < int > arr ( { 5 , 4 , 3 , 2 , 1 } ) ; vector < int > ans = mergeDel ( arr ) ; cout << " [ β " ; for ( auto x : ans ) cout << x << " , β " ; cout << " ] " ; } |
Significant Inversions in an Array | C ++ implementation of the approach ; Function that sorts the input array and returns the number of inversions in the array ; Recursive function that sorts the input array and returns the number of inversions in the array ; Divide the array into two parts and call _mergeSortAndCountInv ( ) for each of the parts ; Inversion count will be sum of the inversions in the left - part , the right - part and the number of inversions in merging ; Merge the two parts ; Function that merges the two sorted arrays and returns the inversion count in the arrays ; i is the index for the left subarray ; j is the index for the right subarray ; k is the index for the resultant merged subarray ; First pass to count number of significant inversions ; i is the index for the left subarray ; j is the index for the right subarray ; k is the index for the resultant merged subarray ; Second pass to merge the two sorted arrays ; Copy the remaining elements of the left subarray ( if there are any ) to temp ; Copy the remaining elements of the right subarray ( if there are any ) to temp ; Copy back the merged elements to the original array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int _mergeSort ( int arr [ ] , int temp [ ] , int left , int right ) ; int merge ( int arr [ ] , int temp [ ] , int left , int mid , int right ) ; int mergeSort ( int arr [ ] , int array_size ) { int temp [ array_size ] ; return _mergeSort ( arr , temp , 0 , array_size - 1 ) ; } int _mergeSort ( int arr [ ] , int temp [ ] , int left , int right ) { int mid , inv_count = 0 ; if ( right > left ) { mid = ( right + left ) / 2 ; inv_count = _mergeSort ( arr , temp , left , mid ) ; inv_count += _mergeSort ( arr , temp , mid + 1 , right ) ; inv_count += merge ( arr , temp , left , mid + 1 , right ) ; } return inv_count ; } int merge ( int arr [ ] , int temp [ ] , int left , int mid , int right ) { int i , j , k ; int inv_count = 0 ; i = left ; j = mid ; k = left ; while ( ( i <= mid - 1 ) && ( j <= right ) ) { if ( arr [ i ] > 2 * arr [ j ] ) { inv_count += ( mid - i ) ; j ++ ; } else { i ++ ; } } i = left ; j = mid ; k = left ; while ( ( i <= mid - 1 ) && ( j <= right ) ) { if ( arr [ i ] <= arr [ j ] ) { temp [ k ++ ] = arr [ i ++ ] ; } else { temp [ k ++ ] = arr [ j ++ ] ; } } while ( i <= mid - 1 ) temp [ k ++ ] = arr [ i ++ ] ; while ( j <= right ) temp [ k ++ ] = arr [ j ++ ] ; for ( i = left ; i <= right ; i ++ ) arr [ i ] = temp [ i ] ; return inv_count ; } int main ( ) { int arr [ ] = { 1 , 20 , 6 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << mergeSort ( arr , n ) ; return 0 ; } |
Find the number of different numbers in the array after applying the given operation q times | CPP implementation for above approach ; To store the tree in lazy propagation ; To store the different numbers ; Function to update in the range [ x , y ) with given value ; check out of bound ; check for complete overlap ; find the mid number ; check for pending updates ; make lazy [ id ] = 0 , so that it has no pending updates ; call for two child nodes ; Function to find non - zero integers in the range [ l , r ) ; if id contains positive number ; There is no need to see the children , because all the interval have same number ; check for out of bound ; find the middle number ; call for two child nodes ; Driver code ; size of the array and number of queries ; Update operation for l , r , x , id , 0 , n ; Query operation to get answer in the range [ 0 , n - 1 ] ; Print the count of non - zero elements | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 100005 NEW_LINE int lazy [ 4 * N ] ; set < int > se ; void update ( int x , int y , int value , int id , int l , int r ) { if ( x >= r or l >= y ) return ; if ( x <= l && r <= y ) { lazy [ id ] = value ; return ; } int mid = ( l + r ) / 2 ; if ( lazy [ id ] ) lazy [ 2 * id ] = lazy [ 2 * id + 1 ] = lazy [ id ] ; lazy [ id ] = 0 ; update ( x , y , value , 2 * id , l , mid ) ; update ( x , y , value , 2 * id + 1 , mid , r ) ; } void query ( int id , int l , int r ) { if ( lazy [ id ] ) { se . insert ( lazy [ id ] ) ; return ; } if ( r - l < 2 ) return ; int mid = ( l + r ) / 2 ; query ( 2 * id , l , mid ) ; query ( 2 * id + 1 , mid , r ) ; } int main ( ) { int n = 5 , q = 3 ; update ( 1 , 4 , 1 , 1 , 0 , n ) ; update ( 0 , 2 , 2 , 1 , 0 , n ) ; update ( 3 , 4 , 3 , 1 , 0 , n ) ; query ( 1 , 0 , n ) ; cout << se . size ( ) << endl ; return 0 ; } |
Find Nth term ( A matrix exponentiation example ) | CPP program to find n - th term of a recursive function using matrix exponentiation . ; This power function returns first row of { Transformation Matrix } ^ n - 1 * Initial Vector ; This is an identity matrix . ; this is Transformation matrix . ; Matrix exponentiation to calculate power of { tMat } ^ n - 1 store res in " res " matrix . ; res store { Transformation matrix } ^ n - 1 hence will be first row of res * Initial Vector . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MOD 1000000009 NEW_LINE #define ll long long int NEW_LINE ll power ( ll n ) { if ( n <= 1 ) return 1 ; n -- ; ll res [ 2 ] [ 2 ] = { 1 , 0 , 0 , 1 } ; ll tMat [ 2 ] [ 2 ] = { 2 , 3 , 1 , 0 } ; while ( n ) { if ( n & 1 ) { ll tmp [ 2 ] [ 2 ] ; tmp [ 0 ] [ 0 ] = ( res [ 0 ] [ 0 ] * tMat [ 0 ] [ 0 ] + res [ 0 ] [ 1 ] * tMat [ 1 ] [ 0 ] ) % MOD ; tmp [ 0 ] [ 1 ] = ( res [ 0 ] [ 0 ] * tMat [ 0 ] [ 1 ] + res [ 0 ] [ 1 ] * tMat [ 1 ] [ 1 ] ) % MOD ; tmp [ 1 ] [ 0 ] = ( res [ 1 ] [ 0 ] * tMat [ 0 ] [ 0 ] + res [ 1 ] [ 1 ] * tMat [ 1 ] [ 0 ] ) % MOD ; tmp [ 1 ] [ 1 ] = ( res [ 1 ] [ 0 ] * tMat [ 0 ] [ 1 ] + res [ 1 ] [ 1 ] * tMat [ 1 ] [ 1 ] ) % MOD ; res [ 0 ] [ 0 ] = tmp [ 0 ] [ 0 ] ; res [ 0 ] [ 1 ] = tmp [ 0 ] [ 1 ] ; res [ 1 ] [ 0 ] = tmp [ 1 ] [ 0 ] ; res [ 1 ] [ 1 ] = tmp [ 1 ] [ 1 ] ; } n = n / 2 ; ll tmp [ 2 ] [ 2 ] ; tmp [ 0 ] [ 0 ] = ( tMat [ 0 ] [ 0 ] * tMat [ 0 ] [ 0 ] + tMat [ 0 ] [ 1 ] * tMat [ 1 ] [ 0 ] ) % MOD ; tmp [ 0 ] [ 1 ] = ( tMat [ 0 ] [ 0 ] * tMat [ 0 ] [ 1 ] + tMat [ 0 ] [ 1 ] * tMat [ 1 ] [ 1 ] ) % MOD ; tmp [ 1 ] [ 0 ] = ( tMat [ 1 ] [ 0 ] * tMat [ 0 ] [ 0 ] + tMat [ 1 ] [ 1 ] * tMat [ 1 ] [ 0 ] ) % MOD ; tmp [ 1 ] [ 1 ] = ( tMat [ 1 ] [ 0 ] * tMat [ 0 ] [ 1 ] + tMat [ 1 ] [ 1 ] * tMat [ 1 ] [ 1 ] ) % MOD ; tMat [ 0 ] [ 0 ] = tmp [ 0 ] [ 0 ] ; tMat [ 0 ] [ 1 ] = tmp [ 0 ] [ 1 ] ; tMat [ 1 ] [ 0 ] = tmp [ 1 ] [ 0 ] ; tMat [ 1 ] [ 1 ] = tmp [ 1 ] [ 1 ] ; } return ( res [ 0 ] [ 0 ] * 1 + res [ 0 ] [ 1 ] * 1 ) % MOD ; } int main ( ) { ll n = 3 ; cout << power ( n ) ; return 0 ; } |
Shuffle 2 n integers in format { a1 , b1 , a2 , b2 , a3 , b3 , ... ... , an , bn } without using extra space | C ++ Naive program to shuffle an array of size 2 n ; function to shuffle an array of size 2 n ; Rotate the element to the left ; swap a [ j - 1 ] , a [ j ] ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void shuffleArray ( int a [ ] , int n ) { for ( int i = 0 , q = 1 , k = n ; i < n ; i ++ , k ++ , q ++ ) for ( int j = k ; j > i + q ; j -- ) swap ( a [ j - 1 ] , a [ j ] ) ; } int main ( ) { int a [ ] = { 1 , 3 , 5 , 7 , 2 , 4 , 6 , 8 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; shuffleArray ( a , n / 2 ) ; for ( int i = 0 ; i < n ; i ++ ) cout << a [ i ] << " β " ; return 0 ; } |
Place k elements such that minimum distance is maximized | C ++ program to find largest minimum distance among k points . ; Returns true if it is possible to arrange k elements of arr [ 0. . n - 1 ] with minimum distance given as mid . ; Place first element at arr [ 0 ] position ; Initialize count of elements placed . ; Try placing k elements with minimum distance mid . ; Place next element if its distance from the previously placed element is greater than current mid ; Return if all elements are placed successfully ; Returns largest minimum distance for k elements in arr [ 0. . n - 1 ] . If elements can 't be placed, returns -1. ; Sort the positions ; Initialize result . ; Consider the maximum possible distance here we are using right value as highest distance difference , so we remove some extra checks ; Do binary search for largest minimum distance ; If it is possible to place k elements with minimum distance mid , search for higher distance . ; Change value of variable max to mid iff all elements can be successfully placed ; If not possible to place k elements , search for lower distance ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isFeasible ( int mid , int arr [ ] , int n , int k ) { int pos = arr [ 0 ] ; int elements = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] - pos >= mid ) { pos = arr [ i ] ; elements ++ ; if ( elements == k ) return true ; } } return 0 ; } int largestMinDist ( int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; int res = -1 ; int left = 1 , right = arr [ n - 1 ] ; while ( left < right ) { int mid = ( left + right ) / 2 ; if ( isFeasible ( mid , arr , n , k ) ) { res = max ( res , mid ) ; left = mid + 1 ; } else right = mid ; } return res ; } int main ( ) { int arr [ ] = { 1 , 2 , 8 , 4 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; cout << largestMinDist ( arr , n , k ) ; return 0 ; } |
Find frequency of each element in a limited range array in less than O ( n ) time | C ++ program to count number of occurrences of each element in the array # include < iostream > ; It prints number of occurrences of each element in the array . ; HashMap to store frequencies ; traverse the array ; update the frequency ; traverse the hashmap ; Driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findFrequency ( int arr [ ] , int n ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) { mp [ arr [ i ] ] ++ ; } for ( auto i : mp ) { cout << " Element β " << i . first << " β occurs β " << i . second << " β times " << endl ; } } int main ( ) { int arr [ ] = { 1 , 1 , 1 , 2 , 3 , 3 , 5 , 5 , 8 , 8 , 8 , 9 , 9 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findFrequency ( arr , n ) ; return 0 ; } |
Sine Rule with Derivation , Example and Implementation | C ++ program for the above approach ; Function to calculate remaining two sides ; Calculate angle B ; Convert angles to their respective radians for using trigonometric functions ; Sine rule ; Precision of 2 decimal spaces ; Print the answer ; Driver Code ; Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findSides ( double A , double C , double c ) { double B = 180 - ( A + C ) ; A = A * ( 3.14159 / 180 ) ; C = C * ( 3.14159 / 180 ) ; B = B * ( 3.14159 / 180 ) ; double a = ( c / sin ( C ) ) * sin ( A ) ; double b = ( c / sin ( C ) ) * sin ( B ) ; cout << fixed << setprecision ( 2 ) ; cout << a << endl ; cout << b << endl ; } int main ( ) { double A = 45.0 ; double C = 35.0 ; double c = 23 ; findSides ( A , C , c ) ; return 0 ; } |
Reverse alternate levels of a perfect binary tree | C ++ program to reverse alternate levels of a binary tree ; A Binary Tree node ; A utility function to create a new Binary Tree Node ; Function to store nodes of alternate levels in an array ; Base case ; Store elements of left subtree ; Store this node only if this is a odd level node ; Function to modify Binary Tree ( All odd level nodes areupdated by taking elements from array in inorder fashion ) ; Base case ; Update nodes in left subtree ; Update this node only if this is an odd level node ; Update nodes in right subtree ; A utility function to reverse an array from index 0 to n - 1 ; The main function to reverse alternate nodes of a binary tree ; Create an auxiliary array to store nodes of alternate levels ; First store nodes of alternate levels ; Reverse the array ; Update tree by taking elements from array ; A utility function to print indorder traversal of a binary tree ; Driver Program to test above functions | #include <bits/stdc++.h> NEW_LINE #define MAX 100 NEW_LINE using namespace std ; struct Node { char data ; struct Node * left , * right ; } ; struct Node * newNode ( char item ) { struct Node * temp = new Node ; temp -> data = item ; temp -> left = temp -> right = NULL ; return temp ; } void storeAlternate ( Node * root , char arr [ ] , int * index , int l ) { if ( root == NULL ) return ; storeAlternate ( root -> left , arr , index , l + 1 ) ; if ( l % 2 != 0 ) { arr [ * index ] = root -> data ; ( * index ) ++ ; } storeAlternate ( root -> right , arr , index , l + 1 ) ; } void modifyTree ( Node * root , char arr [ ] , int * index , int l ) { if ( root == NULL ) return ; modifyTree ( root -> left , arr , index , l + 1 ) ; if ( l % 2 != 0 ) { root -> data = arr [ * index ] ; ( * index ) ++ ; } modifyTree ( root -> right , arr , index , l + 1 ) ; } void reverse ( char arr [ ] , int n ) { int l = 0 , r = n - 1 ; while ( l < r ) { int temp = arr [ l ] ; arr [ l ] = arr [ r ] ; arr [ r ] = temp ; l ++ ; r -- ; } } void reverseAlternate ( struct Node * root ) { char * arr = new char [ MAX ] ; int index = 0 ; storeAlternate ( root , arr , & index , 0 ) ; reverse ( arr , index ) ; index = 0 ; modifyTree ( root , arr , & index , 0 ) ; } void printInorder ( struct Node * root ) { if ( root == NULL ) return ; printInorder ( root -> left ) ; cout << root -> data << " β " ; printInorder ( root -> right ) ; } int main ( ) { struct Node * root = newNode ( ' a ' ) ; root -> left = newNode ( ' b ' ) ; root -> right = newNode ( ' c ' ) ; root -> left -> left = newNode ( ' d ' ) ; root -> left -> right = newNode ( ' e ' ) ; root -> right -> left = newNode ( ' f ' ) ; root -> right -> right = newNode ( ' g ' ) ; root -> left -> left -> left = newNode ( ' h ' ) ; root -> left -> left -> right = newNode ( ' i ' ) ; root -> left -> right -> left = newNode ( ' j ' ) ; root -> left -> right -> right = newNode ( ' k ' ) ; root -> right -> left -> left = newNode ( ' l ' ) ; root -> right -> left -> right = newNode ( ' m ' ) ; root -> right -> right -> left = newNode ( ' n ' ) ; root -> right -> right -> right = newNode ( ' o ' ) ; cout << " Inorder β Traversal β of β given β tree STRNEWLINE " ; printInorder ( root ) ; reverseAlternate ( root ) ; cout << " Inorder Traversal of modified tree " ; printInorder ( root ) ; return 0 ; } |
Equation of a straight line passing through a point and making a given angle with a given line | C ++ program for the above approach ; Function to find slope of given line ; Special case when slope of line is infinity or is perpendicular to x - axis ; Function to find equations of lines passing through the given point and making an angle with given line ; Store slope of given line ; Convert degrees to radians ; Special case when slope of given line is infinity : In this case slope of one line will be equal to alfa and the other line will be equal to ( 180 - alfa ) ; In this case slope of required lines can 't be infinity ; g and f are the variables of required equations ; Print first line equation ; Print second line equation ; Special case when slope of required line becomes infinity ; General case ; g and f are the variables of required equations ; Print first line equation ; Print second line equation ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; double line_slope ( double a , double b ) { if ( a != 0 ) return - b / a ; else return ( -2 ) ; } void line_equation ( double a , double b , double c , double x1 , double y1 , double alfa ) { double given_slope = line_slope ( a , b ) ; double x = alfa * 3.14159 / 180 ; if ( given_slope == -2 ) { double slope_1 = tan ( x ) ; double slope_2 = tan ( 3.14159 - x ) ; int g = x1 , f = x1 ; g *= ( - slope_1 ) ; g += y1 ; if ( g > 0 ) cout << " y β = β " << slope_1 << " x β + " << g << endl ; if ( g <= 0 ) cout << " y β = β " << slope_1 << " x β " << g << endl ; f *= ( - slope_2 ) ; f += y1 ; if ( f > 0 ) { cout << " y β = β " << slope_2 << " x β + " << f << endl ; } if ( f <= 0 ) cout << " y β = β " << slope_2 << " x β " << f << endl ; return ; } if ( 1 - tan ( x ) * given_slope == 0 ) { cout << " x β = β " << x1 << endl ; } if ( 1 + tan ( x ) * given_slope == 0 ) { cout << " x β = β " << x1 << endl ; } double slope_1 = ( given_slope + tan ( x ) ) / ( 1 - tan ( x ) * given_slope ) ; double slope_2 = ( given_slope - tan ( x ) ) / ( 1 + tan ( x ) * given_slope ) ; int g = x1 , f = x1 ; g *= ( - slope_1 ) ; g += y1 ; if ( g > 0 && 1 - tan ( x ) * given_slope != 0 ) cout << " y β = β " << slope_1 << " x β + " << g << endl ; if ( g <= 0 && 1 - tan ( x ) * given_slope != 0 ) cout << " y β = β " << slope_1 << " x β " << g << endl ; f *= ( - slope_2 ) ; f += y1 ; if ( f > 0 && 1 + tan ( x ) * given_slope != 0 ) { cout << " y β = β " << slope_2 << " x β + " << f << endl ; } if ( f <= 0 && 1 + tan ( x ) * given_slope != 0 ) cout << " y β = β " << slope_2 << " x β " << f << endl ; } int main ( ) { double a = 2 , b = 3 , c = -7 ; double x1 = 4 , y1 = 9 ; double alfa = 30 ; line_equation ( a , b , c , x1 , y1 , alfa ) ; return 0 ; } cout << fixed << setprecision ( 2 ) ; |
Equation of a normal to a Circle from a given point | C ++ program for the above approach ; Function to calculate the slope ; Store the coordinates the center of the circle ; If slope becomes infinity ; Stores the slope ; If slope is zero ; Return the result ; Function to find the equation of the normal to a circle from a given point ; Stores the slope of the normal ; If slope becomes infinity ; If slope is zero ; Otherwise , print the equation of the normal ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; double normal_slope ( double a , double b , double x1 , double y1 ) { double g = a / 2 ; double f = b / 2 ; if ( g - x1 == 0 ) return ( -1 ) ; double slope = ( f - y1 ) / ( g - x1 ) ; if ( slope == 0 ) return ( -2 ) ; return slope ; } void normal_equation ( double a , double b , double x1 , double y1 ) { double slope = normal_slope ( a , b , x1 , y1 ) ; if ( slope == -1 ) { cout << " x β = β " << x1 ; } if ( slope == -2 ) { cout << " y β = β " << y1 ; } if ( slope != -1 && slope != -2 ) { x1 *= - slope ; x1 += y1 ; if ( x1 > 0 ) cout << " y β = β " << slope << " x β + β " << x1 ; else cout << " y β = β " << slope << " x β " << x1 ; } } int main ( ) { int a = 4 , b = 6 , c = 5 ; int x1 = 12 , y1 = 14 ; normal_equation ( a , b , x1 , y1 ) ; return 0 ; } |
Sum of squares of distances between all pairs from given points | C ++ program for the above approach ; Function to find the sum of squares of distance between all distinct pairs ; Stores final answer ; Traverse the array ; Adding the effect of this point for all the previous x - points ; Temporarily add the square of x - coordinate ; Add the effect of this point for all the previous y - points ; Print the desired answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findSquareSum ( int Coordinates [ ] [ 2 ] , int N ) { long long xq = 0 , yq = 0 ; long long xs = 0 , ys = 0 ; long long res = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int a , b ; a = Coordinates [ i ] [ 0 ] ; b = Coordinates [ i ] [ 1 ] ; res += xq ; res -= 2 * xs * a ; res += i * ( long long ) ( a * a ) ; xq += a * a ; xs += a ; res += yq ; res -= 2 * ys * b ; res += i * ( long long ) b * b ; yq += b * b ; ys += b ; } cout << res ; } int main ( ) { int arr [ ] [ 2 ] = { { 1 , 1 } , { -1 , -1 } , { 1 , -1 } , { -1 , 1 } } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findSquareSum ( arr , N ) ; return 0 ; } |
Count points from an array that lies inside a semi | C ++ program for above approach ; Traverse the array ; Stores if a point lies above the diameter or not ; Stores if the R is less than or equal to the distance between center and point ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getPointsIns ( int x1 , int y1 , int radius , int x2 , int y2 , vector < pair < int , int > > points ) { int ans = 0 ; for ( int i = 0 ; i < points . size ( ) ; i ++ ) { bool condOne = false , condTwo = false ; if ( ( points [ i ] . second - y2 ) * ( x2 - x1 ) - ( y2 - y1 ) * ( points [ i ] . first - x2 ) >= 0 ) { condOne = true ; } if ( radius >= ( int ) sqrt ( pow ( ( y1 - points [ i ] . second ) , 2 ) + pow ( x1 - points [ i ] . first , 2 ) ) ) { condTwo = true ; } if ( condOne && condTwo ) { ans += 1 ; } } return ans ; } int main ( ) { int X = 0 ; int Y = 0 ; int R = 5 ; int P = 5 ; int Q = 0 ; vector < pair < int , int > > arr = { make_pair ( 2 , 3 ) , make_pair ( 5 , 6 ) , make_pair ( -1 , 4 ) , make_pair ( 5 , 5 ) } ; cout << getPointsIns ( X , Y , R , P , Q , arr ) ; return 0 ; } |
Count pairs of points having distance between them equal to integral values in a K | C ++ program for the above approach ; Function to find pairs whose distance between the points of is an integer value . ; Stores count of pairs whose distance between points is an integer ; Traverse the array , points [ ] ; Stores distance between points ( i , j ) ; Traverse all the points of current pair ; Update temp ; Update dist ; If dist is a perfect square ; Update ans ; Driver Code ; Given value of K ; Given points ; Given value of N ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void cntPairs ( vector < vector < int > > points , int n , int K ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { int dist = 0 ; for ( int k = 0 ; k < K ; k ++ ) { int temp = ( points [ i ] [ k ] - points [ j ] [ k ] ) ; dist += temp * temp ; } if ( sqrt ( dist ) * sqrt ( dist ) == dist ) { ans += 1 ; } } } cout << ans << endl ; } int main ( ) { int K = 2 ; vector < vector < int > > points = { { 1 , 2 } , { 5 , 5 } , { -2 , 8 } } ; int n = points . size ( ) ; cntPairs ( points , n , K ) ; return 0 ; } |
Circumradius of a Cyclic Quadrilateral using the length of Sides | C ++ program to find circumradius of a cyclic quadrilateral using sides ; Function to return the circumradius of a cyclic quadrilateral using sides ; Find semiperimeter ; Calculate the radius ; Driver Code ; Function call ; Print the radius | #include <bits/stdc++.h> NEW_LINE using namespace std ; double Circumradius ( int a , int b , int c , int d ) { double s = ( a + b + c + d ) / 2.0 ; double radius = sqrt ( ( ( a * b ) + ( c * d ) ) * ( ( a * c ) + ( b * d ) ) * ( ( a * d ) + ( b * c ) ) / ( ( s - a ) * ( s - b ) * ( s - c ) * ( s - d ) ) ) ; return radius / 4 ; } int main ( ) { int A = 3 ; int B = 4 ; int C = 5 ; int D = 6 ; double ans = Circumradius ( A , B , C , D ) ; cout << setprecision ( 3 ) << ans ; return 0 ; } |
Area of Triangle using Side | C ++ program to calculate the area of a triangle when the length of two adjacent sides and the angle between them is provided ; Function to return the area of triangle using Side - Angle - Side formula ; Driver Code ; Function Call ; Print the final answer | #include <bits/stdc++.h> NEW_LINE using namespace std ; float Area_of_Triangle ( int a , int b , int k ) { float area = ( float ) ( ( 1 / 2.0 ) * a * b * ( sin ( k ) ) ) ; return area ; } int main ( ) { int a = 9 ; int b = 12 ; int k = 2 ; float ans = Area_of_Triangle ( a , b , k ) ; cout << ans << endl ; } |
Find if a point lies inside , outside or on the circumcircle of three points A , B , C | C ++ program to find the points which lies inside , outside or on the circle ; Structure Pointer to store x and y coordinates ; Function to find the line given two points ; Function which converts the input line to its perpendicular bisector . It also inputs the points whose mid - point lies o on the bisector ; Find the mid point ; x coordinates ; y coordinates ; c = - bx + ay ; Assign the coefficient of a and b ; Returns the intersection point of two lines ; Find determinant ; Returns the intersection point of two lines ; Find determinant ; Function to find the point lies inside , outside or on the circle ; Store the coordinates radius of circumcircle ; Line PQ is represented as ax + by = c ; Line QR is represented as ex + fy = g ; Converting lines PQ and QR to perpendicular bisectors . After this , L = ax + by = c M = ex + fy = g ; The point of intersection of L and M gives r as the circumcenter ; Length of radius ; Distance between radius and the given point D ; Condition for point lies inside circumcircle ; Condition for point lies on circumcircle ; Condition for point lies outside circumcircle ; Driver Code ; Given Points ; Function call to find the point lies inside , outside or on the circle | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct point { double x , y ; } ; void lineFromPoints ( point P , point Q , double & a , double & b , double & c ) { a = Q . y - P . y ; b = P . x - Q . x ; c = a * ( P . x ) + b * ( P . y ) ; } void perpenBisectorFromLine ( point P , point Q , double & a , double & b , double & c ) { point mid_point ; mid_point . x = ( P . x + Q . x ) / 2 ; mid_point . y = ( P . y + Q . y ) / 2 ; c = - b * ( mid_point . x ) + a * ( mid_point . y ) ; double temp = a ; a = - b ; b = temp ; } double LineInterX ( double a1 , double b1 , double c1 , double a2 , double b2 , double c2 ) { double determ = a1 * b2 - a2 * b1 ; double x = ( b2 * c1 - b1 * c2 ) ; x /= determ ; return x ; } double LineInterY ( double a1 , double b1 , double c1 , double a2 , double b2 , double c2 ) { double determ = a1 * b2 - a2 * b1 ; double y = ( a1 * c2 - a2 * c1 ) ; y /= determ ; return y ; } void findPosition ( point P , point Q , point R , point D ) { point r ; double a , b , c ; lineFromPoints ( P , Q , a , b , c ) ; double e , f , g ; lineFromPoints ( Q , R , e , f , g ) ; perpenBisectorFromLine ( P , Q , a , b , c ) ; perpenBisectorFromLine ( Q , R , e , f , g ) ; r . x = LineInterX ( a , b , c , e , f , g ) ; r . y = LineInterY ( a , b , c , e , f , g ) ; double q = ( r . x - P . x ) * ( r . x - P . x ) + ( r . y - P . y ) * ( r . y - P . y ) ; double dis = ( r . x - D . x ) * ( r . x - D . x ) + ( r . y - D . y ) * ( r . y - D . y ) ; if ( dis < q ) { cout << " Point β ( " << D . x << " , β " << D . y << " ) β is β inside β " << " the β circumcircle " ; } else if ( dis == q ) { cout << " Point β ( " << D . x << " , β " << D . y << " ) β lies β on β the β " << " circumcircle " ; } else { cout << " Point β ( " << D . x << " , β " << D . y << " ) β lies β outside " << " β the β circumcircle " ; } } int main ( ) { point A , B , C , D ; A = { 2 , 8 } ; B = { 2 , 1 } ; C = { 4 , 5 } ; D = { 3 , 0 } ; findPosition ( A , B , C , D ) ; return 0 ; } |
Find the maximum angle at which we can tilt the bottle without spilling any water | C ++ program to find the maximum angle at which we can tilt the bottle without spilling any water ; Now we have the volume of rectangular prism a * a * b ; Now we have 2 cases ! ; Taking the tangent inverse of value d As we want to take out the required angle ; Taking the tangent inverse of value d As we want to take out the required angle ; As of now the angle is in radian . So we have to convert it in degree . ; Driver Code ; Enter the Base square side length ; Enter the Height of rectangular prism ; Enter the Base square side length | #include <bits/stdc++.h> NEW_LINE using namespace std ; float find_angle ( int x , int y , int z ) { int volume = x * x * y ; float ans = 0 ; if ( z < volume / 2 ) { float d = ( x * y * y ) / ( 2.0 * z ) ; ans = atan ( d ) ; } else { z = volume - z ; float d = ( 2 * z ) / ( float ) ( x * x * x ) ; ans = atan ( d ) ; } ans = ( ans * 180 ) / 3.14159265 ; return ans ; } int main ( ) { int x = 12 ; int y = 21 ; int z = 10 ; cout << find_angle ( x , y , z ) << endl ; } |
Count of distinct rectangles inscribed in an equilateral triangle | C ++ implementation of the approach ; Function to return the count of rectangles when n is odd ; Calculating number of dots in vertical level ; Calculating number of ways to select two points in the horizontal level i ; Multiply both to obtain the number of rectangles formed at that level ; Calculating number of dots in vertical level ; Calculating number of ways to select two points in the horizontal level i ; Multiply both to obtain the number of rectangles formed at that level ; Function to return the count of rectangles when n is even ; Driver code ; If n is odd | #include <iostream> NEW_LINE using namespace std ; int countOdd ( int n ) { int coun = 0 , m , j , i ; for ( i = n - 2 ; i >= 1 ; i -- ) { if ( i & 1 ) { m = ( n - i ) / 2 ; j = ( i * ( i + 1 ) ) / 2 ; coun += j * m ; } else { m = ( ( n - 1 ) - i ) / 2 ; j = ( i * ( i + 1 ) ) / 2 ; coun += j * m ; } } return coun ; } int countEven ( int n ) { int coun = 0 , m , j , i ; for ( i = n - 2 ; i >= 1 ; i -- ) { if ( i & 1 ) { m = ( ( n - 1 ) - i ) / 2 ; j = ( i * ( i + 1 ) ) / 2 ; coun += j * m ; } else { m = ( n - i ) / 2 ; j = ( i * ( i + 1 ) ) / 2 ; coun += j * m ; } } return coun ; } int main ( ) { int n = 5 ; if ( n & 1 ) cout << countOdd ( n ) ; else cout << countEven ( n ) ; return 0 ; } |
Find same contacts in a list of contacts | A C ++ program to find same contacts in a list of contacts ; Structure for storing contact details . ; A utility function to fill entries in adjacency matrix representation of graph ; Initialize the adjacency matrix ; Traverse through all contacts ; Add mat from i to j and vice versa , if possible . Since length of each contact field is at max some constant . ( say 30 ) so body execution of this for loop takes constant time . ; A recuesive function to perform DFS with vertex i as source ; Finds similar contacrs in an array of contacts ; vector for storing the solution ; Declare 2D adjaceny matrix for mats ; visited array to keep track of visited nodes ; Fill adjacency matrix ; Since , we made a graph with contacts as nodes with fields as links . two nodes are linked if they represent the same person . so , total number of connected components and nodes in each component will be our answer . ; Add delimeter to separate nodes of one component from other . ; Print the solution ; Drive Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct contact { string field1 , field2 , field3 ; } ; void buildGraph ( contact arr [ ] , int n , int * mat [ ] ) { for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) mat [ i ] [ j ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) if ( arr [ i ] . field1 == arr [ j ] . field1 arr [ i ] . field1 == arr [ j ] . field2 arr [ i ] . field1 == arr [ j ] . field3 arr [ i ] . field2 == arr [ j ] . field1 arr [ i ] . field2 == arr [ j ] . field2 arr [ i ] . field2 == arr [ j ] . field3 arr [ i ] . field3 == arr [ j ] . field1 arr [ i ] . field3 == arr [ j ] . field2 arr [ i ] . field3 == arr [ j ] . field3 ) { mat [ i ] [ j ] = 1 ; mat [ j ] [ i ] = 1 ; break ; } } } void DFSvisit ( int i , int * mat [ ] , bool visited [ ] , vector < int > & sol , int n ) { visited [ i ] = true ; sol . push_back ( i ) ; for ( int j = 0 ; j < n ; j ++ ) if ( mat [ i ] [ j ] && ! visited [ j ] ) DFSvisit ( j , mat , visited , sol , n ) ; } void findSameContacts ( contact arr [ ] , int n ) { vector < int > sol ; int * * mat = new int * [ n ] ; for ( int i = 0 ; i < n ; i ++ ) mat [ i ] = new int [ n ] ; bool visited [ n ] ; memset ( visited , 0 , sizeof ( visited ) ) ; buildGraph ( arr , n , mat ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! visited [ i ] ) { DFSvisit ( i , mat , visited , sol , n ) ; sol . push_back ( -1 ) ; } } for ( int i = 0 ; i < sol . size ( ) ; i ++ ) if ( sol [ i ] == -1 ) cout << endl ; else cout << sol [ i ] << " β " ; } int main ( ) { contact arr [ ] = { { " Gaurav " , " gaurav @ gmail . com " , " gaurav @ gfgQA . com " } , { " Lucky " , " lucky @ gmail . com " , " + 1234567" } , { " gaurav123" , " + 5412312" , " gaurav123 @ skype . com " } , { " gaurav1993" , " + 5412312" , " gaurav @ gfgQA . com " } , { " raja " , " + 2231210" , " raja @ gfg . com " } , { " bahubali " , " + 878312" , " raja " } } ; int n = sizeof arr / sizeof arr [ 0 ] ; findSameContacts ( arr , n ) ; return 0 ; } |
Area of the biggest ellipse inscribed within a rectangle | C ++ Program to find the biggest ellipse which can be inscribed within the rectangle ; Function to find the area of the ellipse ; The sides cannot be negative ; Area of the ellipse ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; float ellipse ( float l , float b ) { if ( l < 0 b < 0 ) return -1 ; float x = ( 3.14 * l * b ) / 4 ; return x ; } int main ( ) { float l = 5 , b = 3 ; cout << ellipse ( l , b ) << endl ; return 0 ; } |
Determine the number of squares of unit area that a given line will pass through . | ; Function to return the required position ; Driver Code | / * C ++ program to determine the number of squares that line will pass through * #include < bits / stdc ++ . h > using namespace std ; int noOfSquares ( int x1 , int y1 , int x2 , int y2 ) { int dx = abs ( x2 - x1 ) ; int dy = abs ( y2 - y1 ) ; int ans = dx + dy - __gcd ( dx , dy ) ; cout << ans ; } int main ( ) { int x1 = 1 , y1 = 1 , x2 = 4 , y2 = 3 ; noOfSquares ( x1 , y1 , x2 , y2 ) ; return 0 ; } |
Count paths with distance equal to Manhattan distance | C ++ implementation of the approach ; Function to return the value of nCk ; Since C ( n , k ) = C ( n , n - k ) ; Calculate value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; Function to return the number of paths ; Difference between the ' x ' coordinates of the given points ; Difference between the ' y ' coordinates of the given points ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE ll binomialCoeff ( int n , int k ) { ll res = 1 ; if ( k > n - k ) k = n - k ; for ( int i = 0 ; i < k ; ++ i ) { res *= ( n - i ) ; res /= ( i + 1 ) ; } return res ; } ll countPaths ( int x1 , int y1 , int x2 , int y2 ) { int m = abs ( x1 - x2 ) ; int n = abs ( y1 - y2 ) ; return ( binomialCoeff ( m + n , n ) ) ; } int main ( ) { int x1 = 2 , y1 = 3 , x2 = 4 , y2 = 5 ; cout << countPaths ( x1 , y1 , x2 , y2 ) ; return 0 ; } |
Find the area of largest circle inscribed in ellipse | CPP program to find the area of the circle ; Area of the Reuleaux triangle ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define pi 3.1415926 NEW_LINE double areaCircle ( double b ) { double area = pi * b * b ; return area ; } int main ( ) { double a = 10 , b = 8 ; cout << areaCircle ( b ) ; return 0 ; } |
Section formula for 3 D | CPP program to find point that divides given line in given ratio in 3D . ; Function to find the section of the line ; Applying section formula ; Printing result ; Driver code | #include <iostream> NEW_LINE using namespace std ; void section ( double x1 , double x2 , double y1 , double y2 , double z1 , double z2 , double m , double n ) { double x = ( ( m * x2 ) + ( n * x1 ) ) / ( m + n ) ; double y = ( ( m * y2 ) + ( n * y1 ) ) / ( m + n ) ; double z = ( ( m * z2 ) + ( n * z1 ) ) / ( m + n ) ; cout << " ( " << x << " , β " ; cout << y << " , β " ; cout << z << " ) " << endl ; } int main ( ) { double x1 = 2 , x2 = 4 , y1 = -1 , y2 = 3 , z1 = 4 , z2 = 2 , m = 2 , n = 3 ; section ( x1 , x2 , y1 , y2 , z1 , z2 , m , n ) ; return 0 ; } |
Program to find the Circumcircle of any regular polygon | C ++ Program to find the radius of the circumcircle of the given polygon ; Function to find the radius of the circumcircle ; these cannot be negative ; Radius of the circumcircle ; Return the radius ; Driver code ; Find the radius of the circumcircle | #include <bits/stdc++.h> NEW_LINE using namespace std ; float findRadiusOfcircumcircle ( float n , float a ) { if ( n < 0 a < 0 ) return -1 ; float radius = a / sqrt ( 2 - ( 2 * cos ( 360 / n ) ) ) ; return radius ; } int main ( ) { float n = 5 , a = 6 ; cout << findRadiusOfcircumcircle ( n , a ) << endl ; return 0 ; } |
Program to find the Radius of the incircle of the triangle | C ++ Program to find the radius of the incircle of the given triangle ; Function to find the radius of the incircle ; the sides cannot be negative ; semi - perimeter of the circle ; area of the triangle ; Radius of the incircle ; Return the radius ; Driver code ; Get the sides of the triangle ; Find the radius of the incircle | #include <bits/stdc++.h> NEW_LINE using namespace std ; float findRadiusOfIncircle ( float a , float b , float c ) { if ( a < 0 b < 0 c < 0 ) return -1 ; float p = ( a + b + c ) / 2 ; float area = sqrt ( p * ( p - a ) * ( p - b ) * ( p - c ) ) ; float radius = area / p ; return radius ; } int main ( ) { float a = 2 , b = 2 , c = 3 ; cout << findRadiusOfIncircle ( a , b , c ) << endl ; return 0 ; } |
Find area of triangle if two vectors of two adjacent sides are given | C ++ program to calculate area of triangle if vectors of 2 adjacent sides are given ; function to calculate area of triangle ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; float area ( int x1 , int y1 , int z1 , int x2 , int y2 , int z2 ) { float area = sqrt ( pow ( ( y1 * z2 - y2 * z1 ) , 2 ) + pow ( ( x1 * z2 - x2 * z1 ) , 2 ) + pow ( ( x1 * y2 - x2 * y1 ) , 2 ) ) ; area = area / 2 ; return area ; } int main ( ) { int x1 = -2 ; int y1 = 0 ; int z1 = -5 ; int x2 = 1 ; int y2 = -2 ; int z2 = -1 ; float a = area ( x1 , y1 , z1 , x2 , y2 , z2 ) ; cout << " Area β = β " << a << endl ; return 0 ; } |
Largest trapezoid that can be inscribed in a semicircle | C ++ Program to find the biggest trapezoid which can be inscribed within the semicircle ; Function to find the area of the biggest trapezoid ; the radius cannot be negative ; area of the trapezoid ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; float trapezoidarea ( float r ) { if ( r < 0 ) return -1 ; float a = ( 3 * sqrt ( 3 ) * pow ( r , 2 ) ) / 4 ; return a ; } int main ( ) { float r = 5 ; cout << trapezoidarea ( r ) << endl ; return 0 ; } |
Largest rectangle that can be inscribed in a semicircle | C ++ Program to find the the biggest rectangle which can be inscribed within the semicircle ; Function to find the area of the biggest rectangle ; the radius cannot be negative ; area of the rectangle ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; float rectanglearea ( float r ) { if ( r < 0 ) return -1 ; float a = r * r ; return a ; } int main ( ) { float r = 5 ; cout << rectanglearea ( r ) << endl ; return 0 ; } |
Maximum distinct lines passing through a single point | C ++ program to find maximum number of lines which can pass through a single point ; function to find maximum lines which passes through a single point ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxLines ( int n , int x1 [ ] , int y1 [ ] , int x2 [ ] , int y2 [ ] ) { unordered_set < double > s ; double slope ; for ( int i = 0 ; i < n ; ++ i ) { if ( x1 [ i ] == x2 [ i ] ) slope = INT_MAX ; else slope = ( y2 [ i ] - y1 [ i ] ) * 1.0 / ( x2 [ i ] - x1 [ i ] ) * 1.0 ; s . insert ( slope ) ; } return s . size ( ) ; } int main ( ) { int n = 2 , x1 [ ] = { 1 , 2 } , y1 [ ] = { 1 , 2 } , x2 [ ] = { 2 , 4 } , y2 [ ] = { 2 , 10 } ; cout << maxLines ( n , x1 , y1 , x2 , y2 ) ; return 0 ; } |
Find area of parallelogram if vectors of two adjacent sides are given | C ++ code to calculate area of parallelogram if vectors of 2 adjacent sides are given ; Function to calculate area of parallelogram ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; float area ( float x1 , float y1 , float z1 , float x2 , float y2 , float z2 ) { float area = sqrt ( pow ( ( y1 * z2 - y2 * z1 ) , 2 ) + pow ( ( x1 * z2 - x2 * z1 ) , 2 ) + pow ( ( x1 * y2 - x2 * y1 ) , 2 ) ) ; return area ; } int main ( ) { float x1 = 3 ; float y1 = 1 ; float z1 = -2 ; float x2 = 1 ; float y2 = -3 ; float z2 = 4 ; float a = area ( x1 , y1 , z1 , x2 , y2 , z2 ) ; cout << " Area β = β " << a ; return 0 ; } |
Maximum possible intersection by moving centers of line segments | Function to print the maximum intersection ; Case 1 ; Case 2 ; Case 3 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int max_intersection ( int * center , int length , int k ) { sort ( center , center + 3 ) ; if ( center [ 2 ] - center [ 0 ] >= 2 * k + length ) { return 0 ; } else if ( center [ 2 ] - center [ 0 ] >= 2 * k ) { return ( 2 * k - ( center [ 2 ] - center [ 0 ] - length ) ) ; } else return length ; } int main ( ) { int center [ 3 ] = { 1 , 2 , 3 } ; int L = 1 ; int K = 1 ; cout << max_intersection ( center , L , K ) ; } |
Haversine formula to find distance between two points on a sphere | C ++ program for the haversine formula C ++ program for the haversine formula ; distance between latitudes and longitudes ; convert to radians ; apply formulae ; Driver code | #include <iostream> NEW_LINE #include <cmath> NEW_LINE using namespace std ; static double haversine ( double lat1 , double lon1 , double lat2 , double lon2 ) { double dLat = ( lat2 - lat1 ) * M_PI / 180.0 ; double dLon = ( lon2 - lon1 ) * M_PI / 180.0 ; lat1 = ( lat1 ) * M_PI / 180.0 ; lat2 = ( lat2 ) * M_PI / 180.0 ; double a = pow ( sin ( dLat / 2 ) , 2 ) + pow ( sin ( dLon / 2 ) , 2 ) * cos ( lat1 ) * cos ( lat2 ) ; double rad = 6371 ; double c = 2 * asin ( sqrt ( a ) ) ; return rad * c ; } int main ( ) { double lat1 = 51.5007 ; double lon1 = 0.1246 ; double lat2 = 40.6892 ; double lon2 = 74.0445 ; cout << haversine ( lat1 , lon1 , lat2 , lon2 ) << " β K . M . " ; return 0 ; } |
Pentatope number | C ++ Program to find the nth Pentatope Number ; Function that returns nth pentatope number ; Drivers Code ; For 5 th PentaTope Number ; For 11 th PentaTope Number | #include <bits/stdc++.h> NEW_LINE using namespace std ; int pentatopeNum ( int n ) { return ( n * ( n + 1 ) * ( n + 2 ) * ( n + 3 ) ) / 24 ; } int main ( ) { int n = 5 ; cout << pentatopeNum ( n ) << endl ; n = 11 ; cout << pentatopeNum ( n ) << endl ; return 0 ; } |
Heptagonal number | C ++ program to find the nth Heptagonal number ; Function to return Nth Heptagonal number ; Drivers Code | #include <iostream> NEW_LINE using namespace std ; int heptagonalNumber ( int n ) { return ( ( 5 * n * n ) - ( 3 * n ) ) / 2 ; } int main ( ) { int n = 2 ; cout << heptagonalNumber ( n ) << endl ; n = 15 ; cout << heptagonalNumber ( n ) << endl ; return 0 ; } |
Icosidigonal number | C ++ program to find nth Icosidigonal number ; Function to calculate Icosidigonal number ; Formula for finding nth Icosidigonal number ; Driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int icosidigonal_num ( long int n ) { return ( 20 * n * n - 18 * n ) / 2 ; } int main ( ) { long int n = 4 ; cout << n << " th β Icosidigonal β number β : " << icosidigonal_num ( n ) ; cout << endl ; n = 8 ; cout << n << " th β Icosidigonal β number : " << icosidigonal_num ( n ) ; return 0 ; } |
Hypercube Graph | C ++ program to find vertices in a hypercube graph of order n ; function to find power of 2 ; driver program | #include <iostream> NEW_LINE using namespace std ; int power ( int n ) { if ( n == 1 ) return 2 ; return 2 * power ( n - 1 ) ; } int main ( ) { int n = 4 ; cout << power ( n ) ; return 0 ; } |
Reflection of a point at 180 degree rotation of another point | CPP Program tof find the 180 degree reflection of one point around another point . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findPoint ( int x1 , int y1 , int x2 , int y2 ) { cout << " ( " << 2 * x2 - x1 << " , β " << 2 * y2 - y1 << " ) " ; } int main ( ) { int x1 = 0 , y1 = 0 , x2 = 1 , y2 = 1 ; findPoint ( x1 , y1 , x2 , y2 ) ; return 0 ; } |
Program to check if the points are parallel to X axis or Y axis | CPP program to check for parallel to X and Y Axis ; To check for parallel line ; checking for parallel to X and Y axis condition ; To display the output ; Driver 's Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void parallel ( int n , int a [ ] [ 2 ] ) { bool x = true , y = true ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( a [ i ] [ 0 ] != a [ i + 1 ] [ 0 ] ) x = false ; if ( a [ i ] [ 1 ] != a [ i + 1 ] [ 1 ] ) y = false ; } if ( x ) cout << " parallel β to β Y β Axis " << endl ; else if ( y ) cout << " parallel β to β X β Axis " << endl ; else cout << " Not β parallel β to β X " << " β and β Y β Axis " << endl ; } int main ( ) { int a [ ] [ 2 ] = { { 1 , 2 } , { 1 , 4 } , { 1 , 6 } , { 1 , 0 } } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; parallel ( n , a ) ; return 0 ; } |
Triangular Matchstick Number | C ++ program to find X - th triangular matchstick number ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int numberOfSticks ( int x ) { return ( 3 * x * ( x + 1 ) ) / 2 ; } int main ( ) { cout << numberOfSticks ( 7 ) ; return 0 ; } |
Total area of two overlapping rectangles | C ++ program to find total area of two overlapping Rectangles ; Returns Total Area of two overlap rectangles ; Area of 1 st Rectangle ; Area of 2 nd Rectangle ; Length of intersecting part i . e start from max ( l1 . x , l2 . x ) of x - coordinate and end at min ( r1 . x , r2 . x ) x - coordinate by subtracting start from end we get required lengths ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Point { int x , y ; } ; int overlappingArea ( Point l1 , Point r1 , Point l2 , Point r2 ) { int area1 = abs ( l1 . x - r1 . x ) * abs ( l1 . y - r1 . y ) ; int area2 = abs ( l2 . x - r2 . x ) * abs ( l2 . y - r2 . y ) ; int x_dist = min ( r1 . x , r2 . x ) - max ( l1 . x , l2 . x ) ; int y_dist = ( min ( r1 . y , r2 . y ) - max ( l1 . y , l2 . y ) ) ; int areaI = 0 ; if ( x_dist > 0 && y_dist > 0 ) { areaI = x_dist * y_dist ; } return ( area1 + area2 - areaI ) ; } int main ( ) { Point l1 = { 2 , 2 } , r1 = { 5 , 7 } ; Point l2 = { 3 , 4 } , r2 = { 6 , 9 } ; cout << overlappingArea ( l1 , r1 , l2 , r2 ) ; return 0 ; } |
Area of square Circumscribed by Circle | C ++ program to find Area of square Circumscribed by Circle ; Function to find area of square ; Driver code ; Radius of a circle ; Call Function to find an area of square | #include <iostream> NEW_LINE using namespace std ; int find_Area ( int r ) { return ( 2 * r * r ) ; } int main ( ) { int r = 3 ; cout << " β Area β of β square β = β " << find_Area ( r ) ; return 0 ; } |
Check whether triangle is valid or not if sides are given | C ++ program to check if three sides form a triangle or not ; function to check if three sider form a triangle or not ; check condition ; Driver function ; function calling and print output | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkValidity ( int a , int b , int c ) { if ( a + b <= c a + c <= b b + c <= a ) return false ; else return true ; } int main ( ) { int a = 7 , b = 10 , c = 5 ; if ( checkValidity ( a , b , c ) ) cout << " Valid " ; else cout << " Invalid " ; } |
Print Longest Palindromic Subsequence | CPP program to print longest palindromic subsequence ; Returns LCS X and Y ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains length of LCS of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] ; Following code is used to print LCS ; Create a string length index + 1 and fill it with \ 0 ; Start from the right - most - bottom - most corner and one by one store characters in lcs [ ] ; If current character in X [ ] and Y are same , then current character is part of LCS ; Put current character in result ; reduce values of i , j and index ; If not same , then find the larger of two and go in the direction of larger value ; Returns longest palindromic subsequence of str ; Find reverse of str ; Return LCS of str and its reverse ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; string lcs ( string & X , string & Y ) { int m = X . length ( ) ; int n = Y . length ( ) ; int L [ m + 1 ] [ n + 1 ] ; for ( int i = 0 ; i <= m ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) L [ i ] [ j ] = 0 ; else if ( X [ i - 1 ] == Y [ j - 1 ] ) L [ i ] [ j ] = L [ i - 1 ] [ j - 1 ] + 1 ; else L [ i ] [ j ] = max ( L [ i - 1 ] [ j ] , L [ i ] [ j - 1 ] ) ; } } int index = L [ m ] [ n ] ; string lcs ( index + 1 , ' \0' ) ; int i = m , j = n ; while ( i > 0 && j > 0 ) { if ( X [ i - 1 ] == Y [ j - 1 ] ) { lcs [ index - 1 ] = X [ i - 1 ] ; i -- ; j -- ; index -- ; } else if ( L [ i - 1 ] [ j ] > L [ i ] [ j - 1 ] ) i -- ; else j -- ; } return lcs ; } string longestPalSubseq ( string & str ) { string rev = str ; reverse ( rev . begin ( ) , rev . end ( ) ) ; return lcs ( str , rev ) ; } int main ( ) { string str = " GEEKSFORGEEKS " ; cout << longestPalSubseq ( str ) ; return 0 ; } |
Find the Surface area of a 3D figure | CPP program to find the Surface area of a 3D figure ; Declaring the size of the matrix ; Absolute Difference between the height of two consecutive blocks ; Function To calculate the Total surfaceArea . ; Traversing the matrix . ; If we are traveling the topmost row in the matrix , we declare the wall above it as 0 as there is no wall above it . ; If we are traveling the leftmost column in the matrix , we declare the wall left to it as 0 as there is no wall left it . ; If its not the topmost row ; If its not the leftmost column ; Summing up the contribution of by the current block ; If its the rightmost block of the matrix it will contribute area equal to its height as a wall on the right of the figure ; If its the lowest block of the matrix it will contribute area equal to its height as a wall on the bottom of the figure ; Adding the contribution by the base and top of the figure ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int M = 3 ; const int N = 3 ; int contribution_height ( int current , int previous ) { return abs ( current - previous ) ; } int surfaceArea ( int A [ N ] [ M ] ) { int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { int up = 0 ; int left = 0 ; if ( i > 0 ) up = A [ i - 1 ] [ j ] ; if ( j > 0 ) left = A [ i ] [ j - 1 ] ; ans += contribution_height ( A [ i ] [ j ] , up ) + contribution_height ( A [ i ] [ j ] , left ) ; if ( i == N - 1 ) ans += A [ i ] [ j ] ; if ( j == M - 1 ) ans += A [ i ] [ j ] ; } } ans += N * M * 2 ; return ans ; } int main ( ) { int A [ N ] [ M ] = { { 1 , 3 , 4 } , { 2 , 2 , 3 } , { 1 , 2 , 4 } } ; cout << surfaceArea ( A ) << endl ; return 0 ; } |
Program to calculate area and volume of a Tetrahedron | C ++ Program to Calculate area of tetrahedron ; Utility Function ; Driver Code | #include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; double area_of_tetrahedron ( int side ) { return ( sqrt ( 3 ) * ( side * side ) ) ; } int main ( ) { int side = 3 ; cout << " Area β of β Tetrahedron β = " << area_of_tetrahedron ( side ) ; } |
Program to calculate area and volume of a Tetrahedron | C ++ code to find the volume of a tetrahedron ; Function to calculate volume ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; double vol_tetra ( int side ) { double volume = ( pow ( side , 3 ) / ( 6 * sqrt ( 2 ) ) ) ; return volume ; } int main ( ) { int side = 3 ; double vol = vol_tetra ( side ) ; vol = ( double ) round ( vol * 100 ) / 100 ; cout << vol ; return 0 ; } |
Counting pairs when a person can form pair with at most one | Number of ways in which participant can take part . ; Driver code | #include <iostream> NEW_LINE using namespace std ; int numberOfWays ( int x ) { int dp [ x + 1 ] ; dp [ 0 ] = dp [ 1 ] = 1 ; for ( int i = 2 ; i <= x ; i ++ ) dp [ i ] = dp [ i - 1 ] + ( i - 1 ) * dp [ i - 2 ] ; return dp [ x ] ; } int main ( ) { int x = 3 ; cout << numberOfWays ( x ) << endl ; return 0 ; } |
Program to find slope of a line | C ++ program for slope of line ; function to find the slope of a straight line ; driver code to check the above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; float slope ( float x1 , float y1 , float x2 , float y2 ) { if ( x1 == x2 ) return INT_MAX ; return ( y2 - y1 ) / ( x2 - x1 ) ; } int main ( ) { float x1 = 4 , y1 = 2 ; float x2 = 2 , y2 = 5 ; cout << " Slope β is : β " << slope ( x1 , y1 , x2 , y2 ) ; return 0 ; } |
Program to calculate area and perimeter of equilateral triangle | CPP program to find area and perimeter of equilateral triangle ; Function to calculate Area of equilateral triangle ; Function to calculate Perimeter of equilateral triangle ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; float area_equi_triangle ( float side ) { return sqrt ( 3 ) / 4 * side * side ; } float peri_equi_triangle ( float side ) { return 3 * side ; } int main ( ) { float side = 4 ; cout << " Area β of β Equilateral β Triangle : β " << area_equi_triangle ( side ) << endl ; cout << " Perimeter β of β Equilateral β Triangle : β " << peri_equi_triangle ( side ) ; return 0 ; } |
Maximum integral co | C ++ program to find maximum integral points such that distances between any two is not integer . ; Making set of coordinates such that any two points are non - integral distance apart ; used to avoid duplicates in result ; Driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printSet ( int x , int y ) { set < pair < int , int > > arr ; for ( int i = 0 ; i <= min ( x , y ) ; i ++ ) { pair < int , int > pq ; pq = make_pair ( i , min ( x , y ) - i ) ; arr . insert ( pq ) ; } for ( auto it = arr . begin ( ) ; it != arr . end ( ) ; it ++ ) cout << ( * it ) . first << " β " << ( * it ) . second << endl ; } int main ( ) { int x = 4 , y = 4 ; printSet ( x , y ) ; return 0 ; } |
Program for Volume and Surface Area of Cuboid | CPP program to find volume and total surface area of cuboid ; utility function ; driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; double areaCuboid ( double l , double h , double w ) { return ( l * h * w ) ; } double surfaceAreaCuboid ( double l , double h , double w ) { return ( 2 * l * w + 2 * w * h + 2 * l * h ) ; } int main ( ) { double l = 1 ; double h = 5 ; double w = 7 ; cout << " Area β = β " << areaCuboid ( l , h , w ) << endl ; cout << " Total β Surface β Area β = β " << surfaceAreaCuboid ( l , h , w ) ; return 0 ; } |
Program to find Circumference of a Circle | CPP program to find circumference of circle ; utility function ; driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define PI 3.1415 NEW_LINE double circumference ( double r ) { double cir = 2 * PI * r ; return cir ; } int main ( ) { double r = 5 ; cout << " Circumference β = β " << circumference ( r ) ; return 0 ; } |
Number of rectangles in N * M grid | C ++ program to count number of rectangles in a n x m grid ; driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int rectCount ( int n , int m ) { return ( m * n * ( n + 1 ) * ( m + 1 ) ) / 4 ; } int main ( ) { int n = 5 , m = 4 ; cout << rectCount ( n , m ) ; return 0 ; } |
Number of unique rectangles formed using N unit squares | C ++ program to count rotationally equivalent rectangles with n unit squares ; height >= length is maintained ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countRect ( int n ) { int ans = 0 ; for ( int length = 1 ; length <= sqrt ( n ) ; ++ length ) for ( int height = length ; height * length <= n ; ++ height ) ans ++ ; return ans ; } int main ( ) { int n = 5 ; printf ( " % d " , countRect ( n ) ) ; return 0 ; } |
Find the Missing Point of Parallelogram | C ++ program to find missing point of a parallelogram ; main method ; coordinates of A ; coordinates of B ; coordinates of C | #include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { int ax = 5 , ay = 0 ; int bx = 1 , by = 1 ; int cx = 2 , cy = 5 ; cout << ax + cx - bx << " , β " << ay + cy - by ; return 0 ; } |
Represent a given set of points by the best possible straight line | C ++ Program to find m and c for a straight line given , x and y ; function to calculate m and c that best fit points represented by x [ ] and y [ ] ; Driver main function | #include <cmath> NEW_LINE #include <iostream> NEW_LINE using namespace std ; void bestApproximate ( int x [ ] , int y [ ] , int n ) { float m , c , sum_x = 0 , sum_y = 0 , sum_xy = 0 , sum_x2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum_x += x [ i ] ; sum_y += y [ i ] ; sum_xy += x [ i ] * y [ i ] ; sum_x2 += pow ( x [ i ] , 2 ) ; } m = ( n * sum_xy - sum_x * sum_y ) / ( n * sum_x2 - pow ( sum_x , 2 ) ) ; c = ( sum_y - m * sum_x ) / n ; cout << " m β = " << m ; cout << " c = " } int main ( ) { int x [ ] = { 1 , 2 , 3 , 4 , 5 } ; int y [ ] = { 14 , 27 , 40 , 55 , 68 } ; int n = sizeof ( x ) / sizeof ( x [ 0 ] ) ; bestApproximate ( x , y , n ) ; return 0 ; } |
Check for star graph | CPP to find whether given graph is star or not ; define the size of incidence matrix ; function to find star graph ; initialize number of vertex with deg 1 and n - 1 ; check for S1 ; check for S2 ; check for Sn ( n > 2 ) ; driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define size 4 NEW_LINE bool checkStar ( int mat [ ] [ size ] ) { int vertexD1 = 0 , vertexDn_1 = 0 ; if ( size == 1 ) return ( mat [ 0 ] [ 0 ] == 0 ) ; if ( size == 2 ) return ( mat [ 0 ] [ 0 ] == 0 && mat [ 0 ] [ 1 ] == 1 && mat [ 1 ] [ 0 ] == 1 && mat [ 1 ] [ 1 ] == 0 ) ; for ( int i = 0 ; i < size ; i ++ ) { int degreeI = 0 ; for ( int j = 0 ; j < size ; j ++ ) if ( mat [ i ] [ j ] ) degreeI ++ ; if ( degreeI == 1 ) vertexD1 ++ ; else if ( degreeI == size - 1 ) vertexDn_1 ++ ; } return ( vertexD1 == ( size - 1 ) && vertexDn_1 == 1 ) ; } int main ( ) { int mat [ size ] [ size ] = { { 0 , 1 , 1 , 1 } , { 1 , 0 , 0 , 0 } , { 1 , 0 , 0 , 0 } , { 1 , 0 , 0 , 0 } } ; checkStar ( mat ) ? cout << " Star β Graph " : cout << " Not β a β Star β Graph " ; return 0 ; } |
Dynamic Convex hull | Adding Points to an Existing Convex Hull | C ++ program to add given a point p to a given convext hull . The program assumes that the point of given convext hull are in anti - clockwise order . ; checks whether the point crosses the convex hull or not ; Returns the square of distance between two input points ; Checks whether the point is inside the convex hull or not ; Initialize the centroid of the convex hull ; Multiplying with n to avoid floating point arithmetic . ; if the mid and the given point lies always on the same side w . r . t every edge of the convex hull , then the point lies inside the convex hull ; Adds a point p to given convex hull a [ ] ; If point is inside p ; point having minimum distance from the point p ; Find the upper tangent ; Find the lower tangent ; Initialize result ; making the final hull by traversing points from up to low of given convex hull . ; Modify the original vector ; Driver code ; the set of points in the convex hull ; Print the modified Convex Hull | #include <bits/stdc++.h> NEW_LINE using namespace std ; int orientation ( pair < int , int > a , pair < int , int > b , pair < int , int > c ) { int res = ( b . second - a . second ) * ( c . first - b . first ) - ( c . second - b . second ) * ( b . first - a . first ) ; if ( res == 0 ) return 0 ; if ( res > 0 ) return 1 ; return -1 ; } int sqDist ( pair < int , int > p1 , pair < int , int > p2 ) { return ( p1 . first - p2 . first ) * ( p1 . first - p2 . first ) + ( p1 . second - p2 . second ) * ( p1 . second - p2 . second ) ; } bool inside ( vector < pair < int , int > > a , pair < int , int > p ) { pair < int , int > mid = { 0 , 0 } ; int n = a . size ( ) ; p . first *= n ; p . second *= n ; for ( int i = 0 ; i < n ; i ++ ) { mid . first += a [ i ] . first ; mid . second += a [ i ] . second ; a [ i ] . first *= n ; a [ i ] . second *= n ; } for ( int i = 0 , j ; i < n ; i ++ ) { j = ( i + 1 ) % n ; int x1 = a [ i ] . first , x2 = a [ j ] . first ; int y1 = a [ i ] . second , y2 = a [ j ] . second ; int a1 = y1 - y2 ; int b1 = x2 - x1 ; int c1 = x1 * y2 - y1 * x2 ; int for_mid = a1 * mid . first + b1 * mid . second + c1 ; int for_p = a1 * p . first + b1 * p . second + c1 ; if ( for_mid * for_p < 0 ) return false ; } return true ; } void addPoint ( vector < pair < int , int > > & a , pair < int , int > p ) { if ( inside ( a , p ) ) return ; int ind = 0 ; int n = a . size ( ) ; for ( int i = 1 ; i < n ; i ++ ) if ( sqDist ( p , a [ i ] ) < sqDist ( p , a [ ind ] ) ) ind = i ; int up = ind ; while ( orientation ( p , a [ up ] , a [ ( up + 1 ) % n ] ) >= 0 ) up = ( up + 1 ) % n ; int low = ind ; while ( orientation ( p , a [ low ] , a [ ( n + low - 1 ) % n ] ) <= 0 ) low = ( n + low - 1 ) % n ; vector < pair < int , int > > ret ; int curr = up ; ret . push_back ( a [ curr ] ) ; while ( curr != low ) { curr = ( curr + 1 ) % n ; ret . push_back ( a [ curr ] ) ; } ret . push_back ( p ) ; a . clear ( ) ; for ( int i = 0 ; i < ret . size ( ) ; i ++ ) a . push_back ( ret [ i ] ) ; } int main ( ) { vector < pair < int , int > > a ; a . push_back ( { 0 , 0 } ) ; a . push_back ( { 3 , -1 } ) ; a . push_back ( { 4 , 5 } ) ; a . push_back ( { -1 , 4 } ) ; int n = a . size ( ) ; pair < int , int > p = { 100 , 100 } ; addPoint ( a , p ) ; for ( auto e : a ) cout << " ( " << e . first << " , β " << e . second << " ) β " ; return 0 ; } |
Find all angles of a given triangle | C ++ Code to find all three angles of a triangle given coordinate of all three vertices ; returns square of distance b / w two points ; Square of lengths be a2 , b2 , c2 ; length of sides be a , b , c ; From Cosine law ; Converting to degree ; printing all the angles ; Driver code | #include <iostream> NEW_LINE using namespace std ; #define PI 3.1415926535 NEW_LINE int lengthSquare ( pair < int , int > X , pair < int , int > Y ) { int xDiff = X . first - Y . first ; int yDiff = X . second - Y . second ; return xDiff * xDiff + yDiff * yDiff ; } void printAngle ( pair < int , int > A , pair < int , int > B , pair < int , int > C ) { int a2 = lengthSquare ( B , C ) ; int b2 = lengthSquare ( A , C ) ; int c2 = lengthSquare ( A , B ) ; float a = sqrt ( a2 ) ; float b = sqrt ( b2 ) ; float c = sqrt ( c2 ) ; float alpha = acos ( ( b2 + c2 - a2 ) / ( 2 * b * c ) ) ; float betta = acos ( ( a2 + c2 - b2 ) / ( 2 * a * c ) ) ; float gamma = acos ( ( a2 + b2 - c2 ) / ( 2 * a * b ) ) ; alpha = alpha * 180 / PI ; betta = betta * 180 / PI ; gamma = gamma * 180 / PI ; cout << " alpha β : β " << alpha << endl ; cout << " betta β : β " << betta << endl ; cout << " gamma β : β " << gamma << endl ; } int main ( ) { pair < int , int > A = make_pair ( 0 , 0 ) ; pair < int , int > B = make_pair ( 0 , 1 ) ; pair < int , int > C = make_pair ( 1 , 0 ) ; printAngle ( A , B , C ) ; return 0 ; } |
Triangle with no point inside | C / C ++ program to find triangle with no point inside ; method to get square of distance between ( x1 , y1 ) and ( x2 , y2 ) ; Method prints points which make triangle with no point inside ; any point can be chosen as first point of triangle ; choose nearest point as second point of triangle ; Get distance from first point and choose nearest one ; Pick third point by finding the second closest point with different slope . ; if already chosen point then skip them ; get distance from first point ; here cross multiplication is compared instead of division comparison ; Driver code to test above methods | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getDistance ( int x1 , int y1 , int x2 , int y2 ) { return ( x2 - x1 ) * ( x2 - x1 ) + ( y2 - y1 ) * ( y2 - y1 ) ; } void triangleWithNoPointInside ( int points [ ] [ 2 ] , int N ) { int first = 0 ; int second , third ; int minD = INT_MAX ; for ( int i = 0 ; i < N ; i ++ ) { if ( i == first ) continue ; int d = getDistance ( points [ i ] [ 0 ] , points [ i ] [ 1 ] , points [ first ] [ 0 ] , points [ first ] [ 1 ] ) ; if ( minD > d ) { minD = d ; second = i ; } } minD = INT_MAX ; for ( int i = 0 ; i < N ; i ++ ) { if ( i == first i == second ) continue ; int d = getDistance ( points [ i ] [ 0 ] , points [ i ] [ 1 ] , points [ first ] [ 0 ] , points [ first ] [ 1 ] ) ; if ( ( points [ i ] [ 0 ] - points [ first ] [ 0 ] ) * ( points [ second ] [ 1 ] - points [ first ] [ 1 ] ) != ( points [ second ] [ 0 ] - points [ first ] [ 0 ] ) * ( points [ i ] [ 1 ] - points [ first ] [ 1 ] ) && minD > d ) { minD = d ; third = i ; } } cout << points [ first ] [ 0 ] << " , β " << points [ first ] [ 1 ] << endl ; cout << points [ second ] [ 0 ] << " , β " << points [ second ] [ 1 ] << endl ; cout << points [ third ] [ 0 ] << " , β " << points [ third ] [ 1 ] << endl ; } int main ( ) { int points [ ] [ 2 ] = { { 0 , 0 } , { 0 , 2 } , { 2 , 0 } , { 2 , 2 } , { 1 , 1 } } ; int N = sizeof ( points ) / sizeof ( points [ 0 ] ) ; triangleWithNoPointInside ( points , N ) ; return 0 ; } |
Minimum steps to minimize n as per given condition | A tabulation based solution ; driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getMinSteps ( int n ) { int table [ n + 1 ] ; table [ 1 ] = 0 ; for ( int i = 2 ; i <= n ; i ++ ) { if ( ! ( i % 2 ) && ( i % 3 ) ) table [ i ] = 1 + min ( table [ i - 1 ] , table [ i / 2 ] ) ; else if ( ! ( i % 3 ) && ( i % 2 ) ) table [ i ] = 1 + min ( table [ i - 1 ] , table [ i / 3 ] ) ; else if ( ! ( i % 2 ) && ! ( i % 3 ) ) table [ i ] = 1 + min ( table [ i - 1 ] , min ( table [ i / 2 ] , table [ i / 3 ] ) ) ; else table [ i ] = 1 + table [ i - 1 ] ; } return table [ n ] ; } int main ( ) { int n = 14 ; cout << getMinSteps ( n ) ; return 0 ; } |
Minimize swaps required to make all prime | Function to pre - calculate the prime [ ] prime [ i ] denotes whether i is prime or not ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked . ; Function to count minimum number of swaps required ; To count the minimum number of swaps required to convert the array into perfectly prime ; To count total number of prime indexes in the array ; To count the total number of prime numbers in the array ; Check whether index is prime or not ; Element is not prime ; If the total number of prime numbers is greater than or equal to the total number of prime indices , then it is possible to convert the array into perfectly prime ; Driver Code ; Pre - calculate prime [ ] | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int mxn = 1e4 + 1 ; bool prime [ mxn + 1 ] ; void SieveOfEratosthenes ( ) { memset ( prime , true , sizeof ( prime ) ) ; for ( int p = 2 ; p * p <= mxn ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= mxn ; i += p ) prime [ i ] = false ; } } } int countMin ( int arr [ ] , int n ) { int cMinSwaps = 0 ; int cPrimeIndices = 0 ; int cPrimeNos = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ i + 1 ] ) { cPrimeIndices ++ ; if ( ! prime [ arr [ i ] ] ) cMinSwaps ++ ; else cPrimeNos ++ ; } else if ( prime [ arr [ i ] ] ) { cPrimeNos ++ ; } } if ( cPrimeNos >= cPrimeIndices ) return cMinSwaps ; else return -1 ; } int main ( ) { SieveOfEratosthenes ( ) ; int n = 5 ; int arr [ 5 ] = { 2 , 7 , 8 , 5 , 13 } ; cout << countMin ( arr , n ) ; return 0 ; } |
Find the size of Largest Subset with positive Bitwise AND | C ++ program for the above approach ; Function to find the largest possible subset having Bitwise AND positive ; Stores the number of set bits at each bit position ; Traverse the given array arr [ ] ; Current bit position ; Loop till array element becomes zero ; If the last bit is set ; Increment frequency ; Divide array element by 2 ; Decrease the bit position ; Size of the largest possible subset ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void largestSubset ( int a [ ] , int N ) { int bit [ 32 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { int x = 31 ; while ( a [ i ] > 0 ) { if ( a [ i ] & 1 == 1 ) { bit [ x ] ++ ; } a [ i ] = a [ i ] >> 1 ; x -- ; } } cout << * max_element ( bit , bit + 32 ) ; } int main ( ) { int arr [ ] = { 7 , 13 , 8 , 2 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; largestSubset ( arr , N ) ; return 0 ; } |
Maximum element in connected component of given node for Q queries | C ++ program for the above approach ; Function to perform the find operation to find the parent of a disjoint set ; FUnction to perform union operation of disjoint set union ; If the rank are the same ; Update the maximum value ; Function to find the maximum element of the set which belongs to the element queries [ i ] ; Stores the parent elements of the sets ; Stores the rank of the sets ; Stores the maxValue of the sets ; Update parent [ i ] and maxValue [ i ] to i ; Add arr [ i ] . first and arr [ i ] . second elements to the same set ; Find the parent element of the element queries [ i ] ; Print the maximum value of the set which belongs to the element P ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Find ( vector < int > & parent , int a ) { return parent [ a ] = ( parent [ a ] == a ) ? a : ( Find ( parent , parent [ a ] ) ) ; } void Union ( vector < int > & parent , vector < int > & rank , vector < int > & maxValue , int a , int b ) { a = Find ( parent , a ) ; b = Find ( parent , b ) ; if ( a == b ) return ; if ( rank [ a ] == rank [ b ] ) { rank [ a ] ++ ; } if ( rank [ a ] < rank [ b ] ) { int temp = a ; a = b ; b = temp ; } parent [ b ] = a ; maxValue [ a ] = max ( maxValue [ a ] , maxValue [ b ] ) ; } void findMaxValueOfSet ( vector < pair < int , int > > & arr , vector < int > & queries , int R , int N , int M ) { vector < int > parent ( R + 1 ) ; vector < int > rank ( R + 1 , 0 ) ; vector < int > maxValue ( R + 1 ) ; for ( int i = 1 ; i < R + 1 ; i ++ ) { parent [ i ] = maxValue [ i ] = i ; } for ( int i = 0 ; i < N ; i ++ ) { Union ( parent , rank , maxValue , arr [ i ] . first , arr [ i ] . second ) ; } for ( int i = 0 ; i < M ; i ++ ) { int P = Find ( parent , queries [ i ] ) ; cout << maxValue [ P ] << " β " ; } } int main ( ) { int R = 5 ; vector < pair < int , int > > arr { { 1 , 2 } , { 2 , 3 } , { 4 , 5 } } ; vector < int > queries { 2 , 4 , 1 , 3 } ; int N = arr . size ( ) ; int M = queries . size ( ) ; findMaxValueOfSet ( arr , queries , R , N , M ) ; return 0 ; } |
Maximum sum of segments among all segments formed in array after Q queries | C ++ program for the above approach ; Stores the maximum integer of the sets for each query ; Function to perform the find operation of disjoint set union ; Function to perform the Union operation of disjoint set union ; Find the parent of a and b ; Update the parent ; Update the sum of set a ; Function to find the maximum element from the sets after each operation ; Stores the parent elements of the sets ; Stores the rank of the sets ; Stores the sum of the sets ; Stores the maximum element for each query ; Initially set is empty ; Update the sum as the current element ; After the last query set will be empty and sum will be 0 ; Check if the current element is not in any set then make parent as current element of the queries ; Check left side of the queries [ i ] is not added in any set ; Add the queries [ i ] and the queries [ i ] - 1 in one set ; Check right side of the queries [ i ] is not added in any set ; Add queries [ i ] and the queries [ i ] + 1 in one set ; Update the maxAns ; Push maxAns to the currMax ; Print currMax values in the reverse order ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxAns = INT_MIN ; int Find ( vector < int > & parent , int a ) { return parent [ a ] = ( parent [ a ] == a ) ? a : ( Find ( parent , parent [ a ] ) ) ; } void Union ( vector < int > & parent , vector < int > & rank , vector < int > & setSum , int a , int b ) { a = Find ( parent , a ) ; b = Find ( parent , b ) ; if ( a == b ) return ; if ( rank [ a ] > rank [ b ] ) rank [ a ] ++ ; if ( rank [ b ] > rank [ a ] ) swap ( a , b ) ; parent [ b ] = a ; setSum [ a ] += setSum [ b ] ; } void maxValues ( vector < int > arr , vector < int > queries , int N ) { vector < int > parent ( N + 1 ) ; vector < int > rank ( N + 1 , 0 ) ; vector < int > setSum ( N + 1 , 0 ) ; vector < int > currMax ; for ( int i = 1 ; i < N + 1 ; i ++ ) { parent [ i ] = -1 ; setSum [ i ] = arr [ i - 1 ] ; } currMax . push_back ( 0 ) ; for ( int i = N - 1 ; i > 0 ; i -- ) { if ( parent [ queries [ i ] ] == -1 ) { parent [ queries [ i ] ] = queries [ i ] ; } if ( queries [ i ] - 1 >= 0 && parent [ queries [ i ] - 1 ] != -1 ) { Union ( parent , rank , setSum , queries [ i ] , queries [ i ] - 1 ) ; } if ( queries [ i ] + 1 <= N && parent [ queries [ i ] + 1 ] != -1 ) { Union ( parent , rank , setSum , queries [ i ] , queries [ i ] + 1 ) ; } maxAns = max ( setSum [ queries [ i ] ] , maxAns ) ; currMax . push_back ( maxAns ) ; } for ( int i = currMax . size ( ) - 1 ; i >= 0 ; i -- ) { cout << currMax [ i ] << " β " ; } } int main ( ) { vector < int > arr = { 1 , 3 , 2 , 5 } ; vector < int > queries = { 3 , 4 , 1 , 2 } ; int N = arr . size ( ) ; maxValues ( arr , queries , N ) ; return 0 ; } |
ZigZag Level Order Traversal of an N | C ++ program for the above approach ; Structure of a tree node ; Function to create a new node ; Function to perform zig zag traversal of the given tree ; Stores the vectors containing nodes in each level of tree respectively ; Create a queue for BFS ; Enqueue Root of the tree ; Standard Level Order Traversal code using queue ; Stores the element in the current level ; Iterate over all nodes of the current level ; Insert all children of the current node into the queue ; Insert curLevel into result ; Loop to Print the ZigZag Level order Traversal of the given tree ; If i + 1 is even reverse the order of nodes in the current level ; Print the node of ith level ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int val ; vector < Node * > child ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> val = key ; return temp ; } void zigzagLevelOrder ( Node * root ) { if ( root == NULL ) return ; vector < vector < int > > result ; queue < Node * > q ; q . push ( root ) ; while ( ! q . empty ( ) ) { int size = q . size ( ) ; vector < int > curLevel ; for ( int i = 0 ; i < size ; i ++ ) { Node * node = q . front ( ) ; q . pop ( ) ; curLevel . push_back ( node -> val ) ; for ( int j = 0 ; j < node -> child . size ( ) ; j ++ ) { q . push ( node -> child [ j ] ) ; } } result . push_back ( curLevel ) ; } for ( int i = 0 ; i < result . size ( ) ; i ++ ) { if ( ( i + 1 ) % 2 == 0 ) { reverse ( result [ i ] . begin ( ) , result [ i ] . end ( ) ) ; } for ( int j = 0 ; j < result [ i ] . size ( ) ; j ++ ) { cout << result [ i ] [ j ] << " β " ; } cout << endl ; } } zigzagLevelOrder ( root ) ; return 0 ; } |
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 ; Vector to store our edges ; Storing the edgees in the Vector ; Initialize queue ; BFS from first node using queue ; Pop from queue ; Traversing its adjacency list ; Initialize queue ; BFS from last node using queue ; Pop from queue ; Traversing its adjacency list ; Printing the minimum distance including node i ; If not reachable ; Path exists ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE void minDisIncludingNode ( 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 > > q ; q . push ( { 0 , 0 } ) ; vector < int > dist ( n , 1e9 ) ; dist [ 0 ] = 0 ; while ( ! q . empty ( ) ) { auto up = q . front ( ) ; q . pop ( ) ; int x = up . first ; int lev = up . second ; if ( lev > dist [ x ] ) continue ; if ( x == n - 1 ) continue ; for ( ll y : g [ x ] ) { if ( dist [ y ] > lev + 1 ) { dist [ y ] = lev + 1 ; q . push ( { y , lev + 1 } ) ; } } } queue < pair < ll , ll > > q1 ; q1 . push ( { n - 1 , 0 } ) ; vector < int > dist1 ( n , 1e9 ) ; dist1 [ n - 1 ] = 0 ; while ( ! q1 . empty ( ) ) { auto up = q1 . front ( ) ; q1 . pop ( ) ; int x = up . first ; int lev = up . second ; if ( lev > dist1 [ x ] ) continue ; if ( x == 0 ) continue ; for ( ll y : g [ x ] ) { if ( dist1 [ y ] > lev + 1 ) { dist1 [ y ] = lev + 1 ; q1 . push ( { y , lev + 1 } ) ; } } } for ( int i = 0 ; i < n ; i ++ ) { if ( dist [ i ] + dist1 [ i ] > 1e9 ) cout << -1 << " β " ; else cout << dist [ i ] + dist1 [ i ] << " β " ; } } int main ( ) { int n = 5 ; int m = 7 ; int edges [ m ] [ 2 ] = { { 1 , 2 } , { 1 , 4 } , { 2 , 3 } , { 2 , 5 } , { 4 , 3 } , { 4 , 5 } , { 1 , 5 } } ; minDisIncludingNode ( n , m , edges ) ; return 0 ; } |
Check if possible to make Array sum equal to Array product by replacing exactly one element | C ++ Program to implement the above approach ; Function to check if it is possible to form an array whose sum and the product is the same or not ; Find the sum of the array initialize sum ; Iterate through all elements and add them to sum ; Find the product of the array ; Check a complete integer y for every x ; If got such y ; If no such y exist ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int canPossibleReplacement ( int N , int arr [ ] ) { int S = 0 ; int i ; for ( i = 0 ; i < N ; i ++ ) S += arr [ i ] ; int P = 1 ; for ( i = 0 ; i < N ; i ++ ) { P *= i ; } for ( int i = 0 ; i < N ; i ++ ) { int x = arr [ i ] ; int y = ( S - x ) / ( P / x - 1 ) ; if ( ( S - x + y ) == ( P * y ) / x ) return 1 ; } return 0 ; } int main ( ) { int N = 3 ; int arr [ ] = { 1 , 3 , 4 } ; if ( canPossibleReplacement ( N , arr ) == 1 ) cout << ( " Yes " ) ; else cout << ( " No " ) ; return 0 ; } |
Check if all the digits of the given number are same | Function to check if all the digits in the number N is the same or not ; Get the length of N ; Form the number M of the type K * 111. . . where K is the rightmost digit of N ; Check if the numbers are equal ; Otherwise ; Driver Code | #include <iostream> NEW_LINE using namespace std ; string checkSameDigits ( int N ) { int length = ( N ) + 1 ; int M = ( ( 10 , length ) - 1 ) / ( 10 - 1 ) ; M *= N % 10 ; if ( M = N ) return " Yes " ; return " No " ; } int main ( ) { int N = 222 ; cout << checkSameDigits ( N ) ; } |
Maximize sum of path from the Root to a Leaf node in N | C ++ program for the above approach ; Structure of a node in the tree ; Utility function to create a new node in the tree ; Recursive function to calculate the maximum sum in a path using DFS ; If current node is a leaf node ; Traversing all children of the current node ; Recursive call for all the children nodes ; Given Generic Tree ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int val ; vector < Node * > child ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> val = key ; return temp ; } void DFS ( Node * root , int sum , int & ans ) { if ( root -> child . size ( ) == 0 ) { ans = max ( ans , sum ) ; return ; } for ( int i = 0 ; i < root -> child . size ( ) ; i ++ ) { DFS ( root -> child [ i ] , sum + root -> child [ i ] -> val , ans ) ; } } Node * root = newNode ( 1 ) ; ( root -> child ) . push_back ( newNode ( 2 ) ) ; ( root -> child ) . push_back ( newNode ( 3 ) ) ; ( root -> child [ 0 ] -> child ) . push_back ( newNode ( 4 ) ) ; ( root -> child [ 1 ] -> child ) . push_back ( newNode ( 6 ) ) ; ( root -> child [ 0 ] -> child ) . push_back ( newNode ( 5 ) ) ; ( root -> child [ 1 ] ) -> child . push_back ( newNode ( 7 ) ) ; ( root -> child [ 1 ] -> child ) . push_back ( newNode ( 8 ) ) ; int maxSumPath = 0 ; DFS ( root , root -> val , maxSumPath ) ; cout << maxSumPath ; return 0 ; } |
Count of even sum triplets in the array for Q range queries | C ++ program for above approach ; Function to count number of triplets with even sum in range l , r for each query ; Initialization of array ; Initialization of variables ; Traversing array ; If element is odd ; If element is even ; Storing count of even and odd till each i ; Traversing each query ; Count of odd numbers in l to r ; Count of even numbers in l to r ; Finding the ans ; Printing the ans ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void countTriplets ( int size , int queries , int arr [ ] , int Q [ ] [ 2 ] ) { int arr_even [ size + 1 ] , arr_odd [ size + 1 ] ; int even = 0 , odd = 0 ; arr_even [ 0 ] = 0 ; arr_odd [ 0 ] = 0 ; for ( int i = 0 ; i < size ; i ++ ) { if ( arr [ i ] % 2 ) { odd ++ ; } else { even ++ ; } arr_even [ i + 1 ] = even ; arr_odd [ i + 1 ] = odd ; } for ( int i = 0 ; i < queries ; i ++ ) { int l = Q [ i ] [ 0 ] , r = Q [ i ] [ 1 ] ; int odd = arr_odd [ r ] - arr_odd [ l - 1 ] ; int even = arr_even [ r ] - arr_even [ l - 1 ] ; int ans = ( even * ( even - 1 ) * ( even - 2 ) ) / 6 + ( odd * ( odd - 1 ) / 2 ) * even ; cout << ans << " β " ; } } int main ( ) { int N = 6 , Q = 2 ; int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int queries [ ] [ 2 ] = { { 1 , 3 } , { 2 , 5 } } ; countTriplets ( N , Q , arr , queries ) ; return 0 ; } |
Maximize the rightmost element of an array in k operations in Linear Time | C ++ program for above approach ; Function to calculate maximum value of Rightmost element ; Calculating maximum value of Rightmost element ; Checking if arr [ i ] is operationable ; Performing operation of i - th element ; Decreasing the value of k by 1 ; Printing rightmost element ; Driver Code ; Given Input ; Function Call | #include <iostream> NEW_LINE using namespace std ; void maxRightmostElement ( int N , int k , int p , int arr [ ] ) { while ( k ) { for ( int i = N - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] >= p ) { arr [ i ] = arr [ i ] - p ; arr [ i + 1 ] = arr [ i + 1 ] + p ; break ; } } k -- ; } cout << arr [ N - 1 ] << endl ; } int main ( ) { int N = 4 , p = 2 , k = 5 , arr [ ] = { 3 , 8 , 1 , 4 } ; maxRightmostElement ( N , k , p , arr ) ; return 0 ; } |
Mean of minimum of all possible K | C ++ program for the above approach ; Function to find the value of nCr ; Base Case ; Find nCr recursively ; Function to find the expected minimum values of all the subsets of size K ; Find the factorials that will be used later ; Find the factorials ; Total number of subsets ; Stores the sum of minimum over all possible subsets ; Iterate over all possible minimum ; Find the mean over all subsets ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int nCr ( int n , int r , int f [ ] ) { if ( n < r ) { return 0 ; } return f [ n ] / ( f [ r ] * f [ n - r ] ) ; } int findMean ( int N , int X ) { int f [ N + 1 ] ; f [ 0 ] = 1 ; for ( int i = 1 ; i <= N ; i ++ ) { f [ i ] = f [ i - 1 ] * i ; } int total = nCr ( N , X , f ) ; int count = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { count += nCr ( N - i , X - 1 , f ) * i ; } double E_X = double ( count ) / double ( total ) ; cout << setprecision ( 10 ) << E_X ; return 0 ; } int main ( ) { int N = 3 , X = 2 ; findMean ( N , X ) ; return 0 ; } |
Maximize count of odd | C ++ code implementation for above approach ; To find maximum number of pairs in array with conversion of at most one element ; Initialize count of even elements ; Initialize count of odd elements ; If current number is even then increment x by 1 ; If current number is odd then increment y by 1 ; Initialize the answer by min ( x , y ) ; If difference in count of odd and even is more than 2 than increment answer ; Return final answer ; Driver code ; Given array | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumNumberofpairs ( int n , int arr [ ] ) { int x = 0 ; int y = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % 2 == 0 ) { x ++ ; } else { y ++ ; } } int answer = min ( x , y ) ; if ( abs ( x - y ) >= 2 ) { answer ++ ; } return answer ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 6 , 5 , 10 , 12 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maximumNumberofpairs ( n , arr ) << endl ; return 0 ; } |
Sum of product of all unordered pairs in given range with update queries | C ++ Program for the above approach ; Function to calculate the Pairwise Product Sum in range from L to R ; Loop to iterate over all possible pairs from L to R ; Print answer ; Function to update the Array element at index P to X ; Update the value at Pth index in the array ; Function to solve Q queries ; If Query is of type 1 ; If Query is of type 2 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void pairwiseProductSum ( int a [ ] , int l , int r ) { int sum = 0 ; for ( int j = l - 1 ; j <= r - 1 ; j ++ ) { for ( int k = j + 1 ; k <= r - 1 ; k ++ ) { sum += ( a [ j ] * a [ k ] ) ; } } cout << sum << endl ; } void updateArray ( int * a , int p , int x ) { a [ p - 1 ] = x ; } void solveQueries ( int * a , int n , int Q , int query [ ] [ 3 ] ) { 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 ; } |
Check if final remainder is present in original Array by reducing it based on given conditions | C ++ program to implement above approach ; copying original array ; loop till length of array become 2. ; find middle element ; pop element from front and rear ; find remainder ; append remainder to a ; now since length of array is 2 take product and divide it by n ; if remainder is present is original array return 1 , else return 0 ; calling function Reduced ; if x = 1 print YES else NO | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Reduced ( vector < int > a , int n ) { vector < int > original_array ; original_array = a ; while ( a . size ( ) != 2 ) { int mid = a . size ( ) / 2 ; int mid_ele = a [ mid ] ; int start = a [ 0 ] ; a . erase ( a . begin ( ) ) ; int end = a [ a . size ( ) - 1 ] ; a . pop_back ( ) ; int rmd = ( start * end ) % mid_ele ; a . push_back ( rmd ) ; int remainder = ( a [ 0 ] * a [ 1 ] ) % n ; for ( int i = 0 ; i < original_array . size ( ) ; i ++ ) { if ( original_array [ i ] == remainder ) { return 1 ; } } } return 0 ; } int main ( ) { vector < int > Arr = { 2 , 3 , 4 , 8 , 5 , 7 } ; int N = Arr . size ( ) ; int x = Reduced ( Arr , N ) ; if ( x ) cout << ( " YES " ) ; else cout << ( " NO " ) ; return 0 ; } |
Find two numbers from their sum and OR | C ++ program for the above approach ; Function to find the two integers from the given sum and Bitwise OR value ; Check if Z is non negative ; Iterate through all the bits ; Find the kth bit of A & B ; Find the kth bit of A | B ; If bit1 = 1 and bit2 = 0 , then there will be no possible pairs ; Print the possible pairs ; Driver Code | #include <bits/stdc++.h> NEW_LINE #define MaxBit 32 NEW_LINE using namespace std ; int possiblePair ( int X , int Y ) { int Z = Y - X ; if ( Z < 0 ) { cout << " - 1" ; return 0 ; } for ( int k = 0 ; k < MaxBit ; k ++ ) { int bit1 = ( Z >> k ) & 1 ; int bit2 = ( Z >> k ) & 1 ; if ( bit1 && ! bit2 ) { cout << " - 1" ; return 0 ; } } cout << Z << ' β ' << X ; return 0 ; } int main ( ) { int X = 7 , Y = 11 ; possiblePair ( X , Y ) ; return 0 ; } |
Maximum frequencies in each M | C ++ program for the above approach ; Function to find the frequency of the most common element in each M length subarrays ; Stores frequency of array element ; Stores the maximum frequency ; Iterate for the first sub - array and store the maximum ; Print the maximum frequency for the first subarray ; Iterate over the range [ M , N ] ; Subtract the A [ i - M ] and add the A [ i ] in the map ; Find the maximum frequency ; Print the maximum frequency for the current subarray ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void maxFrequencySubarrayUtil ( vector < int > A , int N , int M ) { int i = 0 ; unordered_map < int , int > m ; int val = 0 ; for ( ; i < M ; i ++ ) { m [ A [ i ] ] ++ ; val = max ( val , m [ A [ i ] ] ) ; } cout << val << " β " ; for ( i = M ; i < N ; i ++ ) { m [ A [ i - M ] ] -- ; m [ A [ i ] ] ++ ; val = 0 ; for ( auto x : m ) { val = max ( val , x . second ) ; } cout << val << " β " ; } } int main ( ) { vector < int > A = { 1 , 1 , 2 , 2 , 3 , 5 } ; int N = A . size ( ) ; int M = 4 ; maxFrequencySubarrayUtil ( A , N , M ) ; return 0 ; } |
Maximum number of pairs of distinct array elements possible by including each element in only one pair | C ++ program for the above approach ; Function to count the maximum number of pairs having different element from the given array ; Stores the frequency of array element ; Stores maximum count of pairs ; Increasing the frequency of every element ; Stores the frequencies of array element from highest to lowest ; Pushing the frequencies to the priority queue ; Iterate until size of PQ > 1 ; Stores the top two element ; Form the pair between the top two pairs ; Decrement the frequencies ; Insert updated frequencies if it is greater than 0 ; Return the total count of resultant pairs ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumPairs ( int a [ ] , int n ) { map < int , int > freq ; int count = 0 ; for ( int i = 0 ; i < n ; ++ i ) freq [ a [ i ] ] ++ ; priority_queue < int > pq ; for ( auto itr = freq . begin ( ) ; itr != freq . end ( ) ; itr ++ ) { pq . push ( itr -> second ) ; } while ( pq . size ( ) > 1 ) { int freq1 = pq . top ( ) ; pq . pop ( ) ; int freq2 = pq . top ( ) ; pq . pop ( ) ; count ++ ; freq1 -- ; freq2 -- ; if ( freq1 > 0 ) pq . push ( freq1 ) ; if ( freq2 > 0 ) pq . push ( freq2 ) ; } return count ; } int main ( ) { int arr [ ] = { 4 , 2 , 4 , 1 , 4 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maximumPairs ( arr , N ) ; return 0 ; } |
Generate an N | C ++ program for above approach ; Function to print target array ; Sort the given array ; Seeking for index of elements with minimum diff . ; Seeking for index ; To store target array ; Copying element ; Copying remaining element ; Printing target array ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printArr ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int minDifference = INT_MAX ; int minIndex = -1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( minDifference > abs ( arr [ i ] - arr [ i - 1 ] ) ) { minDifference = abs ( arr [ i ] - arr [ i - 1 ] ) ; minIndex = i - 1 ; } } int Arr [ n ] ; Arr [ 0 ] = arr [ minIndex ] ; Arr [ n - 1 ] = arr [ minIndex + 1 ] ; int pos = 1 ; for ( int i = minIndex + 2 ; i < n ; i ++ ) { Arr [ pos ++ ] = arr [ i ] ; } for ( int i = 0 ; i < minIndex ; i ++ ) { Arr [ pos ++ ] = arr [ i ] ; } for ( int i = 0 ; i < n ; i ++ ) { cout << Arr [ i ] << " β " ; } } int main ( ) { int N = 8 ; int arr [ ] = { 4 , 6 , 2 , 6 , 8 , 2 , 6 , 4 } ; printArr ( arr , N ) ; return 0 ; } |
Construct a Perfect Binary Tree from Preorder Traversal | C ++ program for the above approach ; Structure of the tree ; Function to create a new node with the value val ; Return the newly created node ; Function to create the Perfect Binary Tree ; If preStart > preEnd return NULL ; Initialize root as pre [ preStart ] ; If the only node is left , then return node ; Parameters for further recursion ; Recursive Call to build the subtree of root node ; Return the created root ; Function to build Perfect Binary Tree ; Function to print the Inorder of the given Tree ; Base Case ; Left Recursive Call ; Print the data ; Right Recursive Call ; Driver Code ; Function Call ; Print Inorder Traversal | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; Node ( int val ) { data = val ; left = right = NULL ; } } ; Node * getNewNode ( int val ) { Node * newNode = new Node ( val ) ; newNode -> data = val ; newNode -> left = newNode -> right = NULL ; return newNode ; } Node * buildPerfectBT_helper ( int preStart , int preEnd , int pre [ ] ) { if ( preStart > preEnd ) return NULL ; Node * root = getNewNode ( pre [ preStart ] ) ; ; if ( preStart == preEnd ) return root ; int leftPreStart = preStart + 1 ; int rightPreStart = leftPreStart + ( preEnd - leftPreStart + 1 ) / 2 ; int leftPreEnd = rightPreStart - 1 ; int rightPreEnd = preEnd ; root -> left = buildPerfectBT_helper ( leftPreStart , leftPreEnd , pre ) ; root -> right = buildPerfectBT_helper ( rightPreStart , rightPreEnd , pre ) ; return root ; } Node * buildPerfectBT ( int pre [ ] , int size ) { return buildPerfectBT_helper ( 0 , size - 1 , pre ) ; } void printInorder ( Node * root ) { if ( ! root ) return ; printInorder ( root -> left ) ; cout << root -> data << " β " ; printInorder ( root -> right ) ; } int main ( ) { int pre [ ] = { 1 , 2 , 4 , 5 , 3 , 6 , 7 } ; int N = sizeof ( pre ) / sizeof ( pre [ 0 ] ) ; Node * root = buildPerfectBT ( pre , N ) ; cout << " Inorder traversal of the tree : " ; printInorder ( root ) ; return 0 ; } |
Minimum number of moves to make M and N equal by repeatedly adding any divisor of number to itself except 1 and the number | C ++ program for the above approach . ; Function to find the minimum number of moves to make N and M equal . ; Array to maintain the numbers included . ; pair of vertex , count ; run bfs from N ; if we reached goal ; Iterate in the range ; If i is a factor of aux ; If i is less than M - aux and is not included earlier . ; If aux / i is less than M - aux and is not included earlier . ; Not possible ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countOperations ( int N , int M ) { bool visited [ 100001 ] ; fill ( visited , visited + 100001 , false ) ; queue < pair < int , int > > Q ; Q . push ( make_pair ( N , 0 ) ) ; visited [ N ] = true ; while ( ! Q . empty ( ) ) { int aux = Q . front ( ) . first ; int cont = Q . front ( ) . second ; Q . pop ( ) ; if ( aux == M ) return cont ; for ( int i = 2 ; i * i <= aux ; i ++ ) if ( aux % i == 0 ) { if ( aux + i <= M && ! visited [ aux + i ] ) { Q . push ( make_pair ( aux + i , cont + 1 ) ) ; visited [ aux + i ] = true ; } if ( aux + aux / i <= M && ! visited [ aux + aux / i ] ) { Q . push ( make_pair ( aux + aux / i , cont + 1 ) ) ; visited [ aux + aux / i ] = true ; } } } return -1 ; } int main ( ) { int N = 4 , M = 24 ; cout << countOperations ( N , M ) ; return 0 ; } |
Finding Astronauts from different countries | C ++ program for the above approach ; Function to perform the DFS Traversal to find the count of connected components ; Marking vertex visited ; DFS call to neighbour vertices ; If the current node is not visited , then recursively call DFS ; Function to find the number of ways to choose two astronauts from the different countries ; Stores the Adjacency list ; Constructing the graph ; Stores the visited vertices ; Stores the size of every connected components ; DFS call to the graph ; Store size of every connected component ; Stores the total number of ways to count the pairs ; Traverse the array ; Print the value of ans ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void dfs ( int v , vector < vector < int > > & adj , vector < bool > & visited , int & num ) { visited [ v ] = true ; num ++ ; for ( int i = 0 ; i < adj [ v ] . size ( ) ; i ++ ) { if ( ! visited [ adj [ v ] [ i ] ] ) { dfs ( adj [ v ] [ i ] , adj , visited , num ) ; } } } void numberOfPairs ( int N , vector < vector < int > > arr ) { vector < vector < int > > adj ( N ) ; for ( vector < int > & i : arr ) { adj [ i [ 0 ] ] . push_back ( i [ 1 ] ) ; adj [ i [ 1 ] ] . push_back ( i [ 0 ] ) ; } vector < bool > visited ( N ) ; vector < int > v ; int num = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( ! visited [ i ] ) { dfs ( i , adj , visited , num ) ; v . push_back ( num ) ; num = 0 ; } } int ans = N * ( N - 1 ) / 2 ; for ( int i : v ) { ans -= ( i * ( i - 1 ) / 2 ) ; } cout << ans ; } int main ( ) { int N = 6 ; vector < vector < int > > arr = { { 0 , 1 } , { 0 , 2 } , { 2 , 5 } } ; numberOfPairs ( N , arr ) ; return 0 ; } |
Count of Perfect Numbers in given range for Q queries | C ++ program for the above approach ; Function to check whether a number is perfect Number ; Stores sum of divisors ; Itearate over the range [ 2 , sqrt ( N ) ] ; If sum of divisors is equal to N , then N is a perfect number ; Function to find count of perfect numbers in a given range ; Stores the count of perfect Numbers upto a every number less than MAX ; Iterate over the range [ 1 , MAX ] ; Traverse the array arr [ ] ; Print the count of perfect numbers in the range [ arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ] ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100005 ; bool isPerfect ( long long int N ) { long long int sum = 1 ; for ( long long int i = 2 ; i * i <= N ; i ++ ) { if ( N % i == 0 ) { if ( i * i != N ) sum = sum + i + N / i ; else sum = sum + i ; } } if ( sum == N && N != 1 ) return true ; return false ; } void Query ( int arr [ ] [ 2 ] , int N ) { int prefix [ MAX + 1 ] = { 0 } ; for ( int i = 2 ; i <= MAX ; i ++ ) { prefix [ i ] = prefix [ i - 1 ] + isPerfect ( i ) ; } for ( int i = 0 ; i < N ; i ++ ) { cout << prefix [ arr [ i ] [ 1 ] ] - prefix [ arr [ i ] [ 0 ] - 1 ] << " β " ; } } int main ( ) { int arr [ ] [ 2 ] = { { 1 , 1000 } , { 1000 , 2000 } , { 2000 , 3000 } } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; Query ( arr , N ) ; } |
2 Keys Keyboard Problem | C ++ program for the above approach ; Function to find the minimum number of steps required to form N number of A 's ; Stores the count of steps needed ; Traverse over the range [ 2 , N ] ; Iterate while N is divisible by d ; Increment the value of ans by d ; Divide N by d ; If N is not 1 ; Return the ans ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minSteps ( int N ) { int ans = 0 ; for ( int d = 2 ; d * d <= N ; d ++ ) { while ( N % d == 0 ) { ans += d ; N /= d ; } } if ( N != 1 ) { ans += N ; } return ans ; } int main ( ) { int N = 3 ; cout << minSteps ( N ) ; return 0 ; } |
Find any possible two coordinates of Rectangle whose two coordinates are given | C ++ program for the above approach ; Function to find the remaining two rectangle coordinates ; Pairs to store the position of given two coordinates of the rectangle . ; Pairs to store the remaining two coordinates of the rectangle . ; Traverse through matrix and find pairs p1 and p2 ; First Case ; Second Case ; Third Case ; Print the matrix ; Driver code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void Create_Rectangle ( vector < string > arr , int n ) { pair < int , int > p1 = { -1 , -1 } ; pair < int , int > p2 = { -1 , -1 } ; pair < int , int > p3 ; pair < int , int > p4 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ i ] [ j ] == '1' ) if ( p1 . first == -1 ) p1 = { i , j } ; else p2 = { i , j } ; } } p3 = p1 ; p4 = p2 ; if ( p1 . first == p2 . first ) { p3 . first = ( p1 . first + 1 ) % n ; p4 . first = ( p2 . first + 1 ) % n ; } else if ( p1 . second == p2 . second ) { p3 . second = ( p1 . second + 1 ) % n ; p4 . second = ( p2 . second + 1 ) % n ; } else { swap ( p3 . first , p4 . first ) ; } arr [ p3 . first ] [ p3 . second ] = '1' ; arr [ p4 . first ] [ p4 . second ] = '1' ; for ( int i = 0 ; i < n ; i ++ ) { cout << arr [ i ] << endl ; } } int main ( ) { int n = 4 ; vector < string > arr { "0010" , "0000" , "1000" , "0000" } ; Create_Rectangle ( arr , n ) ; return 0 ; } |
Sum of all the prime divisors of a number | Set 2 | C ++ program for the above approach ; Function to find sum of prime divisors of the given number N ; Add the number 2 if it divides N ; Traverse the loop from [ 3 , sqrt ( N ) ] ; If i divides N , add i and divide N ; This condition is to handle the case when N is a prime number greater than 2 ; Driver code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int SumOfPrimeDivisors ( int n ) { int sum = 0 ; if ( n % 2 == 0 ) { sum = sum + 2 ; } while ( n % 2 == 0 ) { n = n / 2 ; } for ( int i = 3 ; i <= sqrt ( n ) ; i = i + 2 ) { if ( n % i == 0 ) { sum = sum + i ; } while ( n % i == 0 ) { n = n / i ; } } if ( n > 2 ) { sum = sum + n ; } return sum ; } int main ( ) { int n = 10 ; cout << SumOfPrimeDivisors ( n ) ; return 0 ; } |
Minimum insertions to form a palindrome | DP | A Naive recursive program to find minimum number insertions needed to make a string palindrome ; Recursive function to find minimum number of insertions ; Base Cases ; Check if the first and last characters are same . On the basis of the comparison result , decide which subrpoblem ( s ) to call ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinInsertions ( char str [ ] , int l , int h ) { if ( l > h ) return INT_MAX ; if ( l == h ) return 0 ; if ( l == h - 1 ) return ( str [ l ] == str [ h ] ) ? 0 : 1 ; return ( str [ l ] == str [ h ] ) ? findMinInsertions ( str , l + 1 , h - 1 ) : ( min ( findMinInsertions ( str , l , h - 1 ) , findMinInsertions ( str , l + 1 , h ) ) + 1 ) ; } int main ( ) { char str [ ] = " geeks " ; cout << findMinInsertions ( str , 0 , strlen ( str ) - 1 ) ; return 0 ; } |
Count bases which contains a set bit as the Most Significant Bit in the representation of N | C ++ program for the above approach ; Function to count bases having MSB of N as a set bit ; Store the required count ; Iterate over the range [ 2 , N ] ; Store the MSB of N ; If MSB is 1 , then increment the count by 1 ; Return the count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countOfBase ( int N ) { int count = 0 ; for ( int i = 2 ; i <= N ; ++ i ) { int highestPower = ( int ) ( log ( N ) / log ( i ) ) ; int firstDigit = N / ( int ) pow ( i , highestPower ) ; if ( firstDigit == 1 ) { ++ count ; } } return count ; } int main ( ) { int N = 6 ; cout << countOfBase ( N ) ; return 0 ; } |
K | c ++ program for the above approach ; Function to find the kth digit from last in an integer n ; If k is less than equal to 0 ; Convert integer into string ; If k is greater than length of the string temp ; Print the k digit from last ; Driver code ; Given Input ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void kthDigitFromLast ( int n , int k ) { if ( k <= 0 ) { cout << -1 << endl ; return ; } string temp = to_string ( n ) ; if ( k > temp . length ( ) ) { cout << -1 << endl ; } else { cout << temp [ temp . length ( ) - k ] - '0' ; } } int main ( ) { int n = 2354 ; int k = 2 ; kthDigitFromLast ( n , k ) ; } |
Count ways to split array into three non | C ++ program for the above approach ; Function to count ways to split array into three subarrays with equal Bitwise XOR ; Stores the XOR value of arr [ ] ; Update the value of arr_xor ; Stores the XOR value of prefix and suffix array respectively ; Stores the ending points of all the required prefix arrays ; Stores the count of suffix arrays whose XOR value is equal to the total XOR value at each index ; Find all prefix arrays with XOR value equal to arr_xor ; Update pref_xor ; Fill the values of suff_inds [ ] ; Update suff_xor ; Update suff_inds [ i ] ; Stores the total number of ways ; Count total number of ways ; Return the final count ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countWays ( int arr [ ] , int N ) { int arr_xor = 0 ; for ( int i = 0 ; i < N ; i ++ ) arr_xor ^= arr [ i ] ; int pref_xor = 0 , suff_xor = 0 ; vector < int > pref_ind ; int suff_inds [ N + 1 ] ; memset ( suff_inds , 0 , sizeof suff_inds ) ; for ( int i = 0 ; i < N ; i ++ ) { pref_xor ^= arr [ i ] ; if ( pref_xor == arr_xor ) pref_ind . push_back ( i ) ; } for ( int i = N - 1 ; i >= 0 ; i -- ) { suff_xor ^= arr [ i ] ; suff_inds [ i ] += suff_inds [ i + 1 ] ; if ( suff_xor == arr_xor ) suff_inds [ i ] ++ ; } int tot_ways = 0 ; for ( int idx : pref_ind ) { if ( idx < N - 1 ) tot_ways += suff_inds [ idx + 2 ] ; } return tot_ways ; } int main ( ) { int arr [ ] = { 7 , 0 , 5 , 2 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countWays ( arr , N ) ; return 0 ; } |
Count pairs up to N having sum equal to their XOR | C ++ program for the above approach ; 2D array for memoization ; Recursive Function to count pairs ( x , y ) such that x + y = x ^ y ; If the string is traversed completely ; If the current subproblem is already calculated ; If bound = 1 and s [ i ] = = '0' , only ( 0 , 0 ) can be placed ; Otherwise ; Placing ( 0 , 1 ) and ( 1 , 0 ) are equivalent . Hence , multiply by 2. ; Place ( 0 , 0 ) at the current position . ; Return the answer ; Utility Function to convert N to its binary representation ; Function to count pairs ( x , y ) such that x + y = x ^ y ; Convert the number to equivalent binary representation ; Initialize dp array with - 1. ; Print answer returned by recursive function ; Driver code ; Input ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 1000 ] [ 2 ] ; int IsSumEqualsXor ( int i , int n , bool bound , string & s ) { if ( i == n ) return 1 ; if ( dp [ i ] [ bound ] != -1 ) return dp [ i ] [ bound ] ; int ans = 0 ; if ( bound and s [ i ] == '0' ) { ans = IsSumEqualsXor ( i + 1 , n , 1 , s ) ; } else { ans = 2 * IsSumEqualsXor ( i + 1 , n , bound & ( s [ i ] == '1' ) , s ) ; ans += IsSumEqualsXor ( i + 1 , n , 0 , s ) ; } return dp [ i ] [ bound ] = ans ; } string convertToBinary ( int n ) { string ans ; while ( n ) { char rem = char ( n % 2 + '0' ) ; ans . push_back ( rem ) ; n /= 2 ; } reverse ( ans . begin ( ) , ans . end ( ) ) ; return ans ; } void IsSumEqualsXorUtil ( int N ) { string s = convertToBinary ( N ) ; memset ( dp , -1 , sizeof dp ) ; cout << IsSumEqualsXor ( 0 , s . size ( ) , 1 , s ) << endl ; } int main ( ) { int N = 10 ; IsSumEqualsXorUtil ( N ) ; return 0 ; } |
Mean of fourth powers of first N natural numbers | C ++ program for the above approach ; Function to find the average of the fourth power of first N natural numbers ; Stores the sum of the fourth powers of first N natural numbers ; Calculate the sum of fourth power ; Return the average ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; double findAverage ( int N ) { double S = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { S += i * i * i * i ; } return S / N ; } int main ( ) { int N = 3 ; cout << findAverage ( N ) ; return 0 ; } |
Construct a graph from given degrees of all vertices | C ++ program to generate a graph for a given fixed degrees ; A function to print the adjacency matrix . ; n is number of vertices ; For each pair of vertex decrement the degree of both vertex . ; Print the result in specified format ; driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printMat ( int degseq [ ] , int n ) { int mat [ n ] [ n ] ; memset ( mat , 0 , sizeof ( mat ) ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( degseq [ i ] > 0 && degseq [ j ] > 0 ) { degseq [ i ] -- ; degseq [ j ] -- ; mat [ i ] [ j ] = 1 ; mat [ j ] [ i ] = 1 ; } } } cout << " STRNEWLINE " << setw ( 3 ) << " TABSYMBOL " ; for ( int i = 0 ; i < n ; i ++ ) cout << setw ( 3 ) << " ( " << i << " ) " ; cout << " STRNEWLINE STRNEWLINE " ; for ( int i = 0 ; i < n ; i ++ ) { cout << setw ( 4 ) << " ( " << i << " ) " ; for ( int j = 0 ; j < n ; j ++ ) cout << setw ( 5 ) << mat [ i ] [ j ] ; cout << " STRNEWLINE " ; } } int main ( ) { int degseq [ ] = { 2 , 2 , 1 , 1 , 1 } ; int n = sizeof ( degseq ) / sizeof ( degseq [ 0 ] ) ; printMat ( degseq , n ) ; return 0 ; } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.