text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Remove duplicates from a given string | CPP program to remove duplicate character from character array and print in sorted order ; create a set using string characters excluding ' \0' ; print content of the set ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; char * removeDuplicate ( char str [ ] , int n ) { set < char > s ( str , str + n - 1 ) ; int i = 0 ; for ( auto x : s ) str [ i ++ ] = x ; str [ i ] = ' \0' ; return str ; } int main ( ) { char str [ ] = " geeksforgeeks " ; int n = sizeof ( str ) / sizeof ( str [ 0 ] ) ; cout << removeDuplicate ( str , n ) ; return 0 ; }
Shortest path from a source cell to a destination cell of a Binary Matrix through cells consisting only of 1 s | C ++ program for the above approach ; Stores the coordinates of the matrix cell ; Stores coordinates of a cell and its distance ; Check if the given cell is valid or not ; Stores the moves of the directions of adjacent cells ; Function to find the shortest path from the source to destination in the given matrix ; Stores the distance for each cell from the source cell ; Distance of source cell is 0 ; Initialize a visited array ; Mark source cell as visited ; Create a queue for BFS ; Distance of source cell is 0 ; Enqueue source cell ; Keeps track of whether destination is reached or not ; Iterate until queue is not empty ; Deque front of the queue ; If the destination cell is reached , then find the path ; Assign the distance of destination to the distance matrix ; Stores the smallest path ; Iterate until source is reached ; Append D ; Append U ; Append R ; Append L ; Reverse the backtracked path ; Pop the start of queue ; Explore all adjacent directions ; If the current cell is valid cell and can be traversed ; Mark the adjacent cells as visited ; Enque the adjacent cells ; Update the distance of the adjacent cells ; If the destination is not reachable ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ROW 4 NEW_LINE #define COL 4 NEW_LINE struct Point { int x , y ; } ; struct Node { Point pt ; int dist ; } ; bool isValid ( int row , int col ) { return ( row >= 0 ) && ( col >= 0 ) && ( row < ROW ) && ( col < COL ) ; } int dRow [ ] = { -1 , 0 , 0 , 1 } ; int dCol [ ] = { 0 , -1 , 1 , 0 } ; void pathMoves ( char mat [ ] [ COL ] , Point src , Point dest ) { int d [ ROW ] [ COL ] ; memset ( d , -1 , sizeof d ) ; d [ src . x ] [ src . y ] = 0 ; bool visited [ ROW ] [ COL ] ; memset ( visited , false , sizeof visited ) ; visited [ src . x ] [ src . y ] = true ; queue < Node > q ; Node s = { src , 0 } ; q . push ( s ) ; bool ok = false ; while ( ! q . empty ( ) ) { Node curr = q . front ( ) ; Point pt = curr . pt ; if ( pt . x == dest . x && pt . y == dest . y ) { int xx = pt . x , yy = pt . y ; int dist = curr . dist ; d [ pt . x ] [ pt . y ] = dist ; string pathmoves = " " ; while ( xx != src . x yy != src . y ) { if ( xx > 0 && d [ xx - 1 ] [ yy ] == dist - 1 ) { pathmoves += ' D ' ; xx -- ; } if ( xx < ROW - 1 && d [ xx + 1 ] [ yy ] == dist - 1 ) { pathmoves += ' U ' ; xx ++ ; } if ( yy > 0 && d [ xx ] [ yy - 1 ] == dist - 1 ) { pathmoves += ' R ' ; yy -- ; } if ( yy < COL - 1 && d [ xx ] [ yy + 1 ] == dist - 1 ) { pathmoves += ' L ' ; yy ++ ; } dist -- ; } reverse ( pathmoves . begin ( ) , pathmoves . end ( ) ) ; cout << pathmoves ; ok = true ; break ; } q . pop ( ) ; for ( int i = 0 ; i < 4 ; i ++ ) { int row = pt . x + dRow [ i ] ; int col = pt . y + dCol [ i ] ; if ( isValid ( row , col ) && ( mat [ row ] [ col ] == '1' mat [ row ] [ col ] == ' s ' mat [ row ] [ col ] == ' d ' ) && ! visited [ row ] [ col ] ) { visited [ row ] [ col ] = true ; Node adjCell = { { row , col } , curr . dist + 1 } ; q . push ( adjCell ) ; d [ row ] [ col ] = curr . dist + 1 ; } } } if ( ! ok ) cout << -1 ; } int main ( ) { char mat [ ROW ] [ COL ] = { { '0' , '1' , '0' , '1' } , { '1' , '0' , '1' , '1' } , { '0' , '1' , '1' , '1' } , { '1' , '1' , '1' , '0' } } ; Point src = { 0 , 3 } ; Point dest = { 3 , 0 } ; pathMoves ( mat , src , dest ) ; return 0 ; }
Check if K can be obtained by performing arithmetic operations on any permutation of an Array | C ++ program for the above approach ; Function that finds the string of possible combination of operations ; If only one number left then check for result ; If resultant value is K ; Else return 0 ; Choose all combination of numbers and operators and operate them ; Choose the first two and operate it with ' + ' ; Place it to 0 th position ; Place ( n - 1 ) th element on 1 st position ; Evaluate the expression with current combination ; Now , we have N - 1 elements ; Try ' - ' operation ; Evaluate the expression with current combination ; Try reverse ' - ' ; Evaluate the expression with current combination ; Try ' * ' operation ; Evaluate the expression with current combination ; Try ' / ' ; Evaluate the expression with current combination ; Try reverse ' / ' ; Evaluate the expression with current combination ; Backtracking Step ; Return 0 if there doesnt exist any combination that gives K ; Function that finds the possible combination of operation to get the resultant value K ; Store the resultant operation ; Function Call ; Driver Code ; Given array arr [ ] ; Resultant value K ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool find ( vector < double > & v , int n , double dest , string s ) { if ( n == 1 ) { if ( abs ( v [ 0 ] - dest ) <= 0.0000001 ) { cout << s + to_string ( int ( dest ) ) << " ▁ " ; return 1 ; } return 0 ; } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { double a = v [ i ] , b = v [ j ] ; string p = s ; v [ i ] = a + b ; v [ j ] = v [ n - 1 ] ; s = ( s + to_string ( int ( a ) ) + ' + ' + to_string ( int ( b ) ) + " ▁ = > ▁ " ) ; if ( find ( v , n - 1 , dest , s ) ) return 1 ; s = p ; v [ i ] = a - b ; v [ j ] = v [ n - 1 ] ; s = ( s + to_string ( int ( a ) ) + ' - ' + to_string ( int ( b ) ) + " ▁ = > ▁ " ) ; if ( find ( v , n - 1 , dest , s ) ) return 1 ; s = p ; v [ i ] = b - a ; v [ j ] = v [ n - 1 ] ; s = ( s + to_string ( int ( b ) ) + ' - ' + to_string ( int ( a ) ) + " ▁ = > ▁ " ) ; if ( find ( v , n - 1 , dest , s ) ) return 1 ; s = p ; v [ i ] = a * b ; v [ j ] = v [ n - 1 ] ; s = ( s + to_string ( int ( a ) ) + ' * ' + to_string ( int ( b ) ) + " ▁ = > ▁ " ) ; if ( find ( v , n - 1 , dest , s ) ) return 1 ; s = p ; if ( b != 0 ) { v [ i ] = a / b ; v [ j ] = v [ n - 1 ] ; s = ( s + to_string ( int ( a ) ) + ' / ' + to_string ( int ( b ) ) + " ▁ = > ▁ " ) ; if ( find ( v , n - 1 , dest , s ) ) return 1 ; } s = p ; if ( a != 0 ) { v [ i ] = b / a ; v [ j ] = v [ n - 1 ] ; s = ( s + to_string ( int ( b ) ) + ' / ' + to_string ( int ( a ) ) + " ▁ = > ▁ " ) ; if ( find ( v , n - 1 , dest , s ) ) return 1 ; } s = p ; v [ i ] = a ; v [ j ] = b ; } } return 0 ; } void checkPossibleOperation ( vector < double > & arr , double K ) { string s = " " ; if ( ! find ( arr , arr . size ( ) , K , s ) ) { cout << " - 1" ; } } int main ( ) { vector < double > arr = { 2 , 0 , 0 , 2 } ; double K = 4 ; checkPossibleOperation ( arr , K ) ; return 0 ; }
Sudoku | Backtracking | ; N is the size of the 2D matrix N * N ; A utility function to print grid ; Checks whether it will be legal to assign num to the given row , col ; Check if we find the same num in the similar row , we return false ; Check if we find the same num in the similar column , we return false ; Check if we find the same num in the particular 3 * 3 matrix , we return false ; Takes a partially filled - in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution ( non - duplication across rows , columns , and boxes ) ; Check if we have reached the 8 th row and 9 th column ( 0 indexed matrix ) , we are returning true to avoid further backtracking ; Check if column value becomes 9 , we move to next row and column start from 0 ; Check if the current position of the grid already contains value > 0 , we iterate for next column ; Check if it is safe to place the num ( 1 - 9 ) in the given row , col -> we move to next column ; Assigning the num in the current ( row , col ) position of the grid and assuming our assigned num in the position is correct ; Checking for next possibility with next column ; Removing the assigned num , since our assumption was wrong , and we go for next assumption with diff num value ; Driver Code ; 0 means unassigned cells
#include <iostream> NEW_LINE using namespace std ; #define N 9 NEW_LINE void print ( int arr [ N ] [ N ] ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) cout << arr [ i ] [ j ] << " ▁ " ; cout << endl ; } } bool isSafe ( int grid [ N ] [ N ] , int row , int col , int num ) { for ( int x = 0 ; x <= 8 ; x ++ ) if ( grid [ row ] [ x ] == num ) return false ; for ( int x = 0 ; x <= 8 ; x ++ ) if ( grid [ x ] [ col ] == num ) return false ; int startRow = row - row % 3 , startCol = col - col % 3 ; for ( int i = 0 ; i < 3 ; i ++ ) for ( int j = 0 ; j < 3 ; j ++ ) if ( grid [ i + startRow ] [ j + startCol ] == num ) return false ; return true ; } bool solveSuduko ( int grid [ N ] [ N ] , int row , int col ) { if ( row == N - 1 && col == N ) return true ; if ( col == N ) { row ++ ; col = 0 ; } if ( grid [ row ] [ col ] > 0 ) return solveSuduko ( grid , row , col + 1 ) ; for ( int num = 1 ; num <= N ; num ++ ) { if ( isSafe ( grid , row , col , num ) ) { grid [ row ] [ col ] = num ; if ( solveSuduko ( grid , row , col + 1 ) ) return true ; } grid [ row ] [ col ] = 0 ; } return false ; } int main ( ) { int grid [ N ] [ N ] = { { 3 , 0 , 6 , 5 , 0 , 8 , 4 , 0 , 0 } , { 5 , 2 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 8 , 7 , 0 , 0 , 0 , 0 , 3 , 1 } , { 0 , 0 , 3 , 0 , 1 , 0 , 0 , 8 , 0 } , { 9 , 0 , 0 , 8 , 6 , 3 , 0 , 0 , 5 } , { 0 , 5 , 0 , 0 , 9 , 0 , 6 , 0 , 0 } , { 1 , 3 , 0 , 0 , 0 , 0 , 2 , 5 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 7 , 4 } , { 0 , 0 , 5 , 2 , 0 , 6 , 3 , 0 , 0 } } ; if ( solveSuduko ( grid , 0 , 0 ) ) print ( grid ) ; else cout << " no ▁ solution ▁ exists ▁ " << endl ; return 0 ; }
Subset Sum | Backtracking | ; prints subset found ; qsort compare function ; inputs s - set vector t - tuplet vector s_size - set size t_size - tuplet size so far sum - sum so far ite - nodes count target_sum - sum to be found ; We found sum ; constraint check ; Exclude previous added item and consider next candidate ; constraint check ; generate nodes along the breadth ; consider next level node ( along depth ) ; Wrapper that prints subsets that sum to target_sum ; sort the set ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ARRAYSIZE ( a ) (sizeof(a))/(sizeof(a[0])) NEW_LINE static int total_nodes ; void printSubset ( int A [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) { cout << " ▁ " << A [ i ] ; } cout << " STRNEWLINE " ; } int comparator ( const void * pLhs , const void * pRhs ) { int * lhs = ( int * ) pLhs ; int * rhs = ( int * ) pRhs ; return * lhs > * rhs ; } void subset_sum ( int s [ ] , int t [ ] , int s_size , int t_size , int sum , int ite , int const target_sum ) { total_nodes ++ ; if ( target_sum == sum ) { printSubset ( t , t_size ) ; if ( ite + 1 < s_size && sum - s [ ite ] + s [ ite + 1 ] <= target_sum ) { subset_sum ( s , t , s_size , t_size - 1 , sum - s [ ite ] , ite + 1 , target_sum ) ; } return ; } else { if ( ite < s_size && sum + s [ ite ] <= target_sum ) { for ( int i = ite ; i < s_size ; i ++ ) { t [ t_size ] = s [ i ] ; if ( sum + s [ i ] <= target_sum ) { subset_sum ( s , t , s_size , t_size + 1 , sum + s [ i ] , i + 1 , target_sum ) ; } } } } } void generateSubsets ( int s [ ] , int size , int target_sum ) { int * tuplet_vector = ( int * ) malloc ( size * sizeof ( int ) ) ; int total = 0 ; qsort ( s , size , sizeof ( int ) , & comparator ) ; for ( int i = 0 ; i < size ; i ++ ) { total += s [ i ] ; } if ( s [ 0 ] <= target_sum && total >= target_sum ) { subset_sum ( s , tuplet_vector , size , 0 , 0 , 0 , target_sum ) ; } free ( tuplet_vector ) ; } int main ( ) { int weights [ ] = { 15 , 22 , 14 , 26 , 32 , 9 , 16 , 8 } ; int target = 53 ; int size = ARRAYSIZE ( weights ) ; generateSubsets ( weights , size , target ) ; cout << " Nodes ▁ generated ▁ " << total_nodes ; return 0 ; }
Given an array A [ ] and a number x , check for pair in A [ ] with sum as x | C ++ program to check if given array has 2 elements whose sum is equal to the given value ; function to check for the given sum in the array ; checking for condition ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printPairs ( int arr [ ] , int arr_size , int sum ) { unordered_set < int > s ; for ( int i = 0 ; i < arr_size ; i ++ ) { int temp = sum - arr [ i ] ; if ( s . find ( temp ) != s . end ( ) ) cout << " Pair ▁ with ▁ given ▁ sum ▁ " << sum << " ▁ is ▁ ( " << arr [ i ] << " , " << temp << " ) " << endl ; s . insert ( arr [ i ] ) ; } } int main ( ) { int A [ ] = { 1 , 4 , 45 , 6 , 10 , 8 } ; int n = 16 ; int arr_size = sizeof ( A ) / sizeof ( A [ 0 ] ) ; printPairs ( A , arr_size , n ) ; return 0 ; }
Longest consecutive sequence in Binary tree | C / C ++ program to find longest consecutive sequence in binary tree ; A binary tree node has data , pointer to left child and a pointer to right child ; A utility function to create a node ; Utility method to return length of longest consecutive sequence of tree ; if root data has one more than its parent then increase current length ; update the maximum by current length ; recursively call left and right subtree with expected value 1 more than root data ; method returns length of longest consecutive sequence rooted at node root ; call utility method with current length 0 ; Driver code to test above methods
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } void longestConsecutiveUtil ( Node * root , int curLength , int expected , int & res ) { if ( root == NULL ) return ; if ( root -> data == expected ) curLength ++ ; else curLength = 1 ; res = max ( res , curLength ) ; longestConsecutiveUtil ( root -> left , curLength , root -> data + 1 , res ) ; longestConsecutiveUtil ( root -> right , curLength , root -> data + 1 , res ) ; } int longestConsecutive ( Node * root ) { if ( root == NULL ) return 0 ; int res = 0 ; longestConsecutiveUtil ( root , 0 , root -> data , res ) ; return res ; } int main ( ) { Node * root = newNode ( 6 ) ; root -> right = newNode ( 9 ) ; root -> right -> left = newNode ( 7 ) ; root -> right -> right = newNode ( 10 ) ; root -> right -> right -> right = newNode ( 11 ) ; printf ( " % d STRNEWLINE " , longestConsecutive ( root ) ) ; return 0 ; }
Find remainder when a number A raised to N factorial is divided by P | C ++ program for above approach ; Function to calculate ( A ^ N ! ) % P in O ( log y ) ; Initialize result ; Update x if it is more than or Equal to p ; In case x is divisible by p ; ; If y is odd , multiply x with result ; y must be even now ; Returning modular power ; Function to calculate resultant remainder ; Initializing ans to store final remainder ; Calculating remainder ; Returning resultant remainder ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long int power ( long long x , long long int y , long long int p ) { long long int res = 1 ; x = x % p ; if ( x == 0 ) return 0 ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % p ; y = y >> 1 ; x = ( x * x ) % p ; } return res ; } long long int remainder ( long long int n , long long int a , long long int p ) { long long int ans = a % p ; for ( long long int i = 1 ; i <= n ; i ++ ) ans = power ( ans , i , p ) ; return ans ; } int main ( ) { long long int A = 2 , N = 1 , P = 2 ; cout << remainder ( N , A , P ) << endl ; }
Find all array elements occurring more than Γ’Ε’Ε N / 3 Γ’Ε’ β€Ή times | C ++ program to find Majority element in an array ; Function to find Majority element in an array ; if this element is previously seen , increment count1 . ; if this element is previously seen , increment count2 . ; if current element is different from both the previously seen variables , decrement both the counts . ; gain traverse the array and find the actual counts . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMajority ( int arr [ ] , int n ) { int count1 = 0 , count2 = 0 ; int first = INT_MAX , second = INT_MAX ; int flag = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( first == arr [ i ] ) count1 ++ ; else if ( second == arr [ i ] ) count2 ++ ; else if ( count1 == 0 ) { count1 ++ ; first = arr [ i ] ; } else if ( count2 == 0 ) { count2 ++ ; second = arr [ i ] ; } else { count1 -- ; count2 -- ; } } count1 = 0 ; count2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == first ) count1 ++ ; else if ( arr [ i ] == second ) count2 ++ ; } if ( count1 > n / 3 ) { cout << first << " ▁ " ; flag = 1 ; } if ( count2 > n / 3 ) { cout << second << " ▁ " ; flag = 1 ; } if ( flag == 0 ) { cout << " No ▁ Majority ▁ Element " << endl ; } } int main ( ) { int arr [ ] = { 2 , 2 , 3 , 1 , 3 , 2 , 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findMajority ( arr , n ) ; return 0 ; }
Modular Exponentiation of Complex Numbers | ; Function to multiply two complex numbers modulo M ; Multiplication of two complex numbers is ( a + ib ) ( c + id ) = ( ac - bd ) + i ( ad + bc ) ; Return the multiplied value ; Function to calculate the complex modular exponentiation ; Here , res is initialised to ( 1 + i0 ) ; If k is odd ; Multiply ' complex ' with ' res ' ; Make complex as complex * complex ; Make k as k / 2 ; Return the required answer ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; pair < int , int > Multiply ( pair < int , int > p , pair < int , int > q , int M ) { int x = ( ( p . first * q . first ) % M - ( p . second * q . second ) % M + M ) % M ; int y = ( ( p . first * q . second ) % M + ( p . second * q . first ) % M ) % M ; return { x , y } ; } pair < int , int > compPow ( pair < int , int > complex , int k , int M ) { pair < int , int > res = { 1 , 0 } ; while ( k > 0 ) { if ( k & 1 ) { res = Multiply ( res , complex , M ) ; } complex = Multiply ( complex , complex , M ) ; k = k >> 1 ; } return res ; } int main ( ) { int A = 7 , B = 3 , k = 10 , M = 97 ; pair < int , int > ans = compPow ( { A , B } , k , M ) ; cout << ans . first << " ▁ + ▁ i " << ans . second ; return 0 ; }
Sum of maximum of all subarrays | Divide and Conquer | C ++ implementation of the above approach ; Array to store segment tree . In first we will store the maximum of a range In second , we will store index of that range ; Size of array declared global to maintain simplicity in code ; Function to build segment tree ; Base case ; Finding the maximum among left and right child ; Returning the maximum to parent ; Function to perform range - max query in segment tree ; Base cases ; Finding the maximum among left and right child ; Function to find maximum sum subarray ; base case ; range - max query to determine largest in the range . ; divide the array in two parts ; Driver Code ; Input array ; Size of array ; Builind the segment - tree
#include <bits/stdc++.h> NEW_LINE #define seg_max 51 NEW_LINE using namespace std ; pair < int , int > seg_tree [ seg_max ] ; int n ; pair < int , int > buildMaxTree ( int l , int r , int i , int arr [ ] ) { if ( l == r ) { seg_tree [ i ] = { arr [ l ] , l } ; return seg_tree [ i ] ; } seg_tree [ i ] = max ( buildMaxTree ( l , ( l + r ) / 2 , 2 * i + 1 , arr ) , buildMaxTree ( ( l + r ) / 2 + 1 , r , 2 * i + 2 , arr ) ) ; return seg_tree [ i ] ; } pair < int , int > rangeMax ( int l , int r , int arr [ ] , int i = 0 , int sl = 0 , int sr = n - 1 ) { if ( sr < l sl > r ) return { INT_MIN , -1 } ; if ( sl >= l and sr <= r ) return seg_tree [ i ] ; return max ( rangeMax ( l , r , arr , 2 * i + 1 , sl , ( sl + sr ) / 2 ) , rangeMax ( l , r , arr , 2 * i + 2 , ( sl + sr ) / 2 + 1 , sr ) ) ; } int maxSumSubarray ( int arr [ ] , int l = 0 , int r = n - 1 ) { if ( l > r ) return 0 ; pair < int , int > a = rangeMax ( l , r , arr ) ; return a . first * ( r - a . second + 1 ) * ( a . second - l + 1 ) + maxSumSubarray ( arr , l , a . second - 1 ) + maxSumSubarray ( arr , a . second + 1 , r ) ; } int main ( ) { int arr [ ] = { 1 , 3 , 1 , 7 } ; n = sizeof ( arr ) / sizeof ( int ) ; buildMaxTree ( 0 , n - 1 , 0 , arr ) ; cout << maxSumSubarray ( arr ) ; return 0 ; }
Modular exponentiation ( Recursive ) | Recursive C ++ program to compute modular power ; Base cases ; If B is even ; If B is odd ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int exponentMod ( int A , int B , int C ) { if ( A == 0 ) return 0 ; if ( B == 0 ) return 1 ; long y ; if ( B % 2 == 0 ) { y = exponentMod ( A , B / 2 , C ) ; y = ( y * y ) % C ; } else { y = A % C ; y = ( y * exponentMod ( A , B - 1 , C ) % C ) % C ; } return ( int ) ( ( y + C ) % C ) ; } int main ( ) { int A = 2 , B = 5 , C = 13 ; cout << " Power ▁ is ▁ " << exponentMod ( A , B , C ) ; 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 in O ( n ) time and O ( 1 ) space ; check if the current element is equal to previous element . ; reset the frequency ; print the last element and its frequency ; Driver code
#include <iostream> NEW_LINE using namespace std ; void findFrequencies ( int ele [ ] , int n ) { int freq = 1 ; int idx = 1 ; int element = ele [ 0 ] ; while ( idx < n ) { if ( ele [ idx - 1 ] == ele [ idx ] ) { freq ++ ; idx ++ ; } else { cout << element << " ▁ " << freq << endl ; element = ele [ idx ] ; idx ++ ; freq = 1 ; } } cout << element << " ▁ " << freq ; } int main ( ) { cout << " - - - frequencies ▁ in ▁ a ▁ sorted ▁ array - - - - " << endl ; int arr [ ] = { 10 , 20 , 30 , 30 , 30 , 40 , 50 , 50 , 50 , 50 , 70 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findFrequencies ( arr , n ) ; }
Modular Exponentiation ( Power in Modular Arithmetic ) | Iterative Function to calculate ( x ^ y ) in O ( log y ) ; Initialize answer ; If y is odd , multiply x with result ; y = y / 2 ; Change x to x ^ 2
int power ( int x , int y ) { int res = 1 ; while ( y ) { if ( y % 2 == 1 ) res = ( res * x ) ; y = y >> 1 ; x = ( x * x ) ; } return res ; }
Modular Exponentiation ( Power in Modular Arithmetic ) | Iterative C ++ program to compute modular power ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize result ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now ; Driver code
#include <iostream> NEW_LINE using namespace std ; int power ( long long x , unsigned int y , int p ) { int res = 1 ; x = x % p ; if ( x == 0 ) return 0 ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % p ; y = y >> 1 ; y = y / 2 x = ( x * x ) % p ; } return res ; } int main ( ) { int x = 2 ; int y = 5 ; int p = 13 ; cout << " Power ▁ is ▁ " << power ( x , y , p ) ; return 0 ; }
Path length having maximum number of bends | C ++ program to find path length having maximum number of bends ; structure node ; Utility function to create a new node ; Recursive function to calculate the path length having maximum number of bends . The following are parameters for this function . node -- > pointer to the current node dir -- > determines whether the current node is left or right child of it 's parent node bends --> number of bends so far in the current path. maxBends --> maximum number of bends in a path from root to leaf soFar --> length of the current path so far traversed len --> length of the path having maximum number of bends ; Base Case ; Leaf node ; Recurring for both left and right child ; Helper function to call findMaxBendsUtil ( ) ; Call for left subtree of the root ; Call for right subtree of the root ; Include the root node as well in the path length ; Driver code ; Constructed binary tree is 10 / \ 8 2 / \ / 3 5 2 \ 1 / 9
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * left ; struct Node * right ; } ; struct Node * newNode ( int key ) { struct Node * node = new Node ( ) ; node -> left = NULL ; node -> right = NULL ; node -> key = key ; return node ; } void findMaxBendsUtil ( struct Node * node , char dir , int bends , int * maxBends , int soFar , int * len ) { if ( node == NULL ) return ; if ( node -> left == NULL && node -> right == NULL ) { if ( bends > * maxBends ) { * maxBends = bends ; * len = soFar ; } } else { if ( dir == ' l ' ) { findMaxBendsUtil ( node -> left , dir , bends , maxBends , soFar + 1 , len ) ; findMaxBendsUtil ( node -> right , ' r ' , bends + 1 , maxBends , soFar + 1 , len ) ; } else { findMaxBendsUtil ( node -> right , dir , bends , maxBends , soFar + 1 , len ) ; findMaxBendsUtil ( node -> left , ' l ' , bends + 1 , maxBends , soFar + 1 , len ) ; } } } int findMaxBends ( struct Node * node ) { if ( node == NULL ) return 0 ; int len = 0 , bends = 0 , maxBends = -1 ; if ( node -> left ) findMaxBendsUtil ( node -> left , ' l ' , bends , & maxBends , 1 , & len ) ; if ( node -> right ) findMaxBendsUtil ( node -> right , ' r ' , bends , & maxBends , 1 , & len ) ; len ++ ; return len ; } int main ( ) { struct Node * root = newNode ( 10 ) ; root -> left = newNode ( 8 ) ; root -> right = newNode ( 2 ) ; root -> left -> left = newNode ( 3 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> left = newNode ( 2 ) ; root -> right -> left -> right = newNode ( 1 ) ; root -> right -> left -> right -> left = newNode ( 9 ) ; cout << findMaxBends ( root ) - 1 ; return 0 ; }
Program to calculate angle between two N | C ++ program for the above approach ; Function to find the magnitude of the given vector ; Stores the final magnitude ; Traverse the array ; Return square root of magnitude ; Function to find the dot product of two vectors ; Stores dot product ; Traverse the array ; Return the product ; Stores dot product of two vectors ; Stores magnitude of vector A ; Stores magnitude of vector B ; Stores angle between given vectors ; Print the angle ; Driver Code ; Given magnitude arrays ; Size of the array ; Function call to find the angle between two vectors
#include <bits/stdc++.h> NEW_LINE using namespace std ; double magnitude ( double arr [ ] , int N ) { double magnitude = 0 ; for ( int i = 0 ; i < N ; i ++ ) magnitude += arr [ i ] * arr [ i ] ; return sqrt ( magnitude ) ; } double dotProduct ( double arr [ ] , double brr [ ] , int N ) { double product = 0 ; for ( int i = 0 ; i < N ; i ++ ) product = product + arr [ i ] * brr [ i ] ; return product ; } void angleBetweenVectors ( double arr [ ] , double brr [ ] , int N ) { double dotProductOfVectors = dotProduct ( arr , brr , N ) ; double magnitudeOfA = magnitude ( arr , N ) ; double magnitudeOfB = magnitude ( brr , N ) ; double angle = dotProductOfVectors / ( magnitudeOfA * magnitudeOfB ) ; cout << angle ; } int main ( ) { double arr [ ] = { -0.5 , -2 , 1 } ; double brr [ ] = { -1 , -1 , 0.3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; angleBetweenVectors ( arr , brr , N ) ; return 0 ; }
Sum of sides of largest and smallest child polygons possible from a given polygon | ; Function to find the sum of largest and smallest secondary polygons if possible ; Count edges of primary polygon ; Calculate edges present in the largest secondary polygon ; Driver Code ; Given Exterior Angle
#include <bits/stdc++.h> NEW_LINE using namespace std ; void secondary_polygon ( int Angle ) { int edges_primary = 360 / Angle ; if ( edges_primary >= 6 ) { int edges_max_secondary = edges_primary / 2 ; cout << edges_max_secondary + 3 ; } else cout << " Not ▁ Possible " ; } int main ( ) { int Angle = 45 ; secondary_polygon ( Angle ) ; return 0 ; }
Area of Circumcircle of an Equilateral Triangle using Median | C ++ implementation to find the equation of circle which inscribes equilateral triangle of median M ; Function to find the equation of circle whose center is ( x1 , y1 ) and the radius of circle is r ; Function to find the equation of circle which inscribes equilateral triangle of median M ; Util Function to find the circle equation ; Driver code ; Function Call
#include <iostream> NEW_LINE const double pi = 3.14159265358979323846 ; using namespace std ; void circleArea ( double r ) { cout << ( pi * r * r ) ; } void findCircleAreaByMedian ( double m ) { double r = 2 * m / 3 ; circleArea ( r ) ; } int main ( ) { double m = 3 ; findCircleAreaByMedian ( m ) ; return 0 ; }
Number of turns to reach from one node to other in binary tree | C ++ Program to count number of turns in a Binary Tree . ; A Binary Tree Node ; Utility function to create a new tree Node ; Utility function to find the LCA of two given values n1 and n2 . ; Base case ; If either n1 or n2 matches with root 's key, report the presence by returning root (Note that if a key is ancestor of other, then the ancestor key becomes LCA ; Look for keys in left and right subtrees ; If both of the above calls return Non - NULL , then one key is present in once subtree and other is present in other , So this node is the LCA ; Otherwise check if left subtree or right subtree is LCA ; function count number of turn need to reach given node from it 's LCA we have two way to ; if found the key value in tree ; Case 1 : ; Case 2 : ; Function to find nodes common to given two nodes ; there is no path between these two node ; case 1 : ; count number of turns needs to reached the second node from LCA ; count number of turns needs to reached the first node from LCA ; case 2 : ; count number of turns needs to reached the second node from LCA ; count number of turns needs to reached the first node from LCA1 ; Driver program to test above functions ; Let us create binary tree given in the above example
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { struct Node * left , * right ; int key ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return temp ; } struct Node * findLCA ( struct Node * root , int n1 , int n2 ) { if ( root == NULL ) return NULL ; if ( root -> key == n1 root -> key == n2 ) return root ; Node * left_lca = findLCA ( root -> left , n1 , n2 ) ; Node * right_lca = findLCA ( root -> right , n1 , n2 ) ; if ( left_lca && right_lca ) return root ; return ( left_lca != NULL ) ? left_lca : right_lca ; } bool CountTurn ( Node * root , int key , bool turn , int * count ) { if ( root == NULL ) return false ; if ( root -> key == key ) return true ; if ( turn == true ) { if ( CountTurn ( root -> left , key , turn , count ) ) return true ; if ( CountTurn ( root -> right , key , ! turn , count ) ) { * count += 1 ; return true ; } } else { if ( CountTurn ( root -> right , key , turn , count ) ) return true ; if ( CountTurn ( root -> left , key , ! turn , count ) ) { * count += 1 ; return true ; } } return false ; } int NumberOFTurn ( struct Node * root , int first , int second ) { struct Node * LCA = findLCA ( root , first , second ) ; if ( LCA == NULL ) return -1 ; int Count = 0 ; if ( LCA -> key != first && LCA -> key != second ) { if ( CountTurn ( LCA -> right , second , false , & Count ) || CountTurn ( LCA -> left , second , true , & Count ) ) ; if ( CountTurn ( LCA -> left , first , true , & Count ) || CountTurn ( LCA -> right , first , false , & Count ) ) ; return Count + 1 ; } if ( LCA -> key == first ) { CountTurn ( LCA -> right , second , false , & Count ) ; CountTurn ( LCA -> left , second , true , & Count ) ; return Count ; } else { CountTurn ( LCA -> right , first , false , & Count ) ; CountTurn ( LCA -> left , first , true , & Count ) ; return Count ; } } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> left = newNode ( 6 ) ; root -> right -> right = newNode ( 7 ) ; root -> left -> left -> left = newNode ( 8 ) ; root -> right -> left -> left = newNode ( 9 ) ; root -> right -> left -> right = newNode ( 10 ) ; int turn = 0 ; if ( ( turn = NumberOFTurn ( root , 5 , 10 ) ) ) cout << turn << endl ; else cout << " Not ▁ Possible " << endl ; return 0 ; }
Find the type of triangle from the given sides | C ++ implementation to find the type of triangle with the help of the sides ; Function to find the type of triangle with the help of sides ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void checkTypeOfTriangle ( int a , int b , int c ) { int sqa = pow ( a , 2 ) ; int sqb = pow ( b , 2 ) ; int sqc = pow ( c , 2 ) ; if ( sqa == sqb + sqc sqb == sqc + sqa sqc == sqa + sqb ) { cout << " Right - angled ▁ Triangle " ; } else if ( sqa > sqc + sqb sqb > sqa + sqc sqc > sqa + sqb ) { cout << " Obtuse - angled ▁ Triangle " ; } else { cout << " Acute - angled ▁ Triangle " ; } } int main ( ) { int a , b , c ; a = 2 ; b = 2 ; c = 2 ; checkTypeOfTriangle ( a , b , c ) ; return 0 ; }
Check whether the triangle is valid or not if angles are given | C ++ implementation of the approach ; Function to check if sum of the three angles is 180 or not ; Check condition ; Driver code ; function call ing and print output
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool Valid ( int a , int b , int c ) { if ( a + b + c == 180 && a != 0 && b != 0 && c != 0 ) return true ; else return false ; } int main ( ) { int a = 60 , b = 40 , c = 80 ; if ( Valid ( a , b , c ) ) cout << " Valid " ; else cout << " Invalid " ; }
Area of the Largest Triangle inscribed in a Hexagon | C ++ Program to find the biggest triangle which can be inscribed within the hexagon ; Function to find the area of the triangle ; side cannot be negative ; area of the triangle ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; float trianglearea ( float a ) { if ( a < 0 ) return -1 ; float area = ( 3 * sqrt ( 3 ) * pow ( a , 2 ) ) / 4 ; return area ; } int main ( ) { float a = 6 ; cout << trianglearea ( a ) << endl ; return 0 ; }
Equation of ellipse from its focus , directrix , and eccentricity | C ++ program to find equation of an ellipse using focus and directrix . ; Function to find equation of ellipse . ; Driver Code
#include <bits/stdc++.h> NEW_LINE #include <iomanip> NEW_LINE #include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; void equation_ellipse ( float x1 , float y1 , float a , float b , float c , float e ) { float t = a * a + b * b ; float a1 = t - e * ( a * a ) ; float b1 = t - e * ( b * b ) ; float c1 = ( -2 * t * x1 ) - ( 2 * e * c * a ) ; float d1 = ( -2 * t * y1 ) - ( 2 * e * c * b ) ; float e1 = -2 * e * a * b ; float f1 = ( - e * c * c ) + ( t * x1 * x1 ) + ( t * y1 * y1 ) ; cout << fixed ; cout << setprecision ( 2 ) ; cout << " Equation ▁ of ▁ ellipse ▁ is ▁ STRNEWLINE " << a1 << " ▁ x ^ 2 ▁ + ▁ " << b1 << " ▁ y ^ 2 ▁ + ▁ " << c1 << " ▁ x ▁ + ▁ " << d1 << " ▁ y ▁ + ▁ " << e1 << " ▁ xy ▁ + ▁ " << f1 << " ▁ = ▁ 0" ; } int main ( ) { float x1 = 1 , y1 = 1 , a = 1 , b = -1 , c = 3 , e = 0.5 * 0.5 ; equation_ellipse ( x1 , y1 , a , b , c , e ) ; return 0 ; }
Create loops of even and odd values in a binary tree | C ++ implementation to create odd and even loops in a binary tree ; structure of a node ; Utility function to create a new node ; preorder traversal to place the node pointer in the respective even_ptrs or odd_ptrs list ; place node ptr in even_ptrs list if node contains even number ; else place node ptr in odd_ptrs list ; function to create the even and odd loops ; forming even loop ; for the last element ; Similarly forming odd loop ; traversing the loop from any random node in the loop ; Driver program to test above ; Binary tree formation ; traversing odd loop from any random odd node ; traversing even loop from any random even node
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right , * abtr ; } ; struct Node * newNode ( int data ) { struct Node * node = new Node ; node -> data = data ; node -> left = node -> right = node -> abtr = NULL ; return node ; } void preorderTraversal ( Node * root , vector < Node * > * even_ptrs , vector < Node * > * odd_ptrs ) { if ( ! root ) return ; if ( root -> data % 2 == 0 ) ( * even_ptrs ) . push_back ( root ) ; else ( * odd_ptrs ) . push_back ( root ) ; preorderTraversal ( root -> left , even_ptrs , odd_ptrs ) ; preorderTraversal ( root -> right , even_ptrs , odd_ptrs ) ; } void createLoops ( Node * root ) { vector < Node * > even_ptrs , odd_ptrs ; preorderTraversal ( root , & even_ptrs , & odd_ptrs ) ; int i ; for ( i = 1 ; i < even_ptrs . size ( ) ; i ++ ) even_ptrs [ i - 1 ] -> abtr = even_ptrs [ i ] ; even_ptrs [ i - 1 ] -> abtr = even_ptrs [ 0 ] ; for ( i = 1 ; i < odd_ptrs . size ( ) ; i ++ ) odd_ptrs [ i - 1 ] -> abtr = odd_ptrs [ i ] ; odd_ptrs [ i - 1 ] -> abtr = odd_ptrs [ 0 ] ; } void traverseLoop ( Node * start ) { Node * curr = start ; do { cout << curr -> data << " ▁ " ; curr = curr -> abtr ; } while ( curr != start ) ; } int main ( ) { struct Node * root = NULL ; root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> left = newNode ( 6 ) ; root -> right -> right = newNode ( 7 ) ; createLoops ( root ) ; cout << " Odd ▁ nodes : ▁ " ; traverseLoop ( root -> right ) ; cout << endl << " Even ▁ nodes : ▁ " ; traverseLoop ( root -> left ) ; return 0 ; }
Area of circle which is inscribed in equilateral triangle | C ++ program to find the area of circle which is inscribed in equilateral triangle ; Function return the area of circle inscribed in equilateral triangle ; Driver code
# include <bits/stdc++.h> NEW_LINE # define PI 3.14 NEW_LINE using namespace std ; float circle_inscribed ( int a ) { return PI * ( a * a ) / 12 ; } int main ( ) { int a = 4 ; cout << circle_inscribed ( a ) ; return 0 ; }
Program to find the Volume of an irregular tetrahedron | C ++ implementation of above approach ; Function to find the volume ; Steps to calculate volume of a Tetrahedron using formula ; Driver code ; edge lengths
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define db double NEW_LINE void findVolume ( db u , db v , db w , db U , db V , db W , db b ) { db uPow = pow ( u , 2 ) ; db vPow = pow ( v , 2 ) ; db wPow = pow ( w , 2 ) ; db UPow = pow ( U , 2 ) ; db VPow = pow ( V , 2 ) ; db WPow = pow ( W , 2 ) ; db a = 4 * ( uPow * vPow * wPow ) - uPow * pow ( ( vPow + wPow - UPow ) , 2 ) - vPow * pow ( ( wPow + uPow - VPow ) , 2 ) - wPow * pow ( ( uPow + vPow - WPow ) , 2 ) + ( vPow + wPow - UPow ) * ( wPow + uPow - VPow ) * ( uPow + vPow - WPow ) ; db vol = sqrt ( a ) ; vol /= b ; cout << fixed << setprecision ( 4 ) << vol ; } int main ( ) { db u = 1000 , v = 1000 , w = 1000 ; db U = 3 , V = 4 , W = 5 ; db b = 12 ; findVolume ( u , v , w , U , V , W , b ) ; return 0 ; }
Check if it is possible to create a polygon with a given angle | C ++ implementation of above approach ; Function to check whether it is possible to make a regular polygon with a given angle . ; N denotes the number of sides of polygons possible ; Driver code ; function to print the required answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; void makePolygon ( float a ) { float n = 360 / ( 180 - a ) ; if ( n == ( int ) n ) cout << " YES " ; else cout << " NO " ; } int main ( ) { float a = 90 ; makePolygon ( a ) ; return 0 ; }
Finding Quadrant of a Coordinate with respect to a Circle | CPP Program to find the quadrant of a given coordinate with respect to the centre of a circle ; Thus function returns the quadrant number ; Coincides with center ; Outside circle ; 1 st quadrant ; 2 nd quadrant ; 3 rd quadrant ; 4 th quadrant ; Driver Code ; Coordinates of centre ; Radius of circle ; Coordinates of the given point
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getQuadrant ( int X , int Y , int R , int PX , int PY ) { if ( PX == X && PY == Y ) return 0 ; int val = pow ( ( PX - X ) , 2 ) + pow ( ( PY - Y ) , 2 ) ; if ( val > pow ( R , 2 ) ) return -1 ; if ( PX > X && PY >= Y ) return 1 ; if ( PX <= X && PY > Y ) return 2 ; if ( PX < X && PY <= Y ) return 3 ; if ( PX >= X && PY < Y ) return 4 ; } int main ( ) { int X = 0 , Y = 3 ; int R = 2 ; int PX = 1 , PY = 4 ; int ans = getQuadrant ( X , Y , R , PX , PY ) ; if ( ans == -1 ) cout << " Lies ▁ Outside ▁ the ▁ circle " << endl ; else if ( ans == 0 ) cout << " Coincides ▁ with ▁ centre " << endl ; else cout << ans << " ▁ Quadrant " << endl ; return 0 ; }
Hexadecagonal number | C ++ program to find Nth hexadecagon number ; Function to calculate hexadecagonal number ; Drivers Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int hexadecagonalNum ( long int n ) { return ( ( 14 * n * n ) - 12 * n ) / 2 ; } int main ( ) { long int n = 5 ; cout << n << " th ▁ Hexadecagonal ▁ number ▁ : ▁ " ; cout << hexadecagonalNum ( n ) ; cout << endl ; n = 9 ; cout << n << " th ▁ Hexadecagonal ▁ number ▁ : ▁ " ; cout << hexadecagonalNum ( n ) ; return 0 ; }
Find first non matching leaves in two binary trees | C ++ program to find first leaves that are not same . ; Tree node ; Utility method to create a new node ; Prints the first non - matching leaf node in two trees if it exists , else prints nothing . ; If any of the tree is empty ; Create two stacks for preorder traversals ; If traversal of one tree is over and other tree still has nodes . ; Do iterative traversal of first tree and find first lead node in it as " temp1" ; pushing right childfirst so that left child comes first while popping . ; Do iterative traversal of second tree and find first lead node in it as " temp2" ; If we found leaves in both trees ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int x ) { Node * temp = new Node ; temp -> data = x ; temp -> left = temp -> right = NULL ; return temp ; } bool isLeaf ( Node * t ) { return ( ( t -> left == NULL ) && ( t -> right == NULL ) ) ; } void findFirstUnmatch ( Node * root1 , Node * root2 ) { if ( root1 == NULL root2 == NULL ) return ; stack < Node * > s1 , s2 ; s1 . push ( root1 ) ; s2 . push ( root2 ) ; while ( ! s1 . empty ( ) || ! s2 . empty ( ) ) { if ( s1 . empty ( ) || s2 . empty ( ) ) return ; Node * temp1 = s1 . top ( ) ; s1 . pop ( ) ; while ( temp1 && ! isLeaf ( temp1 ) ) { s1 . push ( temp1 -> right ) ; s1 . push ( temp1 -> left ) ; temp1 = s1 . top ( ) ; s1 . pop ( ) ; } Node * temp2 = s2 . top ( ) ; s2 . pop ( ) ; while ( temp2 && ! isLeaf ( temp2 ) ) { s2 . push ( temp2 -> right ) ; s2 . push ( temp2 -> left ) ; temp2 = s2 . top ( ) ; s2 . pop ( ) ; } if ( temp1 != NULL && temp2 != NULL ) { if ( temp1 -> data != temp2 -> data ) { cout << " First ▁ non ▁ matching ▁ leaves ▁ : ▁ " << temp1 -> data << " ▁ " << temp2 -> data << endl ; return ; } } } } int main ( ) { struct Node * root1 = newNode ( 5 ) ; root1 -> left = newNode ( 2 ) ; root1 -> right = newNode ( 7 ) ; root1 -> left -> left = newNode ( 10 ) ; root1 -> left -> right = newNode ( 11 ) ; struct Node * root2 = newNode ( 6 ) ; root2 -> left = newNode ( 10 ) ; root2 -> right = newNode ( 15 ) ; findFirstUnmatch ( root1 , root2 ) ; return 0 ; }
Maximum points of intersection n circles | CPP program to find maximum umber of intersections of n circles ; Returns maximum number of intersections ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int intersection ( int n ) { return n * ( n - 1 ) ; } int main ( ) { cout << intersection ( 3 ) << endl ; return 0 ; }
Find the perimeter of a cylinder | CPP program to find perimeter of cylinder ; Function to calculate perimeter ; Driver function
#include <iostream> NEW_LINE using namespace std ; int perimeter ( int diameter , int height ) { return 2 * ( diameter + height ) ; } int main ( ) { int diameter = 5 ; int height = 10 ; cout << " Perimeter ▁ = ▁ " ; cout << perimeter ( diameter , height ) ; cout << " ▁ units STRNEWLINE " ; return 0 ; }
Find all possible coordinates of parallelogram | C ++ program to all possible points 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 + bx - cx << " , ▁ " << ay + by - cy << endl ; cout << ax + cx - bx << " , ▁ " << ay + cy - by << endl ; cout << cx + bx - ax << " , ▁ " << cy + by - ax << endl ; return 0 ; }
Check whether a given point lies inside a rectangle or not | ; A utility function to calculate area of triangle formed by ( x1 , y1 ) , ( x2 , y2 ) and ( x3 , y3 ) ; A function to check whether point P ( x , y ) lies inside the rectangle formed by A ( x1 , y1 ) , B ( x2 , y2 ) , C ( x3 , y3 ) and D ( x4 , y4 ) ; Calculate area of rectangle ABCD ; Calculate area of triangle PAB ; Calculate area of triangle PBC ; Calculate area of triangle PCD ; Calculate area of triangle PAD ; Check if sum of A1 , A2 , A3 and A4 is same as A ; Driver program to test above function ; Let us check whether the point P ( 10 , 15 ) lies inside the rectangle formed by A ( 0 , 10 ) , B ( 10 , 0 ) C ( 0 , - 10 ) D ( - 10 , 0 )
#include <bits/stdc++.h> NEW_LINE using namespace std ; float area ( int x1 , int y1 , int x2 , int y2 , int x3 , int y3 ) { return abs ( ( x1 * ( y2 - y3 ) + x2 * ( y3 - y1 ) + x3 * ( y1 - y2 ) ) / 2.0 ) ; } bool check ( int x1 , int y1 , int x2 , int y2 , int x3 , int y3 , int x4 , int y4 , int x , int y ) { float A = area ( x1 , y1 , x2 , y2 , x3 , y3 ) + area ( x1 , y1 , x4 , y4 , x3 , y3 ) ; float A1 = area ( x , y , x1 , y1 , x2 , y2 ) ; float A2 = area ( x , y , x2 , y2 , x3 , y3 ) ; float A3 = area ( x , y , x3 , y3 , x4 , y4 ) ; float A4 = area ( x , y , x1 , y1 , x4 , y4 ) ; return ( A == A1 + A2 + A3 + A4 ) ; } int main ( ) { if ( check ( 0 , 10 , 10 , 0 , 0 , -10 , -10 , 0 , 10 , 15 ) ) cout << " yes " ; else cout << " no " ; return 0 ; }
Get maximum left node in binary tree | CPP program to print maximum element in left node . ; A Binary Tree Node ; Get max of left element using Inorder traversal ; Return maximum of three values 1 ) Recursive max in left subtree 2 ) Value in left node 3 ) Recursive max in right subtree ; Utility function to create a new tree node ; Driver program to test above functions ; Let us create binary tree shown in above diagram ; 7 / \ 6 5 / \ / \ 4 3 2 1
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; int maxOfLeftElement ( Node * root ) { int res = INT_MIN ; if ( root == NULL ) return res ; if ( root -> left != NULL ) res = root -> left -> data ; return max ( { maxOfLeftElement ( root -> left ) , res , maxOfLeftElement ( root -> right ) } ) ; } Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } int main ( ) { Node * root = newNode ( 7 ) ; root -> left = newNode ( 6 ) ; root -> right = newNode ( 5 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 3 ) ; root -> right -> left = newNode ( 2 ) ; root -> right -> right = newNode ( 1 ) ; cout << maxOfLeftElement ( root ) ; return 0 ; }
Pizza cut problem ( Or Circle Division by Lines ) | C ++ program to find maximum no of pieces by given number of cuts ; Function for finding maximum pieces with n cuts . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaximumPieces ( int n ) { return 1 + n * ( n + 1 ) / 2 ; } int main ( ) { cout << findMaximumPieces ( 3 ) ; return 0 ; }
Optimum location of point to minimize total distance | C / C ++ program to find optimum location and total cost ; structure defining a point ; structure defining a line of ax + by + c = 0 form ; method to get distance of point ( x , y ) from point p ; Utility method to compute total distance all points when choose point on given line has x - coordinate value as X ; calculating Y of chosen point by line equation ; Utility method to find minimum total distance ; loop until difference between low and high become less than EPS ; mid1 and mid2 are representative x co - ordiantes of search space ; if mid2 point gives more total distance , skip third part ; if mid1 point gives more total distance , skip first part ; compute optimum distance cost by sending average of low and high as X ; method to find optimum cost ; converting 2D array input to point array ; Driver code to test above method
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define sq ( x ) ((x) * (x)) NEW_LINE #define EPS 1e-6 NEW_LINE #define N 5 NEW_LINE struct point { int x , y ; point ( ) { } point ( int x , int y ) : x ( x ) , y ( y ) { } } ; struct line { int a , b , c ; line ( int a , int b , int c ) : a ( a ) , b ( b ) , c ( c ) { } } ; double dist ( double x , double y , point p ) { return sqrt ( sq ( x - p . x ) + sq ( y - p . y ) ) ; } double compute ( point p [ ] , int n , line l , double X ) { double res = 0 ; double Y = -1 * ( l . c + l . a * X ) / l . b ; for ( int i = 0 ; i < n ; i ++ ) res += dist ( X , Y , p [ i ] ) ; return res ; } double findOptimumCostUtil ( point p [ ] , int n , line l ) { double low = -1e6 ; double high = 1e6 ; while ( ( high - low ) > EPS ) { double mid1 = low + ( high - low ) / 3 ; double mid2 = high - ( high - low ) / 3 ; double dist1 = compute ( p , n , l , mid1 ) ; double dist2 = compute ( p , n , l , mid2 ) ; if ( dist1 < dist2 ) high = mid2 ; else low = mid1 ; } return compute ( p , n , l , ( low + high ) / 2 ) ; } double findOptimumCost ( int points [ N ] [ 2 ] , line l ) { point p [ N ] ; for ( int i = 0 ; i < N ; i ++ ) p [ i ] = point ( points [ i ] [ 0 ] , points [ i ] [ 1 ] ) ; return findOptimumCostUtil ( p , N , l ) ; } int main ( ) { line l ( 1 , -1 , -3 ) ; int points [ N ] [ 2 ] = { { -3 , -2 } , { -1 , 0 } , { -1 , 2 } , { 1 , 2 } , { 3 , 4 } } ; cout << findOptimumCost ( points , l ) << endl ; return 0 ; }
Klee 's Algorithm (Length Of Union Of Segments of a line) | C ++ program to implement Klee 's algorithm ; Returns sum of lengths covered by union of given segments ; Initialize empty points container ; Create a vector to store starting and ending points ; Sorting all points by point value ; Initialize result ; To keep track of counts of current open segments ( Starting point is processed , but ending point is not ) ; Traverse through all points ; If there are open points , then we add the difference between previous and current point . ; If this is an ending point , reduce , count of open points . ; Driver program for the above code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int segmentUnionLength ( const vector < pair < int , int > > & seg ) { int n = seg . size ( ) ; vector < pair < int , bool > > points ( n * 2 ) ; for ( int i = 0 ; i < n ; i ++ ) { points [ i * 2 ] = make_pair ( seg [ i ] . first , false ) ; points [ i * 2 + 1 ] = make_pair ( seg [ i ] . second , true ) ; } sort ( points . begin ( ) , points . end ( ) ) ; int result = 0 ; int Counter = 0 ; for ( unsigned i = 0 ; i < n * 2 ; i ++ ) { if ( Counter ) result += ( points [ i ] . first - points [ i - 1 ] . first ) ; ( points [ i ] . second ) ? Counter -- : Counter ++ ; } return result ; } int main ( ) { vector < pair < int , int > > segments ; segments . push_back ( make_pair ( 2 , 5 ) ) ; segments . push_back ( make_pair ( 4 , 8 ) ) ; segments . push_back ( make_pair ( 9 , 12 ) ) ; cout << segmentUnionLength ( segments ) << endl ; return 0 ; }
Find all duplicate and missing numbers in given permutation array of 1 to N | C ++ program for the above approach ; Function to find the duplicate and the missing elements over the range [ 1 , N ] ; Stores the missing and duplicate numbers in the array arr [ ] ; Making an iterator for set ; Traverse the given array arr [ ] ; Check if the current element is not same as the element at index arr [ i ] - 1 , then swap ; Otherwise , increment the index ; Traverse the array again ; If the element is not at its correct position ; Stores the missing and the duplicate elements ; Print the Missing Number ; Print the Duplicate Number ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findElements ( int arr [ ] , int N ) { int i = 0 ; vector < int > missing ; set < int > duplicate ; set < int > :: iterator it ; while ( i != N ) { cout << i << " ▁ # ▁ " ; if ( arr [ i ] != arr [ arr [ i ] - 1 ] ) { swap ( arr [ i ] , arr [ arr [ i ] - 1 ] ) ; } else { i ++ ; } } for ( i = 0 ; i < N ; i ++ ) { if ( arr [ i ] != i + 1 ) { missing . push_back ( i + 1 ) ; duplicate . insert ( arr [ i ] ) ; } } cout << " Missing ▁ Numbers : ▁ " ; for ( auto & it : missing ) cout << it << ' ▁ ' ; cout << " Duplicate Numbers : " for ( auto & it : duplicate ) cout << it << ' ▁ ' ; } int main ( ) { int arr [ ] = { 1 , 2 , 2 , 2 , 4 , 5 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findElements ( arr , N ) ; return 0 ; }
Check if elements of given array can be rearranged such that ( arr [ i ] + i * K ) % N = i for all values of i in range [ 0 , N | C ++ program for the above approach ; Function to check if it is possible to generate all numbers in range [ 0 , N - 1 ] using the sum of elements in the multiset A and B mod N ; If no more pair of elements can be selected ; If the number of elements in C = N , then return true ; Otherwise return false ; Stores the value of final answer ; Iterate through all the pairs in the given multiset A and B ; Stores the set A without x ; Stores the set B without y ; Stores the set C with ( x + y ) % N ; Recursive call ; Return Answer ; Function to check if it is possible to rearrange array elements such that ( arr [ i ] + i * K ) % N = i ; Stores the values of arr [ ] modulo N ; Stores all the values of i * K modulo N ; Print Answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPossible ( multiset < int > A , multiset < int > B , set < int > C , int N ) { if ( A . size ( ) == 0 || B . size ( ) == 0 ) { if ( C . size ( ) == N ) { return true ; } else { return false ; } } bool ans = false ; for ( auto x : A ) { for ( auto y : B ) { multiset < int > _A = A ; _A . erase ( _A . find ( x ) ) ; multiset < int > _B = B ; _B . erase ( _B . find ( y ) ) ; set < int > _C = C ; _C . insert ( ( x + y ) % N ) ; ans = ( ans || isPossible ( _A , _B , _C , N ) ) ; } } return ans ; } void rearrangeArray ( int arr [ ] , int N , int K ) { multiset < int > A ; for ( int i = 0 ; i < N ; i ++ ) { A . insert ( arr [ i ] % N ) ; } multiset < int > B ; for ( int i = 0 ; i < N ; i ++ ) { B . insert ( ( i * K ) % N ) ; } set < int > C ; if ( isPossible ( A , B , C , N ) ) { cout << " YES " ; } else { cout << " NO " ; } } int main ( ) { int arr [ ] = { 1 , 2 , 0 } ; int K = 5 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; rearrangeArray ( arr , N , K ) ; return 0 ; }
Height of Factor Tree for a given number | C ++ program for the above approach ; Function to find the height of the Factor Tree of the integer N ; Stores the height of Factor Tree ; Loop to iterate over values of N ; Stores if there exist a factor of N or not ; Loop to find the smallest factor of N ; If i is a factor of N ; Increment the height ; If there are no factors of N i . e , N is prime , break loop ; Return Answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int factorTree ( int N ) { int height = 0 ; while ( N > 1 ) { bool flag = false ; for ( int i = 2 ; i <= sqrt ( N ) ; i ++ ) { if ( N % i == 0 ) { N = N / i ; flag = true ; break ; } } height ++ ; if ( ! flag ) { break ; } } return height ; } int main ( ) { int N = 48 ; cout << factorTree ( N ) ; return 0 ; }
Maximize the largest number K such that bitwise and of K till N is 0 | C ++ program for above approach ; Function to find maximum value of k which makes bitwise AND zero . ; Finding the power less than N ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaxK ( int N ) { int p = log2 ( N ) ; return pow ( 2 , p ) ; } int main ( ) { int N = 5 ; cout << findMaxK ( N ) - 1 << endl ; return 0 ; }
Count of Ks in the Array for a given range of indices after array updates for Q queries | C ++ program for the above approach ; Function to build the segment tree ; Base case ; Since the count of zero is required set leaf node as 1 ; If the value in array is not zero , store 0 in the leaf node ; Find the mid ; Recursive call for left subtree ; Recursive call for right subtree ; Parent nodes contains the count of zero in range tl to tr ; Function to find the count of 0 s in range l to r ; Base Case ; Case when no two segment are combining ; Finding the mid ; When it is required to combine left subtree and right subtree to get the range l to r ; Function that updates the segment tree nodes ; Base Case ; If array element is 0 ; If array element is not 0 ; Otherwise ; Find the mid ; Update the tree or count which is stored in parent node ; Function to solve all the queries ; When query type is 1 ; When query type is 2 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void build_tree ( vector < int > & a , vector < int > & seg_tree , int v , int tl , int tr ) { if ( tl == tr ) { if ( a [ tl ] == 0 ) seg_tree [ v ] = 1 ; else seg_tree [ v ] = 0 ; } else { int tm = ( tl + tr ) / 2 ; build_tree ( a , seg_tree , v * 2 , tl , tm ) ; build_tree ( a , seg_tree , v * 2 + 1 , tm + 1 , tr ) ; seg_tree [ v ] = seg_tree [ v * 2 ] + seg_tree [ v * 2 + 1 ] ; } } int frequency_zero ( int v , int tl , int tr , int l , int r , vector < int > & seg_tree ) { if ( l > r ) return 0 ; if ( l == tl && r == tr ) { return seg_tree [ v ] ; } int tm = ( tl + tr ) / 2 ; return frequency_zero ( v * 2 , tl , tm , l , min ( r , tm ) , seg_tree ) + frequency_zero ( v * 2 + 1 , tm + 1 , tr , max ( l , tm + 1 ) , r , seg_tree ) ; } void update ( int v , int tl , int tr , int pos , int new_val , vector < int > & seg_tree ) { if ( tl == tr ) { if ( new_val == 0 ) seg_tree [ v ] = 1 ; else seg_tree [ v ] = 0 ; } else { int tm = ( tl + tr ) / 2 ; if ( pos <= tm ) update ( v * 2 , tl , tm , pos , new_val , seg_tree ) ; else update ( v * 2 + 1 , tm + 1 , tr , pos , new_val , seg_tree ) ; seg_tree [ v ] = seg_tree [ v * 2 ] + seg_tree [ v * 2 + 1 ] ; } } void solve ( int n , int q , vector < int > & arr , vector < vector < int > > & query ) { vector < int > seg_tree ( 4 * n + 1 , 0 ) ; build_tree ( arr , seg_tree , 1 , 0 , n - 1 ) ; for ( int i = 1 ; i <= q ; i ++ ) { if ( query [ i - 1 ] [ 0 ] == 1 ) { int l = query [ i - 1 ] [ 1 ] ; int r = query [ i - 1 ] [ 2 ] ; cout << frequency_zero ( 1 , 0 , n - 1 , l , r , seg_tree ) << ' ' ; } else { arr [ query [ i - 1 ] [ 1 ] ] = query [ i - 1 ] [ 2 ] ; int pos = query [ i - 1 ] [ 1 ] ; int new_val = query [ i - 1 ] [ 2 ] ; update ( 1 , 0 , n - 1 , pos , new_val , seg_tree ) ; } } } int main ( ) { vector < int > arr = { 9 , 5 , 7 , 6 , 9 , 0 , 0 , 0 , 0 , 5 , 6 , 7 , 3 , 9 , 0 , 7 , 0 , 9 , 0 } ; int Q = 5 ; vector < vector < int > > query = { { 1 , 5 , 14 } , { 2 , 6 , 1 } , { 1 , 0 , 8 } , { 2 , 13 , 0 } , { 1 , 6 , 18 } } ; int N = arr . size ( ) ; solve ( N , Q , arr , query ) ; return 0 ; }
Find a number in minimum steps | C ++ program to find a number in minimum steps ; To represent data of a node in tree ; Prints level of node n ; Create a queue and insert root ; Do level order traversal ; Remove a node from queue ; To avoid infinite loop ; Check if dequeued number is same as n ; Insert children of dequeued node to queue ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define InF 99999 NEW_LINE struct number { int no ; int level ; public : number ( ) { } number ( int n , int l ) : no ( n ) , level ( l ) { } } ; void findnthnumber ( int n ) { queue < number > q ; struct number r ( 0 , 1 ) ; q . push ( r ) ; while ( ! q . empty ( ) ) { struct number temp = q . front ( ) ; q . pop ( ) ; if ( temp . no >= InF temp . no <= - InF ) break ; if ( temp . no == n ) { cout << " Found ▁ number ▁ n ▁ at ▁ level ▁ " << temp . level - 1 ; break ; } q . push ( number ( temp . no + temp . level , temp . level + 1 ) ) ; q . push ( number ( temp . no - temp . level , temp . level + 1 ) ) ; } } int main ( ) { findnthnumber ( 13 ) ; return 0 ; }
A Space Optimized DP solution for 0 | C ++ program of a space optimized DP solution for 0 - 1 knapsack problem . ; val [ ] is for storing maximum profit for each weight wt [ ] is for storing weights n number of item W maximum capacity of bag mat [ 2 ] [ W + 1 ] to store final result ; matrix to store final result ; iterate through all items ; one by one traverse each element ; traverse all weights j <= W ; if i is odd that mean till now we have odd number of elements so we store result in 1 th indexed row ; check for each value ; include element ; exclude element ; if i is even that mean till now we have even number of elements so we store result in 0 th indexed row ; Return mat [ 0 ] [ W ] if n is odd , else mat [ 1 ] [ W ] ; Driver program to test the cases
#include <bits/stdc++.h> NEW_LINE using namespace std ; int KnapSack ( int val [ ] , int wt [ ] , int n , int W ) { int mat [ 2 ] [ W + 1 ] ; memset ( mat , 0 , sizeof ( mat ) ) ; int i = 0 ; while ( i < n ) { int j = 0 ; if ( i % 2 != 0 ) { while ( ++ j <= W ) { if ( wt [ i ] <= j ) mat [ 1 ] [ j ] = max ( val [ i ] + mat [ 0 ] [ j - wt [ i ] ] , mat [ 0 ] [ j ] ) ; else mat [ 1 ] [ j ] = mat [ 0 ] [ j ] ; } } else { while ( ++ j <= W ) { if ( wt [ i ] <= j ) mat [ 0 ] [ j ] = max ( val [ i ] + mat [ 1 ] [ j - wt [ i ] ] , mat [ 1 ] [ j ] ) ; else mat [ 0 ] [ j ] = mat [ 1 ] [ j ] ; } } i ++ ; } return ( n % 2 != 0 ) ? mat [ 0 ] [ W ] : mat [ 1 ] [ W ] ; } int main ( ) { int val [ ] = { 7 + D2 : N7 , 8 , 4 } , wt [ ] = { 3 , 8 , 6 } , W = 10 , n = 3 ; cout << KnapSack ( val , wt , n , W ) << endl ; return 0 ; }
Check if all 3 Candy bags can be emptied by removing 2 candies from any one bag and 1 from the other two repeatedly | C ++ code for the above approach ; If total candies are not multiple of 4 then its not possible to be left with 0 candies ; If minimum candies of three bags are less than number of operations required then the task is not possible ; Driver code
#include <bits/stdc++.h> NEW_LINE #define ll long long NEW_LINE using namespace std ; bool can_empty ( ll a , ll b , ll c ) { if ( ( a + b + c ) % 4 != 0 ) return false ; else { int m = min ( a , min ( b , c ) ) ; if ( m < ( ( a + b + c ) / 4 ) ) return false ; } return true ; } int main ( ) { ll a = 4 , b = 2 , c = 2 ; cout << ( can_empty ( a , b , c ) ? " true " : " false " ) << endl ; a = 3 , b = 4 , c = 2 ; cout << ( can_empty ( a , b , c ) ? " true " : " false " ) << endl ; return 0 ; }
Difference between maximum and minimum average of all K | C ++ program for the above approach ; Function to find the difference between averages of the maximum and the minimum subarrays of length k ; Stores min and max sum ; Iterate through starting points ; Sum up next K elements ; Update max and min moving sum ; Return the difference between max and min average ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; double Avgdifference ( double arr [ ] , int N , int K ) { double min = 1000000 , max = -1 ; for ( int i = 0 ; i <= N - K ; i ++ ) { double sum = 0 ; for ( int j = 0 ; j < K ; j ++ ) { sum += arr [ i + j ] ; } if ( min > sum ) min = sum ; if ( max < sum ) max = sum ; } return ( max - min ) / K ; } int main ( ) { double arr [ ] = { 3 , 8 , 9 , 15 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 2 ; cout << Avgdifference ( arr , N , K ) ; return 0 ; }
Find a number in minimum steps | C ++ program to Find a number in minimum steps ; Steps sequence ; Current sum ; Sign of the number ; Basic steps required to get sum >= required value . ; If we have reached ahead to destination . ; If the last step was an odd number , then it has following mechanism for negating a particular number and decreasing the sum to required number Also note that it may require 1 more step in order to reach the sum . ; If the current time instance is even and sum is odd than it takes 2 more steps and few negations in previous elements to reach there . ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > find ( int n ) { vector < int > ans ; int sum = 0 ; int i ; int sign = ( n >= 0 ? 1 : -1 ) ; n = abs ( n ) ; for ( i = 1 ; sum < n ; i ++ ) { ans . push_back ( sign * i ) ; sum += i ; } if ( sum > sign * n ) { if ( i % 2 ) { sum -= n ; if ( sum % 2 ) { ans . push_back ( sign * i ) ; sum += i ++ ; } ans [ ( sum / 2 ) - 1 ] *= -1 ; } else { sum -= n ; if ( sum % 2 ) { sum -- ; ans . push_back ( sign * i ) ; ans . push_back ( sign * -1 * ( i + 1 ) ) ; } ans [ ( sum / 2 ) - 1 ] *= -1 ; } } return ans ; } int main ( ) { int n = 20 ; if ( n == 0 ) cout << " Minimum ▁ number ▁ of ▁ Steps : ▁ 0 STRNEWLINE Step ▁ sequence : STRNEWLINE 0" ; else { vector < int > a = find ( n ) ; cout << " Minimum ▁ number ▁ of ▁ Steps : ▁ " << a . size ( ) << " Step sequence : " for ( int i : a ) cout << i << " ▁ " ; } return 0 ; }
Maximum range length such that A [ i ] is maximum in given range for all i from [ 1 , N ] | C ++ program for the above approach ; Function to find maximum range for each i such that arr [ i ] is max in range ; Vector to store the left and right index for each i such that left [ i ] > arr [ i ] and right [ i ] > arr [ i ] ; Traverse the array ; While s . top ( ) . first < a [ i ] remove the top element from the stack ; Modify left [ i ] ; Clear the stack ; Traverse the array to find right [ i ] for each i ; While s . top ( ) . first < a [ i ] remove the top element from the stack ; Modify right [ i ] ; Print the value range for each i ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void MaxRange ( vector < int > A , int n ) { vector < int > left ( n ) , right ( n ) ; stack < pair < int , int > > s ; s . push ( { INT_MAX , -1 } ) ; for ( int i = 0 ; i < n ; i ++ ) { while ( s . top ( ) . first < A [ i ] ) s . pop ( ) ; left [ i ] = s . top ( ) . second ; s . push ( { A [ i ] , i } ) ; } while ( ! s . empty ( ) ) s . pop ( ) ; s . push ( make_pair ( INT_MAX , n ) ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { while ( s . top ( ) . first < A [ i ] ) s . pop ( ) ; right [ i ] = s . top ( ) . second ; s . push ( { A [ i ] , i } ) ; } for ( int i = 0 ; i < n ; i ++ ) { cout << left [ i ] + 1 << ' ▁ ' << right [ i ] - 1 << " STRNEWLINE " ; } } int main ( ) { vector < int > arr { 1 , 3 , 2 } ; int n = arr . size ( ) ; MaxRange ( arr , n ) ; return 0 ; }
Find Nth smallest number having exactly 4 divisors | C ++ program for the above approach ; Function to find the nth number which has exactly 4 divisors ; The divs [ ] array to store number of divisors of every element ; The vis [ ] array to check if given number is considered or not ; The cnt stores number of elements having exactly 4 divisors ; Iterate while cnt less than n ; If i is a prime ; Iterate in the range [ 2 * i , 1000000 ] with increment of i ; If the number j is already considered ; Dividing currNum by i until currNum % i is equal to 0 ; Case a single prime in its factorization ; Case of two distinct primes which divides j exactly once each ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int nthNumber ( int n ) { int divs [ 1000000 ] ; bool vis [ 1000000 ] ; int cnt = 0 ; for ( int i = 2 ; cnt < n ; i ++ ) { if ( divs [ i ] == 0 ) { for ( int j = 2 * i ; j < 1000000 ; j += i ) { if ( vis [ j ] ) { continue ; } vis [ j ] = 1 ; int currNum = j ; int count = 0 ; while ( currNum % i == 0 ) { divs [ j ] ++ ; currNum = currNum / i ; count ++ ; } if ( currNum == 1 && count == 3 && divs [ j ] == 3 ) { cnt ++ ; } else if ( currNum != 1 && divs [ currNum ] == 0 && count == 1 && divs [ j ] == 1 ) { cnt ++ ; } if ( cnt == n ) { return j ; } } } } return -1 ; } int main ( ) { int N = 24 ; cout << nthNumber ( N ) << endl ; return 0 ; }
Maximum number formed from the digits of given three numbers | C ++ program for the above approach ; Function to find the maximum number formed by taking the maximum digit at the same position from each number ; Stores the result ; Stores the position value of a digit ; Stores the digit at the unit place ; Stores the digit at the unit place ; Stores the digit at the unit place ; Update A , B and C ; Stores the maximum digit ; Increment ans cur * a ; Update cur ; Return ans ; Driver Code ; Given Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findkey ( int A , int B , int C ) { int ans = 0 ; int cur = 1 ; while ( A > 0 ) { int a = A % 10 ; int b = B % 10 ; int c = C % 10 ; A = A / 10 ; B = B / 10 ; C = C / 10 ; int m = max ( a , max ( c , b ) ) ; ans += cur * m ; cur = cur * 10 ; } return ans ; } int main ( ) { int A = 3521 , B = 2452 , C = 1352 ; cout << findkey ( A , B , C ) ; return 0 ; }
Count of distinct GCDs among all the non | C ++ program for the above approach ; Function to calculate the number of distinct GCDs among all non - empty subsequences of an array ; variables to store the largest element in array and the required count ; Map to store whether a number is present in A ; calculate largest number in A and mapping A to Mp ; iterate over all possible values of GCD ; variable to check current GCD ; iterate over all multiples of i ; If j is present in A ; calculate gcd of all encountered multiples of i ; current GCD is possible ; return answer ; Driver code ; Input ; Function calling
#include <bits/stdc++.h> NEW_LINE using namespace std ; int distinctGCDs ( int arr [ ] , int N ) { int M = -1 , ans = 0 ; map < int , int > Mp ; for ( int i = 0 ; i < N ; i ++ ) { M = max ( M , arr [ i ] ) ; Mp [ arr [ i ] ] = 1 ; } for ( int i = 1 ; i <= M ; i ++ ) { int currGcd = 0 ; for ( int j = i ; j <= M ; j += i ) { if ( Mp [ j ] ) { currGcd = __gcd ( currGcd , j ) ; if ( currGcd == i ) { ans ++ ; break ; } } } } return ans ; } int main ( ) { int arr [ ] = { 3 , 11 , 14 , 6 , 12 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << distinctGCDs ( arr , N ) << endl ; return 0 ; }
Compress a Binary Tree into an integer diagonally | ; Function to compress the elements in an array into an integer ; Check for each bit position ; Update the count of set and non - set bits ; If number of set bits exceeds the number of non - set bits , then add set bits value to ans ; Perform Inorder Traversal on the Binary Tree ; Store all nodes of the same line together as a vector ; Increase the vertical distance of left child ; Vertical distance remains same for right child ; Function to compress a given Binary Tree into an integer ; Declare a map ; Store all the compressed values of diagonal elements in an array ; Compress the array into an integer ; Driver Code Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct TreeNode { int val ; TreeNode * left , * right ; TreeNode ( int v ) { val = v ; left = NULL ; right = NULL ; } } ; int findCompressValue ( vector < int > arr ) { int ans = 0 ; int getBit = 1 ; for ( int i = 0 ; i < 32 ; i ++ ) { int S = 0 ; int NS = 0 ; for ( int j : arr ) { if ( getBit & j ) S += 1 ; else NS += 1 ; } if ( S > NS ) ans += pow ( 2 , i ) ; getBit <<= 1 ; } return ans ; } void diagonalOrder ( TreeNode * root , int d , map < int , vector < int > > & mp ) { if ( ! root ) return ; mp [ d ] . push_back ( root -> val ) ; diagonalOrder ( root -> left , d + 1 , mp ) ; diagonalOrder ( root -> right , d , mp ) ; } int findInteger ( TreeNode * root ) { map < int , vector < int > > mp ; diagonalOrder ( root , 0 , mp ) ; vector < int > arr ; for ( auto i : mp ) arr . push_back ( findCompressValue ( i . second ) ) ; return findCompressValue ( arr ) ; } int main ( ) { TreeNode * root = new TreeNode ( 6 ) ; root -> left = new TreeNode ( 5 ) ; root -> right = new TreeNode ( 3 ) ; root -> left -> left = new TreeNode ( 3 ) ; root -> left -> right = new TreeNode ( 5 ) ; root -> right -> left = new TreeNode ( 3 ) ; root -> right -> right = new TreeNode ( 4 ) ; cout << findInteger ( root ) ; return 0 ; }
Egg Dropping Puzzle | DP | ; A utility function to get maximum of two integers ; Function to get minimum number of trials needed in worst case with n eggs and k floors ; If there are no floors , then no trials needed . OR if there is one floor , one trial needed . ; We need k trials for one egg and k floors ; Consider all droppings from 1 st floor to kth floor and return the minimum of these values plus 1. ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int max ( int a , int b ) { return ( a > b ) ? a : b ; } int eggDrop ( int n , int k ) { if ( k == 1 k == 0 ) return k ; if ( n == 1 ) return k ; int min = INT_MAX , x , res ; for ( x = 1 ; x <= k ; x ++ ) { res = max ( eggDrop ( n - 1 , x - 1 ) , eggDrop ( n , k - x ) ) ; if ( res < min ) min = res ; } return min + 1 ; } int main ( ) { int n = 2 , k = 10 ; cout << " Minimum ▁ number ▁ of ▁ trials ▁ " " in ▁ worst ▁ case ▁ with ▁ " << n << " ▁ eggs ▁ and ▁ " << k << " ▁ floors ▁ is ▁ " << eggDrop ( n , k ) << endl ; 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 ; Divide the number n by 10 upto k - 1 times ; If the number n is equal 0 ; Print the right most digit ; 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 ; } while ( ( k - 1 ) > 0 && n > 0 ) { n = n / 10 ; k -- ; } if ( n == 0 ) { cout << -1 << endl ; } else { cout << n % 10 << endl ; } } int main ( ) { int n = 2354 ; int k = 2 ; kthDigitFromLast ( n , k ) ; }
Edit Distance | DP | A Space efficient Dynamic Programming based C ++ program to find minimum number operations to convert str1 to str2 ; Create a DP array to memoize result of previous computations ; Base condition when second string is empty then we remove all characters ; Start filling the DP This loop run for every character in second string ; This loop compares the char from second string with first string characters ; if first string is empty then we have to perform add character operation to get second string ; if character from both string is same then we do not perform any operation . here i % 2 is for bound the row number . ; if character from both string is not same then we take the minimum from three specified operation ; after complete fill the DP array if the len2 is even then we end up in the 0 th row else we end up in the 1 th row so we take len2 % 2 to get row ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void EditDistDP ( string str1 , string str2 ) { int len1 = str1 . length ( ) ; int len2 = str2 . length ( ) ; int DP [ 2 ] [ len1 + 1 ] ; memset ( DP , 0 , sizeof DP ) ; for ( int i = 0 ; i <= len1 ; i ++ ) DP [ 0 ] [ i ] = i ; for ( int i = 1 ; i <= len2 ; i ++ ) { for ( int j = 0 ; j <= len1 ; j ++ ) { if ( j == 0 ) DP [ i % 2 ] [ j ] = i ; else if ( str1 [ j - 1 ] == str2 [ i - 1 ] ) { DP [ i % 2 ] [ j ] = DP [ ( i - 1 ) % 2 ] [ j - 1 ] ; } else { DP [ i % 2 ] [ j ] = 1 + min ( DP [ ( i - 1 ) % 2 ] [ j ] , min ( DP [ i % 2 ] [ j - 1 ] , DP [ ( i - 1 ) % 2 ] [ j - 1 ] ) ) ; } } } cout << DP [ len2 % 2 ] [ len1 ] << endl ; } int main ( ) { string str1 = " food " ; string str2 = " money " ; EditDistDP ( str1 , str2 ) ; return 0 ; }
Sum of Bitwise XOR of elements of an array with all elements of another array | C ++ Program for the above approach ; Function to calculate sum of Bitwise XOR of elements of arr [ ] with k ; Initialize sum to be zero ; Iterate over each set bit ; Stores contribution of i - th bet to the sum ; If the i - th bit is set ; Stores count of elements whose i - th bit is not set ; Update value ; Update value ; Add value to sum ; Move to the next power of two ; Stores the count of elements whose i - th bit is set ; Initialize count to 0 for all positions ; Traverse the array ; Iterate over each bit ; If the i - th bit is set ; Increase count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int xorSumOfArray ( int arr [ ] , int n , int k , int count [ ] ) { int sum = 0 ; int p = 1 ; for ( int i = 0 ; i < 31 ; i ++ ) { int val = 0 ; if ( ( k & ( 1 << i ) ) != 0 ) { int not_set = n - count [ i ] ; val = ( ( not_set ) * p ) ; } else { val = ( count [ i ] * p ) ; } sum += val ; p = ( p * 2 ) ; } return sum ; } void sumOfXors ( int arr [ ] , int n , int queries [ ] , int q ) { int count [ 32 ] ; memset ( count , 0 , sizeof ( count ) ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < 31 ; j ++ ) { if ( arr [ i ] & ( 1 << j ) ) count [ j ] ++ ; } } for ( int i = 0 ; i < q ; i ++ ) { int k = queries [ i ] ; cout << xorSumOfArray ( arr , n , k , count ) << " ▁ " ; } } int main ( ) { int arr [ ] = { 5 , 2 , 3 } ; int queries [ ] = { 3 , 8 , 7 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int q = sizeof ( queries ) / sizeof ( int ) ; sumOfXors ( arr , n , queries , q ) ; return 0 ; }
Factor Tree of a given Number | C ++ program to construct Factor Tree for a given number ; Tree node ; Utility function to create a new tree Node ; Constructs factor tree for given value and stores root of tree at given reference . ; the number is factorized ; If we found a factor , we construct left and right subtrees and return . Since we traverse factors starting from smaller to greater , left child will always have smaller factor ; Iterative method to find the height of Binary Tree ; Base Case ; Print front of queue and remove it from queue ; driver program ;
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { struct Node * left , * right ; int key ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return temp ; } void createFactorTree ( struct Node * * node_ref , int v ) { ( * node_ref ) = newNode ( v ) ; for ( int i = 2 ; i < v / 2 ; i ++ ) { if ( v % i != 0 ) continue ; createFactorTree ( & ( ( * node_ref ) -> left ) , i ) ; createFactorTree ( & ( ( * node_ref ) -> right ) , v / i ) ; return ; } } void printLevelOrder ( Node * root ) { if ( root == NULL ) return ; queue < Node * > q ; q . push ( root ) ; while ( q . empty ( ) == false ) { Node * node = q . front ( ) ; cout << node -> key << " ▁ " ; q . pop ( ) ; if ( node -> left != NULL ) q . push ( node -> left ) ; if ( node -> right != NULL ) q . push ( node -> right ) ; } } int main ( ) { int val = 48 ; struct Node * root = NULL ; createFactorTree ( & root , val ) ; cout << " Level ▁ order ▁ traversal ▁ of ▁ " " constructed ▁ factor ▁ tree " ; printLevelOrder ( root ) ; return 0 ; }
Minimum time required to schedule K processes | C ++ program for the above approach ; Function to execute k processes that can be gained in minimum amount of time ; Stores all the array elements ; Push all the elements to the priority queue ; Stores the required result ; Loop while the queue is not empty and K is positive ; Store the top element from the pq ; Add it to the answer ; Divide it by 2 and push it back to the pq ; Print the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void executeProcesses ( int A [ ] , int N , int K ) { priority_queue < int > pq ; for ( int i = 0 ; i < N ; i ++ ) { pq . push ( A [ i ] ) ; } int ans = 0 ; while ( ! pq . empty ( ) && K > 0 ) { int top = pq . top ( ) ; pq . pop ( ) ; ans ++ ; K = K - top ; top = top / 2 ; pq . push ( top ) ; } cout << ans ; } int main ( ) { int A [ ] = { 3 , 1 , 7 , 4 , 2 } ; int K = 15 ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; executeProcesses ( A , N , K ) ; return 0 ; }
Maximum height of an elevation possible such that adjacent matrix cells have a difference of at most height 1 | C ++ program for the above approach ; Utility function to find the matrix having the maximum height ; Stores index pairs for bfs ; Stores info about the visited cells ; Traverse the matrix ; Breadth First Search ; x & y are the row & column of current cell ; Check all the 4 adjacent cells and marking them as visited if not visited yet also marking their height as 1 + height of cell ( x , y ) ; Function to find the matrix having the maximum height ; Stores output matrix ; Calling the helper function ; Print the final output matrix ; Driver Code ; Given matrix ; Function call to find the matrix having the maximum height
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define M 3 NEW_LINE #define N 3 NEW_LINE void findHeightMatrixUtil ( int mat [ ] [ N ] , int height [ M ] [ N ] ) { queue < pair < int , int > > q ; int vis [ M ] [ N ] = { 0 } ; for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( mat [ i ] [ j ] == 1 ) { q . push ( { i , j } ) ; height [ i ] [ j ] = 0 ; vis [ i ] [ j ] = 1 ; } } } while ( q . empty ( ) == 0 ) { pair < int , int > k = q . front ( ) ; q . pop ( ) ; int x = k . first , y = k . second ; if ( x > 0 && vis [ x - 1 ] [ y ] == 0 ) { height [ x - 1 ] [ y ] = height [ x ] [ y ] + 1 ; vis [ x - 1 ] [ y ] = 1 ; q . push ( { x - 1 , y } ) ; } if ( y > 0 && vis [ x ] [ y - 1 ] == 0 ) { height [ x ] [ y - 1 ] = height [ x ] [ y ] + 1 ; vis [ x ] [ y - 1 ] = 1 ; q . push ( { x , y - 1 } ) ; } if ( x < M - 1 && vis [ x + 1 ] [ y ] == 0 ) { height [ x + 1 ] [ y ] = height [ x ] [ y ] + 1 ; vis [ x + 1 ] [ y ] = 1 ; q . push ( { x + 1 , y } ) ; } if ( y < N - 1 && vis [ x ] [ y + 1 ] == 0 ) { height [ x ] [ y + 1 ] = height [ x ] [ y ] + 1 ; vis [ x ] [ y + 1 ] = 1 ; q . push ( { x , y + 1 } ) ; } } } void findHeightMatrix ( int mat [ ] [ N ] ) { int height [ M ] [ N ] ; findHeightMatrixUtil ( mat , height ) ; for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) cout << height [ i ] [ j ] << " ▁ " ; cout << endl ; } } int main ( ) { int mat [ ] [ N ] = { { 0 , 0 } , { 0 , 1 } } ; findHeightMatrix ( mat ) ; return 0 ; }
Median of all nodes from a given range in a Binary Search Tree ( BST ) | C ++ program for the above approach ; Tree Node structure ; Function to create a new BST node ; Function to insert a new node with given key in BST ; If the tree is empty , return a new node ; Otherwise , recur down the tree ; Return the node pointer ; Function to find all the nodes that lies over the range [ node1 , node2 ] ; If the tree is empty , return ; Traverse for the left subtree ; If a second node is found , then update the flag as false ; Traverse the right subtree ; Function to find the median of all the values in the given BST that lies over the range [ node1 , node2 ] ; Stores all the nodes in the range [ node1 , node2 ] ; Store the size of the array ; Print the median of array based on the size of array ; Driver Code ; Given BST
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { struct Node * left , * right ; int key ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return temp ; } Node * insertNode ( Node * node , int key ) { if ( node == NULL ) return newNode ( key ) ; if ( key < node -> key ) node -> left = insertNode ( node -> left , key ) ; else if ( key > node -> key ) node -> right = insertNode ( node -> right , key ) ; return node ; } void getIntermediateNodes ( Node * root , vector < int > & interNodes , int node1 , int node2 ) { if ( root == NULL ) return ; getIntermediateNodes ( root -> left , interNodes , node1 , node2 ) ; if ( root -> key <= node2 and root -> key >= node1 ) { interNodes . push_back ( root -> key ) ; } getIntermediateNodes ( root -> right , interNodes , node1 , node2 ) ; } float findMedian ( Node * root , int node1 , int node2 ) { vector < int > interNodes ; getIntermediateNodes ( root , interNodes , node1 , node2 ) ; int nSize = interNodes . size ( ) ; return ( nSize % 2 == 1 ) ? ( float ) interNodes [ nSize / 2 ] : ( float ) ( interNodes [ ( nSize - 1 ) / 2 ] + interNodes [ nSize / 2 ] ) / 2 ; } int main ( ) { struct Node * root = NULL ; root = insertNode ( root , 8 ) ; insertNode ( root , 3 ) ; insertNode ( root , 1 ) ; insertNode ( root , 6 ) ; insertNode ( root , 4 ) ; insertNode ( root , 11 ) ; insertNode ( root , 15 ) ; cout << findMedian ( root , 3 , 11 ) ; return 0 ; }
Count number of pairs ( i , j ) up to N that can be made equal on multiplying with a pair from the range [ 1 , N / 2 ] | C ++ program for the above approach ; Function to compute totient of all numbers smaller than or equal to N ; Iterate over the range [ 2 , N ] ; If phi [ p ] is not computed already , then p is prime ; Phi of a prime number p is ( p - 1 ) ; Update phi values of all multiples of p ; Add contribution of p to its multiple i by multiplying with ( 1 - 1 / p ) ; Function to count the pairs ( i , j ) from the range [ 1 , N ] , satisfying the given condition ; Stores the counts of first and second type of pairs respectively ; Count of first type of pairs ; Stores the phi or totient values ; Calculate the Phi values ; Iterate over the range [ N / 2 + 1 , N ] ; Update the value of cnt_type2 ; Print the total count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void computeTotient ( int N , int phi [ ] ) { for ( int p = 2 ; p <= N ; p ++ ) { if ( phi [ p ] == p ) { phi [ p ] = p - 1 ; for ( int i = 2 * p ; i <= N ; i += p ) { phi [ i ] = ( phi [ i ] / p ) * ( p - 1 ) ; } } } } void countPairs ( int N ) { int cnt_type1 = 0 , cnt_type2 = 0 ; int half_N = N / 2 ; cnt_type1 = ( half_N * ( half_N - 1 ) ) / 2 ; int phi [ N + 1 ] ; for ( int i = 1 ; i <= N ; i ++ ) { phi [ i ] = i ; } computeTotient ( N , phi ) ; for ( int i = ( N / 2 ) + 1 ; i <= N ; i ++ ) cnt_type2 += ( i - phi [ i ] - 1 ) ; cout << cnt_type1 + cnt_type2 ; } int main ( ) { int N = 6 ; countPairs ( N ) ; return 0 ; }
Sum of subsets nearest to K possible from two given arrays | C ++ program of the above approach ; Stores the sum closest to K ; Stores the minimum absolute difference ; Function to choose the elements from the array B [ ] ; If absolute difference is less then minimum value ; Update the minimum value ; Update the value of ans ; If absolute difference between curr and K is equal to minimum ; Update the value of ans ; If i is greater than M - 1 ; Includes the element B [ i ] once ; Includes the element B [ i ] twice ; Excludes the element B [ i ] ; Function to find a subset sum whose sum is closest to K ; Traverse the array A [ ] ; Function Call ; Return the ans ; Driver Code ; Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int ans = INT_MAX ; int mini = INT_MAX ; void findClosestTarget ( int i , int curr , int B [ ] , int M , int K ) { if ( abs ( curr - K ) < mini ) { mini = abs ( curr - K ) ; ans = curr ; } if ( abs ( curr - K ) == mini ) { ans = min ( ans , curr ) ; } if ( i >= M ) return ; findClosestTarget ( i + 1 , curr + B [ i ] , B , M , K ) ; findClosestTarget ( i + 1 , curr + 2 * B [ i ] , B , M , K ) ; findClosestTarget ( i + 1 , curr , B , M , K ) ; } int findClosest ( int A [ ] , int B [ ] , int N , int M , int K ) { for ( int i = 0 ; i < N ; i ++ ) { findClosestTarget ( 0 , A [ i ] , B , M , K ) ; } return ans ; } int main ( ) { int A [ ] = { 2 , 3 } ; int B [ ] = { 4 , 5 , 30 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int M = sizeof ( B ) / sizeof ( B [ 0 ] ) ; int K = 18 ; cout << findClosest ( A , B , N , M , K ) ; return 0 ; }
Check if every node can me made accessible from a node of a Tree by at most N / 2 given operations | C ++ program for the above approach ; Function to check if there is a node in tree from where all other nodes are accessible or not ; Store the indegree of every node ; Store the nodes having indegree equal to 0 ; Traverse the array ; If the indegree of i - th node is 0 ; Increment count0 by 1 ; If the number of operations needed is at most floor ( n / 2 ) ; Otherwise ; Driver Code ; Given number of nodes ; Given Directed Tree
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findNode ( map < int , int > mp , int n ) { int a [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { a [ i ] = mp [ i + 1 ] ; } int count0 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == 0 ) { count0 ++ ; } } count0 -= 1 ; if ( count0 <= floor ( ( ( double ) n ) / ( ( double ) 2 ) ) ) { cout << " Yes " ; } else cout << " No " ; } int main ( ) { int N = 3 ; map < int , int > mp ; mp [ 1 ] = 0 ; mp [ 2 ] = 2 ; mp [ 3 ] = 0 ; findNode ( mp , N ) ; }
Check if Bitwise AND of concatenation of diagonals exceeds that of middle row / column elements of a Binary Matrix | C ++ program for above approach ; Function to convert obtained binary representation to decimal value ; Stores the resultant number ; Traverse string arr ; Return the number formed ; Function to count the number of set bits in the number num ; Stores the count of set bits ; Iterate until num > 0 ; Function to check if the given matrix satisfies the given condition or not ; To get P , S , MR , and MC ; Stores decimal equivalents of binary representations ; Gett the number of set bits ; Print the answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int convert ( vector < int > p ) { int ans = 0 ; for ( int i : p ) { ans = ( ans << 1 ) | i ; } return ans ; } int count ( int num ) { int ans = 0 ; while ( num > 0 ) { ans += num & 1 ; num >>= 1 ; } return ans ; } void checkGoodMatrix ( vector < vector < int > > mat ) { vector < int > P ; vector < int > S ; vector < int > MR ; vector < int > MC ; for ( int i = 0 ; i < mat . size ( ) ; i ++ ) { for ( int j = 0 ; j < mat [ 0 ] . size ( ) ; j ++ ) { if ( i == j ) P . push_back ( mat [ i ] [ j ] ) ; if ( i + j == mat . size ( ) - 1 ) S . push_back ( mat [ i ] [ j ] ) ; if ( i == floor ( ( mat . size ( ) - 1 ) / 2 ) ) MR . push_back ( mat [ i ] [ j ] ) ; if ( j == floor ( ( mat . size ( ) - 1 ) / 2 ) ) MC . push_back ( mat [ i ] [ j ] ) ; } } reverse ( S . begin ( ) , S . end ( ) ) ; int P0 = convert ( P ) ; int S0 = convert ( S ) ; int MR0 = convert ( MR ) ; int MC0 = convert ( MC ) ; int setBitsPS = count ( ( P0 & S0 ) ) ; int setBitsMM = count ( ( MR0 & MC0 ) ) ; if ( setBitsPS > setBitsMM ) cout << " Yes " ; else cout << " No " ; } int main ( ) { vector < vector < int > > mat = { { 1 , 0 , 1 } , { 0 , 0 , 1 } , { 0 , 1 , 1 } } ; checkGoodMatrix ( mat ) ; }
Construct a Tree whose sum of nodes of all the root to leaf path is not divisible by the count of nodes in that path | C ++ program for the above approach ; Function to assign values to nodes of the tree s . t . sum of values of nodes of path between any 2 nodes is not divisible by length of path ; Stores the adjacency list ; Create a adjacency list ; Stores whether node is visited or not ; Stores the node values ; Variable used to assign values to the nodes alternatively to the parent child ; Declare a queue ; Push the 1 st node ; Assign K value to this node ; Dequeue the node ; Mark it as visited ; Upgrade the value of K ; Assign K to the child nodes ; If the child is unvisited ; Enqueue the child ; Assign K to the child ; Print the value assigned to the nodes ; Driver Code ; Function Call
#include " bits / stdc + + . h " NEW_LINE using namespace std ; void assignValues ( int Edges [ ] [ 2 ] , int n ) { vector < int > tree [ n + 1 ] ; for ( int i = 0 ; i < n - 1 ; i ++ ) { int u = Edges [ i ] [ 0 ] ; int v = Edges [ i ] [ 1 ] ; tree [ u ] . push_back ( v ) ; tree [ v ] . push_back ( u ) ; } vector < bool > visited ( n + 1 , false ) ; vector < int > answer ( n + 1 ) ; int K = 1 ; queue < int > q ; q . push ( 1 ) ; answer [ 1 ] = K ; while ( ! q . empty ( ) ) { int node = q . front ( ) ; q . pop ( ) ; visited [ node ] = true ; K = ( ( answer [ node ] == 1 ) ? 2 : 1 ) ; for ( auto child : tree [ node ] ) { if ( ! visited [ child ] ) { q . push ( child ) ; answer [ child ] = K ; } } } for ( int i = 1 ; i <= n ; i ++ ) { cout << answer [ i ] << " ▁ " ; } } int main ( ) { int N = 11 ; int Edges [ ] [ 2 ] = { { 1 , 2 } , { 1 , 3 } , { 1 , 4 } , { 1 , 5 } , { 2 , 6 } , { 2 , 10 } , { 10 , 11 } , { 3 , 7 } , { 4 , 8 } , { 5 , 9 } } ; assignValues ( Edges , N ) ; return 0 ; }
Number of full binary trees such that each node is product of its children | C ++ program to find number of full binary tree such that each node is product of its children . ; Return the number of all possible full binary tree with given product property . ; Finding the minimum and maximum values in given array . ; Marking the presence of each array element and initialising the number of possible full binary tree for each integer equal to 1 because single node will also contribute as a full binary tree . ; From minimum value to maximum value of array finding the number of all possible Full Binary Trees . ; Find if value present in the array ; For each multiple of i , less than equal to maximum value of array ; If multiple is not present in the array then continue . ; Finding the number of possible Full binary trees for multiple j by multiplying number of possible Full binary tree from the number i and number of possible Full binary tree from i / j . ; Condition for possiblity when left chid became right child and vice versa . ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int numoffbt ( int arr [ ] , int n ) { int maxvalue = INT_MIN , minvalue = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { maxvalue = max ( maxvalue , arr [ i ] ) ; minvalue = min ( minvalue , arr [ i ] ) ; } int mark [ maxvalue + 2 ] ; int value [ maxvalue + 2 ] ; memset ( mark , 0 , sizeof ( mark ) ) ; memset ( value , 0 , sizeof ( value ) ) ; for ( int i = 0 ; i < n ; i ++ ) { mark [ arr [ i ] ] = 1 ; value [ arr [ i ] ] = 1 ; } int ans = 0 ; for ( int i = minvalue ; i <= maxvalue ; i ++ ) { if ( mark [ i ] ) { for ( int j = i + i ; j <= maxvalue && j / i <= i ; j += i ) { if ( ! mark [ j ] ) continue ; value [ j ] = value [ j ] + ( value [ i ] * value [ j / i ] ) ; if ( i != j / i ) value [ j ] = value [ j ] + ( value [ i ] * value [ j / i ] ) ; } } ans += value [ i ] ; } return ans ; } int main ( ) { int arr [ ] = { 2 , 3 , 4 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << numoffbt ( arr , n ) << endl ; return 0 ; }
Minimum prime numbers required to be subtracted to make all array elements equal | C ++ program for the above approach ; Stores the sieve of prime numbers ; Function that performs the Sieve of Eratosthenes ; Initialize all numbers as prime ; Iterate over the range [ 2 , 1000 ] ; If the current element is a prime number ; Mark all its multiples as false ; Function to find the minimum number of subtraction of primes numbers required to make all array elements the same ; Perform sieve of eratosthenes ; Find the minimum value ; Stores the value to each array element should be reduced ; If an element exists with value ( M + 1 ) ; Stores the minimum count of subtraction of prime numbers ; Traverse the array ; If D is equal to 0 ; If D is a prime number ; Increase count by 1 ; If D is an even number ; Increase count by 2 ; If D - 2 is prime ; Increase count by 2 ; Otherwise , increase count by 3 ; Driver Code
#include <bits/stdc++.h> NEW_LINE #define limit 100000 NEW_LINE using namespace std ; bool prime [ limit + 1 ] ; void sieve ( ) { memset ( prime , true , sizeof ( prime ) ) ; for ( int p = 2 ; p * p <= limit ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= limit ; i += p ) prime [ i ] = false ; } } } int findOperations ( int arr [ ] , int n ) { sieve ( ) ; int minm = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { minm = min ( minm , arr [ i ] ) ; } int val = minm ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == minm + 1 ) { val = minm - 2 ; break ; } } int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int D = arr [ i ] - val ; if ( D == 0 ) { continue ; } else if ( prime [ D ] == true ) { cnt += 1 ; } else if ( D % 2 == 0 ) { cnt += 2 ; } else { if ( prime [ D - 2 ] == true ) { cnt += 2 ; } else { cnt += 3 ; } } } return cnt ; } int main ( ) { int arr [ ] = { 7 , 10 , 4 , 5 } ; int N = 4 ; cout << findOperations ( arr , N ) ; return 0 ; }
Print all unique digits present in concatenation of all array elements in the order of their occurrence | C ++ program for the above approach ; Function to print long unique elements ; Reverse the list ; Traverse the list ; Function which check for all unique digits ; Stores the final number ; Stores the count of unique digits ; Converting string to long longer to remove leading zeros ; Stores count of digits ; Iterate over the digits of N ; Retrieve the last digit of N ; Increase the count of the last digit ; Remove the last digit of N ; Converting string to long longer again ; Iterate over the digits of N ; Retrieve the last digit of N ; If the value of this digit is not visited ; If its frequency is 1 ( unique ) ; Mark the digit visited ; Remove the last digit of N ; Passing this list to print long the reversed list ; Function to concatenate array elements ; Stores the concatenated number ; Traverse the array ; Convert to equivalent string ; Concatenate the string ; Passing string to checkUnique function ; Driver Code ; Function call to prlong long unique digits present in the concatenation of array elements
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printUnique ( vector < long long > lis ) { reverse ( lis . begin ( ) , lis . end ( ) ) ; for ( long long i : lis ) cout << i << " ▁ " ; } void checkUnique ( string st ) { vector < long long > lis ; long long res = 0 ; long long N = stoll ( st ) ; vector < long long > cnt ( 10 , 0 ) , cnt1 ( 10 , 0 ) ; while ( N > 0 ) { long long rem = N % 10 ; cnt [ rem ] += 1 ; N = N / 10 ; } N = stoll ( st ) ; while ( N > 0 ) { long long rem = N % 10 ; if ( cnt1 [ rem ] == 0 ) { if ( cnt [ rem ] == 1 ) lis . push_back ( rem ) ; } cnt1 [ rem ] = 1 ; N = N / 10 ; } printUnique ( lis ) ; } void combineArray ( vector < long long > lis ) { string st = " " ; for ( long long el : lis ) { string ee = to_string ( el ) ; st = st + ee ; } checkUnique ( st ) ; } int main ( ) { vector < long long > arr = { 122 , 474 , 612 , 932 } ; combineArray ( arr ) ; return 0 ; }
Maximize sum of Bitwise AND of same | C ++ program for the above approach ; Function to calculate sum of Bitwise AND of same indexed elements of the arrays p [ ] and arr [ ] ; Stores the resultant sum ; Traverse the array ; Update sum of Bitwise AND ; Return the value obtained ; Function to generate all permutations and calculate the maximum sum of Bitwise AND of same indexed elements present in any permutation and an array arr [ ] ; If the size of the array is N ; Calculate cost of permutation ; Generate all permutations ; Update chosen [ i ] ; Update the permutation p [ ] ; Generate remaining permutations ; Return the resultant sum ; Function to find the maximum sum of Bitwise AND of same indexed elements in a permutation of first N natural numbers and arr [ ] ; Stores the resultant maximum sum ; Stores the generated permutation P ; Function call to store result ; Print the result ; Driven Program ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calcScore ( vector < int > p , int arr [ ] , int N ) { int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { ans += ( p [ i ] & arr [ i ] ) ; } return ans ; } int getMaxUtil ( vector < int > p , int arr [ ] , int ans , bool chosen [ ] , int N ) { if ( p . size ( ) == N ) { ans = max ( ans , calcScore ( p , arr , N ) ) ; return ans ; } for ( int i = 0 ; i < N ; i ++ ) { if ( chosen [ i ] ) { continue ; } chosen [ i ] = true ; p . push_back ( i ) ; ans = getMaxUtil ( p , arr , ans , chosen , N ) ; chosen [ i ] = false ; p . pop_back ( ) ; } return ans ; } void getMax ( int arr [ ] , int N ) { int ans = 0 ; bool chosen [ N ] ; for ( int i = 0 ; i < N ; i ++ ) chosen [ i ] = false ; vector < int > p ; int res = getMaxUtil ( p , arr , ans , chosen , N ) ; cout << res ; } int main ( ) { int arr [ ] = { 4 , 2 , 3 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; getMax ( arr , N ) ; return 0 ; }
Sum of array elements whose count of set bits are unique | C ++ program for the approach ; Function to count the number of set bits in an integer N ; Stores the count of set bits ; Iterate until N is non - zero ; Stores the resultant count ; Function to calculate sum of all array elements whose count of set bits are unique ; Stores frequency of all possible count of set bits ; Stores the sum of array elements ; Traverse the array ; Count the number of set bits ; Traverse the array And Update the value of ans ; If frequency is 1 ; Driver Code
#include <iostream> NEW_LINE #include <bits/stdc++.h> NEW_LINE using namespace std ; int setBitCount ( int n ) { int ans = 0 ; while ( n ) { ans += n & 1 ; n >>= 1 ; } return ans ; } int getSum ( int * arr , int n ) { map < int , int > mp ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int key = setBitCount ( arr [ i ] ) ; mp [ key ] += 1 ; } for ( int i = 0 ; i < n ; i ++ ) { int key = setBitCount ( arr [ i ] ) ; if ( mp [ key ] == 1 ) ans += arr [ i ] ; } cout << ans ; } int main ( ) { int arr [ 5 ] = { 8 , 3 , 7 , 5 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; getSum ( arr , n ) ; return 0 ; }
Print indices of pair of array elements required to be removed to split array into 3 equal sum subarrays | C ++ program for the above approach ; Function to check if array can be split into three equal sum subarrays by removing a pair ; Stores prefix sum array ; Copy array elements ; Traverse the array ; Stores sums of all three subarrays ; Sum of left subarray ; Sum of middle subarray ; Sum of right subarray ; Check if sum of subarrays are equal ; Print the possible pair ; If no such pair exists , print - 1 ; Driver Code ; Given array ; Size of the array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findSplit ( int arr [ ] , int N ) { vector < int > sum ( N ) ; for ( int i = 0 ; i < N ; i ++ ) { sum [ i ] = arr [ i ] ; } for ( int i = 1 ; i < N ; i ++ ) { sum [ i ] += sum [ i - 1 ] ; } for ( int l = 1 ; l <= N - 4 ; l ++ ) { for ( int r = l + 2 ; r <= N - 2 ; r ++ ) { int lsum = 0 , rsum = 0 , msum = 0 ; lsum = sum [ l - 1 ] ; msum = sum [ r - 1 ] - sum [ l ] ; rsum = sum [ N - 1 ] - sum [ r ] ; if ( lsum == rsum && rsum == msum ) { cout << l << " ▁ " << r << endl ; return ; } } } cout << -1 << endl ; } int main ( ) { int arr [ ] = { 2 , 5 , 12 , 7 , 19 , 4 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findSplit ( arr , N ) ; return 0 ; }
Print indices of pair of array elements required to be removed to split array into 3 equal sum subarrays | C ++ program for the above approach ; Function to check if array can be split into three equal sum subarrays by removing a pair ; Two pointers l and r ; Stores prefix sum array ; Traverse the array ; Two pointer approach ; Sum of left subarray ; Sum of middle subarray ; Sum of right subarray ; Print split indices if sum is equal ; Move left pointer if lsum < rsum ; Move right pointer if rsum > lsum ; Move both pointers if lsum = rsum but they are not equal to msum ; If no possible pair exists , print - 1 ; Driver Code ; Given array ; Size of the array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findSplit ( int arr [ ] , int N ) { int l = 1 , r = N - 2 ; int lsum , msum , rsum ; vector < int > sum ( N ) ; sum [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { sum [ i ] = sum [ i - 1 ] + arr [ i ] ; } while ( l < r ) { lsum = sum [ l - 1 ] ; msum = sum [ r - 1 ] - sum [ l ] ; rsum = sum [ N - 1 ] - sum [ r ] ; if ( lsum == msum and msum == rsum ) { cout << l << " ▁ " << r << endl ; return ; } if ( lsum < rsum ) l ++ ; else if ( lsum > rsum ) r -- ; else { l ++ ; r -- ; } } cout << -1 << endl ; } int main ( ) { int arr [ ] = { 2 , 5 , 12 , 7 , 19 , 4 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findSplit ( arr , N ) ; return 0 ; }
Number of subtrees having odd count of even numbers | C implementation to find number of subtrees having odd count of even numbers ; A binary tree Node ; Helper function that allocates a new Node with the given data and NULL left and right pointers . ; Returns count of subtrees having odd count of even numbers ; base condition ; count even nodes in left subtree ; Add even nodes in right subtree ; Check if root data is an even number ; if total count of even numbers for the subtree is odd ; Total count of even nodes of the subtree ; A wrapper over countRec ( ) ; Driver program to test above ; binary tree formation ; 2 ; / \ ; 1 3 ; / \ / \ ; 4 10 8 5 ; / ; 6
#include <bits/stdc++.h> NEW_LINE struct Node { int data ; struct Node * left , * right ; } ; struct Node * newNode ( int data ) { struct Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } int countRec ( struct Node * root , int * pcount ) { if ( root == NULL ) return 0 ; int c = countRec ( root -> left , pcount ) ; c += countRec ( root -> right , pcount ) ; if ( root -> data % 2 == 0 ) c += 1 ; if ( c % 2 != 0 ) ( * pcount ) ++ ; return c ; } int countSubtrees ( Node * root ) { int count = 0 ; int * pcount = & count ; countRec ( root , pcount ) ; return count ; } int main ( ) { struct Node * root = newNode ( 2 ) ; root -> left = newNode ( 1 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 10 ) ; root -> right -> left = newNode ( 8 ) ; root -> right -> right = newNode ( 5 ) ; root -> left -> right -> left = newNode ( 6 ) ; printf ( " Count ▁ = ▁ % d " , countSubtrees ( root ) ) ; return 0 ; }
Inorder Successor of a node in Binary Tree | CPP program to find inorder successor of a node ; A Binary Tree Node ; Temporary node for case 2 ; Utility function to create a new tree node ; function to find left most node in a tree ; function to find right most node in a tree ; recursive function to find the Inorder Scuccessor when the right child of node x is NULL ; function to find inorder successor of a node ; Case1 : If right child is not NULL ; Case2 : If right child is NULL ; case3 : If x is the right most node ; Driver program to test above functions ; Case 1 ; case 2 ; case 3
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; Node * temp = new Node ; Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } Node * leftMostNode ( Node * node ) { while ( node != NULL && node -> left != NULL ) node = node -> left ; return node ; } Node * rightMostNode ( Node * node ) { while ( node != NULL && node -> right != NULL ) node = node -> right ; return node ; } Node * findInorderRecursive ( Node * root , Node * x ) { if ( ! root ) return NULL ; if ( root == x || ( temp = findInorderRecursive ( root -> left , x ) ) || ( temp = findInorderRecursive ( root -> right , x ) ) ) { if ( temp ) { if ( root -> left == temp ) { cout << " Inorder ▁ Successor ▁ of ▁ " << x -> data ; cout << " ▁ is ▁ " << root -> data << " STRNEWLINE " ; return NULL ; } } return root ; } return NULL ; } void inorderSuccesor ( Node * root , Node * x ) { if ( x -> right != NULL ) { Node * inorderSucc = leftMostNode ( x -> right ) ; cout << " Inorder ▁ Successor ▁ of ▁ " << x -> data << " ▁ is ▁ " ; cout << inorderSucc -> data << " STRNEWLINE " ; } if ( x -> right == NULL ) { int f = 0 ; Node * rightMost = rightMostNode ( root ) ; if ( rightMost == x ) cout << " No ▁ inorder ▁ successor ! ▁ Right ▁ most ▁ node . STRNEWLINE " ; else findInorderRecursive ( root , x ) ; } } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> right = newNode ( 6 ) ; inorderSuccesor ( root , root -> right ) ; inorderSuccesor ( root , root -> left -> left ) ; inorderSuccesor ( root , root -> right -> right ) ; return 0 ; }
Binary Tree | Set 1 ( Introduction ) | ; struct containing left and right child of current node and key value ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left ; struct Node * right ; Node ( int val ) { data = val ; left = NULL ; right = NULL ; } } ; int main ( ) { struct Node * root = new Node ( 1 ) ; root -> left = new Node ( 2 ) ; root -> right = new Node ( 3 ) ; root -> left -> left = new Node ( 4 ) ; return 0 ; }
Find distance from root to given node in a binary tree | C ++ program to find distance of a given node from root . ; A Binary Tree Node ; A utility function to create a new Binary Tree Node ; Returns - 1 if x doesn 't exist in tree. Else returns distance of x from root ; Base case ; Initialize distance ; Check if x is present at root or in left subtree or right subtree . ; Driver Program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int item ) { Node * temp = new Node ; temp -> data = item ; temp -> left = temp -> right = NULL ; return temp ; } int findDistance ( Node * root , int x ) { if ( root == NULL ) return -1 ; int dist = -1 ; if ( ( root -> data == x ) || ( dist = findDistance ( root -> left , x ) ) >= 0 || ( dist = findDistance ( root -> right , x ) ) >= 0 ) return dist + 1 ; return dist ; } int main ( ) { Node * root = newNode ( 5 ) ; root -> left = newNode ( 10 ) ; root -> right = newNode ( 15 ) ; root -> left -> left = newNode ( 20 ) ; root -> left -> right = newNode ( 25 ) ; root -> left -> right -> right = newNode ( 45 ) ; root -> right -> left = newNode ( 30 ) ; root -> right -> right = newNode ( 35 ) ; cout << findDistance ( root , 45 ) ; return 0 ; }
Find right sibling of a binary tree with parent pointers | C program to print right sibling of a node ; A Binary Tree Node ; A utility function to create a new Binary Tree Node ; Method to find right sibling ; GET Parent pointer whose right child is not a parent or itself of this node . There might be case when parent has no right child , but , current node is left child of the parent ( second condition is for that ) . ; Move to the required child , where right sibling can be present ; find right sibling in the given subtree ( from current node ) , when level will be 0 ; Iterate through subtree ; if no child are there , we cannot have right sibling in this path ; This is the case when we reach 9 node in the tree , where we need to again recursively find the right sibling ; Driver Program to test above functions ; passing 10
#include <bits/stdc++.h> NEW_LINE struct Node { int data ; Node * left , * right , * parent ; } ; Node * newNode ( int item , Node * parent ) { Node * temp = new Node ; temp -> data = item ; temp -> left = temp -> right = NULL ; temp -> parent = parent ; return temp ; } Node * findRightSibling ( Node * node , int level ) { if ( node == NULL node -> parent == NULL ) return NULL ; while ( node -> parent -> right == node || ( node -> parent -> right == NULL && node -> parent -> left == node ) ) { if ( node -> parent == NULL node -> parent -> parent == NULL ) return NULL ; node = node -> parent ; level -- ; } node = node -> parent -> right ; if ( node == NULL ) return NULL ; while ( level < 0 ) { if ( node -> left != NULL ) node = node -> left ; else if ( node -> right != NULL ) node = node -> right ; else break ; level ++ ; } if ( level == 0 ) return node ; return findRightSibling ( node , level ) ; } int main ( ) { Node * root = newNode ( 1 , NULL ) ; root -> left = newNode ( 2 , root ) ; root -> right = newNode ( 3 , root ) ; root -> left -> left = newNode ( 4 , root -> left ) ; root -> left -> right = newNode ( 6 , root -> left ) ; root -> left -> left -> left = newNode ( 7 , root -> left -> left ) ; root -> left -> left -> left -> left = newNode ( 10 , root -> left -> left -> left ) ; root -> left -> right -> right = newNode ( 9 , root -> left -> right ) ; root -> right -> right = newNode ( 5 , root -> right ) ; root -> right -> right -> right = newNode ( 8 , root -> right -> right ) ; root -> right -> right -> right -> right = newNode ( 12 , root -> right -> right -> right ) ; Node * res = findRightSibling ( root -> left -> left -> left -> left , 0 ) ; if ( res == NULL ) printf ( " No ▁ right ▁ sibling " ) ; else printf ( " % d " , res -> data ) ; return 0 ; }
Find next right node of a given key | Set 2 | C ++ program to find next right of a given key using preorder traversal ; A Binary Tree Node ; Utility function to create a new tree node ; Function to find next node for given node in same level in a binary tree by using pre - order traversal ; return null if tree is empty ; if desired node is found , set value_level to current level ; if value_level is already set , then current node is the next right node ; recurse for left subtree by increasing level by 1 ; if node is found in left subtree , return it ; recurse for right subtree by increasing level by 1 ; Function to find next node of given node in the same level in given binary tree ; A utility function to test above functions ; Driver program to test above functions ; Let us create binary tree given in the above example
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { struct Node * left , * right ; int key ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return temp ; } Node * nextRightNode ( Node * root , int k , int level , int & value_level ) { if ( root == NULL ) return NULL ; if ( root -> key == k ) { value_level = level ; return NULL ; } else if ( value_level ) { if ( level == value_level ) return root ; } Node * leftNode = nextRightNode ( root -> left , k , level + 1 , value_level ) ; if ( leftNode ) return leftNode ; return nextRightNode ( root -> right , k , level + 1 , value_level ) ; } Node * nextRightNodeUtil ( Node * root , int k ) { int value_level = 0 ; return nextRightNode ( root , k , 1 , value_level ) ; } void test ( Node * root , int k ) { Node * nr = nextRightNodeUtil ( root , k ) ; if ( nr != NULL ) cout << " Next ▁ Right ▁ of ▁ " << k << " ▁ is ▁ " << nr -> key << endl ; else cout << " No ▁ next ▁ right ▁ node ▁ found ▁ for ▁ " << k << endl ; } int main ( ) { Node * root = newNode ( 10 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 6 ) ; root -> right -> right = newNode ( 5 ) ; root -> left -> left = newNode ( 8 ) ; root -> left -> right = newNode ( 4 ) ; test ( root , 10 ) ; test ( root , 2 ) ; test ( root , 6 ) ; test ( root , 5 ) ; test ( root , 8 ) ; test ( root , 4 ) ; return 0 ; }
Top three elements in binary tree | CPP program to find largest three elements in a binary tree . ; Helper function that allocates a new Node with the given data and NULL left and right pointers . ; function to find three largest element ; if data is greater than first large number update the top three list ; if data is greater than second large number and not equal to first update the bottom two list ; if data is greater than third large number and not equal to first & second update the third highest list ; driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left ; struct Node * right ; } ; struct Node * newNode ( int data ) { struct Node * node = new Node ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; return ( node ) ; } void threelargest ( Node * root , int & first , int & second , int & third ) { if ( root == NULL ) return ; if ( root -> data > first ) { third = second ; second = first ; first = root -> data ; } else if ( root -> data > second && root -> data != first ) { third = second ; second = root -> data ; } else if ( root -> data > third && root -> data != first && root -> data != second ) third = root -> data ; threelargest ( root -> left , first , second , third ) ; threelargest ( root -> right , first , second , third ) ; } int main ( ) { struct Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> left = newNode ( 4 ) ; root -> right -> right = newNode ( 5 ) ; int first = 0 , second = 0 , third = 0 ; threelargest ( root , first , second , third ) ; cout << " three ▁ largest ▁ elements ▁ are ▁ " << first << " ▁ " << second << " ▁ " << third ; return 0 ; }
Find maximum ( or minimum ) in Binary Tree | C ++ program to find maximum and minimum in a Binary Tree ; A tree node ; Constructor that allocates a new node with the given data and NULL left and right pointers . ; Returns maximum value in a given Binary Tree ; Base case ; Return maximum of 3 values : 1 ) Root 's data 2) Max in Left Subtree 3) Max in right subtree ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE #include <iostream> NEW_LINE using namespace std ; class Node { public : int data ; Node * left , * right ; Node ( int data ) { this -> data = data ; this -> left = NULL ; this -> right = NULL ; } } ; int findMax ( Node * root ) { if ( root == NULL ) return INT_MIN ; int res = root -> data ; int lres = findMax ( root -> left ) ; int rres = findMax ( root -> right ) ; if ( lres > res ) res = lres ; if ( rres > res ) res = rres ; return res ; } int main ( ) { Node * NewRoot = NULL ; Node * root = new Node ( 2 ) ; root -> left = new Node ( 7 ) ; root -> right = new Node ( 5 ) ; root -> left -> right = new Node ( 6 ) ; root -> left -> right -> left = new Node ( 1 ) ; root -> left -> right -> right = new Node ( 11 ) ; root -> right -> right = new Node ( 9 ) ; root -> right -> right -> left = new Node ( 4 ) ; cout << " Maximum ▁ element ▁ is ▁ " << findMax ( root ) << endl ; return 0 ; }
Extract Leaves of a Binary Tree in a Doubly Linked List | C ++ program to extract leaves of a Binary Tree in a Doubly Linked List ; Structure for tree and linked list ; Main function which extracts all leaves from given Binary Tree . The function returns new root of Binary Tree ( Note that root may changeif Binary Tree has only one node ) . The function also sets * head_ref as head of doubly linked list . left pointer of tree is used as prev in DLL and right pointer is used as next ; Utility function for allocating node for Binary Tree . ; Utility function for printing tree in In - Order . ; Utility function for printing double linked list . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * left , * right ; } ; Node * extractLeafList ( Node * root , Node * * head_ref ) { if ( root == NULL ) return NULL ; if ( root -> left == NULL && root -> right == NULL ) { root -> right = * head_ref ; if ( * head_ref != NULL ) ( * head_ref ) -> left = root ; * head_ref = root ; return NULL ; } root -> right = extractLeafList ( root -> right , head_ref ) ; root -> left = extractLeafList ( root -> left , head_ref ) ; return root ; } Node * newNode ( int data ) { Node * node = new Node ( ) ; node -> data = data ; node -> left = node -> right = NULL ; return node ; } void print ( Node * root ) { if ( root != NULL ) { print ( root -> left ) ; cout << root -> data << " ▁ " ; print ( root -> right ) ; } } void printList ( Node * head ) { while ( head ) { cout << head -> data << " ▁ " ; head = head -> right ; } } int main ( ) { Node * head = NULL ; Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> right = newNode ( 6 ) ; root -> left -> left -> left = newNode ( 7 ) ; root -> left -> left -> right = newNode ( 8 ) ; root -> right -> right -> left = newNode ( 9 ) ; root -> right -> right -> right = newNode ( 10 ) ; cout << " Inorder ▁ Trvaersal ▁ of ▁ given ▁ Tree ▁ is : STRNEWLINE " ; print ( root ) ; root = extractLeafList ( root , & head ) ; cout << " Extracted Double Linked list is : " ; printList ( head ) ; cout << " Inorder traversal of modified tree is : " print ( root ) ; return 0 ; }
Inorder Successor of a node in Binary Tree | C ++ Program to find inorder successor . ; structure of a Binary Node . ; Function to create a new Node . ; function that prints the inorder successor of a target node . next will point the last tracked node , which will be the answer . ; if root is null then return ; if target node found then enter this condition ; Driver Code ; Let 's construct the binary tree as shown in above diagram. ; Case 1 ; case 2 ; case 3
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left ; Node * right ; } ; Node * newNode ( int val ) { Node * temp = new Node ; temp -> data = val ; temp -> left = NULL ; temp -> right = NULL ; return temp ; } void inorderSuccessor ( Node * root , Node * target_node , Node * & next ) { if ( ! root ) return ; inorderSuccessor ( root -> right , target_node , next ) ; if ( root -> data == target_node -> data ) { if ( next == NULL ) cout << " inorder ▁ successor ▁ of ▁ " << root -> data << " ▁ is : ▁ null STRNEWLINE " ; else cout << " inorder ▁ successor ▁ of ▁ " << root -> data << " ▁ is : ▁ " << next -> data << " STRNEWLINE " ; } next = root ; inorderSuccessor ( root -> left , target_node , next ) ; } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> right = newNode ( 6 ) ; Node * next = NULL ; inorderSuccessor ( root , root -> right , next ) ; next = NULL ; inorderSuccessor ( root , root -> left -> left , next ) ; next = NULL ; inorderSuccessor ( root , root -> right -> right , next ) ; return 0 ; }
Graph and its representations | A simple representation of graph using STL ; A utility function to add an edge in an undirected graph . ; A utility function to print the adjacency list representation of graph ; Driver code ; Creating a graph with 5 vertices ; Adding edges one by one
#include <bits/stdc++.h> NEW_LINE using namespace std ; void addEdge ( vector < int > adj [ ] , int u , int v ) { adj [ u ] . push_back ( v ) ; adj [ v ] . push_back ( u ) ; } void printGraph ( vector < int > adj [ ] , int V ) { for ( int v = 0 ; v < V ; ++ v ) { cout << " Adjacency list of vertex " << v < < " head " for ( auto x : adj [ v ] ) cout << " - > ▁ " << x ; printf ( " STRNEWLINE " ) ; } } int main ( ) { int V = 5 ; vector < int > adj [ V ] ; addEdge ( adj , 0 , 1 ) ; addEdge ( adj , 0 , 4 ) ; addEdge ( adj , 1 , 2 ) ; addEdge ( adj , 1 , 3 ) ; addEdge ( adj , 1 , 4 ) ; addEdge ( adj , 2 , 3 ) ; addEdge ( adj , 3 , 4 ) ; printGraph ( adj , V ) ; return 0 ; }
Graph representations using set and hash | A C ++ program to demonstrate adjacency list representation of graphs using sets ; ; Adds an edge to an undirected graph ; Add an edge from src to dest . A new element is inserted to the adjacent list of src . ; Since graph is undirected , add an edge from dest to src also ; A utility function to print the adjacency list representation of graph ; Searches for a given edge in the graph ; Driver code ; Create the graph given in the above figure ; Print the adjacency list representation of the above graph ; Search the given edge in the graph
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Graph { int V ; set < int , greater < int > > * adjList ; } ; Graph * createGraph ( int V ) { Graph * graph = new Graph ; graph -> V = V ; graph -> adjList = new set < int , greater < int > > [ V ] ; return graph ; } void addEdge ( Graph * graph , int src , int dest ) { graph -> adjList [ src ] . insert ( dest ) ; graph -> adjList [ dest ] . insert ( src ) ; } void printGraph ( Graph * graph ) { for ( int i = 0 ; i < graph -> V ; ++ i ) { set < int , greater < int > > lst = graph -> adjList [ i ] ; cout << endl << " Adjacency ▁ list ▁ of ▁ vertex ▁ " << i << endl ; for ( auto itr = lst . begin ( ) ; itr != lst . end ( ) ; ++ itr ) cout << * itr << " ▁ " ; cout << endl ; } } void searchEdge ( Graph * graph , int src , int dest ) { auto itr = graph -> adjList [ src ] . find ( dest ) ; if ( itr == graph -> adjList [ src ] . end ( ) ) cout << endl << " Edge ▁ from ▁ " << src << " ▁ to ▁ " << dest << " ▁ not ▁ found . " << endl ; else cout << endl << " Edge ▁ from ▁ " << src << " ▁ to ▁ " << dest << " ▁ found . " << endl ; } int main ( ) { int V = 5 ; struct Graph * graph = createGraph ( V ) ; addEdge ( graph , 0 , 1 ) ; addEdge ( graph , 0 , 4 ) ; addEdge ( graph , 1 , 2 ) ; addEdge ( graph , 1 , 3 ) ; addEdge ( graph , 1 , 4 ) ; addEdge ( graph , 2 , 3 ) ; addEdge ( graph , 3 , 4 ) ; printGraph ( graph ) ; searchEdge ( graph , 2 , 1 ) ; searchEdge ( graph , 0 , 3 ) ; return 0 ; }
Find k | C ++ program to find K - Cores of a graph ; This class represents a undirected graph using adjacency list representation ; No . of vertices ; Pointer to an array containing adjacency lists ; Constructor ; function to add an edge to graph ; A recursive function to print DFS starting from v . It returns true if degree of v after processing is less than k else false It also updates degree of adjacent if degree of v is less than k . And if degree of a processed adjacent becomes less than k , then it reduces of degree of v also , ; Mark the current node as visited and print it ; Recur for all the vertices adjacent to this vertex ; degree of v is less than k , then degree of adjacent must be reduced ; If adjacent is not processed , process it ; If degree of adjacent after processing becomes less than k , then reduce degree of v also . ; Return true if degree of v is less than k ; Prints k cores of an undirected graph ; INITIALIZATION Mark all the vertices as not visited and not processed . ; Store degrees of all vertices ; If Graph is disconnected . ; PRINTING K CORES ; Only considering those vertices which have degree >= K after BFS ; Traverse adjacency list of v and print only those adjacent which have vDegree >= k after BFS . ; Driver program to test methods of graph class ; Create a graph given in the above diagram
#include <bits/stdc++.h> NEW_LINE using namespace std ; class Graph { int V ; list < int > * adj ; public : Graph :: Graph ( int V ) { this -> V = V ; adj = new list < int > [ V ] ; } void addEdge ( int u , int v ) ; bool DFSUtil ( int , vector < bool > & , vector < int > & , int k ) ; void printKCores ( int k ) ; } ; void Graph :: addEdge ( int u , int v ) { adj [ u ] . push_back ( v ) ; adj [ v ] . push_back ( u ) ; } void Graph :: DFSUtil ( int v , vector < bool > & visited , vector < int > & vDegree , int k ) { visited [ v ] = true ; list < int > :: iterator i ; for ( i = adj [ v ] . begin ( ) ; i != adj [ v ] . end ( ) ; ++ i ) { if ( vDegree [ v ] < k ) vDegree [ * i ] -- ; if ( ! visited [ * i ] ) { DFSUtil ( * i , visited , vDegree , k ) } } return ( vDegree [ v ] < k ) ; } void Graph :: printKCores ( int k ) { vector < bool > visited ( V , false ) ; vector < bool > processed ( V , false ) ; int mindeg = INT_MAX ; int startvertex ; vector < int > vDegree ( V ) ; for ( int i = 0 ; i < V ; i ++ ) { vDegree [ i ] = adj [ i ] . size ( ) ; if ( vDegree [ i ] < mindeg ) { mindeg = vDegree [ i ] ; startvertex = i ; } } DFSUtil ( startvertex , visited , vDegree , k ) ; for ( int i = 0 ; i < V ; i ++ ) if ( visited [ i ] == false ) DFSUtil ( i , visited , vDegree , k ) ; cout << " K - Cores ▁ : ▁ STRNEWLINE " ; for ( int v = 0 ; v < V ; v ++ ) { if ( vDegree [ v ] >= k ) { cout << " STRNEWLINE [ " << v << " ] " ; list < int > :: iterator itr ; for ( itr = adj [ v ] . begin ( ) ; itr != adj [ v ] . end ( ) ; ++ itr ) if ( vDegree [ * itr ] >= k ) cout << " ▁ - > ▁ " << * itr ; } } } int main ( ) { int k = 3 ; Graph g1 ( 9 ) ; g1 . addEdge ( 0 , 1 ) ; g1 . addEdge ( 0 , 2 ) ; g1 . addEdge ( 1 , 2 ) ; g1 . addEdge ( 1 , 5 ) ; g1 . addEdge ( 2 , 3 ) ; g1 . addEdge ( 2 , 4 ) ; g1 . addEdge ( 2 , 5 ) ; g1 . addEdge ( 2 , 6 ) ; g1 . addEdge ( 3 , 4 ) ; g1 . addEdge ( 3 , 6 ) ; g1 . addEdge ( 3 , 7 ) ; g1 . addEdge ( 4 , 6 ) ; g1 . addEdge ( 4 , 7 ) ; g1 . addEdge ( 5 , 6 ) ; g1 . addEdge ( 5 , 8 ) ; g1 . addEdge ( 6 , 7 ) ; g1 . addEdge ( 6 , 8 ) ; g1 . printKCores ( k ) ; cout << endl << endl ; Graph g2 ( 13 ) ; g2 . addEdge ( 0 , 1 ) ; g2 . addEdge ( 0 , 2 ) ; g2 . addEdge ( 0 , 3 ) ; g2 . addEdge ( 1 , 4 ) ; g2 . addEdge ( 1 , 5 ) ; g2 . addEdge ( 1 , 6 ) ; g2 . addEdge ( 2 , 7 ) ; g2 . addEdge ( 2 , 8 ) ; g2 . addEdge ( 2 , 9 ) ; g2 . addEdge ( 3 , 10 ) ; g2 . addEdge ( 3 , 11 ) ; g2 . addEdge ( 3 , 12 ) ; g2 . printKCores ( k ) ; return 0 ; }
Minimum initial vertices to traverse whole matrix with given conditions | C ++ program to find minimum initial vertices to reach whole matrix . ; ( n , m ) is current source cell from which we need to do DFS . N and M are total no . of rows and columns . ; Marking the vertex as visited ; If below neighbor is valid and has value less than or equal to current cell 's value ; If right neighbor is valid and has value less than or equal to current cell 's value ; If above neighbor is valid and has value less than or equal to current cell 's value ; If left neighbor is valid and has value less than or equal to current cell 's value ; Storing the cell value and cell indices in a vector . ; Sorting the newly created array according to cell values ; Create a visited array for DFS and initialize it as false . ; Applying dfs for each vertex with highest value ; If the given vertex is not visited then include it in the set ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100 ; void dfs ( int n , int m , bool visit [ ] [ MAX ] , int adj [ ] [ MAX ] , int N , int M ) { visit [ n ] [ m ] = 1 ; if ( n + 1 < N && adj [ n ] [ m ] >= adj [ n + 1 ] [ m ] && ! visit [ n + 1 ] [ m ] ) dfs ( n + 1 , m , visit , adj , N , M ) ; if ( m + 1 < M && adj [ n ] [ m ] >= adj [ n ] [ m + 1 ] && ! visit [ n ] [ m + 1 ] ) dfs ( n , m + 1 , visit , adj , N , M ) ; if ( n - 1 >= 0 && adj [ n ] [ m ] >= adj [ n - 1 ] [ m ] && ! visit [ n - 1 ] [ m ] ) dfs ( n - 1 , m , visit , adj , N , M ) ; if ( m - 1 >= 0 && adj [ n ] [ m ] >= adj [ n ] [ m - 1 ] && ! visit [ n ] [ m - 1 ] ) dfs ( n , m - 1 , visit , adj , N , M ) ; } void printMinSources ( int adj [ ] [ MAX ] , int N , int M ) { vector < pair < long int , pair < int , int > > > x ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < M ; j ++ ) x . push_back ( make_pair ( adj [ i ] [ j ] , make_pair ( i , j ) ) ) ; sort ( x . begin ( ) , x . end ( ) ) ; bool visit [ N ] [ MAX ] ; memset ( visit , false , sizeof ( visit ) ) ; for ( int i = x . size ( ) - 1 ; i >= 0 ; i -- ) { if ( ! visit [ x [ i ] . second . first ] [ x [ i ] . second . second ] ) { cout << x [ i ] . second . first << " ▁ " << x [ i ] . second . second << endl ; dfs ( x [ i ] . second . first , x [ i ] . second . second , visit , adj , N , M ) ; } } } int main ( ) { int N = 2 , M = 2 ; int adj [ N ] [ MAX ] = { { 3 , 3 } , { 1 , 1 } } ; printMinSources ( adj , N , M ) ; return 0 ; }
Shortest path to reach one prime to other by changing single digit at a time | CPP program to reach a prime number from another by changing single digits and using only prime numbers . ; Finding all 4 digit prime numbers ; 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 ; Forming a vector of prime numbers ; in1 and in2 are two vertices of graph which are actually indexes in pset [ ] ; Returns true if num1 and num2 differ by single digit . ; To compare the digits ; If the numbers differ only by a single digit return true else false ; Generate all 4 digit ; Create a graph where node numbers are indexes in pset [ ] and there is an edge between two nodes only if they differ by single digit . ; Since graph nodes represent indexes of numbers in pset [ ] , we find indexes of num1 and num2 . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; class graph { int V ; list < int > * l ; public : graph ( int V ) { this -> V = V ; l = new list < int > [ V ] ; } void addedge ( int V1 , int V2 ) { l [ V1 ] . push_back ( V2 ) ; l [ V2 ] . push_back ( V1 ) ; } int bfs ( int in1 , int in2 ) ; } ; void SieveOfEratosthenes ( vector < int > & v ) { int n = 9999 ; bool prime [ n + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= n ; i += p ) prime [ i ] = false ; } } for ( int p = 1000 ; p <= n ; p ++ ) if ( prime [ p ] ) v . push_back ( p ) ; } int graph :: bfs ( int in1 , int in2 ) { int visited [ V ] ; memset ( visited , 0 , sizeof ( visited ) ) ; queue < int > que ; visited [ in1 ] = 1 ; que . push ( in1 ) ; list < int > :: iterator i ; while ( ! que . empty ( ) ) { int p = que . front ( ) ; que . pop ( ) ; for ( i = l [ p ] . begin ( ) ; i != l [ p ] . end ( ) ; i ++ ) { if ( ! visited [ * i ] ) { visited [ * i ] = visited [ p ] + 1 ; que . push ( * i ) ; } if ( * i == in2 ) { return visited [ * i ] - 1 ; } } } } bool compare ( int num1 , int num2 ) { string s1 = to_string ( num1 ) ; string s2 = to_string ( num2 ) ; int c = 0 ; if ( s1 [ 0 ] != s2 [ 0 ] ) c ++ ; if ( s1 [ 1 ] != s2 [ 1 ] ) c ++ ; if ( s1 [ 2 ] != s2 [ 2 ] ) c ++ ; if ( s1 [ 3 ] != s2 [ 3 ] ) c ++ ; return ( c == 1 ) ; } int shortestPath ( int num1 , int num2 ) { vector < int > pset ; SieveOfEratosthenes ( pset ) ; graph g ( pset . size ( ) ) ; for ( int i = 0 ; i < pset . size ( ) ; i ++ ) for ( int j = i + 1 ; j < pset . size ( ) ; j ++ ) if ( compare ( pset [ i ] , pset [ j ] ) ) g . addedge ( i , j ) ; int in1 , in2 ; for ( int j = 0 ; j < pset . size ( ) ; j ++ ) if ( pset [ j ] == num1 ) in1 = j ; for ( int j = 0 ; j < pset . size ( ) ; j ++ ) if ( pset [ j ] == num2 ) in2 = j ; return g . bfs ( in1 , in2 ) ; } int main ( ) { int num1 = 1033 , num2 = 8179 ; cout << shortestPath ( num1 , num2 ) ; return 0 ; }
Level of Each node in a Tree from source node ( using BFS ) | CPP Program to determine level of each node and print level ; function to determine level of each node starting from x using BFS ; array to store level of each node ; create a queue ; enqueue element x ; initialize level of source node to 0 ; marked it as visited ; do until queue is empty ; get the first element of queue ; dequeue element ; traverse neighbors of node x ; b is neighbor of node x ; if b is not marked already ; enqueue b in queue ; level of b is level of x + 1 ; mark b ; display all nodes and their levels ; Driver Code ; adjacency graph for tree ; call levels function with source as 0
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printLevels ( vector < int > graph [ ] , int V , int x ) { int level [ V ] ; bool marked [ V ] ; queue < int > que ; que . push ( x ) ; level [ x ] = 0 ; marked [ x ] = true ; while ( ! que . empty ( ) ) { x = que . front ( ) ; que . pop ( ) ; for ( int i = 0 ; i < graph [ x ] . size ( ) ; i ++ ) { int b = graph [ x ] [ i ] ; if ( ! marked [ b ] ) { que . push ( b ) ; level [ b ] = level [ x ] + 1 ; marked [ b ] = true ; } } } cout << " Nodes " << " TABSYMBOL " << " Level " << endl ; for ( int i = 0 ; i < V ; i ++ ) cout << " ▁ " << i << " ▁ - - > ▁ " << level [ i ] << endl ; } int main ( ) { int V = 8 ; vector < int > graph [ V ] ; graph [ 0 ] . push_back ( 1 ) ; graph [ 0 ] . push_back ( 2 ) ; graph [ 1 ] . push_back ( 3 ) ; graph [ 1 ] . push_back ( 4 ) ; graph [ 1 ] . push_back ( 5 ) ; graph [ 2 ] . push_back ( 5 ) ; graph [ 2 ] . push_back ( 6 ) ; graph [ 6 ] . push_back ( 7 ) ; printLevels ( graph , V , 0 ) ; return 0 ; }
Construct binary palindrome by repeated appending and trimming | CPP code to form binary palindrome ; function to apply DFS ; set the parent marked ; if the node has not been visited set it and its children marked ; link which digits must be equal ; connect the two indices ; set everything connected to first character as 1 ; driver code
#include <iostream> NEW_LINE #include <vector> NEW_LINE using namespace std ; void dfs ( int parent , int ans [ ] , vector < int > connectchars [ ] ) { ans [ parent ] = 1 ; for ( int i = 0 ; i < connectchars [ parent ] . size ( ) ; i ++ ) { if ( ! ans [ connectchars [ parent ] [ i ] ] ) dfs ( connectchars [ parent ] [ i ] , ans , connectchars ) ; } } void printBinaryPalindrome ( int n , int k ) { int arr [ n ] , ans [ n ] = { 0 } ; vector < int > connectchars [ k ] ; for ( int i = 0 ; i < n ; i ++ ) arr [ i ] = i % k ; for ( int i = 0 ; i < n / 2 ; i ++ ) { connectchars [ arr [ i ] ] . push_back ( arr [ n - i - 1 ] ) ; connectchars [ arr [ n - i - 1 ] ] . push_back ( arr [ i ] ) ; } dfs ( 0 , ans , connectchars ) ; for ( int i = 0 ; i < n ; i ++ ) cout << ans [ arr [ i ] ] ; } int main ( ) { int n = 10 , k = 4 ; printBinaryPalindrome ( n , k ) ; return 0 ; }
Find n | C ++ program to find n - th node of Postorder Traversal of Binary Tree ; node of tree ; function to create a new node ; function to find the N - th node in the postorder traversal of a given binary tree ; left recursion ; right recursion ; prints the n - th node of preorder traversal ; driver code ; prints n - th node found
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; struct Node * createNode ( int item ) { Node * temp = new Node ; temp -> data = item ; temp -> left = NULL ; temp -> right = NULL ; return temp ; } void NthPostordernode ( struct Node * root , int N ) { static int flag = 0 ; if ( root == NULL ) return ; if ( flag <= N ) { NthPostordernode ( root -> left , N ) ; NthPostordernode ( root -> right , N ) ; flag ++ ; if ( flag == N ) cout << root -> data ; } } int main ( ) { struct Node * root = createNode ( 25 ) ; root -> left = createNode ( 20 ) ; root -> right = createNode ( 30 ) ; root -> left -> left = createNode ( 18 ) ; root -> left -> right = createNode ( 22 ) ; root -> right -> left = createNode ( 24 ) ; root -> right -> right = createNode ( 32 ) ; int N = 6 ; NthPostordernode ( root , N ) ; return 0 ; }
Path in a Rectangle with Circles | C ++ program to find out path in a rectangle containing circles . ; Function to find out if there is any possible path or not . ; Take an array of m * n size and initialize each element to 0. ; Now using Pythagorean theorem find if a cell touches or within any circle or not . ; If the starting cell comes within any circle return false . ; Now use BFS to find if there is any possible path or not . Initialize the queue which holds the discovered cells whose neighbors are not discovered yet . ; Discover cells until queue is not empty ; Discover the eight adjacent nodes . check top - left cell ; check top cell ; check top - right cell ; check left cell ; check right cell ; check bottom - left cell ; check bottom cell ; check bottom - right cell ; Now if the end cell ( i . e . bottom right cell ) is 1 ( reachable ) then we will send true . ; Driver Program ; Test case 1 ; Function call ; Test case 2 ; Function call
#include <iostream> NEW_LINE #include <math.h> NEW_LINE #include <vector> NEW_LINE using namespace std ; bool isPossible ( int m , int n , int k , int r , vector < int > X , vector < int > Y ) { int rect [ m ] [ n ] = { 0 } ; for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { for ( int p = 0 ; p < k ; p ++ ) { if ( sqrt ( ( pow ( ( X [ p ] - 1 - i ) , 2 ) + pow ( ( Y [ p ] - 1 - j ) , 2 ) ) ) <= r ) { rect [ i ] [ j ] = -1 ; } } } } if ( rect [ 0 ] [ 0 ] == -1 ) return false ; vector < vector < int > > qu ; rect [ 0 ] [ 0 ] = 1 ; qu . push_back ( { 0 , 0 } ) ; while ( ! qu . empty ( ) ) { vector < int > arr = qu . front ( ) ; qu . erase ( qu . begin ( ) ) ; int elex = arr [ 0 ] ; int eley = arr [ 1 ] ; if ( ( elex > 0 ) && ( eley > 0 ) && ( rect [ elex - 1 ] [ eley - 1 ] == 0 ) ) { rect [ elex - 1 ] [ eley - 1 ] = 1 ; vector < int > v = { elex - 1 , eley - 1 } ; qu . push_back ( v ) ; } if ( ( elex > 0 ) && ( rect [ elex - 1 ] [ eley ] == 0 ) ) { rect [ elex - 1 ] [ eley ] = 1 ; vector < int > v = { elex - 1 , eley } ; qu . push_back ( v ) ; } if ( ( elex > 0 ) && ( eley < n - 1 ) && ( rect [ elex - 1 ] [ eley + 1 ] == 0 ) ) { rect [ elex - 1 ] [ eley + 1 ] = 1 ; vector < int > v = { elex - 1 , eley + 1 } ; qu . push_back ( v ) ; } if ( ( eley > 0 ) && ( rect [ elex ] [ eley - 1 ] == 0 ) ) { rect [ elex ] [ eley - 1 ] = 1 ; vector < int > v = { elex , eley - 1 } ; qu . push_back ( v ) ; } if ( ( eley < n - 1 ) && ( rect [ elex ] [ eley + 1 ] == 0 ) ) { rect [ elex ] [ eley + 1 ] = 1 ; vector < int > v = { elex , eley + 1 } ; qu . push_back ( v ) ; } if ( ( elex < m - 1 ) && ( eley > 0 ) && ( rect [ elex + 1 ] [ eley - 1 ] == 0 ) ) { rect [ elex + 1 ] [ eley - 1 ] = 1 ; vector < int > v = { elex + 1 , eley - 1 } ; qu . push_back ( v ) ; } if ( ( elex < m - 1 ) && ( rect [ elex + 1 ] [ eley ] == 0 ) ) { rect [ elex + 1 ] [ eley ] = 1 ; vector < int > v = { elex + 1 , eley } ; qu . push_back ( v ) ; } if ( ( elex < m - 1 ) && ( eley < n - 1 ) && ( rect [ elex + 1 ] [ eley + 1 ] == 0 ) ) { rect [ elex + 1 ] [ eley + 1 ] = 1 ; vector < int > v = { elex + 1 , eley + 1 } ; qu . push_back ( v ) ; } } return ( rect [ m - 1 ] [ n - 1 ] == 1 ) ; } int main ( ) { int m1 = 5 , n1 = 5 , k1 = 2 , r1 = 1 ; vector < int > X1 = { 1 , 3 } ; vector < int > Y1 = { 3 , 3 } ; if ( isPossible ( m1 , n1 , k1 , r1 , X1 , Y1 ) ) cout << " Possible " << endl ; else cout << " Not ▁ Possible " << endl ; int m2 = 5 , n2 = 5 , k2 = 2 , r2 = 1 ; vector < int > X2 = { 1 , 1 } ; vector < int > Y2 = { 2 , 3 } ; if ( isPossible ( m2 , n2 , k2 , r2 , X2 , Y2 ) ) cout << " Possible " << endl ; else cout << " Not ▁ Possible " << endl ; return 0 ; }
DFS for a n | CPP code to perform DFS of given tree : ; DFS on tree ; Printing traversed node ; Traversing adjacent edges ; Not traversing the parent node ; Driver program to test above function ; Number of nodes ; Adjacency list ; Designing the tree ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void dfs ( vector < int > list [ ] , int node , int arrival ) { cout << node << ' ' ; for ( int i = 0 ; i < list [ node ] . size ( ) ; i ++ ) { if ( list [ node ] [ i ] != arrival ) dfs ( list , list [ node ] [ i ] , node ) ; } } int main ( ) { int nodes = 5 ; vector < int > list [ 10000 ] ; list [ 1 ] . push_back ( 2 ) ; list [ 2 ] . push_back ( 1 ) ; list [ 1 ] . push_back ( 3 ) ; list [ 3 ] . push_back ( 1 ) ; list [ 2 ] . push_back ( 4 ) ; list [ 4 ] . push_back ( 2 ) ; list [ 3 ] . push_back ( 5 ) ; list [ 5 ] . push_back ( 3 ) ; dfs ( list , 1 , 0 ) ; return 0 ; }
Maximum number of edges to be added to a tree so that it stays a Bipartite graph | CPP code to print maximum edges such that Tree remains a Bipartite graph ; To store counts of nodes with two colors ; Increment count of nodes with current color ; Traversing adjacent nodes ; Not recurring for the parent node ; Finds maximum number of edges that can be added without violating Bipartite property . ; Do a DFS to count number of nodes of each color ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long count_color [ 2 ] ; void dfs ( vector < int > adj [ ] , int node , int parent , int color ) { count_color [ color ] ++ ; for ( int i = 0 ; i < adj [ node ] . size ( ) ; i ++ ) { if ( adj [ node ] [ i ] != parent ) dfs ( adj , adj [ node ] [ i ] , node , ! color ) ; } } int findMaxEdges ( vector < int > adj [ ] , int n ) { dfs ( adj , 1 , 0 , 0 ) ; return count_color [ 0 ] * count_color [ 1 ] - ( n - 1 ) ; } int main ( ) { int n = 5 ; vector < int > adj [ n + 1 ] ; adj [ 1 ] . push_back ( 2 ) ; adj [ 1 ] . push_back ( 3 ) ; adj [ 2 ] . push_back ( 4 ) ; adj [ 3 ] . push_back ( 5 ) ; cout << findMaxEdges ( adj , n ) ; return 0 ; }
Min steps to empty an Array by removing a pair each time with sum at most K | C ++ program for the above approach ; Function to count minimum steps ; Function to sort the array ; Run while loop ; Condition to check whether sum exceed the target or not ; Increment the step by 1 ; Return minimum steps ; Driver Code ; Given array arr [ ] ; Given target value ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countMinSteps ( int arr [ ] , int target , int n ) { sort ( arr , arr + n ) ; int minimumSteps = 0 ; int i = 0 , j = n - 1 ; while ( i <= j ) { if ( arr [ i ] + arr [ j ] <= target ) { i ++ ; j -- ; } else { j -- ; } minimumSteps ++ ; } return minimumSteps ; } int main ( ) { int arr [ ] = { 4 , 6 , 2 , 9 , 6 , 5 , 8 , 10 } ; int target = 11 ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countMinSteps ( arr , target , size ) ; return 0 ; }
Sort the strings based on the numbers of matchsticks required to represent them | C ++ implementation to sort the strings with the number of sticks required to represent them ; Stick [ ] stores the count of sticks required to represent the alphabets ; Number [ ] stores the count of sticks required to represent the numerals ; Function that return the count of sticks required to represent the given string str ; Loop to iterate over every character of the string ; Add the count of sticks required to represent the current character ; Function to sort the array according to the number of sticks required to represent it ; Vector to store the number of sticks required with respective strings ; Inserting number of sticks with respective strings ; Sort the vector , ; Print the sorted vector ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sticks [ ] = { 6 , 7 , 4 , 6 , 5 , 4 , 6 , 5 , 2 , 4 , 4 , 3 , 6 , 6 , 6 , 5 , 7 , 6 , 5 , 3 , 5 , 4 , 6 , 4 , 3 , 4 } ; int number [ ] = { 6 , 2 , 5 , 5 , 4 , 5 , 6 , 3 , 7 , 6 } ; int countSticks ( string str ) { int cnt = 0 ; for ( int i = 0 ; str [ i ] ; i ++ ) { char ch = str [ i ] ; if ( ch >= ' A ' && ch <= ' Z ' ) { cnt += sticks [ ch - ' A ' ] ; } else { cnt += number [ ch - '0' ] ; } } return cnt ; } void sortArr ( string arr [ ] , int n ) { vector < pair < int , string > > vp ; for ( int i = 0 ; i < n ; i ++ ) { vp . push_back ( make_pair ( countSticks ( arr [ i ] ) , arr [ i ] ) ) ; } sort ( vp . begin ( ) , vp . end ( ) ) ; for ( int i = 0 ; i < vp . size ( ) ; i ++ ) cout << vp [ i ] . second << " ▁ " ; } int main ( ) { string arr [ ] = { " GEEKS " , " FOR " , " GEEKSFORGEEKS " } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortArr ( arr , n ) ; return 0 ; }
Count number of pairs with positive sum in an array | Naive approach to count pairs with positive sum . ; Returns number of pairs in arr [ 0. . n - 1 ] with positive sum ; Initialize result ; Consider all possible pairs and check their sums ; If arr [ i ] & arr [ j ] form valid pair ; Driver 's Code ; Function call to find the count of pairs
#include <bits/stdc++.h> NEW_LINE using namespace std ; int CountPairs ( int arr [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( arr [ i ] + arr [ j ] > 0 ) count += 1 ; } } return count ; } int main ( ) { int arr [ ] = { -7 , -1 , 3 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << CountPairs ( arr , n ) ; return 0 ; }
Find if there exists a direction for ranges such that no two range intersect | C ++ implementation of the approach ; Structure to hold details of each interval ; Function that returns true if the assignment of directions is possible ; Sort the intervals based on velocity ; Test the condition for all intervals with same velocity ; If for any velocity , 3 or more intervals share a common point return false ; Driver code
#include <bits/stdc++.h> NEW_LINE #define MAX 100001 NEW_LINE using namespace std ; typedef struct { int l , r , v ; } interval ; bool cmp ( interval a , interval b ) { return a . v < b . v ; } bool isPossible ( int range [ ] [ 3 ] , int N ) { interval test [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { test [ i ] . l = range [ i ] [ 0 ] ; test [ i ] . r = range [ i ] [ 1 ] ; test [ i ] . v = range [ i ] [ 2 ] ; } sort ( test , test + N , cmp ) ; for ( int i = 0 ; i < N ; i ++ ) { int count [ MAX ] = { 0 } ; int current_velocity = test [ i ] . v ; int j = i ; while ( j < N && test [ j ] . v == current_velocity ) { for ( int k = test [ j ] . l ; k <= test [ j ] . r ; k ++ ) { count [ k ] ++ ; if ( count [ k ] >= 3 ) return false ; } j ++ ; } i = j - 1 ; } return true ; } int main ( ) { int range [ ] [ 3 ] = { { 1 , 2 , 3 } , { 2 , 5 , 1 } , { 3 , 10 , 1 } , { 4 , 4 , 1 } , { 5 , 7 , 10 } } ; int n = sizeof ( range ) / sizeof ( range [ 0 ] ) ; if ( isPossible ( range , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
a | C ++ implementation of the approach ; Function to return the modified string ; To store the previous character ; To store the starting indices of all the groups ; Starting index of the first group ; If the current character and the previous character differ ; Push the starting index of the new group ; The current character now becomes previous ; Sort the first group ; Sort all the remaining groups ; cout << str << endl ; Sort the last group ; Return the modified string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string get_string ( string str , int n ) { char prev = str [ 0 ] ; vector < int > result ; result . push_back ( 0 ) ; for ( int i = 1 ; i < n ; i ++ ) { if ( isdigit ( str [ i ] ) != isdigit ( prev ) ) { result . push_back ( i ) ; } prev = str [ i ] ; } sort ( str . begin ( ) , str . begin ( ) + result [ 0 ] ) ; for ( int i = 0 ; i < result . size ( ) - 1 ; i ++ ) { sort ( str . begin ( ) + result [ i ] , str . begin ( ) + result [ i + 1 ] ) ; } sort ( str . begin ( ) + result [ result . size ( ) - 1 ] , str . end ( ) ) ; return str ; } int main ( ) { string str = "121geeks21" ; int n = str . length ( ) ; cout << get_string ( str , n ) ; return 0 ; }