text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Count subtrees that sum up to a given value x only using single recursive function | C ++ program to find if there is a subtree with given sum ; Structure of a node of binary tree ; Function to get a new node ; Allocate space ; Utility function to count subtress that sum up to a given value x ; Driver code ; binary tree creation 5 / \ - 10 3 / \ / \ 9 8 - 4 7
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * getNode ( int data ) { Node * newNode = ( Node * ) malloc ( sizeof ( Node ) ) ; newNode -> data = data ; newNode -> left = newNode -> right = NULL ; return newNode ; } int countSubtreesWithSumXUtil ( Node * root , int x ) { static int count = 0 ; static Node * ptr = root ; int l = 0 , r = 0 ; if ( root == NULL ) return 0 ; l += countSubtreesWithSumXUtil ( root -> left , x ) ; r += countSubtreesWithSumXUtil ( root -> right , x ) ; if ( l + r + root -> data == x ) count ++ ; if ( ptr != root ) return l + root -> data + r ; return count ; } int main ( ) { Node * root = getNode ( 5 ) ; root -> left = getNode ( -10 ) ; root -> right = getNode ( 3 ) ; root -> left -> left = getNode ( 9 ) ; root -> left -> right = getNode ( 8 ) ; root -> right -> left = getNode ( -4 ) ; root -> right -> right = getNode ( 7 ) ; int x = 7 ; cout << " Count ▁ = ▁ " << countSubtreesWithSumXUtil ( root , x ) ; return 0 ; }
How to validate Indian Passport number using Regular Expression | C ++ program to validate the passport number using Regular Expression ; Function to validate the passport number ; Regex to check valid passport number ; If the passport number is empty return false ; Return true if the passport number matched the ReGex ; Driver Code ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 : ; Test Case 5 :
#include <iostream> NEW_LINE #include <regex> NEW_LINE using namespace std ; bool isValidPassportNo ( string str ) { const regex pattern ( " ^ [ A - PR - WYa - pr - wy ] [1-9 ] " " \\ d \\ s ? \\ d { 4 } [ 1-9 ] $ " ) ; if ( str . empty ( ) ) { return false ; } if ( regex_match ( str , pattern ) ) { return true ; } else { return false ; } } int main ( ) { string str1 = " A21 ▁ 90457" ; cout << isValidPassportNo ( str1 ) << endl ; string str2 = " A0296457" ; cout << isValidPassportNo ( str2 ) << endl ; string str3 = " Q2096453" ; cout << isValidPassportNo ( str3 ) << endl ; string str4 = "12096457" ; cout << isValidPassportNo ( str4 ) << endl ; string str5 = " A209645704" ; cout << isValidPassportNo ( str5 ) << endl ; return 0 ; }
How to validate Visa Card number using Regular Expression | C ++ program to validate Visa Card number using Regular Expression ; Function to validate Visa Card number ; Regex to check valid Visa Card number ; If the Visa Card number is empty return false ; Return true if the Visa Card number matched the ReGex ; Driver Code ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 : ; Test Case 5 :
#include <iostream> NEW_LINE #include <regex> NEW_LINE using namespace std ; bool isValidVisaCardNo ( string str ) { const regex pattern ( " ^ 4[0-9 ] { 12 } ( ? : [0-9 ] { 3 } ) ? $ " ) ; if ( str . empty ( ) ) { return false ; } if ( regex_match ( str , pattern ) ) { return true ; } else { return false ; } } int main ( ) { string str1 = "4155279860457" ; cout << isValidVisaCardNo ( str1 ) << endl ; string str2 = "4155279860457201" ; cout << isValidVisaCardNo ( str2 ) << endl ; string str3 = "4155279" ; cout << isValidVisaCardNo ( str3 ) << endl ; string str4 = "6155279860457" ; cout << isValidVisaCardNo ( str4 ) << endl ; string str5 = "415a27 # # 60457" ; cout << isValidVisaCardNo ( str5 ) << endl ; return 0 ; }
How to validate MasterCard number using Regular Expression | C ++ program to validate Master Card number using Regular Expression ; Function to validate Master Card number ; Regex to check valid Master Card number ; If the Master Card number is empty return false ; Return true if the Master Card number matched the ReGex ; Driver Code ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 : ; Test Case 5 :
#include <iostream> NEW_LINE #include <regex> NEW_LINE using namespace std ; bool isValidMasterCardNo ( string str ) { const regex pattern ( " ^ 5[1-5 ] [ 0-9 ] { 14 } | ^ ( 222[1-9 ] ▁ 22[3-9 ] \\ d ▁ 2[3-6 ] \\ d { 2 } ▁ 27[0-1 ] \\ d ▁ 2720 ) [ 0-9 ] { 12 } $ " ) ; if ( str . empty ( ) ) { return false ; } if ( regex_match ( str , pattern ) ) { return true ; } else { return false ; } } int main ( ) { string str1 = "5114496353984312" ; cout << isValidMasterCardNo ( str1 ) << endl ; string str2 = "2720822463109651" ; cout << isValidMasterCardNo ( str2 ) << endl ; string str3 = "5582822410" ; cout << isValidMasterCardNo ( str3 ) << endl ; string str4 = "6082822463100051" ; cout << isValidMasterCardNo ( str4 ) << endl ; string str5 = "2221149a635 # # 843" ; cout << isValidMasterCardNo ( str5 ) << endl ; return 0 ; }
How to validate CVV number using Regular Expression | C ++ program to validate the CVV ( Card Verification Value ) number using Regular Expression ; Function to validate the CVV ( Card Verification Value ) number ; Regex to check valid CVV ( Card Verification Value ) number ; If the CVV ( Card Verification Value ) number is empty return false ; Return true if the CVV ( Card Verification Value ) number matched the ReGex ; Driver Code ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 :
#include <iostream> NEW_LINE #include <regex> NEW_LINE using namespace std ; bool isValidCVVNumber ( string str ) { const regex pattern ( " ^ [ 0-9 ] { 3,4 } $ " ) ; if ( str . empty ( ) ) { return false ; } if ( regex_match ( str , pattern ) ) { return true ; } else { return false ; } } int main ( ) { string str1 = "561" ; cout << isValidCVVNumber ( str1 ) << endl ; string str2 = "5061" ; cout << isValidCVVNumber ( str2 ) << endl ; string str3 = "50614" ; cout << isValidCVVNumber ( str3 ) << endl ; string str4 = "5a # 1" ; cout << isValidCVVNumber ( str4 ) << endl ; return 0 ; }
How to validate IFSC Code using Regular Expression | C ++ program to validate the IFSC ( Indian Financial System ) Code using Regular Expression ; Function to validate the IFSC ( Indian Financial System ) Code . ; Regex to check valid IFSC ( Indian Financial System ) Code . ; If the IFSC ( Indian Financial System ) Code is empty return false ; Return true if the IFSC ( Indian Financial System ) Code matched the ReGex ; Driver Code ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 :
#include <iostream> NEW_LINE #include <regex> NEW_LINE using namespace std ; bool isValidIFSCode ( string str ) { const regex pattern ( " ^ [ A - Z ] { 4 } 0 [ A - Z0-9 ] { 6 } $ " ) ; if ( str . empty ( ) ) { return false ; } if ( regex_match ( str , pattern ) ) { return true ; } else { return false ; } } int main ( ) { string str1 = " SBIN0125620" ; cout << boolalpha << isValidIFSCode ( str1 ) << endl ; string str2 = " SBIN0125" ; cout << boolalpha << isValidIFSCode ( str2 ) << endl ; string str3 = "1234SBIN012" ; cout << boolalpha << isValidIFSCode ( str3 ) << endl ; string str4 = " SBIN7125620" ; cout << boolalpha << isValidIFSCode ( str4 ) << endl ; return 0 ; }
How to validate GST ( Goods and Services Tax ) number using Regular Expression | C ++ program to validate the GST ( Goods and Services Tax ) number using Regular Expression ; Function to validate the GST ( Goods and Services Tax ) number ; Regex to check valid GST ( Goods and Services Tax ) number ; If the GST ( Goods and Services Tax ) number is empty return false ; Return true if the GST number matched the ReGex ; Driver Code ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 : ; Test Case 5 :
#include <iostream> NEW_LINE #include <regex> NEW_LINE using namespace std ; bool isValidGSTNo ( string str ) { const regex pattern ( " ^ [ 0-9 ] { 2 } [ A - Z ] { 5 } " " [ 0-9 ] { 4 } [ A - Z ] { 1 } [ " "1-9A - Z ] { 1 } Z [ 0-9A - Z ] { 1 } $ " ) ; if ( str . empty ( ) ) { return false ; } if ( regex_match ( str , pattern ) ) { return true ; } else { return false ; } } int main ( ) { string str1 = "06BZAHM6385P6Z2" ; cout << isValidGSTNo ( str1 ) << endl ; string str2 = "06BZAF67" ; cout << isValidGSTNo ( str2 ) << endl ; string str3 = " AZBZAHM6385P6Z2" ; cout << isValidGSTNo ( str3 ) << endl ; string str4 = "06BZ63AHM85P6Z2" ; cout << isValidGSTNo ( str4 ) << endl ; string str5 = "06BZAHM6385P6F2" ; cout << isValidGSTNo ( str5 ) << endl ; return 0 ; }
How to validate HTML tag using Regular Expression | C ++ program to validate the HTML tag using Regular Expression ; Function to validate the HTML tag . ; Regex to check valid HTML tag . ; If the HTML tag is empty return false ; Return true if the HTML tag matched the ReGex ; Driver Code ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 : ; Test Case 5 :
#include <iostream> NEW_LINE #include <regex> NEW_LINE using namespace std ; bool isValidHTMLTag ( string str ) { const regex pattern ( " < ( \" [ ^ \" ] * \" ▁ ' [ ^ ' ] * ' ▁ [ ^ ' \" > ] ) * > " ) ; if ( str . empty ( ) ) { return false ; } if ( regex_match ( str , pattern ) ) { return true ; } else { return false ; } } int main ( ) { string str1 = " < input ▁ value ▁ = ▁ ' > ' > " ; cout << isValidHTMLTag ( str1 ) << endl ; string str2 = " < br / > " ; cout << isValidHTMLTag ( str2 ) << endl ; string str3 = " br / > " ; cout << isValidHTMLTag ( str3 ) << endl ; string str4 = " < ' br / > " ; cout << isValidHTMLTag ( str4 ) << endl ; string str5 = " < input ▁ value ▁ = > ▁ > " ; cout << isValidHTMLTag ( str5 ) << endl ; return 0 ; }
How to validate a domain name using Regular Expression | C ++ program to validate the domain name using Regular Expression ; Function to validate the domain name . ; Regex to check valid domain name . ; If the domain name is empty return false ; Return true if the domain name matched the ReGex ; Driver Code ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 : ; Test Case 5 :
#include <iostream> NEW_LINE #include <regex> NEW_LINE using namespace std ; bool isValidDomain ( string str ) { const regex pattern ( " ^ ( ? ! - ) [ A - Za - z0-9 - ] + ( [ \\ - \\ . ] { 1 } [ a - z0-9 ] + ) * \\ . [ A - Za - z ] { 2,6 } $ " ) ; if ( str . empty ( ) ) { return false ; } if ( regex_match ( str , pattern ) ) { return true ; } else { return false ; } } int main ( ) { string str1 = " geeksforgeeks . org " ; cout << isValidDomain ( str1 ) << endl ; string str2 = " contribute . geeksforgeeks . org " ; cout << isValidDomain ( str2 ) << endl ; string str3 = " - geeksforgeeks . org " ; cout << isValidDomain ( str3 ) << endl ; string str4 = " geeksforgeeks . o " ; cout << isValidDomain ( str4 ) << endl ; string str5 = " . org " ; cout << isValidDomain ( str5 ) << endl ; return 0 ; }
How to validate SSN ( Social Security Number ) using Regular Expression | C ++ program to validate the SSN ( Social Security Number ) using Regular Expression ; Function to validate the SSN ( Social Security Number ) ; Regex to check valid SSN ( Social Security Number ) ; If the SSN ( Social Security Number ) is empty return false ; Return true if the SSN ( Social Security Number ) matched the ReGex ; Driver Code ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 :
#include <iostream> NEW_LINE #include <regex> NEW_LINE using namespace std ; bool isValidSSN ( string str ) { const regex pattern ( " ^ ( ? ! 666 ▁ 000 ▁ 9 \\ d { 2 } ) " " \\ d { 3 } - ( ? !00 ) " " \\ d { 2 } - ( ? !0 { 4 } ) \\ d { 4 } $ " ) ; if ( str . empty ( ) ) { return false ; } if ( regex_match ( str , pattern ) ) { return true ; } else { return false ; } } int main ( ) { string str1 = "856-45-6789" ; cout << isValidSSN ( str1 ) << endl ; string str2 = "000-45-6789" ; cout << isValidSSN ( str2 ) << endl ; string str3 = "856-452-6789" ; cout << isValidSSN ( str3 ) << endl ; string str4 = "856-45-0000" ; cout << isValidSSN ( str4 ) << endl ; return 0 ; }
How to validate image file extension using Regular Expression | C ++ program to validate the image file extension using Regular Expression ; Function to validate the image file extension . ; Regex to check valid image file extension . ; If the image file extension is empty return false ; Return true if the image file extension matched the ReGex ; Driver Code ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 : ; Test Case 5 :
#include <iostream> NEW_LINE #include <regex> NEW_LINE using namespace std ; bool imageFile ( string str ) { const regex pattern ( " [ ^ \\ s ] + ( . * ? ) \\ . ( jpg ▁ jpeg ▁ png ▁ gif ▁ JPG ▁ JPEG ▁ PNG ▁ GIF ) $ " ) ; if ( str . empty ( ) ) { return false ; } if ( regex_match ( str , pattern ) ) { return true ; } else { return false ; } } int main ( ) { string str1 = " abc . png " ; cout << imageFile ( str1 ) << endl ; string str2 = " im . jpg " ; cout << imageFile ( str2 ) << endl ; string str3 = " . gif " ; cout << imageFile ( str3 ) << endl ; string str4 = " abc . mp3" ; cout << imageFile ( str4 ) << endl ; string str5 = " ▁ . jpg " ; cout << imageFile ( str5 ) << endl ; return 0 ; }
How to check Aadhar number is valid or not using Regular Expression | C ++ program to validate the Aadhar number using Regular Expression ; Function to validate the Aadhar number . ; Regex to check valid Aadhar number . ; If the Aadhar number is empty return false ; Return true if the Aadhar number matched the ReGex ; Driver Code ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 : ; Test Case 5 :
#include <iostream> NEW_LINE #include <regex> NEW_LINE using namespace std ; bool isValidAadharNumber ( string str ) { const regex pattern ( " ^ [ 2-9 ] { 1 } [ 0-9 ] { 3 } \\ s [ 0-9 ] { 4 } \\ s [ 0-9 ] { 4 } $ " ) ; if ( str . empty ( ) ) { return false ; } if ( regex_match ( str , pattern ) ) { return true ; } else { return false ; } } int main ( ) { string str1 = "3675 ▁ 9834 ▁ 6015" ; cout << isValidAadharNumber ( str1 ) << endl ; string str2 = "4675 ▁ 9834 ▁ 6012 ▁ 8" ; cout << isValidAadharNumber ( str2 ) << endl ; string str3 = "0175 ▁ 9834 ▁ 6012" ; cout << isValidAadharNumber ( str3 ) << endl ; string str4 = "3675 ▁ 98AF ▁ 60#2" ; cout << isValidAadharNumber ( str4 ) << endl ; string str5 = "417598346012" ; cout << isValidAadharNumber ( str5 ) << endl ; return 0 ; }
How to validate pin code of India using Regular Expression | C ++ program to validate the pin code of India using Regular Expression . ; Function to validate the pin code of India . ; Regex to check valid pin code of India . ; If the pin code is empty return false ; Return true if the pin code matched the ReGex ; Driver Code . ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 :
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isValidPinCode ( string pinCode ) { const regex pattern ( " ^ [ 1-9 ] { 1 } [ 0-9 ] { 2 } \\ s { 0,1 } [ 0-9 ] { 3 } $ " ) ; if ( pinCode . empty ( ) ) { return false ; } if ( regex_match ( pinCode , pattern ) ) { return true ; } else { return false ; } } void print ( bool n ) { if ( n == 0 ) { cout << " False " << endl ; } else { cout << " True " << endl ; } } int main ( ) { string num1 = "132103" ; cout << num1 + " : ▁ " ; print ( isValidPinCode ( num1 ) ) ; string num2 = "201 ▁ 305" ; cout << num2 + " : ▁ " ; print ( isValidPinCode ( num2 ) ) ; string num3 = "014205" ; cout << num3 + " : ▁ " ; print ( isValidPinCode ( num3 ) ) ; string num4 = "1473598" ; cout << num4 + " : ▁ " ; print ( isValidPinCode ( num4 ) ) ; return 0 ; }
How to validate time in 24 | C ++ program to validate time in 24 - hour format using Regular Expression ; Function to validate time in 24 - hour format ; Regex to check valid time in 24 - hour format ; If the time in 24 - hour format is empty return false ; Return true if the time in 24 - hour format matched the ReGex ; Driver Code ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 : ; Test Case 5 :
#include <iostream> NEW_LINE #include <regex> NEW_LINE using namespace std ; bool isValidTime ( string str ) { const regex pattern ( " ( [01 ] ? [0-9 ] ▁ 2[0-3 ] ) : [ 0-5 ] [ 0-9 ] " ) ; if ( str . empty ( ) ) { return false ; } if ( regex_match ( str , pattern ) ) { return true ; } else { return false ; } } int main ( ) { string str1 = "13:05" ; cout << str1 + " : ▁ " << isValidTime ( str1 ) << endl ; string str2 = "02:15" ; cout << str2 + " : ▁ " << isValidTime ( str2 ) << endl ; string str3 = "24:00" ; cout << str3 + " : ▁ " << isValidTime ( str3 ) << endl ; string str4 = "10:60" ; cout << str4 + " : ▁ " << isValidTime ( str4 ) << endl ; string str5 = "10:15 ▁ PM " ; cout << str5 + " : ▁ " << isValidTime ( str5 ) << endl ; return 0 ; }
How to validate Hexadecimal Color Code using Regular Expression | C ++ program to validate the hexadecimal color code using Regular Expression ; Function to validate the hexadecimal color code . ; Regex to check valid hexadecimal color code . ; If the hexadecimal color code is empty return false ; Return true if the hexadecimal color code matched the ReGex ; Driver Code ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 : ; Test Case 5 :
#include <iostream> NEW_LINE #include <regex> NEW_LINE using namespace std ; bool isValidHexaCode ( string str ) { const regex pattern ( " ^ # ( [ A - Fa - f0-9 ] { 6 } ▁ [ A - Fa - f0-9 ] { 3 } ) $ " ) ; if ( str . empty ( ) ) { return false ; } if ( regex_match ( str , pattern ) ) { return true ; } else { return false ; } } int main ( ) { string str1 = " # 1AFFa1" ; cout << str1 + " : ▁ " << isValidHexaCode ( str1 ) << endl ; string str2 = " # F00" ; cout << str2 + " : ▁ " << isValidHexaCode ( str2 ) << endl ; string str3 = "123456" ; cout << str3 + " : ▁ " << isValidHexaCode ( str3 ) << endl ; string str4 = " # 123abce " ; cout << str4 + " : ▁ " << isValidHexaCode ( str4 ) << endl ; string str5 = " # afafah " ; cout << str5 + " : ▁ " << isValidHexaCode ( str5 ) << endl ; return 0 ; }
How to validate PAN Card number using Regular Expression | C ++ program to validate the PAN Card number using Regular Expression ; Function to validate the PAN Card number . ; Regex to check valid PAN Card number . ; If the PAN Card number is empty return false ; Return true if the PAN Card number matched the ReGex ; Driver Code ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 : ; Test Case 5 :
#include <iostream> NEW_LINE #include <regex> NEW_LINE using namespace std ; bool isValidPanCardNo ( string panCardNo ) { const regex pattern ( " [ A - Z ] { 5 } [ 0-9 ] { 4 } [ A - Z ] { 1 } " ) ; if ( panCardNo . empty ( ) ) { return false ; } if ( regex_match ( panCardNo , pattern ) ) { return true ; } else { return false ; } } int main ( ) { string str1 = " BNZAA2318J " ; cout << isValidPanCardNo ( str1 ) << endl ; string str2 = "23ZAABN18J " ; cout << isValidPanCardNo ( str2 ) << endl ; string str3 = " BNZAA2318JM " ; cout << isValidPanCardNo ( str3 ) << endl ; string str4 = " BNZAA23184" ; cout << isValidPanCardNo ( str4 ) << endl ; string str5 = " BNZAA ▁ 23184" ; cout << isValidPanCardNo ( str5 ) << endl ; return 0 ; }
How to validate time in 12 | C ++ program to validate time in 12 - hour format using Regular Expression ; Function to validate time in 12 - hour format ; Regex to check valid time in 12 - hour format ; If the time in 12 - hour format is empty return false ; Return true if the time in 12 - hour format matched the ReGex ; Driver Code ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 :
#include <iostream> NEW_LINE #include <regex> NEW_LINE using namespace std ; bool isValidTime ( string str ) { const regex pattern ( " ( ( ( [1-9 ] ) | ( 1[0-2 ] ) ) : ( [ 0-5 ] ) ( [ 0-9 ] ) ( \\ s ) ( A ▁ P ) M ) " ) ; if ( str . empty ( ) ) { return false ; } if ( regex_match ( str , pattern ) ) { return true ; } else { return false ; } } int main ( ) { string str1 = "12:15 ▁ AM " ; cout << isValidTime ( str1 ) << endl ; string str2 = "9:45 ▁ PM " ; cout << isValidTime ( str2 ) << endl ; string str3 = "1:15" ; cout << isValidTime ( str3 ) << endl ; string str4 = "17:30" ; cout << isValidTime ( str4 ) << endl ; return 0 ; }
Minimum flips in a Binary array such that XOR of consecutive subarrays of size K have different parity | C ++ implementation to find the minimum flips required such that alternate subarrays have different parity ; Function to find the minimum flips required in binary array ; Boolean value to indicate odd or even value of 1 's ; Loop to iterate over the subarrays of size K ; curr_index is used to iterate over all the subarrays ; Loop to iterate over the array at the jump of K to consider every parity ; Condition to check if the subarray is at even position ; The value needs to be same as the first subarray ; The value needs to be opposite of the first subarray ; Update the minimum difference ; Condition to check if the 1 s in the subarray is odd ; Driver Code
#include <iostream> NEW_LINE #include <limits.h> NEW_LINE using namespace std ; int count_flips ( int a [ ] , int n , int k ) { bool set = false ; int ans = 0 , min_diff = INT_MAX ; for ( int i = 0 ; i < k ; i ++ ) { int curr_index = i , segment = 0 , count_zero = 0 , count_one = 0 ; while ( curr_index < n ) { if ( segment % 2 == 0 ) { if ( a [ curr_index ] == 1 ) count_zero ++ ; else count_one ++ ; } else { if ( a [ curr_index ] == 0 ) count_zero ++ ; else count_one ++ ; } curr_index = curr_index + k ; segment ++ ; } ans += min ( count_one , count_zero ) ; if ( count_one < count_zero ) set = ! set ; min_diff = min ( min_diff , abs ( count_zero - count_one ) ) ; } if ( set ) return ans ; else return ans + min_diff ; } int main ( ) { int n = 6 , k = 3 ; int a [ ] = { 0 , 0 , 1 , 1 , 0 , 0 } ; cout << count_flips ( a , n , k ) ; }
Check whether nodes of Binary Tree form Arithmetic , Geometric or Harmonic Progression | C ++ implementation to check that nodes of binary tree form AP / GP / HP ; Structure of the node of the binary tree ; Function to find the size of the Binary Tree ; Base Case ; Function to check if the permutation of the sequence form Arithmetic Progression ; If the sequence contains only one element ; Sorting the array ; Loop to check if the sequence have same common difference between its consecutive elements ; Function to check if the permutation of the sequence form Geometric progression ; Condition when the length of the sequence is 1 ; Sorting the array ; Loop to check if the the sequence have same common ratio in consecutive elements ; Function to check if the permutation of the sequence form Harmonic Progression ; Condition when length of sequence in 1 ; Loop to find the reciprocal of the sequence ; Sorting the array ; Loop to check if the common difference of the sequence is same ; Function to check if the nodes of the Binary tree forms AP / GP / HP ; Base Case ; Create an empty queue for level order traversal ; Enqueue Root and initialize height ; Loop to traverse the tree using Level order Traversal ; Enqueue left child ; Enqueue right child ; Condition to check if the sequence form Arithmetic Progression ; Condition to check if the sequence form Geometric Progression ; Condition to check if the sequence form Geometric Progression ; Function to create new node ; Driver Code ; Constructed Binary tree is : 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; int size ( Node * node ) { if ( node == NULL ) return 0 ; else return ( size ( node -> left ) + 1 + size ( node -> right ) ) ; } bool checkIsAP ( double arr [ ] , int n ) { if ( n == 1 ) return true ; sort ( arr , arr + n ) ; double d = arr [ 1 ] - arr [ 0 ] ; for ( int i = 2 ; i < n ; i ++ ) if ( arr [ i ] - arr [ i - 1 ] != d ) return false ; return true ; } bool checkIsGP ( double arr [ ] , int n ) { if ( n == 1 ) return true ; sort ( arr , arr + n ) ; double r = arr [ 1 ] / arr [ 0 ] ; for ( int i = 2 ; i < n ; i ++ ) { if ( arr [ i ] / arr [ i - 1 ] != r ) return false ; } return true ; } bool checkIsHP ( double arr [ ] , int n ) { if ( n == 1 ) { return true ; } double rec [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { rec [ i ] = ( ( 1 / arr [ i ] ) ) ; } sort ( rec , rec + n ) ; double d = ( rec [ 1 ] ) - ( rec [ 0 ] ) ; for ( int i = 2 ; i < n ; i ++ ) { if ( rec [ i ] - rec [ i - 1 ] != d ) { return false ; } } return true ; } void checktype ( Node * root ) { int n = size ( root ) ; double arr [ n ] ; int i = 0 ; if ( root == NULL ) return ; queue < Node * > q ; q . push ( root ) ; while ( q . empty ( ) == false ) { Node * node = q . front ( ) ; arr [ i ] = node -> data ; i ++ ; q . pop ( ) ; if ( node -> left != NULL ) q . push ( node -> left ) ; if ( node -> right != NULL ) q . push ( node -> right ) ; } int flag = 0 ; if ( checkIsAP ( arr , n ) ) { cout << " Arithmetic ▁ Progression " << endl ; flag = 1 ; } else if ( checkIsGP ( arr , n ) ) { cout << " Geometric ▁ Progression " << endl ; flag = 1 ; } else if ( checkIsHP ( arr , n ) ) { cout << " Geometric ▁ Progression " << endl ; flag = 1 ; } else if ( flag == 0 ) { cout << " No " ; } } struct Node * newNode ( int data ) { struct Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } 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 -> right = newNode ( 8 ) ; root -> right -> right -> left = newNode ( 6 ) ; root -> right -> right -> right = newNode ( 7 ) ; checktype ( root ) ; return 0 ; }
Program to build a DFA that checks if a string ends with "01" or "10" | CPP Program to DFA that accepts string ending with 01 or 10. ; Various states of DFA machine are defined using functions . ; End position is checked using the string length value . q0 is the starting state . q1 and q2 are intermediate states . q3 and q4 are final states . ; state transitions 0 takes to q1 , 1 takes to q3 ; state transitions 0 takes to q4 , 1 takes to q2 ; state transitions 0 takes to q4 , 1 takes to q2 ; state transitions 0 takes to q1 , 1 takes to q3 ; state transitions 0 takes to q1 , 1 takes to q2 ; Driver Code ; all state transitions are printed . if string is accpetable , YES is printed . else NO is printed
#include <bits/stdc++.h> NEW_LINE using namespace std ; void q1 ( string , int ) ; void q2 ( string , int ) ; void q3 ( string , int ) ; void q4 ( string , int ) ; void q1 ( string s , int i ) { cout << " q1 - > " ; if ( i == s . length ( ) ) { cout << " NO ▁ STRNEWLINE " ; return ; } if ( s [ i ] == '0' ) q1 ( s , i + 1 ) ; else q3 ( s , i + 1 ) ; } void q2 ( string s , int i ) { cout << " q2 - > " ; if ( i == s . length ( ) ) { cout << " NO ▁ STRNEWLINE " ; return ; } if ( s [ i ] == '0' ) q4 ( s , i + 1 ) ; else q2 ( s , i + 1 ) ; } void q3 ( string s , int i ) { cout << " q3 - > " ; if ( i == s . length ( ) ) { cout << " YES ▁ STRNEWLINE " ; return ; } if ( s [ i ] == '0' ) q4 ( s , i + 1 ) ; else q2 ( s , i + 1 ) ; } void q4 ( string s , int i ) { cout << " q4 - > " ; if ( i == s . length ( ) ) { cout << " YES ▁ STRNEWLINE " ; return ; } if ( s [ i ] == '0' ) q1 ( s , i + 1 ) ; else q3 ( s , i + 1 ) ; } void q0 ( string s , int i ) { cout << " q0 - > " ; if ( i == s . length ( ) ) { cout << " NO ▁ STRNEWLINE " ; return ; } if ( s [ i ] == '0' ) q1 ( s , i + 1 ) ; else q2 ( s , i + 1 ) ; } int main ( ) { string s = "010101" ; cout << " State ▁ transitions ▁ are ▁ " ; q0 ( s , 0 ) ; }
Check whether two strings contain same characters in same order | ; if length of the b = 0 then we return true ; if length of a = 0 that means b is not present in a so we return false ; Driver code
#include <iostream> NEW_LINE using namespace std ; bool checkSequence ( string a , string b ) { if ( b . size ( ) == 0 ) return true ; if ( a . size ( ) == 0 ) return false ; if ( a [ 0 ] == b [ 0 ] ) return checkSequence ( a . substr ( 1 ) , b . substr ( 1 ) ) ; else return checkSequence ( a . substr ( 1 ) , b ) ; } int main ( ) { string s1 = " Geeks " , s2 = " Geks " ; if ( checkSequence ( s1 , s2 ) ) cout << " Yes " ; else cout << " No " ; }
String matching with * ( that matches with any ) in any of the two strings | CPP program for string matching with * ; Function to check if the two strings can be matched or not ; if the string don 't have * then character at that position must be same. ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool doMatch ( string A , string B ) { for ( int i = 0 ; i < A . length ( ) ; i ++ ) if ( A [ i ] != ' * ' && B [ i ] != ' * ' ) if ( A [ i ] != B [ i ] ) return false ; return true ; } int main ( ) { string A = " gee * sforgeeks " ; string B = " geeksforgeeks " ; cout << doMatch ( A , B ) ; return 0 ; }
Find Nth term of the series 0 , 2 , 4 , 8 , 12 , 18. . . | CPP program to find N - th term of the series : 0 , 2 , 4 , 8 , 12 , 18. . . ; Calculate Nth term of series ; Driver Function
#include <iostream> NEW_LINE using namespace std ; int nthTerm ( int N ) { return ( N + N * ( N - 1 ) ) / 2 ; } int main ( ) { int N = 5 ; cout << nthTerm ( N ) ; return 0 ; }
Number of substrings of one string present in other | CPP program to count number of substrings of s1 present in s2 . ; s3 stores all substrings of s1 ; check the presence of s3 in s2 ; Driver code
#include <iostream> NEW_LINE #include <string> NEW_LINE using namespace std ; int countSubstrs ( string s1 , string s2 ) { int ans = 0 ; for ( int i = 0 ; i < s1 . length ( ) ; i ++ ) { string s3 ; for ( int j = i ; j < s1 . length ( ) ; j ++ ) { s3 += s1 [ j ] ; if ( s2 . find ( s3 ) != string :: npos ) ans ++ ; } } return ans ; } int main ( ) { string s1 = " aab " , s2 = " aaaab " ; cout << countSubstrs ( s1 , s2 ) ; return 0 ; }
Find Nth term of series 1 , 4 , 15 , 72 , 420. . . | CPP program to find N - th term of the series : 1 , 4 , 15 , 72 , 420 a ; Function to find factorial of N ; return factorial of N ; calculate Nth term of series ; Driver Function
#include <iostream> NEW_LINE using namespace std ; int factorial ( int N ) { int fact = 1 ; for ( int i = 1 ; i <= N ; i ++ ) fact = fact * i ; return fact ; } int nthTerm ( int N ) { return ( factorial ( N ) * ( N + 2 ) / 2 ) ; } int main ( ) { int N = 6 ; cout << nthTerm ( N ) ; return 0 ; }
Sum of nodes at maximum depth of a Binary Tree | Code to find the sum of the nodes which are present at the maximum depth . ; Function to return a new node ; Function to find the sum of the node which are present at the maximum depth . While traversing the nodes compare the level of the node with max_level ( Maximum level till the current node ) . If the current level exceeds the maximum level , update the max_level as current level . If the max level and current level are same , add the root data to current sum . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sum = 0 , max_level = INT_MIN ; struct Node { int d ; Node * l ; Node * r ; } ; Node * createNode ( int d ) { Node * node ; node = new Node ; node -> d = d ; node -> l = NULL ; node -> r = NULL ; return node ; } void sumOfNodesAtMaxDepth ( Node * ro , int level ) { if ( ro == NULL ) return ; if ( level > max_level ) { sum = ro -> d ; max_level = level ; } else if ( level == max_level ) { sum = sum + ro -> d ; } sumOfNodesAtMaxDepth ( ro -> l , level + 1 ) ; sumOfNodesAtMaxDepth ( ro -> r , level + 1 ) ; } int main ( ) { Node * root ; root = createNode ( 1 ) ; root -> l = createNode ( 2 ) ; root -> r = createNode ( 3 ) ; root -> l -> l = createNode ( 4 ) ; root -> l -> r = createNode ( 5 ) ; root -> r -> l = createNode ( 6 ) ; root -> r -> r = createNode ( 7 ) ; sumOfNodesAtMaxDepth ( root , 0 ) ; cout << sum ; return 0 ; }
Match Expression where a single special character in pattern can match one or more characters | C ++ program for pattern matching where a single special character can match one more characters ; Returns true if pat matches with text ; i is used as an index in pattern and j as an index in text ; Traverse through pattern ; If current character of pattern is not ' # ' ; If does not match with text ; If matches , increment i and j ; Current character is ' # ' ; At least one character must match with # ; Match characters with # until a matching character is found . ; Matching with # is over , move ahead in pattern ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int regexMatch ( string text , string pat ) { int lenText = text . length ( ) ; int letPat = pat . length ( ) ; int i = 0 , j = 0 ; while ( i < letPat ) { if ( pat [ i ] != ' # ' ) { if ( pat [ i ] != text [ j ] ) return false ; i ++ ; j ++ ; } else { j ++ ; while ( text [ j ] != pat [ i + 1 ] ) j ++ ; i ++ ; } } return ( j == lenText ) ; } int main ( ) { string str = " ABABABA " ; string pat = " A # B # A " ; if ( regexMatch ( str , pat ) ) cout << " yes " ; else cout << " no " ; return 0 ; }
Replace all occurrences of string AB with C without using extra space | Efficient C ++ program to replace all occurrences of " AB " with " C " ; Index in modified string ; Index in original string ; Traverse string ; Replace occurrence of " AB " with " C " ; Increment j by 2 ; add a null character to terminate string ; Driver code
#include <bits/stdc++.h> NEW_LINE void translate ( char * str ) { int len = strlen ( str ) ; if ( len < 2 ) return ; int i = 0 ; int j = 0 ; while ( j < len - 1 ) { if ( str [ j ] == ' A ' && str [ j + 1 ] == ' B ' ) { j = j + 2 ; str [ i ++ ] = ' C ' ; continue ; } str [ i ++ ] = str [ j ++ ] ; } if ( j == len - 1 ) str [ i ++ ] = str [ j ] ; str [ i ] = ' ' ; } int main ( ) { char str [ ] = " helloABworldABGfG " ; translate ( str ) ; printf ( " The ▁ modified ▁ string ▁ is ▁ : STRNEWLINE " ) ; printf ( " % s " , str ) ; }
Search a Word in a 2D Grid of characters | C ++ programs to search a word in a 2D grid ; For searching in all 8 direction ; This function searches in all 8 - direction from point ( row , col ) in grid [ ] [ ] ; If first character of word doesn 't match with given starting point in grid. ; Search word in all 8 directions starting from ( row , col ) ; Initialize starting point for current direction ; First character is already checked , match remaining characters ; If out of bound break ; If not matched , break ; Moving in particular direction ; If all character matched , then value of k must be equal to length of word ; Searches given word in a given matrix in all 8 directions ; Consider every point as starting point and search given word ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int x [ ] = { -1 , -1 , -1 , 0 , 0 , 1 , 1 , 1 } ; int y [ ] = { -1 , 0 , 1 , -1 , 1 , -1 , 0 , 1 } ; bool search2D ( char * grid , int row , int col , string word , int R , int C ) { if ( * ( grid + row * C + col ) != word [ 0 ] ) return false ; int len = word . length ( ) ; for ( int dir = 0 ; dir < 8 ; dir ++ ) { int k , rd = row + x [ dir ] , cd = col + y [ dir ] ; for ( k = 1 ; k < len ; k ++ ) { if ( rd >= R rd < 0 cd > = C cd < 0 ) break ; if ( * ( grid + rd * C + cd ) != word [ k ] ) break ; rd += x [ dir ] , cd += y [ dir ] ; } if ( k == len ) return true ; } return false ; } void patternSearch ( char * grid , string word , int R , int C ) { for ( int row = 0 ; row < R ; row ++ ) for ( int col = 0 ; col < C ; col ++ ) if ( search2D ( grid , row , col , word , R , C ) ) cout << " pattern ▁ found ▁ at ▁ " << row << " , ▁ " << col << endl ; } int main ( ) { int R = 3 , C = 13 ; char grid [ R ] [ C ] = { " GEEKSFORGEEKS " , " GEEKSQUIZGEEK " , " IDEQAPRACTICE " } ; patternSearch ( ( char * ) grid , " GEEKS " , R , C ) ; cout << endl ; patternSearch ( ( char * ) grid , " EEE " , R , C ) ; return 0 ; }
Boyer Moore Algorithm for Pattern Searching | C ++ Program for Bad Character Heuristic of Boyer Moore String Matching Algorithm ; The preprocessing function for Boyer Moore 's bad character heuristic ; Initialize all occurrences as - 1 ; Fill the actual value of last occurrence of a character ; A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm ; Fill the bad character array by calling the preprocessing function badCharHeuristic ( ) for given pattern ; int s = 0 ; s is shift of the pattern with respect to text ; Keep reducing index j of pattern while characters of pattern and text are matching at this shift s ; If the pattern is present at current shift , then index j will become - 1 after the above loop ; Shift the pattern so that the next character in text aligns with the last occurrence of it in pattern . The condition s + m < n is necessary for the case when pattern occurs at the end of text ; Shift the pattern so that the bad character in text aligns with the last occurrence of it in pattern . The max function is used to make sure that we get a positive shift . We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; # define NO_OF_CHARS 256 NEW_LINE void badCharHeuristic ( string str , int size , int badchar [ NO_OF_CHARS ] ) { int i ; for ( i = 0 ; i < NO_OF_CHARS ; i ++ ) badchar [ i ] = -1 ; for ( i = 0 ; i < size ; i ++ ) badchar [ ( int ) str [ i ] ] = i ; } void search ( string txt , string pat ) { int m = pat . size ( ) ; int n = txt . size ( ) ; int badchar [ NO_OF_CHARS ] ; badCharHeuristic ( pat , m , badchar ) ; while ( s <= ( n - m ) ) { int j = m - 1 ; while ( j >= 0 && pat [ j ] == txt [ s + j ] ) j -- ; if ( j < 0 ) { cout << " pattern ▁ occurs ▁ at ▁ shift ▁ = ▁ " << s << endl ; s += ( s + m < n ) ? m - badchar [ txt [ s + m ] ] : 1 ; } else s += max ( 1 , j - badchar [ txt [ s + j ] ] ) ; } } int main ( ) { string txt = " ABAAABCD " ; string pat = " ABC " ; search ( txt , pat ) ; return 0 ; }
Sum of nodes at maximum depth of a Binary Tree | C ++ code for sum of nodes at maximum depth ; Constructor ; function to find the sum of nodes at maximum depth arguments are node and max , where max is to match the depth of node at every call to node , if max will be equal to 1 , means we are at deepest node . ; base case ; max == 1 to track the node at deepest level ; recursive call to left and right nodes ; maxDepth function to find the max depth of the tree ; base case ; either leftDepth of rightDepth is greater add 1 to include height of node at which call is ; call to function to calculate max depth ; Driver code ; Constructing tree ; call to calculate required sum
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; Node ( int data ) { this -> data = data ; this -> left = NULL ; this -> right = NULL ; } } ; int sumMaxLevelRec ( Node * node , int max ) { if ( node == NULL ) return 0 ; if ( max == 1 ) return node -> data ; return sumMaxLevelRec ( node -> left , max - 1 ) + sumMaxLevelRec ( node -> right , max - 1 ) ; } int maxDepth ( Node * node ) { if ( node == NULL ) return 0 ; return 1 + max ( maxDepth ( node -> left ) , maxDepth ( node -> right ) ) ; } int sumMaxLevel ( Node * root ) { int MaxDepth = maxDepth ( root ) ; return sumMaxLevelRec ( root , MaxDepth ) ; } int main ( ) { Node * root = new Node ( 1 ) ; root -> left = new Node ( 2 ) ; root -> right = new Node ( 3 ) ; root -> left -> left = new Node ( 4 ) ; root -> left -> right = new Node ( 5 ) ; root -> right -> left = new Node ( 6 ) ; root -> right -> right = new Node ( 7 ) ; cout << ( sumMaxLevel ( root ) ) << endl ; }
Sum of Manhattan distances between repetitions in a String | C ++ program for the above approach ; Function to find the sum of the manhattan distances between same characters in string ; Vector to store indices for each unique character of the string ; Append the position of each character in their respective vectors ; Store the required result ; Iterate over all the characters ; Calculate sum of all elements present in the vector ; Traverse the current vector ; Find suffix [ i + 1 ] ; Adding distance of all pairs whose first element is i and second element belongs to [ i + 1 , n ] ; Print the result ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void SumofDistances ( string s ) { vector < int > v [ 26 ] ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { v [ s [ i ] - ' a ' ] . push_back ( i ) ; } int ans = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) { int sum = 0 ; for ( int j = 0 ; j < v [ i ] . size ( ) ; j ++ ) { sum += v [ i ] [ j ] ; } for ( int j = 0 ; j < v [ i ] . size ( ) ; j ++ ) { sum -= v [ i ] [ j ] ; ans += ( sum - ( v [ i ] . size ( ) - 1 - j ) * ( v [ i ] [ j ] ) ) ; } } cout << ans ; } int main ( ) { string s = " ababa " ; SumofDistances ( s ) ; return 0 ; }
Minimum prefixes required to be flipped to convert a Binary String to another | C ++ program for the above approach ; Function to count flips required to make strings A and B equal ; Stores the count of the number of operations ; Stores the length of the chosen prefixes ; Stores if operations are performed even or odd times ; Traverse the given string ; If current characters in the two strings are unequal ; If A [ i ] is not flipped ; Increment count of operations ; Insert the length of the chosen prefix ; Update invert to true ; If A [ i ] is flipped ; Increment count of operations ; Insert length of the chosen prefix ; Update invert to false ; Print the number of operations required ; Print the chosen prefix length in each operation ; Driver Code ; Given binary strings
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findOperations ( string A , string B , int N ) { int operations = 0 ; vector < int > ops ; bool invert = false ; for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( A [ i ] != B [ i ] ) { if ( ! invert ) { operations ++ ; ops . push_back ( i + 1 ) ; invert = true ; } } else { if ( invert ) { operations ++ ; ops . push_back ( i + 1 ) ; invert = false ; } } } cout << operations << endl ; if ( operations != 0 ) { for ( auto x : ops ) cout << x << " ▁ " ; } } int main ( ) { string A = "001" , B = "000" ; int N = A . size ( ) ; findOperations ( A , B , N ) ; return 0 ; }
Modify string by sorting characters after removal of characters whose frequency is not equal to power of 2 | C ++ program for the above approach ; Function to remove all the characters from a string that whose frequencies are not equal to a perfect power of 2 ; Stores the frequency of each character in S ; Iterate over characters of string ; Update frequency of current character in the array freq [ ] ; Traverse the array freq [ ] ; Check if the i - th letter is absent from string S ; Calculate log of frequency of the current character in the string S ; Calculate power of 2 of lg ; Check if freq [ i ] is a power of 2 ; Print letter i + ' a ' freq [ i ] times ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countFrequency ( string S , int N ) { int freq [ 26 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { freq [ S [ i ] - ' a ' ] ++ ; } for ( int i = 0 ; i < 26 ; i ++ ) { if ( freq [ i ] == 0 ) continue ; int lg = log2 ( freq [ i ] ) ; int a = pow ( 2 , lg ) ; if ( a == freq [ i ] ) { while ( freq [ i ] -- ) cout << ( char ) ( i + ' a ' ) ; } } } int main ( ) { string S = " aaacbb " ; int N = S . size ( ) ; countFrequency ( S , N ) ; return 0 ; }
Queries to calculate sum of squares of ASCII values of characters of a substring with updates | C ++ implementation of the above approach ; Structure of a node of a Segment Tree ; Function to construct the Segment Tree ; If start and end are equal ; Assign squares of positions of the characters ; Stores the mid value of the range [ start , end ] ; Recursive call to left subtree ; Recursive call to right subtree ; Update the current node ; Function to perform the queries of type 2 ; No overlap ; If l <= start and r >= end ; Return the value of treeNode ; Calculate middle of the range [ start , end ] ; Function call to left subtree ; Function call to right subtree ; Return the sum of X and Y ; Function to perform update queries on a Segment Tree ; If start is equal to end and idx is equal to start ; Base Case ; Calculate middle of the range [ start , end ] ; If idx <= mid ; Function call to left subtree ; Otherwise ; Function call to the right subtree ; Update the current node ; Function to perform the given queries ; Stores the segment tree ; Traverse the segment tree ; Assign 0 to each node ; Builds segment tree ; Traverse the query array Q [ ] [ ] ; If query is of type S ; Stores the left boundary ; Stores the right boundary ; Prints the sum of squares of the alphabetic positions of the characters ; Otherwise ; Stores the index of the character to be updated ; Update the segment tree ; Driver Code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct treeNode { int square_sum ; } ; void buildTree ( string s , treeNode * tree , int start , int end , int treeNode ) { if ( start == end ) { tree [ treeNode ] . square_sum = pow ( s [ start ] - ' a ' + 1 , 2 ) ; return ; } int mid = start + ( ( end - start ) / 2 ) ; buildTree ( s , tree , start , mid , 2 * treeNode ) ; buildTree ( s , tree , mid + 1 , end , 1 + 2 * treeNode ) ; tree [ treeNode ] . square_sum = tree [ ( 2 * treeNode ) ] . square_sum + tree [ ( 2 * treeNode ) + 1 ] . square_sum ; } int querySquareSum ( treeNode * tree , int start , int end , int treeNode , int l , int r ) { if ( ( l > end ) || ( r < start ) ) { return 0 ; } if ( ( l <= start ) && ( r >= end ) ) { return tree [ treeNode ] . square_sum ; } int mid = start + ( ( end - start ) / 2 ) ; int X = querySquareSum ( tree , start , mid , 2 * treeNode , l , r ) ; int Y = + querySquareSum ( tree , mid + 1 , end , 1 + 2 * treeNode , l , r ) ; return X + Y ; } void updateTree ( string s , treeNode * tree , int start , int end , int treeNode , int idx , char X ) { if ( ( start == end ) && ( idx == start ) ) { s [ idx ] = X ; tree [ treeNode ] . square_sum = pow ( X - ' a ' + 1 , 2 ) ; return ; } int mid = start + ( ( end - start ) / 2 ) ; if ( idx <= mid ) { updateTree ( s , tree , start , mid , ( 2 * treeNode ) , idx , X ) ; } else { updateTree ( s , tree , mid + 1 , end , ( 2 * treeNode ) + 1 , idx , X ) ; } tree [ treeNode ] . square_sum = tree [ ( 2 * treeNode ) ] . square_sum + tree [ ( 2 * treeNode ) + 1 ] . square_sum ; } void PerformQuery ( string S , vector < vector < string > > Q ) { int n = S . size ( ) ; treeNode * tree = new treeNode [ ( 4 * n ) + 1 ] ; for ( int i = 0 ; i <= ( 4 * n ) ; i = i + 1 ) { tree [ i ] . square_sum = 0 ; } buildTree ( S , tree , 0 , n - 1 , 1 ) ; for ( int i = 0 ; i < Q . size ( ) ; i ++ ) { if ( Q [ i ] [ 0 ] == " S " ) { int L = stoi ( Q [ i ] [ 1 ] ) ; int R = stoi ( Q [ i ] [ 2 ] ) ; cout << querySquareSum ( tree , 0 , n - 1 , 1 , L , R ) << endl ; } else if ( Q [ i ] [ 0 ] == " U " ) { int I = stoi ( Q [ i ] [ 1 ] ) ; updateTree ( S , tree , 0 , n - 1 , 1 , I , Q [ i ] [ 2 ] [ 0 ] ) ; } } } int main ( ) { string S = " geeksforgeeks " ; vector < vector < string > > Q = { { " S " , "0" , "2" } , { " S " , "1" , "2" } , { " U " , "1" , " a " } , { " S " , "0" , "2" } , { " S " , "4" , "5" } } ; PerformQuery ( S , Q ) ; }
Longest Common Subsequence ( LCS ) by repeatedly swapping characters of a string with characters of another string | C ++ program for the above approach ; Function to find the length of LCS possible by swapping any character of a string with that of another string ; Store the size of the strings ; Stores frequency of characters ; Iterate over characters of the string A ; Update frequency of character A [ i ] ; Iterate over characters of the string B ; Update frequency of character B [ i ] ; Store the count of all pairs of similar characters ; Traverse the array freq [ ] ; Update cnt ; Print the minimum of cnt , N and M ; Driver Code ; Given strings
#include <bits/stdc++.h> NEW_LINE using namespace std ; void lcsBySwapping ( string A , string B ) { int N = A . size ( ) ; int M = B . size ( ) ; int freq [ 26 ] ; memset ( freq , 0 , sizeof ( freq ) ) ; for ( int i = 0 ; i < A . size ( ) ; i ++ ) { freq [ A [ i ] - ' a ' ] += 1 ; } for ( int i = 0 ; i < B . size ( ) ; i ++ ) { freq [ B [ i ] - ' a ' ] += 1 ; } int cnt = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) { cnt += freq [ i ] / 2 ; } cout << min ( cnt , min ( N , M ) ) ; } int main ( ) { string A = " abdeff " ; string B = " abbet " ; lcsBySwapping ( A , B ) ; return 0 ; }
Length of longest subsequence whose difference between maximum and minimum ASCII value of characters is exactly one | C ++ program for the above approach ; Function to find the maximum length of subsequence having difference of ASCII value of longest and smallest character as 1 ; Stores frequency of characters ; Iterate over characters of the string ; Stores the resultant length of subsequence ; Check if there exists any elements with ASCII value one less than character ch ; Size of current subsequence ; Update the value of ans ; Print the resultant count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumLengthSubsequence ( string str ) { unordered_map < char , int > mp ; for ( char ch : str ) { mp [ ch ] ++ ; } int ans = 0 ; for ( char ch : str ) { if ( mp . count ( ch - 1 ) ) { int curr_max = mp [ ch ] + mp [ ch - 1 ] ; ans = max ( ans , curr_max ) ; } } cout << ans ; } int main ( ) { string S = " acbbebcg " ; maximumLengthSubsequence ( S ) ; return 0 ; }
Minimum increments by 1 or K required to convert a string into another given string | CPP program for the above approach ; Function to count minimum increments by 1 or K required to convert X to Y ; Traverse the string X ; Case 1 ; Case 2 ; Add the difference / K to the count ; Add the difference % K to the count ; Case 3 ; Add the difference / K to the count ; Add the difference % K to the count ; Print the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countOperations ( string X , string Y , int K ) { int count = 0 ; for ( int i = 0 ; i < X . length ( ) ; i ++ ) { int c = 0 ; if ( X [ i ] == Y [ i ] ) continue ; else if ( X [ i ] < Y [ i ] ) { if ( ( Y [ i ] - X [ i ] ) >= K ) { c = ( Y [ i ] - X [ i ] ) / K ; } c += ( Y [ i ] - X [ i ] ) % K ; } else { int t = 90 - X [ i ] ; t += Y [ i ] - 65 + 1 ; if ( t >= K ) c = t / K ; c += ( t % K ) ; } count += c ; } cout << count << endl ; } int main ( ) { string X = " ABCT " , Y = " PBDI " ; int K = 6 ; countOperations ( X , Y , K ) ; }
Minimum number of swaps required such that a given substring consists of exactly K 1 s | CPP program for the above approach ; Function to find the minimum number of swaps required such that the substring { s [ l ] , . . , s [ r ] } consists of exactly k 1 s ; Store the size of the string ; Store the total number of 1 s and 0 s in the entire string ; Traverse the string S to find the frequency of 1 and 0 ; Store the number of 1 s and 0 s in the substring s [ l , r ] ; Traverse the substring S [ l , r ] to find the frequency of 1 s and 0 s in it ; Store the count of 1 s and 0 s outside substring s [ l , r ] ; Check if the sum of the substring is at most K ; Store number of 1 s required ; Check if there are enough 1 s remaining to be swapped ; If the count of 1 s in the substring exceeds k ; Store the number of 0 s required ; Check if there are enough 0 s remaining to be swapped ; In all other cases , print - 1 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumSwaps ( string s , int l , int r , int k ) { int n = s . length ( ) ; int tot_ones = 0 , tot_zeros = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s [ i ] == '1' ) tot_ones ++ ; else tot_zeros ++ ; } int ones = 0 , zeros = 0 , sum = 0 ; for ( int i = l - 1 ; i < r ; i ++ ) { if ( s [ i ] == '1' ) { ones ++ ; sum ++ ; } else zeros ++ ; } int rem_ones = tot_ones - ones ; int rem_zeros = tot_zeros - zeros ; if ( k >= sum ) { int rem = k - sum ; if ( zeros >= rem && rem_ones >= rem ) return rem ; } else if ( k < sum ) { int rem = sum - k ; if ( ones >= rem && rem_zeros >= rem ) return rem ; } return -1 ; } int main ( ) { string S = "110011111000101" ; int L = 5 , R = 8 , K = 2 ; cout << minimumSwaps ( S , L , R , K ) ; }
Check if given number contains only β€œ 01 ” and β€œ 10 ” as substring in its binary representation | C ++ program for the above approach ; Function to generate all numbers having "01" and "10" as a substring ; Insert 2 and 5 ; Iterate till x is 10 ^ 15 ; Multiply x by 2 ; Update x as x * 2 + 1 ; Function to check if binary representation of N contains only "01" and "10" as substring ; Function Call to generate all such numbers ; Check if a number N exists in Ans [ ] or not ; If the number exists ; Driver Code
#include " bits / stdc + + . h " NEW_LINE using namespace std ; vector < int > Ans ; void populateNumber ( ) { Ans . push_back ( 2 ) ; Ans . push_back ( 5 ) ; long long int x = 5 ; while ( x < 1000000000001 ) { x *= 2 ; Ans . push_back ( x ) ; x = x * 2 + 1 ; Ans . push_back ( x ) ; } } string checkString ( long long int N ) { populateNumber ( ) ; for ( auto & it : Ans ) { if ( it == N ) { return " Yes " ; } } return " No " ; } int main ( ) { long long int N = 5 ; cout << checkString ( N ) ; return 0 ; }
Minimize length by removing subsequences forming valid parenthesis from a given string | C ++ program for the above approach ; Function to find the minimum count of remaining characters left into the string by removing the valid subsequences ; Length of the string ; Stores opening parenthesis ' ( ' of the given string ; Stores square parenthesis ' [ ' of the given string ; Stores count of opening parenthesis ' ( ' in valid subsequences ; Stores count of opening parenthesis ' [ ' in valid subsequences ; Iterate over each characters of S ; If current character is ' [ ' ; insert into stack ; If i is equal to ' ] ' ; If stack is not empty and top element of stack is ' [ ' ; Remove top element from stack ; Update squareCount ; If current character is ' ( ' ; Insert into stack ; If i is equal to ' ) ' ; If stack is not empty and top element of stack is ' ( ' ; Remove top element from stack ; Update roundCount ; Print the minimum number of remaining characters left into S ; Driver code ; input string ; function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void deleteSubseq ( string s ) { int N = s . size ( ) ; stack < char > roundStk ; stack < char > squareStk ; int roundCount = 0 ; int squareCount = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( s [ i ] == ' [ ' ) { squareStk . push ( s [ i ] ) ; } else if ( s [ i ] == ' ] ' ) { if ( squareStk . size ( ) != 0 && squareStk . top ( ) == ' [ ' ) { squareStk . pop ( ) ; squareCount += 1 ; } } else if ( s [ i ] == ' ( ' ) { roundStk . push ( s [ i ] ) ; } else { if ( roundStk . size ( ) != 0 && squareStk . top ( ) == ' ( ' ) { squareStk . pop ( ) ; roundCount += 1 ; } } } cout << ( N - ( 2 * squareCount + 2 * roundCount ) ) ; } int main ( ) { string s = " [ ] ] ) ( [ " ; deleteSubseq ( s ) ; }
Count minimum substring removals required to reduce string to a single distinct character | C ++ program for the above approach ; Function to find minimum removals required to convert given string to single distinct characters only ; Unordered map to store positions of characters X , Y and Z ; Update indices of X , Y , Z ; ; Stores the count of minimum removals ; Traverse the Map ; Count the number of removals required for current character ; Update the answer ; Print the answer ; Driver Code ; Given string ; Size of string ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumOperations ( string s , int n ) { unordered_map < char , vector < int > > mp ; for ( int i = 0 ; i < n ; i ++ ) { mp [ s [ i ] ] . push_back ( i ) ; } int ans = INT_MAX ; for ( auto x : mp ) { int curr = 0 ; int prev = 0 ; bool first = true ; for ( int index : ( x . second ) ) { if ( first ) { if ( index > 0 ) { curr ++ ; } prev = index ; first = false ; } else { if ( index != prev + 1 ) { curr ++ ; } prev = index ; } } if ( prev != n - 1 ) { curr ++ ; } ans = min ( ans , curr ) ; } cout << ans ; } int main ( ) { string s = " YYXYZYXYZXY " ; int N = s . length ( ) ; minimumOperations ( s , N ) ; return 0 ; }
Program to construct DFA accepting odd number of 0 s and odd number of 1 s | C ++ program for the above approach ; Function to check whether the given string is accepted by DFA or not ; Stores initial state of DFA ; Stores final state of DFA ; Stores previous state of DFA ; Iterate through the string ; Checking for all combinations ; Update the previous_state ; If final state is reached ; Otherwise ; Driver Code ; Given string ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void checkValidDFA ( string s ) { int initial_state = 0 ; int final_state ; int previous_state = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( ( s [ i ] == '0' && previous_state == 0 ) || ( s [ i ] == '1' && previous_state == 3 ) ) { final_state = 1 ; } else if ( ( s [ i ] == '0' && previous_state == 3 ) || ( s [ i ] == '1' && previous_state == 0 ) ) { final_state = 2 ; } else if ( ( s [ i ] == '0' && previous_state == 1 ) || ( s [ i ] == '1' && previous_state == 2 ) ) { final_state = 0 ; } else if ( ( s [ i ] == '0' && previous_state == 2 ) || ( s [ i ] == '1' && previous_state == 1 ) ) { final_state = 3 ; } previous_state = final_state ; } if ( final_state == 3 ) { cout << " Accepted " << endl ; } else { cout << " Not ▁ Accepted " << endl ; } } int main ( ) { string s = "010011" ; checkValidDFA ( s ) ; return 0 ; }
Difference between sums of odd level and even level nodes of a Binary Tree | CPP program to find difference between sums of odd level and even level nodes of binary tree ; tree node ; returns a new tree Node ; return difference of sums of odd level and even level ; create a queue for level order traversal ; traverse until the queue is empty ; traverse for complete level ; check if level no . is even or odd and accordingly update the evenSum or oddSum ; check for left child ; check for right child ; driver program ; construct a tree
#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 ; } int evenOddLevelDifference ( Node * root ) { if ( ! root ) return 0 ; queue < Node * > q ; q . push ( root ) ; int level = 0 ; int evenSum = 0 , oddSum = 0 ; while ( ! q . empty ( ) ) { int size = q . size ( ) ; level += 1 ; while ( size > 0 ) { Node * temp = q . front ( ) ; q . pop ( ) ; if ( level % 2 == 0 ) evenSum += temp -> data ; else oddSum += temp -> data ; if ( temp -> left ) { q . push ( temp -> left ) ; } if ( temp -> right ) { q . push ( temp -> right ) ; } size -= 1 ; } } return ( oddSum - evenSum ) ; } int main ( ) { Node * root = newNode ( 5 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 6 ) ; root -> left -> left = newNode ( 1 ) ; root -> left -> right = newNode ( 4 ) ; root -> left -> right -> left = newNode ( 3 ) ; root -> right -> right = newNode ( 8 ) ; root -> right -> right -> right = newNode ( 9 ) ; root -> right -> right -> left = newNode ( 7 ) ; int result = evenOddLevelDifference ( root ) ; cout << " diffence ▁ between ▁ sums ▁ is ▁ : : ▁ " ; cout << result << endl ; return 0 ; }
Difference between sums of odd level and even level nodes of a Binary Tree | A recursive program to find difference between sum of nodes at odd level and sum at even level ; Binary Tree node ; A utility function to allocate a new tree node with given data ; The main function that return difference between odd and even level nodes ; Base case ; Difference for root is root 's data - difference for left subtree - difference for right subtree ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int data ; node * left , * right ; } ; node * newNode ( int data ) { node * Node = new node ( ) ; Node -> data = data ; Node -> left = Node -> right = NULL ; return ( Node ) ; } int getLevelDiff ( node * root ) { if ( root == NULL ) return 0 ; return root -> data - getLevelDiff ( root -> left ) - getLevelDiff ( root -> right ) ; } int main ( ) { node * root = newNode ( 5 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 6 ) ; root -> left -> left = newNode ( 1 ) ; root -> left -> right = newNode ( 4 ) ; root -> left -> right -> left = newNode ( 3 ) ; root -> right -> right = newNode ( 8 ) ; root -> right -> right -> right = newNode ( 9 ) ; root -> right -> right -> left = newNode ( 7 ) ; cout << getLevelDiff ( root ) << " ▁ is ▁ the ▁ required ▁ difference STRNEWLINE " ; return 0 ; }
Maximum spiral sum in Binary Tree | C ++ implementation to find maximum spiral sum ; structure of a node of binary tree ; A utility function to create a new node ; function to find the maximum sum contiguous subarray . implements kadane 's algorithm ; to store the maximum value that is ending up to the current index ; to store the maximum value encountered so far ; traverse the array elements ; if max_ending_here < 0 , then it could not possibly contribute to the maximum sum further ; else add the value arr [ i ] to max_ending_here ; update max_so_far ; required maxium sum contiguous subarray value ; function to find maximum spiral sum ; if tree is empty ; Create two stacks to store alternate levels For levels from right to left ; For levels from left to right ; vector to store spiral order traversal of the binary tree ; Push first level to first stack ' s1' ; traversing tree in spiral form until there are elements in any one of the stacks ; traverse current level from s1 and push nodes of next level to s2 ; push temp - data to ' arr ' ; Note that right is pushed before left ; traverse current level from s2 and push nodes of next level to s1 ; push temp - data to ' arr ' ; Note that left is pushed before right ; required maximum spiral sum ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int data ) { Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return node ; } int maxSum ( vector < int > arr , int n ) { int max_ending_here = INT_MIN ; int max_so_far = INT_MIN ; for ( int i = 0 ; i < n ; i ++ ) { if ( max_ending_here < 0 ) max_ending_here = arr [ i ] ; else max_ending_here += arr [ i ] ; max_so_far = max ( max_so_far , max_ending_here ) ; } return max_so_far ; } int maxSpiralSum ( Node * root ) { if ( root == NULL ) return 0 ; stack < Node * > s1 ; stack < Node * > s2 ; vector < int > arr ; s1 . push ( root ) ; while ( ! s1 . empty ( ) || ! s2 . empty ( ) ) { while ( ! s1 . empty ( ) ) { Node * temp = s1 . top ( ) ; s1 . pop ( ) ; arr . push_back ( temp -> data ) ; if ( temp -> right ) s2 . push ( temp -> right ) ; if ( temp -> left ) s2 . push ( temp -> left ) ; } while ( ! s2 . empty ( ) ) { Node * temp = s2 . top ( ) ; s2 . pop ( ) ; arr . push_back ( temp -> data ) ; if ( temp -> left ) s1 . push ( temp -> left ) ; if ( temp -> right ) s1 . push ( temp -> right ) ; } } return maxSum ( arr , arr . size ( ) ) ; } int main ( ) { Node * root = newNode ( -2 ) ; root -> left = newNode ( -3 ) ; root -> right = newNode ( 4 ) ; root -> left -> left = newNode ( 5 ) ; root -> left -> right = newNode ( 1 ) ; root -> right -> left = newNode ( -2 ) ; root -> right -> right = newNode ( -1 ) ; root -> left -> left -> left = newNode ( -3 ) ; root -> right -> right -> right = newNode ( 2 ) ; cout << " Maximum ▁ Spiral ▁ Sum ▁ = ▁ " << maxSpiralSum ( root ) ; return 0 ; }
Sum of all leaf nodes of binary tree | CPP program to find sum of all leaf nodes of binary tree ; struct binary tree node ; return new node ; utility function which calculates sum of all leaf nodes ; add root data to sum if root is a leaf node ; propagate recursively in left and right subtree ; driver program ; construct binary tree ; variable to store sum of leaf nodes
#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 leafSum ( Node * root , int & sum ) { if ( ! root ) return ; if ( ! root -> left && ! root -> right ) sum += root -> data ; leafSum ( root -> left , sum ) ; leafSum ( root -> right , sum ) ; } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right = newNode ( 3 ) ; root -> right -> right = newNode ( 7 ) ; root -> right -> left = newNode ( 6 ) ; root -> right -> left -> right = newNode ( 8 ) ; int sum = 0 ; leafSum ( root , sum ) ; cout << sum << endl ; return 0 ; }
Inorder Tree Traversal without recursion and without stack ! | ; A binary tree tNode has data , a pointer to left child and a pointer to right child ; Function to traverse the binary tree without recursion and without stack ; Find the inorder predecessor of current ; Make current as the right child of its inorder predecessor ; Revert the changes made in the ' if ' part to restore the original tree i . e . , fix the right child of predecessor ; Helper function that allocates a new tNode with the given data and NULL left and right pointers . ; Driver program to test above functions ; Constructed binary tree is 1 / \ 2 3 / \ 4 5
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct tNode { int data ; struct tNode * left ; struct tNode * right ; } ; void MorrisTraversal ( struct tNode * root ) { struct tNode * current , * pre ; if ( root == NULL ) return ; current = root ; while ( current != NULL ) { if ( current -> left == NULL ) { printf ( " % d ▁ " , current -> data ) ; current = current -> right ; } else { pre = current -> left ; while ( pre -> right != NULL && pre -> right != current ) pre = pre -> right ; if ( pre -> right == NULL ) { pre -> right = current ; current = current -> left ; } else { pre -> right = NULL ; printf ( " % d ▁ " , current -> data ) ; current = current -> right ; } } } } struct tNode * newtNode ( int data ) { struct tNode * node = new tNode ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; return ( node ) ; } int main ( ) { struct tNode * root = newtNode ( 1 ) ; root -> left = newtNode ( 2 ) ; root -> right = newtNode ( 3 ) ; root -> left -> left = newtNode ( 4 ) ; root -> left -> right = newtNode ( 5 ) ; MorrisTraversal ( root ) ; return 0 ; }
Sum of leaf nodes at minimum level | C ++ implementation to find the sum of leaf nodes at minimum level ; structure of a node of binary tree ; function to get a new node ; allocate space ; put in the data ; function to find the sum of leaf nodes at minimum level ; if tree is empty ; if there is only one node ; queue used for level order traversal ; push root node in the queue ' q ' ; count number of nodes in the current level ; traverse the current level nodes ; get front element from ' q ' ; if it is a leaf node ; accumulate data to ' sum ' ; set flag ' f ' to 1 , to signify minimum level for leaf nodes has been encountered ; if top ' s ▁ left ▁ and ▁ right ▁ child ▁ ▁ ▁ exists , ▁ then ▁ push ▁ them ▁ to ▁ ' q ' ; required sum ; Driver program to test above ; binary tree creation
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * getNode ( int data ) { Node * newNode = ( Node * ) malloc ( sizeof ( Node ) ) ; newNode -> data = data ; newNode -> left = newNode -> right = NULL ; return newNode ; } int sumOfLeafNodesAtMinLevel ( Node * root ) { if ( ! root ) return 0 ; if ( ! root -> left && ! root -> right ) return root -> data ; queue < Node * > q ; int sum = 0 ; bool f = 0 ; q . push ( root ) ; while ( f == 0 ) { int nc = q . size ( ) ; while ( nc -- ) { Node * top = q . front ( ) ; q . pop ( ) ; if ( ! top -> left && ! top -> right ) { sum += top -> data ; f = 1 ; } else { if ( top -> left ) q . push ( top -> left ) ; if ( top -> right ) q . push ( top -> right ) ; } } } return sum ; } int main ( ) { Node * root = getNode ( 1 ) ; root -> left = getNode ( 2 ) ; root -> right = getNode ( 3 ) ; root -> left -> left = getNode ( 4 ) ; root -> left -> right = getNode ( 5 ) ; root -> right -> left = getNode ( 6 ) ; root -> right -> right = getNode ( 7 ) ; root -> left -> right -> left = getNode ( 8 ) ; root -> right -> left -> right = getNode ( 9 ) ; cout << " Sum ▁ = ▁ " << sumOfLeafNodesAtMinLevel ( root ) ; return 0 ; }
Root to leaf path sum equal to a given number | ; A binary tree node has data , pointer to left child and a pointer to right child ; Given a tree and a sum , return true if there is a path from the root down to a leaf , such that adding up all the values along the path equals the given sum . Strategy : subtract the node value from the sum when recurring down , and check to see if the sum is 0 when you run out of tree . ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver Code ; Constructed binary tree is 10 / \ 8 2 / \ / 3 5 2
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define bool int NEW_LINE class node { public : int data ; node * left ; node * right ; } ; bool hasPathSum ( node * Node , int sum ) { if ( Node == NULL ) { return ( sum == 0 ) ; } else { bool ans = 0 ; int subSum = sum - Node -> data ; if ( subSum == 0 && Node -> left == NULL && Node -> right == NULL ) return 1 ; if ( Node -> left ) ans = ans || hasPathSum ( Node -> left , subSum ) ; if ( Node -> right ) ans = ans || hasPathSum ( Node -> right , subSum ) ; return ans ; } } node * newnode ( int data ) { node * Node = new node ( ) ; Node -> data = data ; Node -> left = NULL ; Node -> right = NULL ; return ( Node ) ; } int main ( ) { int sum = 21 ; 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 ) ; if ( hasPathSum ( root , sum ) ) cout << " There ▁ is ▁ a ▁ root - to - leaf ▁ path ▁ with ▁ sum ▁ " << sum ; else cout << " There ▁ is ▁ no ▁ root - to - leaf ▁ path ▁ with ▁ sum ▁ " << sum ; return 0 ; }
Sum of all the numbers that are formed from root to leaf paths | C ++ program to find sum of all paths from root to leaves ; function to allocate new node with given data ; Returns sum of all root to leaf paths . The first parameter is root of current subtree , the second parameter is value of the number formed by nodes from root to this node ; Base case ; Update val ; if current node is leaf , return the current value of val ; recur sum of values for left and right subtree ; A wrapper function over treePathsSumUtil ( ) ; Pass the initial value as 0 as there is nothing above root ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int data ; node * left , * right ; } ; node * newNode ( int data ) { node * Node = new node ( ) ; Node -> data = data ; Node -> left = Node -> right = NULL ; return ( Node ) ; } int treePathsSumUtil ( node * root , int val ) { if ( root == NULL ) return 0 ; val = ( val * 10 + root -> data ) ; if ( root -> left == NULL && root -> right == NULL ) return val ; return treePathsSumUtil ( root -> left , val ) + treePathsSumUtil ( root -> right , val ) ; } int treePathsSum ( node * root ) { return treePathsSumUtil ( root , 0 ) ; } int main ( ) { node * root = newNode ( 6 ) ; root -> left = newNode ( 3 ) ; root -> right = newNode ( 5 ) ; root -> left -> left = newNode ( 2 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> right = newNode ( 4 ) ; root -> left -> right -> left = newNode ( 7 ) ; root -> left -> right -> right = newNode ( 4 ) ; cout << " Sum ▁ of ▁ all ▁ paths ▁ is ▁ " << treePathsSum ( root ) ; return 0 ; }
Merge Two Binary Trees by doing Node Sum ( Recursive and Iterative ) | C ++ program to Merge Two Binary Trees ; A binary tree node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Given a binary tree , print its nodes in inorder ; first recur on left child ; then print the data of node ; now recur on right child ; Function to merge given two binary trees ; Driver code ; Let us construct the first Binary Tree 1 / \ 2 3 / \ \ 4 5 6 ; Let us construct the second Binary Tree 4 / \ 1 7 / / \ 3 2 6
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; Node * newNode ( int data ) { Node * new_node = new Node ; new_node -> data = data ; new_node -> left = new_node -> right = NULL ; return new_node ; } void inorder ( Node * node ) { if ( ! node ) return ; inorder ( node -> left ) ; printf ( " % d ▁ " , node -> data ) ; inorder ( node -> right ) ; } Node * MergeTrees ( Node * t1 , Node * t2 ) { if ( ! t1 ) return t2 ; if ( ! t2 ) return t1 ; t1 -> data += t2 -> data ; t1 -> left = MergeTrees ( t1 -> left , t2 -> left ) ; t1 -> right = MergeTrees ( t1 -> right , t2 -> right ) ; return t1 ; } int main ( ) { Node * root1 = newNode ( 1 ) ; root1 -> left = newNode ( 2 ) ; root1 -> right = newNode ( 3 ) ; root1 -> left -> left = newNode ( 4 ) ; root1 -> left -> right = newNode ( 5 ) ; root1 -> right -> right = newNode ( 6 ) ; Node * root2 = newNode ( 4 ) ; root2 -> left = newNode ( 1 ) ; root2 -> right = newNode ( 7 ) ; root2 -> left -> left = newNode ( 3 ) ; root2 -> right -> left = newNode ( 2 ) ; root2 -> right -> right = newNode ( 6 ) ; Node * root3 = MergeTrees ( root1 , root2 ) ; printf ( " The ▁ Merged ▁ Binary ▁ Tree ▁ is : STRNEWLINE " ) ; inorder ( root3 ) ; return 0 ; }
Merge Two Binary Trees by doing Node Sum ( Recursive and Iterative ) | C ++ program to Merge Two Binary Trees ; A binary tree node has data , pointer to left child and a pointer to right child ; Structure to store node pair onto stack ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Given a binary tree , print its nodes in inorder ; first recur on left child ; then print the data of node ; now recur on right child ; Function to merge given two binary trees ; Driver code ; Let us construct the first Binary Tree 1 / \ 2 3 / \ \ 4 5 6 ; Let us construct the second Binary Tree 4 / \ 1 7 / / \ 3 2 6
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; struct snode { Node * l , * r ; } ; Node * newNode ( int data ) { Node * new_node = new Node ; new_node -> data = data ; new_node -> left = new_node -> right = NULL ; return new_node ; } void inorder ( Node * node ) { if ( ! node ) return ; inorder ( node -> left ) ; printf ( " % d ▁ " , node -> data ) ; inorder ( node -> right ) ; } Node * MergeTrees ( Node * t1 , Node * t2 ) { if ( ! t1 ) return t2 ; if ( ! t2 ) return t1 ; stack < snode > s ; snode temp ; temp . l = t1 ; temp . r = t2 ; s . push ( temp ) ; snode n ; while ( ! s . empty ( ) ) { n = s . top ( ) ; s . pop ( ) ; if ( n . l == NULL n . r == NULL ) continue ; n . l -> data += n . r -> data ; if ( n . l -> left == NULL ) n . l -> left = n . r -> left ; else { snode t ; t . l = n . l -> left ; t . r = n . r -> left ; s . push ( t ) ; } if ( n . l -> right == NULL ) n . l -> right = n . r -> right ; else { snode t ; t . l = n . l -> right ; t . r = n . r -> right ; s . push ( t ) ; } } return t1 ; } int main ( ) { Node * root1 = newNode ( 1 ) ; root1 -> left = newNode ( 2 ) ; root1 -> right = newNode ( 3 ) ; root1 -> left -> left = newNode ( 4 ) ; root1 -> left -> right = newNode ( 5 ) ; root1 -> right -> right = newNode ( 6 ) ; Node * root2 = newNode ( 4 ) ; root2 -> left = newNode ( 1 ) ; root2 -> right = newNode ( 7 ) ; root2 -> left -> left = newNode ( 3 ) ; root2 -> right -> left = newNode ( 2 ) ; root2 -> right -> right = newNode ( 6 ) ; Node * root3 = MergeTrees ( root1 , root2 ) ; printf ( " The ▁ Merged ▁ Binary ▁ Tree ▁ is : STRNEWLINE " ) ; inorder ( root3 ) ; return 0 ; }
Find root of the tree where children id sum for every node is given | Find root of tree where children sum for every node id is given . ; Every node appears once as an id , and every node except for the root appears once in a sum . So if we subtract all the sums from all the ids , we 're left with the root id. ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findRoot ( pair < int , int > arr [ ] , int n ) { int root = 0 ; for ( int i = 0 ; i < n ; i ++ ) root += ( arr [ i ] . first - arr [ i ] . second ) ; return root ; } int main ( ) { pair < int , int > arr [ ] = { { 1 , 5 } , { 2 , 0 } , { 3 , 0 } , { 4 , 0 } , { 5 , 5 } , { 6 , 5 } } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " % d STRNEWLINE " , findRoot ( arr , n ) ) ; return 0 ; }
Print Postorder traversal from given Inorder and Preorder traversals | C ++ program to print postorder traversal from preorder and inorder traversals ; A utility function to search x in arr [ ] of size n ; Prints postorder traversal from given inorder and preorder traversals ; The first element in pre [ ] is always root , search it in in [ ] to find left and right subtrees ; If left subtree is not empty , print left subtree ; If right subtree is not empty , print right subtree ; Print root ; Driver program to test above functions
#include <iostream> NEW_LINE using namespace std ; int search ( int arr [ ] , int x , int n ) { for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] == x ) return i ; return -1 ; } void printPostOrder ( int in [ ] , int pre [ ] , int n ) { int root = search ( in , pre [ 0 ] , n ) ; if ( root != 0 ) printPostOrder ( in , pre + 1 , root ) ; if ( root != n - 1 ) printPostOrder ( in + root + 1 , pre + root + 1 , n - root - 1 ) ; cout << pre [ 0 ] << " ▁ " ; } int main ( ) { int in [ ] = { 4 , 2 , 5 , 1 , 3 , 6 } ; int pre [ ] = { 1 , 2 , 4 , 5 , 3 , 6 } ; int n = sizeof ( in ) / sizeof ( in [ 0 ] ) ; cout << " Postorder ▁ traversal ▁ " << endl ; printPostOrder ( in , pre , n ) ; return 0 ; }
Lowest Common Ancestor in a Binary Tree | Set 1 | C ++ Program to find LCA of n1 and n2 using one traversal of Binary Tree ; A Binary Tree Node ; Utility function to create a new tree Node ; This function returns pointer to LCA of two given values n1 and n2 . This function assumes that n1 and n2 are present in Binary Tree ; 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 ; Driver program to test above functions
#include <iostream> 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 ; } 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 ) ; cout << " LCA ( 4 , ▁ 5 ) ▁ = ▁ " << findLCA ( root , 4 , 5 ) -> key ; cout << " nLCA ( 4 , ▁ 6 ) ▁ = ▁ " << findLCA ( root , 4 , 6 ) -> key ; cout << " nLCA ( 3 , ▁ 4 ) ▁ = ▁ " << findLCA ( root , 3 , 4 ) -> key ; cout << " nLCA ( 2 , ▁ 4 ) ▁ = ▁ " << findLCA ( root , 2 , 4 ) -> key ; return 0 ; }
Lowest Common Ancestor in a Binary Tree | Set 1 | C ++ program to find LCA of n1 and n2 using one traversal of Binary Tree . It handles all cases even when n1 or n2 is not there in Binary Tree ; A Binary Tree Node ; Utility function to create a new tree Node ; This function returns pointer to LCA of two given values n1 and n2 . v1 is set as true by this function if n1 is found v2 is set as true by this function if n2 is found ; Base case ; If either n1 or n2 matches with root 's key, report the presence by setting v1 or v2 as true and return 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 ; Returns true if key k is present in tree rooted with root ; This function returns LCA of n1 and n2 only if both n1 and n2 are present in tree , otherwise returns NULL ; ; Initialize n1 and n2 as not visited ; Find lca of n1 and n2 using the technique discussed above ; Return LCA only if both n1 and n2 are present in tree ; Else return NULL ; Driver program to test above functions
#include <iostream> 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 * findLCAUtil ( struct Node * root , int n1 , int n2 , bool & v1 , bool & v2 ) { if ( root == NULL ) return NULL ; if ( root -> key == n1 ) { v1 = true ; return root ; } if ( root -> key == n2 ) { v2 = true ; return root ; } Node * left_lca = findLCAUtil ( root -> left , n1 , n2 , v1 , v2 ) ; Node * right_lca = findLCAUtil ( root -> right , n1 , n2 , v1 , v2 ) ; if ( left_lca && right_lca ) return root ; return ( left_lca != NULL ) ? left_lca : right_lca ; } bool find ( Node * root , int k ) { if ( root == NULL ) return false ; if ( root -> key == k || find ( root -> left , k ) || find ( root -> right , k ) ) return true ; return false ; } Node * findLCA ( Node * root , int n1 , int n2 ) { bool v1 = false , v2 = false ; Node * lca = findLCAUtil ( root , n1 , n2 , v1 , v2 ) ; if ( v1 && v2 || v1 && find ( lca , n2 ) || v2 && find ( lca , n1 ) ) return lca ; return NULL ; } 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 ) ; Node * lca = findLCA ( root , 4 , 5 ) ; if ( lca != NULL ) cout << " LCA ( 4 , ▁ 5 ) ▁ = ▁ " << lca -> key ; else cout << " Keys ▁ are ▁ not ▁ present ▁ " ; lca = findLCA ( root , 4 , 10 ) ; if ( lca != NULL ) cout << " nLCA ( 4 , ▁ 10 ) ▁ = ▁ " << lca -> key ; else cout << " nKeys ▁ are ▁ not ▁ present ▁ " ; return 0 ; }
Lowest Common Ancestor in a Binary Tree | Set 2 ( Using Parent Pointer ) | C ++ program to find lowest common ancestor using parent pointer ; A Tree Node ; A utility function to create a new BST node ; A utility function to insert a new node with given key in Binary Search Tree ; If the tree is empty , return a new node ; Otherwise , recur down the tree ; return the ( unchanged ) node pointer ; A utility function to find depth of a node ( distance of it from root ) ; To find LCA of nodes n1 and n2 in Binary Tree ; Find depths of two nodes and differences ; If n2 is deeper , swap n1 and n2 ; Move n1 up until it reaches the same level as n2 ; Now n1 and n2 are at same levels ; Driver method to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { Node * left , * right , * parent ; int key ; } ; Node * newNode ( int item ) { Node * temp = new Node ; temp -> key = item ; temp -> parent = temp -> left = temp -> right = NULL ; return temp ; } Node * insert ( Node * node , int key ) { if ( node == NULL ) return newNode ( key ) ; if ( key < node -> key ) { node -> left = insert ( node -> left , key ) ; node -> left -> parent = node ; } else if ( key > node -> key ) { node -> right = insert ( node -> right , key ) ; node -> right -> parent = node ; } return node ; } int depth ( Node * node ) { int d = -1 ; while ( node ) { ++ d ; node = node -> parent ; } return d ; } Node * LCA ( Node * n1 , Node * n2 ) { int d1 = depth ( n1 ) , d2 = depth ( n2 ) ; int diff = d1 - d2 ; if ( diff < 0 ) { Node * temp = n1 ; n1 = n2 ; n2 = temp ; diff = - diff ; } while ( diff -- ) n1 = n1 -> parent ; while ( n1 && n2 ) { if ( n1 == n2 ) return n1 ; n1 = n1 -> parent ; n2 = n2 -> parent ; } return NULL ; } int main ( void ) { Node * root = NULL ; root = insert ( root , 20 ) ; root = insert ( root , 8 ) ; root = insert ( root , 22 ) ; root = insert ( root , 4 ) ; root = insert ( root , 12 ) ; root = insert ( root , 10 ) ; root = insert ( root , 14 ) ; Node * n1 = root -> left -> right -> left ; Node * n2 = root -> right ; Node * lca = LCA ( n1 , n2 ) ; printf ( " LCA ▁ of ▁ % d ▁ and ▁ % d ▁ is ▁ % d ▁ STRNEWLINE " , n1 -> key , n2 -> key , lca -> key ) ; return 0 ; }
Lowest Common Ancestor in a Binary Tree | Set 3 ( Using RMQ ) | CPP code to find LCA of given two nodes in a tree ; the graph ; level of each node ; the segment tree ; adding edges to the graph ( tree ) ; assigning level to nodes ; storing the dfs traversal in the array e ; making the array l ; making the array h ; if is already stored ; Range minimum query to return the index of minimum in the subarray L [ qs : qe ] ; out of range ; in the range ; constructs the segment tree ; leaf ; Function to get LCA ; Driver code ; n = number of nodes in the tree q = number of queries to answer ; 1 / | \ 2 3 4 | \ 5 6 / | \ 8 7 9 ( right of 5 ) / | \ | \ 10 11 12 13 14 | 15
#include <bits/stdc++.h> NEW_LINE #define sz ( x ) x.size() NEW_LINE #define pb push_back NEW_LINE #define left 2 * i + 1 NEW_LINE #define right 2 * i + 2 NEW_LINE using namespace std ; const int maxn = 100005 ; vector < vector < int > > g ( maxn ) ; int level [ maxn ] ; vector < int > e ; vector < int > l ; int h [ maxn ] ; int st [ 5 * maxn ] ; void add_edge ( int u , int v ) { g [ u ] . pb ( v ) ; g [ v ] . pb ( u ) ; } void leveling ( int src ) { for ( int i = 0 ; i < sz ( g [ src ] ) ; i ++ ) { int des = g [ src ] [ i ] ; if ( ! level [ des ] ) { level [ des ] = level [ src ] + 1 ; leveling ( des ) ; } } } bool visited [ maxn ] ; void dfs ( int src ) { e . pb ( src ) ; visited [ src ] = 1 ; for ( int i = 0 ; i < sz ( g [ src ] ) ; i ++ ) { int des = g [ src ] [ i ] ; if ( ! visited [ des ] ) { dfs ( des ) ; e . pb ( src ) ; } } } void setting_l ( int n ) { for ( int i = 0 ; i < sz ( e ) ; i ++ ) l . pb ( level [ e [ i ] ] ) ; } void setting_h ( int n ) { for ( int i = 0 ; i <= n ; i ++ ) h [ i ] = -1 ; for ( int i = 0 ; i < sz ( e ) ; i ++ ) { if ( h [ e [ i ] ] == -1 ) h [ e [ i ] ] = i ; } } int RMQ ( int ss , int se , int qs , int qe , int i ) { if ( ss > se ) return -1 ; if ( se < qs qe < ss ) return -1 ; if ( qs <= ss && se <= qe ) return st [ i ] ; int mid = ( ss + se ) >> 1 ; int st = RMQ ( ss , mid , qs , qe , left ) ; int en = RMQ ( mid + 1 , se , qs , qe , right ) ; if ( st != -1 && en != -1 ) { if ( l [ st ] < l [ en ] ) return st ; return en ; } else if ( st != -1 ) return st ; else if ( en != -1 ) return en ; } void SegmentTreeConstruction ( int ss , int se , int i ) { if ( ss > se ) return ; if ( ss == se ) { st [ i ] = ss ; return ; } int mid = ( ss + se ) >> 1 ; SegmentTreeConstruction ( ss , mid , left ) ; SegmentTreeConstruction ( mid + 1 , se , right ) ; if ( l [ st [ left ] ] < l [ st [ right ] ] ) st [ i ] = st [ left ] ; else st [ i ] = st [ right ] ; } int LCA ( int x , int y ) { if ( h [ x ] > h [ y ] ) swap ( x , y ) ; return e [ RMQ ( 0 , sz ( l ) - 1 , h [ x ] , h [ y ] , 0 ) ] ; } int main ( ) { ios :: sync_with_stdio ( 0 ) ; int n = 15 , q = 5 ; add_edge ( 1 , 2 ) ; add_edge ( 1 , 3 ) ; add_edge ( 1 , 4 ) ; add_edge ( 3 , 5 ) ; add_edge ( 4 , 6 ) ; add_edge ( 5 , 7 ) ; add_edge ( 5 , 8 ) ; add_edge ( 5 , 9 ) ; add_edge ( 7 , 10 ) ; add_edge ( 7 , 11 ) ; add_edge ( 7 , 12 ) ; add_edge ( 9 , 13 ) ; add_edge ( 9 , 14 ) ; add_edge ( 12 , 15 ) ; level [ 1 ] = 1 ; leveling ( 1 ) ; dfs ( 1 ) ; setting_l ( n ) ; setting_h ( n ) ; SegmentTreeConstruction ( 0 , sz ( l ) - 1 , 0 ) ; cout << LCA ( 10 , 15 ) << endl ; cout << LCA ( 11 , 14 ) << endl ; return 0 ; }
Print common nodes on path from root ( or common ancestors ) | C ++ Program to find common nodes for given two nodes ; 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 ; Utility Function to print all ancestors of LCA ; base cases ; If target is present in either left or right subtree of this node , then print this node ; Else return false ; Function to find nodes common to given two nodes ; 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 printAncestors ( struct Node * root , int target ) { if ( root == NULL ) return false ; if ( root -> key == target ) { cout << root -> key << " ▁ " ; return true ; } if ( printAncestors ( root -> left , target ) || printAncestors ( root -> right , target ) ) { cout << root -> key << " ▁ " ; return true ; } return false ; } bool findCommonNodes ( struct Node * root , int first , int second ) { struct Node * LCA = findLCA ( root , first , second ) ; if ( LCA == NULL ) return false ; printAncestors ( root , LCA -> key ) ; } 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 ) ; if ( findCommonNodes ( root , 9 , 7 ) == false ) cout << " No ▁ Common ▁ nodes " ; return 0 ; }
Find LCA in Binary Tree using RMQ | C ++ Program to find LCA of u and v by reducing the problem to RMQ ; A Binary Tree node ; number of nodes in input tree ; For Euler tour sequence ; Level of nodes in tour sequence ; First occurrences of nodes in tour ; Variable to fill - in euler and level arrays ; log base 2 of x ; A recursive function to get the minimum value in a given range of array indexes . The following are parameters for this function . st -- > Pointer to segment tree index -- > Index of current node in the segment tree . Initially 0 is passed as root is always at index 0 ss & se -- > Starting and ending indexes of the segment represented by current node , i . e . , st [ index ] qs & qe -- > Starting and ending indexes of query range ; If segment of this node is a part of given range , then return the min of the segment ; If segment of this node is outside the given range ; If a part of this segment overlaps with the given range ; Return minimum of elements in range from index qs ( query start ) to qe ( query end ) . It mainly uses RMQUtil ( ) ; Check for erroneous input values ; A recursive function that constructs Segment Tree for array [ ss . . se ] . si is index of current node in segment tree st ; If there is one element in array , store it in current node of segment tree and return ; If there are more than one elements , then recur for left and right subtrees and store the minimum of two values in this node ; Function to construct segment tree from given array . This function allocates memory for segment tree and calls constructSTUtil ( ) to fill the allocated memory ; Allocate memory for segment tree Height of segment tree ; Maximum size of segment tree 2 * pow ( 2 , x ) - 1 ; Fill the allocated memory st ; Return the constructed segment tree ; Recursive version of the Euler tour of T ; if the passed node exists ; insert in euler array ; insert l in level array ; increment index ; if unvisited , mark first occurrence ; tour left subtree if exists , and remark euler and level arrays for parent on return ; tour right subtree if exists , and remark euler and level arrays for parent on return ; Returns LCA of nodes n1 , n2 ( assuming they are present in the tree ) ; Mark all nodes unvisited . Note that the size of firstOccurrence is 1 as node values which vary from 1 to 9 are used as indexes ; To start filling euler and level arrays from index 0 ; Start Euler tour with root node on level 0 ; construct segment tree on level array ; If v before u in Euler tour . For RMQ to work , first parameter ' u ' must be smaller than second ' v ' ; Starting and ending indexes of query range ; query for index of LCA in tour ; return LCA node ; Driver program to test above functions ; Let us create the Binary Tree as shown in the diagram .
#include <bits/stdc++.h> NEW_LINE struct Node { int key ; struct Node * left , * right ; } ; Node * newNode ( int k ) { Node * temp = new Node ; temp -> key = k ; temp -> left = temp -> right = NULL ; return temp ; } #define V 9 NEW_LINE int euler [ 2 * V - 1 ] ; int level [ 2 * V - 1 ] ; int firstOccurrence [ V + 1 ] ; int ind ; int Log2 ( int x ) { int ans = 0 ; while ( x >>= 1 ) ans ++ ; return ans ; } int RMQUtil ( int index , int ss , int se , int qs , int qe , int * st ) { if ( qs <= ss && qe >= se ) return st [ index ] ; else if ( se < qs ss > qe ) return -1 ; int mid = ( ss + se ) / 2 ; int q1 = RMQUtil ( 2 * index + 1 , ss , mid , qs , qe , st ) ; int q2 = RMQUtil ( 2 * index + 2 , mid + 1 , se , qs , qe , st ) ; if ( q1 == -1 ) return q2 ; else if ( q2 == -1 ) return q1 ; return ( level [ q1 ] < level [ q2 ] ) ? q1 : q2 ; } int RMQ ( int * st , int n , int qs , int qe ) { if ( qs < 0 qe > n -1 qs > qe ) { printf ( " Invalid ▁ Input " ) ; return - 1 ; } return RMQUtil ( 0 , 0 , n - 1 , qs , qe , st ) ; } void constructSTUtil ( int si , int ss , int se , int arr [ ] , int * st ) { if ( ss == se ) st [ si ] = ss ; else { int mid = ( ss + se ) / 2 ; constructSTUtil ( si * 2 + 1 , ss , mid , arr , st ) ; constructSTUtil ( si * 2 + 2 , mid + 1 , se , arr , st ) ; if ( arr [ st [ 2 * si + 1 ] ] < arr [ st [ 2 * si + 2 ] ] ) st [ si ] = st [ 2 * si + 1 ] ; else st [ si ] = st [ 2 * si + 2 ] ; } } int * constructST ( int arr [ ] , int n ) { int x = Log2 ( n ) + 1 ; int max_size = 2 * ( 1 << x ) - 1 ; int * st = new int [ max_size ] ; constructSTUtil ( 0 , 0 , n - 1 , arr , st ) ; return st ; } void eulerTour ( Node * root , int l ) { if ( root ) { euler [ ind ] = root -> key ; level [ ind ] = l ; ind ++ ; if ( firstOccurrence [ root -> key ] == -1 ) firstOccurrence [ root -> key ] = ind - 1 ; if ( root -> left ) { eulerTour ( root -> left , l + 1 ) ; euler [ ind ] = root -> key ; level [ ind ] = l ; ind ++ ; } if ( root -> right ) { eulerTour ( root -> right , l + 1 ) ; euler [ ind ] = root -> key ; level [ ind ] = l ; ind ++ ; } } } int findLCA ( Node * root , int u , int v ) { memset ( firstOccurrence , -1 , sizeof ( int ) * ( V + 1 ) ) ; ind = 0 ; eulerTour ( root , 0 ) ; int * st = constructST ( level , 2 * V - 1 ) ; if ( firstOccurrence [ u ] > firstOccurrence [ v ] ) std :: swap ( u , v ) ; int qs = firstOccurrence [ u ] ; int qe = firstOccurrence [ v ] ; int index = RMQ ( st , 2 * V - 1 , qs , qe ) ; return euler [ index ] ; } 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 -> right -> left = newNode ( 8 ) ; root -> left -> right -> right = newNode ( 9 ) ; int u = 4 , v = 9 ; printf ( " The ▁ LCA ▁ of ▁ node ▁ % d ▁ and ▁ node ▁ % d ▁ is ▁ node ▁ % d . STRNEWLINE " , u , v , findLCA ( root , u , v ) ) ; return 0 ; }
Print Postorder traversal from given Inorder and Preorder traversals | C ++ program to print Postorder traversal from given Inorder and Preorder traversals . ; Find index of next item in preorder traversal in inorder . ; traverse left tree ; traverse right tree ; print root node at the end of traversal ; Driver code
#include <iostream> NEW_LINE using namespace std ; int preIndex = 0 ; int search ( int arr [ ] , int startIn , int endIn , int data ) { int i = 0 ; for ( i = startIn ; i < endIn ; i ++ ) { if ( arr [ i ] == data ) { return i ; } } return i ; } void printPost ( int arr [ ] , int pre [ ] , int inStrt , int inEnd ) { if ( inStrt > inEnd ) { return ; } int inIndex = search ( arr , inStrt , inEnd , pre [ preIndex ++ ] ) ; printPost ( arr , pre , inStrt , inIndex - 1 ) ; printPost ( arr , pre , inIndex + 1 , inEnd ) ; cout << arr [ inIndex ] << " ▁ " ; } int main ( ) { int arr [ ] = { 4 , 2 , 5 , 1 , 3 , 6 } ; int pre [ ] = { 1 , 2 , 4 , 5 , 3 , 6 } ; int len = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printPost ( arr , pre , 0 , len - 1 ) ; }
Binary Tree | Set 1 ( Introduction ) |
struct node { int data ; struct node * left ; struct node * right ; } ;
Maximum difference between node and its ancestor in Binary Tree | C ++ program to find maximum difference between node and its ancestor ; A binary tree node has key , pointer to left child and a pointer to right child ; To create a newNode of tree and return pointer ; Recursive function to calculate maximum ancestor - node difference in binary tree . It updates value at ' res ' to store the result . The returned value of this function is minimum value in subtree rooted with ' t ' ; Returning Maximum int value if node is not there ( one child case ) ; If leaf node then just return node 's value ; Recursively calling left and right subtree for minimum value ; Updating res if ( node value - minimum value from subtree ) is bigger than res ; Returning minimum value got so far ; This function mainly calls maxDiffUtil ( ) ; Initialising result with minimum int value ; Helper function to print inorder traversal of binary tree ; Driver program to test above functions ; Making above given diagram 's binary tree
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * left , * right ; } ; struct Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return ( temp ) ; } int maxDiffUtil ( Node * t , int * res ) { if ( t == NULL ) return INT_MAX ; if ( t -> left == NULL && t -> right == NULL ) return t -> key ; int val = min ( maxDiffUtil ( t -> left , res ) , maxDiffUtil ( t -> right , res ) ) ; * res = max ( * res , t -> key - val ) ; return min ( val , t -> key ) ; } int maxDiff ( Node * root ) { int res = INT_MIN ; maxDiffUtil ( root , & res ) ; return res ; } void inorder ( Node * root ) { if ( root ) { inorder ( root -> left ) ; printf ( " % d ▁ " , root -> key ) ; inorder ( root -> right ) ; } } int main ( ) { Node * root ; root = newNode ( 8 ) ; root -> left = newNode ( 3 ) ; root -> left -> left = newNode ( 1 ) ; root -> left -> right = newNode ( 6 ) ; root -> left -> right -> left = newNode ( 4 ) ; root -> left -> right -> right = newNode ( 7 ) ; root -> right = newNode ( 10 ) ; root -> right -> right = newNode ( 14 ) ; root -> right -> right -> left = newNode ( 13 ) ; printf ( " Maximum ▁ difference ▁ between ▁ a ▁ node ▁ and " " ▁ its ▁ ancestor ▁ is ▁ : ▁ % d STRNEWLINE " , maxDiff ( root ) ) ; }
Print the path common to the two paths from the root to the two given nodes | C ++ implementation to print the path common to the two paths from the root to the two given nodes ; Initialize n1 and n2 as not visited ; structure of a node of binary tree ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; This function returns pointer to LCA of two given values n1 and n2 . v1 is set as true by this function if n1 is found v2 is set as true by this function if n2 is found ; Base case ; If either n1 or n2 matches with root 's data, report the presence by setting v1 or v2 as true and return root (Note that if a key is ancestor of other, then the ancestor key becomes LCA) ; Look for nodes in left and right subtrees ; If both of the above calls return Non - NULL , then one node is present in one subtree and other is present in other , So this current node is the LCA ; Otherwise check if left subtree or right subtree is LCA ; Returns true if key k is present in tree rooted with root ; Base Case ; If key k is present at root , or in left subtree or right subtree , return true ; Else return false ; This function returns LCA of n1 and n2 only if both n1 and n2 are present in tree , otherwise returns NULL ; Find lca of n1 and n2 ; Return LCA only if both n1 and n2 are present in tree ; Else return NULL ; function returns true if there is a path from root to the given node . It also populates ' arr ' with the given path ; if root is NULL there is no path ; push the node ' s ▁ value ▁ in ▁ ' arr ' ; if it is the required node return true ; else check whether there the required node lies in the left subtree or right subtree of the current node ; required node does not lie either in the left or right subtree of the current node Thus , remove current node ' s ▁ value ▁ from ▁ ' arr ' and then return false; ; function to print the path common to the two paths from the root to the two given nodes if the nodes lie in the binary tree ; vector to store the common path ; LCA of node n1 and n2 ; if LCA of both n1 and n2 exists ; then print the path from root to LCA node ; LCA is not present in the binary tree either n1 or n2 or both are not present ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool v1 = false , v2 = false ; struct Node { int data ; Node * left , * right ; } ; struct Node * getNode ( int data ) { struct Node * newNode = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; newNode -> data = data ; newNode -> left = newNode -> right = NULL ; return newNode ; } struct Node * findLCAUtil ( struct Node * root , int n1 , int n2 , bool & v1 , bool & v2 ) { if ( root == NULL ) return NULL ; if ( root -> data == n1 ) { v1 = true ; return root ; } if ( root -> data == n2 ) { v2 = true ; return root ; } Node * left_lca = findLCAUtil ( root -> left , n1 , n2 , v1 , v2 ) ; Node * right_lca = findLCAUtil ( root -> right , n1 , n2 , v1 , v2 ) ; if ( left_lca && right_lca ) return root ; return ( left_lca != NULL ) ? left_lca : right_lca ; } bool find ( Node * root , int k ) { if ( root == NULL ) return false ; if ( root -> data == k || find ( root -> left , k ) || find ( root -> right , k ) ) return true ; return false ; } Node * findLCA ( Node * root , int n1 , int n2 ) { Node * lca = findLCAUtil ( root , n1 , n2 , v1 , v2 ) ; if ( v1 && v2 || v1 && find ( lca , n2 ) || v2 && find ( lca , n1 ) ) return lca ; return NULL ; } bool hasPath ( Node * root , vector < int > & arr , int x ) { if ( ! root ) return false ; arr . push_back ( root -> data ) ; if ( root -> data == x ) return true ; if ( hasPath ( root -> left , arr , x ) || hasPath ( root -> right , arr , x ) ) return true ; arr . pop_back ( ) ; return false ; } void printCommonPath ( Node * root , int n1 , int n2 ) { vector < int > arr ; Node * lca = findLCA ( root , n1 , n2 ) ; if ( lca ) { if ( hasPath ( root , arr , lca -> data ) ) { for ( int i = 0 ; i < arr . size ( ) - 1 ; i ++ ) cout << arr [ i ] << " - > " ; cout << arr [ arr . size ( ) - 1 ] ; } } else cout << " No ▁ Common ▁ Path " ; } int main ( ) { struct Node * root = getNode ( 1 ) ; root -> left = getNode ( 2 ) ; root -> right = getNode ( 3 ) ; root -> left -> left = getNode ( 4 ) ; root -> left -> right = getNode ( 5 ) ; root -> right -> left = getNode ( 6 ) ; root -> right -> right = getNode ( 7 ) ; root -> left -> right -> left = getNode ( 8 ) ; root -> right -> left -> right = getNode ( 9 ) ; int n1 = 4 , n2 = 8 ; printCommonPath ( root , n1 , n2 ) ; return 0 ; }
Query for ancestor | C / C ++ program to query whether two node has ancestor - descendant relationship or not ; Utility dfs method to assign in and out time to each node ; assign In - time to node u ; call dfs over all neighbors except parent ; assign Out - time to node u ; method to preprocess all nodes for assigning time ; construct array of vector data structure for tree ; call dfs method from root ; method returns " yes " if u is a ancestor node of v ; Driver code to test abovea methods
#include <bits/stdc++.h> NEW_LINE using namespace std ; void dfs ( vector < int > g [ ] , int u , int parent , int timeIn [ ] , int timeOut [ ] , int & cnt ) { timeIn [ u ] = cnt ++ ; for ( int i = 0 ; i < g [ u ] . size ( ) ; i ++ ) { int v = g [ u ] [ i ] ; if ( v != parent ) dfs ( g , v , u , timeIn , timeOut , cnt ) ; } timeOut [ u ] = cnt ++ ; } void preProcess ( int edges [ ] [ 2 ] , int V , int timeIn [ ] , int timeOut [ ] ) { vector < int > g [ V ] ; for ( int i = 0 ; i < V - 1 ; i ++ ) { int u = edges [ i ] [ 0 ] ; int v = edges [ i ] [ 1 ] ; g [ u ] . push_back ( v ) ; g [ v ] . push_back ( u ) ; } int cnt = 0 ; dfs ( g , 0 , -1 , timeIn , timeOut , cnt ) ; } string isAncestor ( int u , int v , int timeIn [ ] , int timeOut [ ] ) { bool b = ( timeIn [ u ] <= timeIn [ v ] && timeOut [ v ] <= timeOut [ u ] ) ; return ( b ? " yes " : " no " ) ; } int main ( ) { int edges [ ] [ 2 ] = { { 0 , 1 } , { 0 , 2 } , { 1 , 3 } , { 1 , 4 } , { 2 , 5 } , { 4 , 6 } , { 5 , 7 } } ; int E = sizeof ( edges ) / sizeof ( edges [ 0 ] ) ; int V = E + 1 ; int timeIn [ V ] , timeOut [ V ] ; preProcess ( edges , V , timeIn , timeOut ) ; int u = 1 ; int v = 6 ; cout << isAncestor ( u , v , timeIn , timeOut ) << endl ; u = 1 ; v = 7 ; cout << isAncestor ( u , v , timeIn , timeOut ) << endl ; return 0 ; }
Print path from root to a given node in a binary tree | C ++ implementation to print the path from root to a given node in a binary tree ; structure of a node of binary tree ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Returns true if there is a path from root to the given node . It also populates ' arr ' with the given path ; if root is NULL there is no path ; push the node ' s ▁ value ▁ in ▁ ' arr ' ; if it is the required node return true ; else check whether the required node lies in the left subtree or right subtree of the current node ; required node does not lie either in the left or right subtree of the current node Thus , remove current node ' s ▁ value ▁ from ▁ ▁ ▁ ' arr 'and then return false ; function to print the path from root to the given node if the node lies in the binary tree ; vector to store the path ; if required node ' x ' is present then print the path ; ' x ' is not present in the binary tree ; Driver program to test above ; binary tree formation
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; struct Node * getNode ( int data ) { struct Node * newNode = new Node ; newNode -> data = data ; newNode -> left = newNode -> right = NULL ; return newNode ; } bool hasPath ( Node * root , vector < int > & arr , int x ) { if ( ! root ) return false ; arr . push_back ( root -> data ) ; if ( root -> data == x ) return true ; if ( hasPath ( root -> left , arr , x ) || hasPath ( root -> right , arr , x ) ) return true ; arr . pop_back ( ) ; return false ; } void printPath ( Node * root , int x ) { vector < int > arr ; if ( hasPath ( root , arr , x ) ) { for ( int i = 0 ; i < arr . size ( ) - 1 ; i ++ ) cout << arr [ i ] << " - > " ; cout << arr [ arr . size ( ) - 1 ] ; } else cout << " No ▁ Path " ; } int main ( ) { struct Node * root = getNode ( 1 ) ; root -> left = getNode ( 2 ) ; root -> right = getNode ( 3 ) ; root -> left -> left = getNode ( 4 ) ; root -> left -> right = getNode ( 5 ) ; root -> right -> left = getNode ( 6 ) ; root -> right -> right = getNode ( 7 ) ; int x = 5 ; printPath ( root , x ) ; return 0 ; }
Print Ancestors of a given node in Binary Tree | C ++ program to print ancestors of given node ; A binary tree node has data , pointer to left child and a pointer to right child ; If target is present in tree , then prints the ancestors and returns true , otherwise returns false . ; base cases ; If target is present in either left or right subtree of this node , then print this node ; Else return false ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver program to test above functions ; Construct the following binary tree 1 / \ 2 3 / \ 4 5 / 7
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int data ; struct node * left ; struct node * right ; } ; bool printAncestors ( struct node * root , int target ) { if ( root == NULL ) return false ; if ( root -> data == target ) return true ; if ( printAncestors ( root -> left , target ) || printAncestors ( root -> right , target ) ) { cout << root -> data << " ▁ " ; return true ; } return false ; } struct node * newnode ( int data ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; return ( node ) ; } 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 -> left -> left -> left = newnode ( 7 ) ; printAncestors ( root , 7 ) ; getchar ( ) ; return 0 ; }
Kth ancestor of a node in binary tree | Set 2 | C ++ program to calculate Kth ancestor of given node ; A Binary Tree Node ; temporary node to keep track of Node returned from previous recursive call during backtrack ; recursive function to calculate Kth ancestor ; Base case ; print the kth ancestor ; return NULL to stop further backtracking ; return current node to previous call ; Utility function to create a new tree node ; Driver program to test above functions ; print kth ancestor of given node ; check if parent is not NULL , it means there is no Kth ancestor of the node
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; Node * temp = NULL ; Node * kthAncestorDFS ( Node * root , int node , int & k ) { if ( ! root ) return NULL ; if ( root -> data == node || ( temp = kthAncestorDFS ( root -> left , node , k ) ) || ( temp = kthAncestorDFS ( root -> right , node , k ) ) ) { if ( k > 0 ) k -- ; else if ( k == 0 ) { cout << " Kth ▁ ancestor ▁ is : ▁ " << root -> data ; return NULL ; } return root ; } } Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; int k = 2 ; int node = 5 ; Node * parent = kthAncestorDFS ( root , node , k ) ; if ( parent ) cout << " - 1" ; return 0 ; }
Succinct Encoding of Binary Tree | C ++ program to demonstrate Succinct Tree Encoding and decoding ; A Binary Tree Node ; Utility function to create new Node ; This function fills lists ' struc ' and ' data ' . ' struc ' list stores structure information . ' data ' list stores tree data ; If root is NULL , put 0 in structure array and return ; Else place 1 in structure array , key in ' data ' array and recur for left and right children ; Constructs tree from ' struc ' and ' data ' ; Remove one item from structure list ; If removed bit is 1 , ; remove an item from data list ; Create a tree node with the removed data ; And recur to create left and right subtrees ; A utility function to print tree ; Driver program ; Let us construct the Tree shown in the above figure ; Structure iterator ; Data iterator
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * left , * right ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return ( temp ) ; } void EncodeSuccinct ( Node * root , list < bool > & struc , list < int > & data ) { if ( root == NULL ) { struc . push_back ( 0 ) ; return ; } struc . push_back ( 1 ) ; data . push_back ( root -> key ) ; EncodeSuccinct ( root -> left , struc , data ) ; EncodeSuccinct ( root -> right , struc , data ) ; } Node * DecodeSuccinct ( list < bool > & struc , list < int > & data ) { if ( struc . size ( ) <= 0 ) return NULL ; bool b = struc . front ( ) ; struc . pop_front ( ) ; if ( b == 1 ) { int key = data . front ( ) ; data . pop_front ( ) ; Node * root = newNode ( key ) ; root -> left = DecodeSuccinct ( struc , data ) ; root -> right = DecodeSuccinct ( struc , data ) ; return root ; } return NULL ; } void preorder ( Node * root ) { if ( root ) { cout << " key : ▁ " << root -> key ; if ( root -> left ) cout << " ▁ | ▁ left ▁ child : ▁ " << root -> left -> key ; if ( root -> right ) cout << " ▁ | ▁ right ▁ child : ▁ " << root -> right -> key ; cout << endl ; preorder ( root -> left ) ; preorder ( root -> right ) ; } } int main ( ) { Node * root = newNode ( 10 ) ; root -> left = newNode ( 20 ) ; root -> right = newNode ( 30 ) ; root -> left -> left = newNode ( 40 ) ; root -> left -> right = newNode ( 50 ) ; root -> right -> right = newNode ( 70 ) ; cout << " Given ▁ Tree STRNEWLINE " ; preorder ( root ) ; list < bool > struc ; list < int > data ; EncodeSuccinct ( root , struc , data ) ; cout << " Encoded Tree " cout << " Structure ▁ List STRNEWLINE " ; list < bool > :: iterator si ; for ( si = struc . begin ( ) ; si != struc . end ( ) ; ++ si ) cout << * si << " ▁ " ; cout << " Data List " list < int > :: iterator di ; for ( di = data . begin ( ) ; di != data . end ( ) ; ++ di ) cout << * di << " ▁ " ; Node * newroot = DecodeSuccinct ( struc , data ) ; cout << " Preorder traversal of decoded tree " ; preorder ( newroot ) ; return 0 ; }
Binary Indexed Tree : Range Updates and Point Queries | C ++ program to demonstrate Range Update and Point Queries Without using BIT ; Updates such that getElement ( ) gets an increased value when queried from l to r . ; Get the element indexed at i ; To get ith element sum of all the elements from 0 to i need to be computed ; Driver program to test above function ; Find the element at Index 4 ; Find the element at Index 3
#include <bits/stdc++.h> NEW_LINE using namespace std ; void update ( int arr [ ] , int l , int r , int val ) { arr [ l ] += val ; arr [ r + 1 ] -= val ; } int getElement ( int arr [ ] , int i ) { int res = 0 ; for ( int j = 0 ; j <= i ; j ++ ) res += arr [ j ] ; return res ; } int main ( ) { int arr [ ] = { 0 , 0 , 0 , 0 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int l = 2 , r = 4 , val = 2 ; update ( arr , l , r , val ) ; int index = 4 ; cout << " Element ▁ at ▁ index ▁ " << index << " ▁ is ▁ " << getElement ( arr , index ) << endl ; l = 0 , r = 3 , val = 4 ; update ( arr , l , r , val ) ; index = 3 ; cout << " Element ▁ at ▁ index ▁ " << index << " ▁ is ▁ " << getElement ( arr , index ) << endl ; return 0 ; }
Binary Indexed Tree : Range Updates and Point Queries | C ++ code to demonstrate Range Update and Point Queries on a Binary Index Tree ; Updates a node in Binary Index Tree ( BITree ) at given index in BITree . The given value ' val ' is added to BITree [ i ] and all of its ancestors in tree . ; index in BITree [ ] is 1 more than the index in arr [ ] ; Traverse all ancestors and add ' val ' ; Add ' val ' to current node of BI Tree ; Update index to that of parent in update View ; Constructs and returns a Binary Indexed Tree for given array of size n . ; Create and initialize BITree [ ] as 0 ; Store the actual values in BITree [ ] using update ( ) ; SERVES THE PURPOSE OF getElement ( ) Returns sum of arr [ 0. . index ] . This function assumes that the array is preprocessed and partial sums of array elements are stored in BITree [ ] ; Iniialize result ; index in BITree [ ] is 1 more than the index in arr [ ] ; Traverse ancestors of BITree [ index ] ; Add current element of BITree to sum ; Move index to parent node in getSum View ; Return the sum ; Updates such that getElement ( ) gets an increased value when queried from l to r . ; Increase value at ' l ' by ' val ' ; Decrease value at ' r + 1' by ' val ' ; Driver program to test above function ; Add 2 to all the element from [ 2 , 4 ] ; Find the element at Index 4 ; Add 2 to all the element from [ 0 , 3 ] ; Find the element at Index 3
#include <bits/stdc++.h> NEW_LINE using namespace std ; void updateBIT ( int BITree [ ] , int n , int index , int val ) { index = index + 1 ; while ( index <= n ) { BITree [ index ] += val ; index += index & ( - index ) ; } } int * constructBITree ( int arr [ ] , int n ) { int * BITree = new int [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) BITree [ i ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) updateBIT ( BITree , n , i , arr [ i ] ) ; return BITree ; } int getSum ( int BITree [ ] , int index ) { int sum = 0 ; index = index + 1 ; while ( index > 0 ) { sum += BITree [ index ] ; index -= index & ( - index ) ; } return sum ; } void update ( int BITree [ ] , int l , int r , int n , int val ) { updateBIT ( BITree , n , l , val ) ; updateBIT ( BITree , n , r + 1 , - val ) ; } int main ( ) { int arr [ ] = { 0 , 0 , 0 , 0 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int * BITree = constructBITree ( arr , n ) ; int l = 2 , r = 4 , val = 2 ; update ( BITree , l , r , n , val ) ; int index = 4 ; cout << " Element ▁ at ▁ index ▁ " << index << " ▁ is ▁ " << getSum ( BITree , index ) << " STRNEWLINE " ; l = 0 , r = 3 , val = 4 ; update ( BITree , l , r , n , val ) ; index = 3 ; cout << " Element ▁ at ▁ index ▁ " << index << " ▁ is ▁ " << getSum ( BITree , index ) << " STRNEWLINE " ; return 0 ; }
Print Postorder traversal from given Inorder and Preorder traversals | C ++ program to print Postorder traversal from given Inorder and Preorder traversals . ; Find index of next item in preorder traversal in inorder . ; traverse left tree ; traverse right tree ; print root node at the end of traversal ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int preIndex = 0 ; void printPost ( int in [ ] , int pre [ ] , int inStrt , int inEnd , map < int , int > hm ) { if ( inStrt > inEnd ) return ; int inIndex = hm [ pre [ preIndex ++ ] ] ; printPost ( in , pre , inStrt , inIndex - 1 , hm ) ; printPost ( in , pre , inIndex + 1 , inEnd , hm ) ; cout << in [ inIndex ] << " ▁ " ; } void printPostMain ( int in [ ] , int pre [ ] , int n ) { map < int , int > hm ; for ( int i = 0 ; i < n ; i ++ ) hm [ in [ i ] ] = i ; printPost ( in , pre , 0 , n - 1 , hm ) ; } int main ( ) { int in [ ] = { 4 , 2 , 5 , 1 , 3 , 6 } ; int pre [ ] = { 1 , 2 , 4 , 5 , 3 , 6 } ; int n = sizeof ( pre ) / sizeof ( pre [ 0 ] ) ; printPostMain ( in , pre , n ) ; return 0 ; }
Coordinates of the last cell in a Matrix on which performing given operations exits from the Matrix | CPP program for the above approach ; Function to check if the indices ( i , j ) are valid indices in a Matrix or not ; Cases for invalid cells ; Return true if valid ; Function to find indices of cells of a matrix from which traversal leads to out of the matrix ; Starting from cell ( 0 , 0 ) , traverse in right direction ; Stores direction changes ; Iterate until the current cell exceeds beyond the matrix ; Current index ; If the current cell is 1 ; Update arr [ i ] [ j ] = 0 ; Update indices according to the direction ; Otherwise ; Update indices according to the direction ; The exit cooridnates ; Driver Code ; Number of rows ; Number of columns ; Given matrix arr [ ] [ ]
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool issafe ( int m , int n , int i , int j ) { if ( i < 0 ) return false ; if ( j < 0 ) return false ; if ( i >= m ) return false ; if ( j >= n ) return false ; return true ; } pair < int , int > endpoints ( vector < vector < int > > arr , int m , int n ) { int i = 0 ; int j = 0 ; int current_i = 0 ; int current_j = 0 ; char current_d = ' r ' ; map < char , char > rcd = { { ' l ' , ' u ' } , { ' u ' , ' r ' } , { ' r ' , ' d ' } , { ' d ' , ' l ' } } ; while ( issafe ( m , n , i , j ) ) { current_i = i ; current_j = j ; if ( arr [ i ] [ j ] == 1 ) { char move_in = rcd [ current_d ] ; arr [ i ] [ j ] = 0 ; if ( move_in == ' u ' ) i -= 1 ; else if ( move_in == ' d ' ) i += 1 ; else if ( move_in == ' l ' ) j -= 1 ; else if ( move_in == ' r ' ) j += 1 ; current_d = move_in ; } else { if ( current_d == ' u ' ) i -= 1 ; else if ( current_d == ' d ' ) i += 1 ; else if ( current_d == ' l ' ) j -= 1 ; else if ( current_d == ' r ' ) j += 1 ; } } return { current_i , current_j } ; } int main ( ) { int M = 3 ; int N = 5 ; vector < vector < int > > arr { { 0 , 1 , 1 , 1 , 0 } , { 1 , 0 , 1 , 0 , 1 } , { 1 , 1 , 1 , 0 , 0 } } ; pair < int , int > p = endpoints ( arr , M , N ) ; cout << " ( " << p . first << " , ▁ " << p . second << " ) " << endl ; }
Check if a number can be represented as sum of two positive perfect cubes | C ++ program for the above approach ; Function to check if N can be represented as sum of two perfect cubes or not ; Stores the perfect cubes of first N natural numbers ; Traverse the map ; Stores first number ; Stores second number ; Search the pair for the first number to obtain sum N from the Map ; If N cannot be represented as sum of two positive perfect cubes ; Driver Code ; Function call to check if N can be represented as sum of two perfect cubes or not
#include <bits/stdc++.h> NEW_LINE using namespace std ; void sumOfTwoPerfectCubes ( int N ) { map < int , int > cubes ; for ( int i = 1 ; i * i * i <= N ; i ++ ) cubes [ i * i * i ] = i ; map < int , int > :: iterator itr ; for ( itr = cubes . begin ( ) ; itr != cubes . end ( ) ; itr ++ ) { int firstNumber = itr -> first ; int secondNumber = N - itr -> first ; if ( cubes . find ( secondNumber ) != cubes . end ( ) ) { cout << " True " ; return ; } } cout << " False " ; } int main ( ) { int N = 28 ; sumOfTwoPerfectCubes ( N ) ; return 0 ; }
Count subsets consisting of each element as a factor of the next element in that subset | C ++ program for the above approach ; Function to find number of subsets satisfying the given condition ; Stores number of required sets ; Stores maximum element of arr [ ] that defines the size of sieve ; Iterate through the arr [ ] ; If current element > maxE , then update maxE ; Declare an array sieve of size N + 1 ; Mark all elements corresponding in the array , by one as there will always exists a singleton set ; Iterate from range [ 1 , N ] ; If element is present in array ; Traverse through all its multiples <= n ; Update them if they are present in array ; Iterate from the range [ 1 , N ] ; Update the value of cnt ; Print the result ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE #define mod 1000000007 NEW_LINE using namespace std ; void countSets ( int * arr , int n ) { int cnt = 0 ; int maxE = -1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( maxE < arr [ i ] ) maxE = arr [ i ] ; } int * sieve = new int [ maxE + 1 ] ; for ( int i = 0 ; i <= maxE ; i ++ ) sieve [ i ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) sieve [ arr [ i ] ] = 1 ; for ( int i = 1 ; i <= maxE ; i ++ ) { if ( sieve [ i ] != 0 ) { for ( int j = i * 2 ; j <= maxE ; j += i ) { if ( sieve [ j ] != 0 ) sieve [ j ] = ( sieve [ j ] + sieve [ i ] ) % mod ; } } } for ( int i = 0 ; i <= maxE ; i ++ ) cnt = ( cnt % mod + sieve [ i ] % mod ) % mod ; delete [ ] sieve ; cout << cnt % mod ; } int main ( ) { int arr [ ] = { 16 , 18 , 6 , 7 , 2 , 19 , 20 , 9 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countSets ( arr , N ) ; return 0 ; }
Count distinct prime factors for each element of an array | C ++ program for the above approach ; Stores smallest prime factor for every number ; Stores distinct prime factors ; Function to find the smallest prime factor of every number ; Mark the smallest prime factor of every number to itself ; Separately mark all the smallest prime factor of every even number to be 2 ; If i is prime ; Mark spf for all numbers divisible by i ; Mark spf [ j ] if it is not previously marked ; Function to find the distinct prime factors ; Push all distinct of x prime factor in v [ x ] ; Pushback into v [ i ] ; Increment the idx ; Update x = ( x / spf [ x ] ) ; Function to get the distinct factor count of arr [ ] ; Precompute the smallest Prime Factors ; For distinct prime factors Fill the v [ ] vector ; Count of Distinct Prime Factors of each array element ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100001 NEW_LINE int spf [ MAX ] ; vector < int > v [ MAX ] ; void sieve ( ) { for ( int i = 1 ; i < MAX ; i ++ ) spf [ i ] = i ; for ( int i = 4 ; i < MAX ; i = i + 2 ) spf [ i ] = 2 ; for ( int i = 3 ; i * i < MAX ; i ++ ) if ( spf [ i ] == i ) { for ( int j = i * i ; j < MAX ; j = j + i ) { if ( spf [ j ] == j ) spf [ j ] = i ; } } } void DistPrime ( ) { for ( int i = 1 ; i < MAX ; i ++ ) { int idx = 1 ; int x = i ; if ( x != 1 ) v [ i ] . push_back ( spf [ x ] ) ; x = x / spf [ x ] ; while ( x != 1 ) { if ( v [ i ] [ idx - 1 ] != spf [ x ] ) { v [ i ] . push_back ( spf [ x ] ) ; idx += 1 ; } x = x / spf [ x ] ; } } } void getFactorCount ( int arr [ ] , int N ) { sieve ( ) ; DistPrime ( ) ; for ( int i = 0 ; i < N ; i ++ ) { cout << ( int ) v [ arr [ i ] ] . size ( ) << " ▁ " ; } } int main ( ) { int arr [ ] = { 6 , 9 , 12 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; getFactorCount ( arr , N ) ; return 0 ; }
Find the first day of a given year from a base year having first day as Monday | C ++ Implementation of the above approach ; Function to find the day of 1 st January of Y year ; Count years between years Y and B ; Count leap years ; Non leap years ; Total number of days in the years lying between the years Y and B ; Actual day ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findDay ( int Y , int B ) { int lyear , rest , totaldays , day ; Y = ( Y - 1 ) - B ; lyear = Y / 4 ; rest = Y - lyear ; totaldays = ( rest * 365 ) + ( lyear * 366 ) + 1 ; day = ( totaldays % 7 ) ; if ( day == 0 ) printf ( " Monday " ) ; else if ( day == 1 ) printf ( " Tuesday " ) ; else if ( day == 2 ) printf ( " Wednesday " ) ; else if ( day == 3 ) printf ( " Thursday " ) ; else if ( day == 4 ) printf ( " Friday " ) ; else if ( day == 5 ) printf ( " Saturday " ) ; else if ( day == 6 ) printf ( " Sunday " ) ; else printf ( " INPUT ▁ YEAR ▁ IS ▁ WRONG ! " ) ; } int main ( ) { int Y = 2020 , B = 1900 ; findDay ( Y , B ) ; return 0 ; }
Queries to update array elements in a range [ L , R ] to satisfy given conditions | C ++ program to implement the above approach ; Function to print the array ; Function to perform the query in range [ L , R ] such that arr [ i ] += i - L + 1 ; Initialize array ; Traverse the query array ; Stores range in 1 - based index ; Update arr1 [ L ] ; Update arr1 [ R + 1 ] ; Update arr2 [ R + 1 ] ; Calculate prefix sum ; Traverse the array , arr2 [ ] ; Copy arr2 [ ] into arr [ ] ; Driver Code ; Given array ; Size of the array ; Stores count of query ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printArray ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { cout << arr [ i ] << " ▁ " ; } } void modifyArray ( int arr [ ] , int N , int Q [ ] [ 2 ] , int cntQuery ) { int arr1 [ N + 1 ] = { 0 } ; int arr2 [ N + 1 ] = { 0 } ; for ( int i = 0 ; i < cntQuery ; i ++ ) { int L = Q [ i ] [ 0 ] + 1 , R = Q [ i ] [ 1 ] + 1 ; arr1 [ L ] ++ ; arr1 [ R + 1 ] -- ; arr2 [ R + 1 ] -= R - L + 1 ; } for ( int i = 1 ; i <= N ; i ++ ) arr1 [ i ] += arr1 [ i - 1 ] ; for ( int i = 1 ; i <= N ; i ++ ) arr2 [ i ] += arr2 [ i - 1 ] + arr1 [ i ] ; for ( int i = 1 ; i <= N ; i ++ ) arr [ i - 1 ] = arr2 [ i ] ; printArray ( arr , N ) ; } int main ( ) { int arr [ ] = { 0 , 0 , 0 , 0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int Q [ ] [ 2 ] = { { 1 , 3 } , { 0 , 1 } } ; int cntQuery = sizeof ( Q ) / sizeof ( Q [ 0 ] ) ; modifyArray ( arr , N , Q , cntQuery ) ; return 0 ; }
Maximize product obtained by taking one element from each array of a given list | CPP program for the above approach ; Function to return the product of 2 numbers ; If any of the two numbers is None ; Otherwise , return the product ; Function to calculate maximum product by taking only one element from each array present in the list ; Find the maximum and minimum present in the current array ; If last index is reached , then return the highest ( positive ) and lowest ( negative ) values ; Store the positive and negative products returned by calculating for the remaining arrays ; Store highest positive product ; Store product of highest with negative ; Store product of lowest with positive ; Store lowest negative product ; Return the maximum positive and minimum negative product ; Driver Code ; Count of given arrays ; Given list of N arrays ; Store the maximum positive and minimum negative product possible ; Print the maximum product
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findProduct ( int number_1 , int number_2 ) { if ( number_1 == INT_MIN or number_2 == INT_MIN ) return 0 ; else return number_1 * number_2 ; } pair < int , int > calculateProduct ( vector < vector < int > > List , int index ) { int highest = * max_element ( List [ index ] . begin ( ) , List [ index ] . end ( ) ) ; int lowest = * min_element ( List [ index ] . begin ( ) , List [ index ] . end ( ) ) ; if ( index + 1 == List . size ( ) ) { if ( lowest < 0 and highest > = 0 ) return { highest , lowest } ; else if ( lowest <= 0 and highest <= 0 ) return { INT_MIN , lowest } ; else if ( lowest >= 0 and highest >= 0 ) return { highest , INT_MIN } ; } pair < int , int > temp = calculateProduct ( List , index + 1 ) ; int positive = temp . first ; int negative = temp . second ; int highPos = findProduct ( highest , positive ) ; int highNeg = findProduct ( highest , negative ) ; int lowPos = findProduct ( lowest , positive ) ; int lowNeg = findProduct ( lowest , negative ) ; if ( lowest < 0 and highest > = 0 ) return { max ( highPos , lowNeg ) , min ( highNeg , lowPos ) } ; else if ( lowest <= 0 and highest <= 0 ) return { lowNeg , lowPos } ; else if ( lowest >= 0 and highest >= 0 ) return { max ( lowPos , highPos ) , min ( lowNeg , highNeg ) } ; } int main ( ) { int N = 2 ; vector < vector < int > > arr { { -3 , -4 } , { 1 , 2 , -3 } } ; pair < int , int > ans = calculateProduct ( arr , 0 ) ; cout << ans . first << endl ; }
Reduce a number N by at most D to maximize count of trailing nines | CPP program for the above approach ; Function to find a number with maximum count of trailing nine ; Stores count of digits in n ; Stores power of 10 ; If last i digits greater than or equal to d ; Update res ; Update p10 ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE using namespace std ; void maxNumTrailNine ( int n , int d ) { int res = n ; int cntDigits = log10 ( n ) + 1 ; int p10 = 10 ; for ( int i = 1 ; i <= cntDigits ; i ++ ) { if ( n % p10 >= d ) { break ; } else { res = n - n % p10 - 1 ; } p10 = p10 * 10 ; } cout << res ; } int main ( ) { int n = 1025 , d = 6 ; maxNumTrailNine ( n , d ) ; }
Split array into minimum number of subsets such that elements of all pairs are present in different subsets at least once | C ++ program to to implement the above approach ; Function to find minimum count of ways to split the array into two subset such that elements of each pair occurs in two different subset ; Stores minimum count of ways to split array into two subset such that elements of each pair occurs in two different subset ; If N is odd ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MinimumNoOfWays ( int arr [ ] , int n ) { int mini_no_of_ways ; if ( n % 2 == 0 ) { mini_no_of_ways = n / 2 ; } else { mini_no_of_ways = n / 2 + 1 ; } return mini_no_of_ways ; } int main ( ) { int arr [ ] = { 3 , 4 , 2 , 1 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << MinimumNoOfWays ( arr , N ) ; return 0 ; }
Chocolate Distribution Problem | Set 2 | C ++ program for above approach ; Function to return minimum number of chocolates ; decreasing sequence ; add the chocolates received by that person ; end point of decreasing sequence ; val = 1 ; reset value at that index ; increasing sequence ; flat sequence ; add value of chocolates at position n - 1 ; Helper function to get sum of decreasing sequence ; value obtained from decreasing sequence also the count of values in the sequence ; assigning max of values obtained from increasing and decreasing sequences ; sum of count - 1 values & peak value sum of natural numbers : ( n * ( n + 1 ) ) / 2 ; Driver code
#include <iostream> NEW_LINE using namespace std ; int minChocolates ( int a [ ] , int n ) { int i = 0 , j = 0 ; int res = 0 , val = 1 ; while ( j < n - 1 ) { if ( a [ j ] > a [ j + 1 ] ) { j += 1 ; continue ; } if ( i == j ) res += val ; else { res += get_sum ( val , i , j ) ; } if ( a [ j ] < a [ j + 1 ] ) val += 1 ; else val = 1 ; j += 1 ; i = j ; } if ( i == j ) res += val ; else res += get_sum ( val , i , j ) ; return res ; } int get_sum ( int peak , int start , int end ) { int count = end - start + 1 ; peak = max ( peak , count ) ; int s = peak + ( ( ( count - 1 ) * count ) >> 1 ) ; return s ; } int main ( ) { int a [ ] = { 5 , 5 , 4 , 3 , 2 , 1 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << " Minimum ▁ number ▁ of ▁ chocolates ▁ = ▁ " << minChocolates ( a , n ) << " STRNEWLINE " ; return 0 ; }
Remove array elements to reduce frequency of each array element to at most K | C ++ program for the above approach ; Function to remove array elements such that frequency of each distinct array element is at most K ; Base Case ; Stores index of array element by removing the array element such that the frequency of array elements is at most K ; Traverse the array ; If j < k or arr [ i ] > arr [ j - k ] ; Update arr [ j ] ; Remove array elements ; Function to print the array ; Traverse the array ; Utility Function to remove array elements such that frequency of each distinct array element is at most K ; Print updated array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > RemoveElemArr ( vector < int > & arr , int n , int k ) { if ( n == 0 n == 1 ) return arr ; int j = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( j < k arr [ i ] > arr [ j - k ] ) { arr [ j ++ ] = arr [ i ] ; } } while ( arr . size ( ) > j ) { arr . pop_back ( ) ; } return arr ; } void printArray ( vector < int > & arr ) { for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { cout << arr [ i ] << " ▁ " ; } } void UtilRemov ( vector < int > & arr , int n , int k ) { arr = RemoveElemArr ( arr , n , k ) ; printArray ( arr ) ; } int main ( ) { vector < int > arr = { 1 , 2 , 2 , 3 , 4 , 4 , 4 , 5 , 5 } ; int k = 2 ; int n = arr . size ( ) ; UtilRemov ( arr , n , k ) ; return 0 ; }
Count pairs of equal array elements remaining after every removal | C ++ program to implement the above approach ; Function to count pairs of equal elements by removing arr [ i ] from the array ; Stores total count of pairs of equal elements ; Store frequency of each distinct array element ; Traverse the array ; Update frequency of arr [ i ] ; Traverse the map ; Stores key of an element ; Traverse the array ; Stores count of pairs of equal element by removing arr [ i ] ; Driver Code ; Given Array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void pairs_after_removing ( int arr [ ] , int N ) { int cntPairs = 0 ; unordered_map < int , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { mp [ arr [ i ] ] ++ ; } for ( auto element : mp ) { int i = element . first ; cntPairs += mp [ i ] * ( mp [ i ] - 1 ) / 2 ; } for ( int i = 0 ; i < N ; i ++ ) { int pairs_after_arr_i_removed = cntPairs + 1 - mp [ arr [ i ] ] ; cout << pairs_after_arr_i_removed << ' ▁ ' ; } return ; } int main ( ) { int arr [ ] = { 2 , 3 , 4 , 3 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; pairs_after_removing ( arr , N ) ; return 0 ; }
Modify N by adding its smallest positive divisor exactly K times | C ++ program to implement the above approach ; Function to find the smallest divisor of N greater than 1 ; If i is a divisor of N ; If N is a prime number ; Function to find the value of N by performing the operations K times ; If N is an even number ; Update N ; If N is an odd number ; Update N ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int smallestDivisorGr1 ( int N ) { for ( int i = 2 ; i <= sqrt ( N ) ; i ++ ) { if ( N % i == 0 ) { return i ; } } return N ; } int findValOfNWithOperat ( int N , int K ) { if ( N % 2 == 0 ) { N += K * 2 ; } else { N += smallestDivisorGr1 ( N ) + ( K - 1 ) * 2 ; } return N ; } int main ( ) { int N = 6 , K = 4 ; cout << findValOfNWithOperat ( N , K ) ; return 0 ; }
Partition array into minimum number of equal length subsets consisting of a single distinct value | C ++ program to implement the above approach ; Function to find the minimum count of subsets by partitioning the array with given conditions ; Store frequency of each distinct element of the array ; Traverse the array ; Update frequency of arr [ i ] ; Stores GCD of frequency of each distinct element of the array ; Update freqGCD ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int CntOfSubsetsByPartitioning ( int arr [ ] , int N ) { unordered_map < int , int > freq ; for ( int i = 0 ; i < N ; i ++ ) { freq [ arr [ i ] ] ++ ; } int freqGCD = 0 ; for ( auto i : freq ) { freqGCD = __gcd ( freqGCD , i . second ) ; } return ( N ) / freqGCD ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 4 , 3 , 2 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << CntOfSubsetsByPartitioning ( arr , N ) ; return 0 ; }
Construct a Matrix such that each cell consists of sum of adjacent elements of respective cells in given Matrix | C ++ program for the above approach ; Initialize rows and columns ; Store all 8 directions ; Function to check if a cell ( i , j ) is valid or not ; Function to find sum of adjacent cells for cell ( i , j ) ; Initialize sum ; Visit all 8 directions ; Check if cell is valid ; Return sum ; Function to print sum of adjacent elements ; Stores the resultant matrix ; Iterate each elements of matrix ; Find adjacent sum ; Driver Code ; Given matrix ; Size of matrix ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int r , c ; vector < vector < int > > dir = { { 1 , 0 } , { -1 , 0 } , { 0 , 1 } , { 0 , -1 } , { -1 , -1 } , { -1 , 1 } , { 1 , 1 } , { 1 , -1 } } ; bool valid ( int i , int j ) { if ( i >= 0 && j >= 0 && i < r && j < c ) return 1 ; return 0 ; } int find ( int i , int j , vector < vector < int > > & v ) { int s = 0 ; for ( auto x : dir ) { int ni = i + x [ 0 ] , nj = j + x [ 1 ] ; if ( valid ( ni , nj ) ) s += v [ ni ] [ nj ] ; } return s ; } void findsumofneighbors ( vector < vector < int > > & M ) { vector < vector < int > > v ( r , vector < int > ( c , 0 ) ) ; for ( int i = 0 ; i < r ; i ++ ) { for ( int j = 0 ; j < c ; j ++ ) { v [ i ] [ j ] = find ( i , j , M ) ; cout << v [ i ] [ j ] << " ▁ " ; } cout << " STRNEWLINE " ; } } int main ( ) { vector < vector < int > > M = { { 1 , 4 , 1 } , { 2 , 4 , 5 } , { 3 , 1 , 2 } } ; r = M . size ( ) , c = M [ 0 ] . size ( ) ; findsumofneighbors ( M ) ; }
Nth term of a recurrence relation generated by two given arrays | C ++ program for the above approach ; Declare T [ ] [ ] as global matrix ; Result matrix ; Function to multiply two matrices ; Create an auxiliary matrix to store elements of the multiplication matrix ; Iterate over range [ 0 , K ] ; Update temp [ i ] [ j ] ; Update the final matrix ; Function to multiply two matrices ; Create an auxiliary matrix to store elements of the multiplication matrix ; Iterate over range [ 0 , K ] ; Update temp [ i ] [ j ] ; Update the final matrix ; Function to calculate matrix ^ n using binary exponentaion ; Initialize result matrix and unity matrix ; Function to calculate nth term of general recurrence ; Fill T [ ] [ ] with appropriate value ; Function Call to calculate T ^ n ; Calculate nth term as first element of F * ( T ^ n ) ; Print the result ; Driver Code ; Given Initial terms ; Given coefficients ; Given K ; Given N ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int mod = 1e9 + 7 ; int T [ 2000 ] [ 2000 ] ; int result [ 2000 ] [ 2000 ] ; void mul_2 ( int K ) { int temp [ K + 1 ] [ K + 1 ] ; memset ( temp , 0 , sizeof temp ) ; for ( int i = 1 ; i <= K ; i ++ ) { for ( int j = 1 ; j <= K ; j ++ ) { for ( int k = 1 ; k <= K ; k ++ ) { temp [ i ] [ j ] = ( temp [ i ] [ j ] + ( T [ i ] [ k ] * T [ k ] [ j ] ) % mod ) % mod ; } } } for ( int i = 1 ; i <= K ; i ++ ) { for ( int j = 1 ; j <= K ; j ++ ) { T [ i ] [ j ] = temp [ i ] [ j ] ; } } } void mul_1 ( int K ) { int temp [ K + 1 ] [ K + 1 ] ; memset ( temp , 0 , sizeof temp ) ; for ( int i = 1 ; i <= K ; i ++ ) { for ( int j = 1 ; j <= K ; j ++ ) { for ( int k = 1 ; k <= K ; k ++ ) { temp [ i ] [ j ] = ( temp [ i ] [ j ] + ( result [ i ] [ k ] * T [ k ] [ j ] ) % mod ) % mod ; } } } for ( int i = 1 ; i <= K ; i ++ ) { for ( int j = 1 ; j <= K ; j ++ ) { result [ i ] [ j ] = temp [ i ] [ j ] ; } } } void matrix_pow ( int K , int n ) { for ( int i = 1 ; i <= K ; i ++ ) { for ( int j = 1 ; j <= K ; j ++ ) { if ( i == j ) result [ i ] [ j ] = 1 ; } } while ( n > 0 ) { if ( n % 2 == 1 ) mul_1 ( K ) ; mul_2 ( K ) ; n /= 2 ; } } int NthTerm ( int F [ ] , int C [ ] , int K , int n ) { for ( int i = 1 ; i <= K ; i ++ ) T [ i ] [ K ] = C [ K - i ] ; for ( int i = 1 ; i <= K ; i ++ ) T [ i + 1 ] [ i ] = 1 ; matrix_pow ( K , n ) ; int answer = 0 ; for ( int i = 1 ; i <= K ; i ++ ) { answer += F [ i - 1 ] * result [ i ] [ 1 ] ; } cout << answer << endl ; return 0 ; } int main ( ) { int F [ ] = { 1 , 2 , 3 } ; int C [ ] = { 1 , 1 , 1 } ; int K = 3 ; int N = 10 ; NthTerm ( F , C , K , N ) ; return 0 ; }
Calculate Root Mean Kth power of all array elements | C ++ program for the above approach ; Function to find the Nth root ; Initially guessing random numberbetween 0 and 9 ; Smaller eps for more accuracy ; Initialize difference between the two roots by INT_MAX ; xK denotes current value of x ; Iterate until desired accuracy is reached ; Find the current value from previous value by newton 's method ; Function to calculate the Root Mean kth power of array elements ; Calculate sum of kth power ; Calculate Mean ; Calculate kth Root of mean ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; double nthRoot ( int A , int N ) { double xPre = rand ( ) % 10 ; double eps = 1e-3 ; double delX = INT_MAX ; double xK ; while ( delX > eps ) { xK = ( ( N - 1.0 ) * xPre + ( double ) A / pow ( xPre , N - 1 ) ) / ( double ) N ; delX = abs ( xK - xPre ) ; xPre = xK ; } return xK ; } float RMNValue ( int arr [ ] , int n , int k ) { int Nth = 0 ; float mean = 0.0 , root = 0.0 ; for ( int i = 0 ; i < n ; i ++ ) { Nth += pow ( arr [ i ] , k ) ; } mean = ( Nth / ( float ) ( n ) ) ; root = nthRoot ( mean , k ) ; return root ; } int main ( ) { int arr [ ] = { 10 , 4 , 6 , 8 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; cout << RMNValue ( arr , N , K ) ; return 0 ; }
Add two numbers represented by Stacks | C ++ program to implement the above approach ; Function to return the stack that contains the sum of two numbers ; Calculate the sum of the top elements of both the stacks ; Push the sum into the stack ; Store the carry ; Pop the top elements ; If N1 is not empty ; If N2 is not empty ; If carry remains ; Reverse the stack . so that most significant digit is at the bottom of the stack ; Function to display the resultamt stack ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; stack < int > addStack ( stack < int > N1 , stack < int > N2 ) { stack < int > res ; int sum = 0 , rem = 0 ; while ( ! N1 . empty ( ) and ! N2 . empty ( ) ) { sum = ( rem + N1 . top ( ) + N2 . top ( ) ) ; res . push ( sum % 10 ) ; rem = sum / 10 ; N1 . pop ( ) ; N2 . pop ( ) ; } while ( ! N1 . empty ( ) ) { sum = ( rem + N1 . top ( ) ) ; res . push ( sum % 10 ) ; rem = sum / 10 ; N1 . pop ( ) ; } while ( ! N2 . empty ( ) ) { sum = ( rem + N2 . top ( ) ) ; res . push ( sum % 10 ) ; rem = sum / 10 ; N2 . pop ( ) ; } while ( rem > 0 ) { res . push ( rem ) ; rem /= 10 ; } while ( ! res . empty ( ) ) { N1 . push ( res . top ( ) ) ; res . pop ( ) ; } res = N1 ; return res ; } void display ( stack < int > & res ) { int N = res . size ( ) ; string s = " " ; while ( ! res . empty ( ) ) { s = to_string ( res . top ( ) ) + s ; res . pop ( ) ; } cout << s << endl ; } int main ( ) { stack < int > N1 ; N1 . push ( 5 ) ; N1 . push ( 8 ) ; N1 . push ( 7 ) ; N1 . push ( 4 ) ; stack < int > N2 ; N2 . push ( 2 ) ; N2 . push ( 1 ) ; N2 . push ( 3 ) ; stack < int > res = addStack ( N1 , N2 ) ; display ( res ) ; return 0 ; }
Check if a number has an odd count of odd divisors and even count of even divisors | C ++ implementation of the above approach ; Function to check if the number is a perfect square ; Find floating point value of square root of x . ; If square root is an integer ; Function to check if count of even divisors is even and count of odd divisors is odd ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define lli long long int NEW_LINE bool isPerfectSquare ( long double x ) { long double sr = sqrt ( x ) ; return ( ( sr - floor ( sr ) ) == 0 ) ; } void checkFactors ( lli N ) { if ( isPerfectSquare ( N ) ) cout << " Yes " << endl ; else cout << " No " << endl ; } int main ( ) { lli N = 36 ; checkFactors ( N ) ; return 0 ; }
Queries to find the XOR of an Array after replacing all occurrences of X by Y | C ++ Program to implement the above approach ; Stores the bitwise XOR of array elements ; Function to find the total xor ; Loop to find the xor of all the elements ; Function to find the XOR after replacing all occurrences of X by Y for Q queries ; Remove contribution of X from total_xor ; Adding contribution of Y to total_xor ; Print total_xor ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int total_xor ; void initialize_xor ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { total_xor = total_xor ^ arr [ i ] ; } } void find_xor ( int X , int Y ) { total_xor = total_xor ^ X ; total_xor = total_xor ^ Y ; cout << total_xor << " STRNEWLINE " ; } int main ( ) { int arr [ ] = { 5 , 7 , 8 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; initialize_xor ( arr , n ) ; vector < vector < int > > Q = { { 5 , 6 } , { 8 , 1 } } ; for ( int i = 0 ; i < Q . size ( ) ; i ++ ) { find_xor ( Q [ i ] [ 0 ] , Q [ i ] [ 1 ] ) ; } return 0 ; }
Check whether a given number is an ugly number or not | C ++ implementation to check if a number is an ugly number or not ; Function to check if a number is an ugly number or not ; Base Cases ; Condition to check if the number is divided by 2 , 3 , or 5 ; Driver Code
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int isUgly ( int n ) { if ( n == 1 ) return 1 ; if ( n <= 0 ) return 0 ; if ( n % 2 == 0 ) { return ( isUgly ( n / 2 ) ) ; } if ( n % 3 == 0 ) { return ( isUgly ( n / 3 ) ) ; } if ( n % 5 == 0 ) { return ( isUgly ( n / 5 ) ) ; } return 0 ; } int main ( ) { int no = isUgly ( 14 ) ; if ( no == 1 ) printf ( " Yes " ) ; else printf ( " No " ) ; return 0 ; }
Maximum possible GCD for a pair of integers with sum N | C ++ Program to find the maximum possible GCD of any pair with sum N ; Function to find the required GCD value ; If i is a factor of N ; Return the largest factor possible ; If N is a prime number ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxGCD ( int N ) { for ( int i = 2 ; i * i <= N ; i ++ ) { if ( N % i == 0 ) { return N / i ; } } return 1 ; } int main ( ) { int N = 33 ; cout << " Maximum ▁ Possible ▁ GCD ▁ value ▁ is ▁ : ▁ " << maxGCD ( N ) << endl ; return 0 ; }
Minimize K whose XOR with given array elements leaves array unchanged | C ++ program for the above approach ; Function to find the minimum value of K in given range ; Declare a set ; Initialize count variable ; Iterate in range [ 1 , 1024 ] ; counter set as 0 ; Iterating through the Set ; Check if the XOR calculated is present in the Set ; If the value of Bitwise XOR inside the given set then increment count ; Check if the value of count is equal to the size of set ; Return minimum value of K ; If no such K is found ; Driver Code ; Given array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int min_value ( int arr [ ] , int N ) { int x , X , K ; set < int > S ; for ( int i = 0 ; i < N ; i ++ ) { S . insert ( arr [ i ] ) ; } int count = 0 ; for ( int i = 1 ; i <= 1024 ; i ++ ) { count = 0 ; for ( auto it = S . begin ( ) ; it != S . end ( ) ; it ++ ) { X = ( ( i * it ) - ( i & * it ) ) ; if ( S . find ( X ) != S . end ( ) ) { count ++ ; } } if ( count == S . size ( ) ) { K = i ; return K ; } } return -1 ; } int main ( ) { int arr [ ] = { 1 , 0 , 3 , 3 , 0 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << min_value ( arr , N ) ; return 0 ; }
Junction Numbers | C ++ implementation for the above approach ; Function to find the sum Of digits of N ; To store sum of N and sumOfdigitsof ( N ) ; extracting digit ; Function to check Junction numbers ; To store count of ways n can be represented as i + SOD ( i ) ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sum ( int n ) { int sum = 0 ; while ( n != 0 ) { int r = n % 10 ; sum = sum + r ; n = n / 10 ; } return sum ; } bool isJunction ( int n ) { int count = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { if ( i + sum ( i ) == n ) count ++ ; } return count >= 2 ; } int main ( ) { int N = 111 ; if ( isJunction ( N ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Pointer | C ++ implementation for the above approach ; Function to find the product of digits of a number N ; Function that returns true if n is prime else returns false ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to return the smallest prime number greater than N ; Base case ; Loop continuously until isPrime returns true for a number greater than n ; Function to check Pointer - Prime numbers ; Driver Code ; Given Number N ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int digProduct ( int n ) { int product = 1 ; while ( n != 0 ) { product = product * ( n % 10 ) ; n = n / 10 ; } return product ; } bool isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; return true ; } int nextPrime ( int N ) { if ( N <= 1 ) return 2 ; int prime = N ; bool found = false ; while ( ! found ) { prime ++ ; if ( isPrime ( prime ) ) found = true ; } return prime ; } bool isPointerPrime ( int n ) { if ( isPrime ( n ) && ( n + digProduct ( n ) == nextPrime ( n ) ) ) return true ; else return false ; } int main ( ) { int N = 23 ; if ( isPointerPrime ( N ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Perfect Digital Invariants number | C ++ program for the above approach ; Function to calculate x raised to the power y ; Function to check whether the given number is Perfect Digital Invariant number or not ; For each digit in temp ; If satisfies Perfect Digital Invariant condition ; If sum exceeds n , then not possible ; Driver Code ; Given Number N ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int power ( int x , unsigned int y ) { if ( y == 0 ) { return 1 ; } if ( y % 2 == 0 ) { return ( power ( x , y / 2 ) * power ( x , y / 2 ) ) ; } return ( x * power ( x , y / 2 ) * power ( x , y / 2 ) ) ; } bool isPerfectDigitalInvariant ( int x ) { for ( int fixed_power = 1 ; ; fixed_power ++ ) { int temp = x , sum = 0 ; while ( temp ) { int r = temp % 10 ; sum += power ( r , fixed_power ) ; temp = temp / 10 ; } if ( sum == x ) { return true ; } if ( sum > x ) { return false ; } } } int main ( ) { int N = 4150 ; if ( isPerfectDigitalInvariant ( N ) ) cout << " Yes " ; else cout << " No " ; }
Brilliant Numbers | C ++ implementation for the above approach ; Function to generate all prime numbers less than n ; Initialize all entries of boolean array as true . A value in isPrime [ i ] will finally be false if i is Not a prime ; If isPrime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Function to return the number of digits in a number ; Function to check if N is a Brilliant number ; Generating primes using Sieve ; Traversing all numbers to find first pair ; Driver Code ; Given Number ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool SieveOfEratosthenes ( int n , bool isPrime [ ] ) { isPrime [ 0 ] = isPrime [ 1 ] = false ; for ( int i = 2 ; i <= n ; i ++ ) isPrime [ i ] = true ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( isPrime [ p ] == true ) { for ( int i = p * 2 ; i <= n ; i += p ) isPrime [ i ] = false ; } } } int countDigit ( long long n ) { return floor ( log10 ( n ) + 1 ) ; } bool isBrilliant ( int n ) { int flag = 0 ; bool isPrime [ n + 1 ] ; SieveOfEratosthenes ( n , isPrime ) ; for ( int i = 2 ; i < n ; i ++ ) { int x = n / i ; if ( isPrime [ i ] && isPrime [ x ] and x * i == n ) { if ( countDigit ( i ) == countDigit ( x ) ) return true ; } } return false ; } int main ( ) { int n = 1711 ; if ( isBrilliant ( n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }