text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Check if a number exists having exactly N factors and K prime factors | C ++ program to check if it is possible to make a number having total N factors and K prime factors ; Function to compute the number of factors of the given number ; Vector to store the prime factors ; While there are no two multiples in the number , divide it by 2 ; If the size is already greater than K , then return true ; Computing the remaining divisors of the number ; If n is divisible by i , then it is a divisor ; If the size is already greater than K , then return true ; If the size is already greater than K , then return true ; If none of the above conditions satisfies , then return false ; Function to check if it is possible to make a number having total N factors and K prime factors ; If total divisors are less than the number of prime divisors , then print No ; Find the number of factors of n ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool factors ( int n , int k ) { vector < int > v ; while ( n % 2 == 0 ) { v . push_back ( 2 ) ; n /= 2 ; } if ( v . size ( ) >= k ) return true ; for ( int i = 3 ; i * i <= n ; i += 2 ) { while ( n % i == 0 ) { n = n / i ; v . push_back ( i ) ; } if ( v . size ( ) >= k ) return true ; } if ( n > 2 ) v . push_back ( n ) ; if ( v . size ( ) >= k ) return true ; return false ; } void operation ( int n , int k ) { bool answered = false ; if ( n < k ) { answered = true ; cout << " No " << " STRNEWLINE " ; } bool ok = factors ( n , k ) ; if ( ! ok && ! answered ) { answered = true ; cout << " No " << " STRNEWLINE " ; } if ( ok && ! answered ) cout << " Yes " << " STRNEWLINE " ; } int main ( ) { int n = 4 ; int k = 2 ; operation ( n , k ) ; return 0 ; }
To Generate a One Time Password or Unique Identification URL | A C / C ++ Program to generate OTP ( One Time Password ) ; A Function to generate a unique OTP everytime ; All possible characters of my OTP ; String to hold my OTP ; Driver Program to test above functions ; For different values each time we run the code ; Declare the length of OTP
#include <bits/stdc++.h> NEW_LINE using namespace std ; string generateOTP ( int len ) { string str = " abcdefghijklmnopqrstuvwxyzABCD " " EFGHIJKLMNOPQRSTUVWXYZ0123456789" ; int n = str . length ( ) ; string OTP ; for ( int i = 1 ; i <= len ; i ++ ) OTP . push_back ( str [ rand ( ) % n ] ) ; return ( OTP ) ; } int main ( ) { srand ( time ( NULL ) ) ; int len = 6 ; printf ( " Your ▁ OTP ▁ is ▁ - ▁ % s " , generateOTP ( len ) . c_str ( ) ) ; return ( 0 ) ; }
No of Factors of n ! | C ++ program to count number of factors of n ; Sieve of Eratosthenes to mark all prime number in array prime as 1 ; Initialize all numbers as prime ; Mark composites ; Returns the highest exponent of p in n ! ; Returns the no of factors in n ! ; ans stores the no of factors in n ! ; Find all primes upto n ; Multiply exponent ( of primes ) added with 1 ; if p is a prime then p is also a prime factor of n ! ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; typedef long long int ll ; void sieve ( int n , bool prime [ ] ) { for ( int i = 1 ; i <= n ; i ++ ) prime [ i ] = 1 ; prime [ 1 ] = 0 ; for ( int i = 2 ; i * i <= n ; i ++ ) { if ( prime [ i ] ) { for ( int j = i * i ; j <= n ; j += i ) prime [ j ] = 0 ; } } } int expFactor ( int n , int p ) { int x = p ; int exponent = 0 ; while ( ( n / x ) > 0 ) { exponent += n / x ; x *= p ; } return exponent ; } ll countFactors ( int n ) { ll ans = 1 ; bool prime [ n + 1 ] ; sieve ( n , prime ) ; for ( int p = 1 ; p <= n ; p ++ ) { if ( prime [ p ] == 1 ) ans *= ( expFactor ( n , p ) + 1 ) ; } return ans ; } int main ( ) { int n = 16 ; printf ( " Count ▁ of ▁ factors ▁ of ▁ % d ! ▁ is ▁ % lld STRNEWLINE " , n , countFactors ( n ) ) ; return 0 ; }
LCM of given array elements | ; recursive implementation ; lcm ( a , b ) = ( a * b / gcd ( a , b ) ) ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int LcmOfArray ( vector < int > arr , int idx ) { if ( idx == arr . size ( ) - 1 ) { return arr [ idx ] ; } int a = arr [ idx ] ; int b = LcmOfArray ( arr , idx + 1 ) ; return ( a * b / __gcd ( a , b ) ) ; } int main ( ) { vector < int > arr = { 1 , 2 , 8 , 3 } ; cout << LcmOfArray ( arr , 0 ) << " STRNEWLINE " ; arr = { 2 , 7 , 3 , 9 , 4 } ; cout << LcmOfArray ( arr , 0 ) << " STRNEWLINE " ; return 0 ; }
Check if a number is a power of another number | C ++ program to check if a number is power of another number ; Returns 1 if y is a power of x ; The only power of 1 is 1 itself ; Repeatedly comput power of x ; Check if power of x becomes y ; Driver program to test above function ; check the result for true / false and print
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPower ( int x , long int y ) { if ( x == 1 ) return ( y == 1 ) ; long int pow = 1 ; while ( pow < y ) pow *= x ; return ( pow == y ) ; } int main ( ) { check the result for true / false and print cout << isPower ( 10 , 1 ) << endl ; cout << isPower ( 1 , 20 ) << endl ; cout << isPower ( 2 , 128 ) << endl ; cout << isPower ( 2 , 30 ) << endl ; return 0 ; }
Number of perfect squares between two given numbers | An Efficient Method to count squares between a and b ; An efficient solution to count square between a and b ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSquares ( int a , int b ) { return ( floor ( sqrt ( b ) ) - ceil ( sqrt ( a ) ) + 1 ) ; } int main ( ) { int a = 9 , b = 25 ; cout << " Count ▁ of ▁ squares ▁ is ▁ " << countSquares ( a , b ) ; return 0 ; }
Count positive integers with 0 as a digit and maximum ' d ' digits | C ++ program to find the count of natural numbers upto a given number of digits that contain atleast one zero ; Utility function to calculate the count of natural numbers upto a given number of digits that contain atleast one zero ; Sum of two GP series ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findCountUpto ( int d ) { int GP1_Sum = 9 * ( ( pow ( 10 , d ) - 1 ) / 9 ) ; int GP2_Sum = 9 * ( ( pow ( 9 , d ) - 1 ) / 8 ) ; return GP1_Sum - GP2_Sum ; } int main ( ) { int d = 1 ; cout << findCountUpto ( d ) << endl ; d = 2 ; cout << findCountUpto ( d ) << endl ; d = 4 ; cout << findCountUpto ( d ) << endl ; return 0 ; }
Check if count of divisors is even or odd | Naive Solution to find if count of divisors is even or odd ; Function to count the divisors ; Initialize count of divisors ; Note that this loop runs till square root ; If divisors are equal increment count by one Otherwise increment count by 2 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countDivisors ( int n ) { int count = 0 ; for ( int i = 1 ; i <= sqrt ( n ) + 1 ; i ++ ) { if ( n % i == 0 ) count += ( n / i == i ) ? 1 : 2 ; } if ( count % 2 == 0 ) cout << " Even " << endl ; else cout << " Odd " << endl ; } int main ( ) { cout << " The ▁ count ▁ of ▁ divisor : ▁ " ; countDivisors ( 10 ) ; return 0 ; }
Gray to Binary and Binary to Gray conversion | C ++ program for above approach ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int greyConverter ( int n ) { return n ^ ( n >> 1 ) ; } int main ( ) { int n = 3 ; cout << greyConverter ( n ) << endl ; n = 9 ; cout << greyConverter ( n ) << endl ; return 0 ; }
Compute n ! under modulo p | C ++ program to Returns n % p using Sieve of Eratosthenes ; Returns largest power of p that divides n ! ; Initialize result ; Calculate x = n / p + n / ( p ^ 2 ) + n / ( p ^ 3 ) + ... . ; Utility function to do modular exponentiation . It returns ( x ^ y ) % p ; Initialize result Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 ; y = y / 2 ; Returns n ! % p ; Use Sieve of Eratosthenes to find all primes smaller than n ; Consider all primes found by Sieve ; Find the largest power of prime ' i ' that divides n ; Multiply result with ( i ^ k ) % p ; Driver method
#include <bits/stdc++.h> NEW_LINE using namespace std ; int largestPower ( int n , int p ) { int x = 0 ; while ( n ) { n /= p ; x += n ; } return x ; } int power ( int x , int y , int p ) { int res = 1 ; x = x % p ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return res ; } int modFact ( int n , int p ) { if ( n >= p ) return 0 ; int res = 1 ; bool isPrime [ n + 1 ] ; memset ( isPrime , 1 , sizeof ( isPrime ) ) ; for ( int i = 2 ; i * i <= n ; i ++ ) { if ( isPrime [ i ] ) { for ( int j = 2 * i ; j <= n ; j += i ) isPrime [ j ] = 0 ; } } for ( int i = 2 ; i <= n ; i ++ ) { if ( isPrime [ i ] ) { int k = largestPower ( n , i ) ; res = ( res * power ( i , k , p ) ) % p ; } } return res ; } int main ( ) { int n = 25 , p = 29 ; cout << modFact ( n , p ) ; return 0 ; }
Count number of squares in a rectangle | C ++ program to count squares in a rectangle of size m x n ; Returns count of all squares in a rectangle of size m x n ; If n is smaller , swap m and n ; Now n is greater dimension , apply formula ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int countSquares ( int m , int n ) { if ( n < m ) swap ( m , n ) ; return m * ( m + 1 ) * ( 2 * m + 1 ) / 6 + ( n - m ) * m * ( m + 1 ) / 2 ; } int main ( ) { int m = 4 , n = 3 ; cout << " Count ▁ of ▁ squares ▁ is ▁ " << countSquares ( m , n ) ; }
Add two numbers using ++ and / or | C ++ program to add two numbers using ++ ; Returns value of x + y without using + ; If y is positive , y times add 1 to x ; If y is negative , y times subtract 1 from x ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int add ( int x , int y ) { while ( y > 0 && y -- ) x ++ ; while ( y < 0 && y ++ ) x -- ; return x ; } int main ( ) { cout << add ( 43 , 23 ) << endl ; cout << add ( 43 , -23 ) << endl ; return 0 ; }
Count factorial numbers in a given range | Program to count factorial numbers in given range ; Function to count factorial ; Find the first factorial number ' fact ' greater than or equal to ' low ' ; Count factorial numbers in range [ low , high ] ; Return the count ; Driver program to test above function
#include <iostream> NEW_LINE using namespace std ; int countFact ( int low , int high ) { int fact = 1 , x = 1 ; while ( fact < low ) { fact = fact * x ; x ++ ; } int res = 0 ; while ( fact <= high ) { res ++ ; fact = fact * x ; x ++ ; } return res ; } int main ( ) { cout << " Count ▁ is ▁ " << countFact ( 2 , 720 ) ; return 0 ; }
Find number of days between two given dates | C ++ program two find number of days between two given dates ; A date has day ' d ' , month ' m ' and year ' y ' ; To store number of days in all months from January to Dec . ; This function counts number of leap years before the given date ; Check if the current year needs to be considered for the count of leap years or not ; An year is a leap year if it is a multiple of 4 , multiple of 400 and not a multiple of 100. ; This function returns number of days between two given dates ; initialize count using years and day ; Add days for months in given date ; Since every leap year is of 366 days , Add a day for every leap year ; SIMILARLY , COUNT TOTAL NUMBER OF DAYS BEFORE ' dt2' ; return difference between two counts ; Driver code ; Function call
#include <iostream> NEW_LINE using namespace std ; struct Date { int d , m , y ; } ; const int monthDays [ 12 ] = { 31 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 } ; int countLeapYears ( Date d ) { int years = d . y ; if ( d . m <= 2 ) years -- ; return years / 4 - years / 100 + years / 400 ; } int getDifference ( Date dt1 , Date dt2 ) { long int n1 = dt1 . y * 365 + dt1 . d ; for ( int i = 0 ; i < dt1 . m - 1 ; i ++ ) n1 += monthDays [ i ] ; n1 += countLeapYears ( dt1 ) ; long int n2 = dt2 . y * 365 + dt2 . d ; for ( int i = 0 ; i < dt2 . m - 1 ; i ++ ) n2 += monthDays [ i ] ; n2 += countLeapYears ( dt2 ) ; return ( n2 - n1 ) ; } int main ( ) { Date dt1 = { 1 , 2 , 2000 } ; Date dt2 = { 1 , 2 , 2004 } ; cout << " Difference ▁ between ▁ two ▁ dates ▁ is ▁ " << getDifference ( dt1 , dt2 ) ; return 0 ; }
Find length of period in decimal value of 1 / n | C ++ program to find length of period of 1 / n without using map or hash ; Function to find length of period in 1 / n ; Find the ( n + 1 ) th remainder after decimal point in value of 1 / n ; Store ( n + 1 ) th remainder ; Count the number of remainders before next occurrence of ( n + 1 ) ' th ▁ remainder ▁ ' d ' ; Driver program to test above function
#include <iostream> NEW_LINE using namespace std ; int getPeriod ( int n ) { int rem = 1 ; for ( int i = 1 ; i <= n + 1 ; i ++ ) rem = ( 10 * rem ) % n ; int d = rem ; int count = 0 ; do { rem = ( 10 * rem ) % n ; count ++ ; } while ( rem != d ) ; return count ; } int main ( ) { cout << getPeriod ( 3 ) << endl ; cout << getPeriod ( 7 ) << endl ; return 0 ; }
Replace all Γ’ β‚¬Λœ 0 Γ’ €ℒ with Γ’ β‚¬Λœ 5 Γ’ €ℒ in an input Integer | ; Returns the number to be added to the input to replace all zeroes with five ; Amount to be added ; Unit decimal place ; A number divisible by 10 , then this is a zero occurrence in the input ; Move one decimal place ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calculateAddedValue ( int number ) { int result = 0 ; int decimalPlace = 1 ; if ( number == 0 ) { result += ( 5 * decimalPlace ) ; } while ( number > 0 ) { if ( number % 10 == 0 ) { result += ( 5 * decimalPlace ) ; } number /= 10 ; decimalPlace *= 10 ; } return result ; } int replace0with5 ( int number ) { return number += calculateAddedValue ( number ) ; } int main ( ) { cout << replace0with5 ( 1020 ) ; }
Program to find remainder without using modulo or % operator | C ++ program to find remainder without using modulo operator ; This function returns remainder of num / divisor without using % ( modulo ) operator ; Driver program to test above functions
#include <iostream> NEW_LINE using namespace std ; int getRemainder ( int num , int divisor ) { return ( num - divisor * ( num / divisor ) ) ; } int main ( ) { cout << getRemainder ( 100 , 7 ) ; return 0 ; }
Efficient Program to Compute Sum of Series 1 / 1 ! + 1 / 2 ! + 1 / 3 ! + 1 / 4 ! + . . + 1 / n ! | A simple C ++ program to compute sum of series 1 / 1 ! + 1 / 2 ! + . . + 1 / n ! ; An Efficient Function to return value of 1 / 1 ! + 1 / 2 ! + . . + 1 / n ! ; Update factorial ; Update series sum ; Driver program to test above functions
#include <iostream> NEW_LINE using namespace std ; double sum ( int n ) { double sum = 0 ; int fact = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { fact *= i ; sum += 1.0 / fact ; } return sum ; } int main ( ) { int n = 5 ; cout << sum ( n ) ; return 0 ; }
Print first k digits of 1 / n where n is a positive integer | CPP code to Print first k digits of 1 / n where n is a positive integer ; Function to print first k digits after dot in value of 1 / n . n is assumed to be a positive integer . ; Initialize remainder ; Run a loop k times to print k digits ; The next digit can always be obtained as doing ( 10 * rem ) / 10 ; Update remainder ; Driver program to test above function
#include <iostream> NEW_LINE using namespace std ; void print ( int n , int k ) { int rem = 1 ; for ( int i = 0 ; i < k ; i ++ ) { cout << ( 10 * rem ) / n ; rem = ( 10 * rem ) % n ; } } int main ( ) { int n = 7 , k = 3 ; print ( n , k ) ; cout << endl ; n = 21 , k = 4 ; print ( n , k ) ; return 0 ; }
Program to find sum of series 1 + 1 / 2 + 1 / 3 + 1 / 4 + . . + 1 / n | C ++ program to find sum of series ; Function to return sum of 1 / 1 + 1 / 2 + 1 / 3 + . . + 1 / n ; Driver code
#include <iostream> NEW_LINE using namespace std ; class gfg { public : double sum ( int n ) { double i , s = 0.0 ; for ( i = 1 ; i <= n ; i ++ ) s = s + 1 / i ; return s ; } } ; int main ( ) { gfg g ; int n = 5 ; cout << " Sum ▁ is ▁ " << g . sum ( n ) ; return 0 ; }
Program to find GCD or HCF of two numbers | C ++ program to find GCD of two numbers ; Recursive function to return gcd of a and b ; Driver program to test above function
#include <iostream> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } int main ( ) { int a = 98 , b = 56 ; cout << " GCD ▁ of ▁ " << a << " ▁ and ▁ " << b << " ▁ is ▁ " << gcd ( a , b ) ; return 0 ; }
Rearrange an array so that arr [ i ] becomes arr [ arr [ i ] ] with O ( 1 ) extra space | ; The function to rearrange an array in - place so that arr [ i ] becomes arr [ arr [ i ] ] . ; First step : Increase all values by ( arr [ arr [ i ] ] % n ) * n ; Second Step : Divide all values by n ; A utility function to print an array of size n ; Driver program to test above functions
#include <iostream> NEW_LINE using namespace std ; void rearrange ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) arr [ i ] += ( arr [ arr [ i ] ] % n ) * n ; for ( int i = 0 ; i < n ; i ++ ) arr [ i ] /= n ; } void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; cout << endl ; } int main ( ) { int arr [ ] = { 3 , 2 , 0 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Given ▁ array ▁ is ▁ STRNEWLINE " ; printArr ( arr , n ) ; rearrange ( arr , n ) ; cout << " Modified ▁ array ▁ is ▁ STRNEWLINE " ; printArr ( arr , n ) ; return 0 ; }
Print all sequences of given length | C ++ program of above approach ; A utility function that prints a given arr [ ] of length size ; The core function that recursively generates and prints all sequences of length k ; A function that uses printSequencesRecur ( ) to prints all sequences from 1 , 1 , . .1 to n , n , . . n ; Driver Program to test above functions
#include <iostream> NEW_LINE using namespace std ; void printArray ( int arr [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) cout << " ▁ " << arr [ i ] ; cout << " STRNEWLINE " ; return ; } void printSequencesRecur ( int arr [ ] , int n , int k , int index ) { int i ; if ( k == 0 ) { printArray ( arr , index ) ; } if ( k > 0 ) { for ( i = 1 ; i <= n ; ++ i ) { arr [ index ] = i ; printSequencesRecur ( arr , n , k - 1 , index + 1 ) ; } } } void printSequences ( int n , int k ) { int * arr = new int [ k ] ; printSequencesRecur ( arr , n , k , 0 ) ; return ; } int main ( ) { int n = 3 ; int k = 2 ; printSequences ( n , k ) ; return 0 ; }
Check if a number is multiple of 5 without using / and % operators | ; assumes that n is a positive integer ; Driver Code
#include <iostream> NEW_LINE using namespace std ; bool isMultipleof5 ( int n ) { while ( n > 0 ) n = n - 5 ; if ( n == 0 ) return true ; return false ; } int main ( ) { int n = 19 ; if ( isMultipleof5 ( n ) == true ) cout << n << " ▁ is ▁ multiple ▁ of ▁ 5" ; else cout << n << " ▁ is ▁ not ▁ a ▁ multiple ▁ of ▁ 5" ; return 0 ; }
Count pairs from an array having sum of twice of their AND and XOR equal to K | C ++ program for the above approach ; Function to count number of pairs satisfying the given conditions ; Stores the frequency of array elements ; Stores the total number of pairs ; Traverse the array ; Add it to cnt ; Update frequency of current array element ; Print the count ; Driver Code ; Given array ; Size of the array ; Given value of K
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countPairs ( int arr [ ] , int N , int K ) { unordered_map < int , int > mp ; int cnt = 0 ; for ( int i = 0 ; i < N ; i ++ ) { cnt += mp [ K - arr [ i ] ] ; mp [ arr [ i ] ] ++ ; } cout << cnt ; } int main ( ) { int arr [ ] = { 1 , 5 , 4 , 8 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 9 ; countPairs ( arr , N , K ) ; return 0 ; }
Queries to count array elements from a given range having a single set bit | C ++ program for the above approach ; Function to check whether only one bit is set or not ; Function to perform Range - query ; Function to count array elements with a single set bit for each range in a query ; Initialize array for Prefix sum ; Driver Code ; Given array ; Size of the array ; Given queries ; Size of queries array
#include <bits/stdc++.h> NEW_LINE using namespace std ; int check ( int x ) { if ( ( ( x ) & ( x - 1 ) ) == 0 ) return 1 ; return 0 ; } int query ( int l , int r , int pre [ ] ) { if ( l == 0 ) return pre [ r ] ; else return pre [ r ] - pre [ l - 1 ] ; } void countInRange ( int arr [ ] , int N , vector < pair < int , int > > queries , int Q ) { int pre [ N ] = { 0 } ; pre [ 0 ] = check ( arr [ 0 ] ) ; for ( int i = 1 ; i < N ; i ++ ) { pre [ i ] = pre [ i - 1 ] + check ( arr [ i ] ) ; } int c = 0 ; while ( Q -- ) { int l = queries . first ; int r = queries . second ; c ++ ; cout << query ( l , r , pre ) << ' ▁ ' ; } } int main ( ) { int arr [ ] = { 12 , 11 , 16 , 8 , 2 , 5 , 1 , 3 , 256 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; vector < pair < int , int > > queries = { { 0 , 9 } , { 4 , 9 } } ; int Q = queries . size ( ) ; countInRange ( arr , N , queries , Q ) ; return 0 ; }
Bitwise operations on Subarrays of size K | C ++ program for minimum values of each bitwise AND operation on elements of subarray of size K ; Function to convert bit array to decimal number ; Function to find minimum values of each bitwise AND operation on element of subarray of size K ; Maintain an integer array bit [ ] of size 32 all initialized to 0 ; Create a sliding window of size k ; Function call ; Perform operation to removed element ; Perform operation to add element ; Taking minimum value ; Return the result ; Driver Code ; Given array arr [ ] ; Given subarray size K ; Function Call
#include <iostream> NEW_LINE using namespace std ; int build_num ( int bit [ ] , int k ) { int ans = 0 ; for ( int i = 0 ; i < 32 ; i ++ ) if ( bit [ i ] == k ) ans += ( 1 << i ) ; return ans ; } int minimumAND ( int arr [ ] , int n , int k ) { int bit [ 32 ] = { 0 } ; for ( int i = 0 ; i < k ; i ++ ) { for ( int j = 0 ; j < 32 ; j ++ ) { if ( arr [ i ] & ( 1 << j ) ) bit [ j ] ++ ; } } int min_and = build_num ( bit , k ) ; for ( int i = k ; i < n ; i ++ ) { for ( int j = 0 ; j < 32 ; j ++ ) { if ( arr [ i - k ] & ( 1 << j ) ) bit [ j ] -- ; } for ( int j = 0 ; j < 32 ; j ++ ) { if ( arr [ i ] & ( 1 << j ) ) bit [ j ] ++ ; } min_and = min ( build_num ( bit , k ) , min_and ) ; } return min_and ; } int main ( ) { int arr [ ] = { 2 , 5 , 3 , 6 , 11 , 13 } ; int k = 3 ; int n = sizeof arr / sizeof arr [ 0 ] ; cout << minimumAND ( arr , n , k ) ; return 0 ; }
Equal Sum and XOR of three Numbers | C ++ implementation of the above approach ; Function to calculate power of 3 ; Function to return the count of the unset bit ( zeros ) ; Check the bit is 0 or not ; Right shifting ( dividing by 2 ) ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; typedef unsigned long long int ull ; ull calculate ( int bit_cnt ) { ull res = 1 ; while ( bit_cnt -- ) { res = res * 3 ; } return res ; } int unset_bit_count ( ull n ) { int count = 0 ; while ( n ) { if ( ( n & 1 ) == 0 ) count ++ ; n = n >> 1 ; } return count ; } int main ( ) { ull n ; n = 2 ; int count = unset_bit_count ( n ) ; ull ans = calculate ( count ) ; cout << ans << endl ; return 0 ; }
Count pairs of elements such that number of set bits in their AND is B [ i ] | C ++ implementation of the approach ; Function to return the count of pairs which satisfy the given condition ; Check if the count of set bits in the AND value is B [ j ] ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( int A [ ] , int B [ ] , int n ) { int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i ; j < n ; j ++ ) if ( __builtin_popcount ( A [ i ] & A [ j ] ) == B [ j ] ) { cnt ++ ; } return cnt ; } int main ( ) { int A [ ] = { 2 , 3 , 1 , 4 , 5 } ; int B [ ] = { 2 , 2 , 1 , 4 , 2 } ; int size = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << solve ( A , B , size ) ; return 0 ; }
Total pairs in an array such that the bitwise AND , bitwise OR and bitwise XOR of LSB is 1 | C ++ implementation of the approach ; Function to find the count of required pairs ; To store the count of elements which give remainder 0 i . e . even values ; To store the count of elements which give remainder 1 i . e . odd values ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void CalculatePairs ( int a [ ] , int n ) { int cnt_zero = 0 ; int cnt_one = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] % 2 == 0 ) cnt_zero += 1 ; else cnt_one += 1 ; } long int total_XOR_pairs = cnt_zero * cnt_one ; long int total_AND_pairs = ( cnt_one ) * ( cnt_one - 1 ) / 2 ; long int total_OR_pairs = cnt_zero * cnt_one + ( cnt_one ) * ( cnt_one - 1 ) / 2 ; cout << " cntXOR ▁ = ▁ " << total_XOR_pairs << endl ; cout << " cntAND ▁ = ▁ " << total_AND_pairs << endl ; cout << " cntOR ▁ = ▁ " << total_OR_pairs << endl ; } int main ( ) { int a [ ] = { 1 , 3 , 4 , 2 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; CalculatePairs ( a , n ) ; return 0 ; }
Assign other value to a variable from two possible values | CPP program to change value of x according to its current value . ; Function to alternate the values ; Main function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void alternate ( int & a , int & b , int & x ) { x = a + b - x ; } int main ( ) { int a = -10 ; int b = 15 ; int x = a ; cout << " x ▁ is ▁ : ▁ " << x ; alternate ( a , b , x ) ; cout << " After change " cout << " STRNEWLINE x ▁ is ▁ : ▁ " << x ; }
Highest power of two that divides a given number | CPP program to find highest power of 2 that divides n . ; Driver code
#include <iostream> NEW_LINE using namespace std ; int highestPowerOf2 ( int n ) { return ( n & ( ~ ( n - 1 ) ) ) ; } int main ( ) { int n = 48 ; cout << highestPowerOf2 ( n ) ; return 0 ; }
Check whether bitwise AND of a number with any subset of an array is zero or not | C ++ program to check whether bitwise AND of a number with any subset of an array is zero or not ; Function to check whether bitwise AND of a number with any subset of an array is zero or not ; variable to store the AND of all the elements ; find the AND of all the elements of the array ; if the AND of all the array elements and N is equal to zero ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void isSubsetAndZero ( int array [ ] , int length , int N ) { int arrAnd = array [ 0 ] ; for ( int i = 1 ; i < length ; i ++ ) { arrAnd = arrAnd & array [ i ] ; } if ( ( arrAnd & N ) == 0 ) cout << " YES " << endl ; else cout << " NO " << endl ; } int main ( ) { int array [ ] = { 1 , 2 , 4 } ; int length = sizeof ( array ) / sizeof ( int ) ; int N = 3 ; isSubsetAndZero ( array , length , N ) ; }
Finding the Parity of a number Efficiently | Program to find the parity of a given number ; Function to find the parity ; Rightmost bit of y holds the parity value if ( y & 1 ) is 1 then parity is odd else even ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool findParity ( int x ) { int y = x ^ ( x >> 1 ) ; y = y ^ ( y >> 2 ) ; y = y ^ ( y >> 4 ) ; y = y ^ ( y >> 8 ) ; y = y ^ ( y >> 16 ) ; if ( y & 1 ) return 1 ; return 0 ; } int main ( ) { ( findParity ( 9 ) == 0 ) ? cout << " Even ▁ Parity STRNEWLINE " : cout << " Odd ▁ Parity STRNEWLINE " ; ( findParity ( 13 ) == 0 ) ? cout << " Even ▁ Parity STRNEWLINE " : cout << " Odd ▁ Parity STRNEWLINE " ; return 0 ; }
Check if bits in range L to R of two numbers are complement of each other or not | C ++ implementation to check whether all the bits in the given range of two numbers are complement of each other ; function to check whether all the bits are set in the given range or not ; calculating a number ' num ' having ' r ' number of bits and bits in the range l to r are the only set bits ; new number which will only have one or more set bits in the range l to r and nowhere else ; if both are equal , then all bits are set in the given range ; else all bits are not set ; function to check whether all the bits in the given range of two numbers are complement of each other ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool allBitsSetInTheGivenRange ( unsigned int n , unsigned int l , unsigned int r ) { int num = ( ( 1 << r ) - 1 ) ^ ( ( 1 << ( l - 1 ) ) - 1 ) ; int new_num = n & num ; if ( num == new_num ) return true ; return false ; } bool bitsAreComplement ( unsigned int a , unsigned int b , unsigned int l , unsigned int r ) { unsigned int xor_value = a ^ b ; return allBitsSetInTheGivenRange ( xor_value , l , r ) ; } int main ( ) { unsigned int a = 10 , b = 5 ; unsigned int l = 1 , r = 3 ; if ( bitsAreComplement ( a , b , l , r ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Sum of the series 2 ^ 0 + 2 ^ 1 + 2 ^ 2 + ... . . + 2 ^ n | C ++ program to find sum ; function to calculate sum of series ; initialize sum as 0 ; loop to calculate sum of series ; calculate 2 ^ i and add it to sum ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calculateSum ( int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum = sum + ( 1 << i ) ; } return sum ; } int main ( ) { int n = 10 ; cout << " Sum ▁ of ▁ series ▁ of ▁ power ▁ of ▁ 2 ▁ is ▁ : ▁ " << calculateSum ( n ) ; }
Print all the combinations of N elements by changing sign such that their sum is divisible by M | ; Function to print all the combinations ; Iterate for all combinations ; Initially 100 in binary if n is 3 as 1 << ( 3 - 1 ) = 100 in binary ; Iterate in the array and assign signs to the array elements ; If the j - th bit from left is set take ' + ' sign ; Right shift to check if jth bit is set or not ; re - initialize ; Iterate in the array elements ; If the jth from left is set ; right shift ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printCombinations ( int a [ ] , int n , int m ) { for ( int i = 0 ; i < ( 1 << n ) ; i ++ ) { int sum = 0 ; int num = 1 << ( n - 1 ) ; for ( int j = 0 ; j < n ; j ++ ) { if ( i & num ) sum += a [ j ] ; else sum += ( -1 * a [ j ] ) ; num = num >> 1 ; } if ( sum % m == 0 ) { num = 1 << ( n - 1 ) ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( i & num ) ) cout << " + " << a [ j ] << " ▁ " ; else cout << " - " << a [ j ] << " ▁ " ; num = num >> 1 ; } cout << endl ; } } } int main ( ) { int a [ ] = { 3 , 5 , 6 , 8 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int m = 5 ; printCombinations ( a , n , m ) ; return 0 ; }
Same Number Of Set Bits As N | CPP program to find numbers less than N that have same Number Of Set Bits As N ; function ; __builtin_popcount function that count set bits in n ; Iterate from n - 1 to 1 ; check if the number of set bits equals to temp increment count ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int smallerNumsWithSameSetBits ( int n ) { int temp = __builtin_popcount ( n ) ; int count = 0 ; for ( int i = n - 1 ; i > 0 ; i -- ) { if ( temp == __builtin_popcount ( i ) ) count ++ ; } return count ; } int main ( ) { int n = 4 ; cout << smallerNumsWithSameSetBits ( n ) ; return 0 ; }
Multiply any Number with 4 using Bitwise Operator | C ++ program to multiply a number with 4 using Bitwise Operator ; function the return multiply a number with 4 using bitwise operator ; returning a number with multiply with 4 using2 bit shifring right ; derive function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int multiplyWith4 ( int n ) { return ( n << 2 ) ; } int main ( ) { int n = 4 ; cout << multiplyWith4 ( n ) << endl ; return 0 ; }
Leftover element after performing alternate Bitwise OR and Bitwise XOR operations on adjacent pairs | CPP program to print the Leftover element after performing alternate Bitwise OR and Bitwise XOR operations to the pairs . ; array to store the tree ; array to store the level of every parent ; function to construct the tree ; level of child is always 0 ; recursive call ; increase the level of every parent , which is level of child + 1 ; if the parent is at odd level , then do a bitwise OR ; if the parent is at even level , then do a bitwise XOR ; function that updates the tree ; if it is a leaf and the leaf which is to be updated ; out of range ; not a leaf then recurse ; recursive call ; check if the parent is at odd or even level and perform OR or XOR according to that ; function that assigns value to a [ index ] and calls update function to update the tree ; Driver Code ; builds the tree ; 1 st query ; 2 nd query
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 1000 NEW_LINE int tree [ N ] ; int level [ N ] ; void constructTree ( int low , int high , int pos , int a [ ] ) { if ( low == high ) { level [ pos ] = 0 ; tree [ pos ] = a [ high ] ; return ; } int mid = ( low + high ) / 2 ; constructTree ( low , mid , 2 * pos + 1 , a ) ; constructTree ( mid + 1 , high , 2 * pos + 2 , a ) ; level [ pos ] = level [ 2 * pos + 1 ] + 1 ; if ( level [ pos ] & 1 ) tree [ pos ] = tree [ 2 * pos + 1 ] | tree [ 2 * pos + 2 ] ; else tree [ pos ] = tree [ 2 * pos + 1 ] ^ tree [ 2 * pos + 2 ] ; } void update ( int low , int high , int pos , int index , int a [ ] ) { if ( low == high and low == index ) { tree [ pos ] = a [ low ] ; return ; } if ( index < low index > high ) return ; if ( low != high ) { int mid = ( low + high ) / 2 ; update ( low , mid , 2 * pos + 1 , index , a ) ; update ( mid + 1 , high , 2 * pos + 2 , index , a ) ; if ( level [ pos ] & 1 ) tree [ pos ] = tree [ 2 * pos + 1 ] | tree [ 2 * pos + 2 ] ; else tree [ pos ] = tree [ 2 * pos + 1 ] ^ tree [ 2 * pos + 2 ] ; } } void updateValue ( int index , int value , int a [ ] , int n ) { a [ index ] = value ; update ( 0 , n - 1 , 0 , index , a ) ; } int main ( ) { int a [ ] = { 1 , 4 , 5 , 6 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; constructTree ( 0 , n - 1 , 0 , a ) ; int index = 0 ; int value = 2 ; updateValue ( index , value , a , n ) ; cout << tree [ 0 ] << endl ; index = 3 ; value = 5 ; updateValue ( index , value , a , n ) ; cout << tree [ 0 ] << endl ; return 0 ; }
Set all even bits of a number | Simple CPP program to set all even bits of a number ; Sets even bits of n and returns modified number . ; Generate 101010. . .10 number and store in res . ; if bit is even then generate number and or with res ; return OR number ;
#include <iostream> NEW_LINE using namespace std ; int evenbitsetnumber ( int n ) { int count = 0 , res = 0 ; for ( int temp = n ; temp > 0 ; temp >>= 1 ) { if ( count % 2 == 1 ) res |= ( 1 << count ) ; count ++ ; } return ( n res ) ; } / * Driver code * int main ( ) { int n = 10 ; cout << evenbitsetnumber ( n ) ; return 0 ; }
Set all even bits of a number | Efficient CPP program to set all even bits of a number ; return msb set number ; set all bits ; return msb increment n by 1 and shift by 1 ; return even seted number ; get msb here ; generate even bits like 101010. . ; if bits is odd then shift by 1 ; return even set bits number ; set all even bits here ; take or with even set bits number ; Driver code
#include <iostream> NEW_LINE using namespace std ; int getmsb ( int n ) { n |= n >> 1 ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; return ( n + 1 ) >> 1 ; } int getevenbits ( int n ) { n = getmsb ( n ) ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; if ( n & 1 ) n = n >> 1 ; return n ; } int setallevenbits ( int n ) { return n | getevenbits ( n ) ; } int main ( ) { int n = 10 ; cout << setallevenbits ( n ) ; return 0 ; }
Set all odd bits of a number | CPP code Set all odd bits of a number ; set all odd bit ; res for store 010101. . number ; generate number form of 010101. . ... till temp size ; if bit is odd , then generate number and or with res ; Driver code
#include <iostream> NEW_LINE using namespace std ; int oddbitsetnumber ( int n ) { int count = 0 ; int res = 0 ; for ( int temp = n ; temp > 0 ; temp >>= 1 ) { if ( count % 2 == 0 ) res |= ( 1 << count ) ; count ++ ; } return ( n res ) ; } int main ( ) { int n = 10 ; cout << oddbitsetnumber ( n ) ; return 0 ; }
Set all odd bits of a number | Efficient CPP program to set all odd bits number ; return MSB set number ; set all bits including MSB . ; return MSB ; Returns a number of same size ( MSB atsame position ) as n and all odd bits set . ; generate odd bits like 010101. . ; if bits is even then shift by 1 ; return odd set bits number ; set all odd bits here ; take OR with odd set bits number ; Driver code
#include <iostream> NEW_LINE using namespace std ; int getmsb ( int n ) { n |= n >> 1 ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; return ( n + 1 ) >> 1 ; } int getevenbits ( int n ) { n = getmsb ( n ) ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; if ( ( n & 1 ) == 0 ) n = n >> 1 ; return n ; } int setalloddbits ( int n ) { return n | getevenbits ( n ) ; } int main ( ) { int n = 10 ; cout << setalloddbits ( n ) ; return 0 ; }
Print numbers in the range 1 to n having bits in alternate pattern | C ++ implementation to print numbers in the range 1 to n having bits in alternate pattern ; function to print numbers in the range 1 to n having bits in alternate pattern ; first number having bits in alternate pattern ; display ; loop until n < curr_num ; generate next number having alternate bit pattern ; if true then break ; display ; generate next number having alternate bit pattern ; if true then break ; display ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printNumHavingAltBitPatrn ( int n ) { int curr_num = 1 ; cout << curr_num << " ▁ " ; while ( 1 ) { curr_num <<= 1 ; if ( n < curr_num ) break ; cout << curr_num << " ▁ " ; curr_num = ( ( curr_num ) << 1 ) ^ 1 ; if ( n < curr_num ) break ; cout << curr_num << " ▁ " ; } } int main ( ) { int n = 50 ; printNumHavingAltBitPatrn ( n ) ; return 0 ; }
Smallest perfect power of 2 greater than n ( without using arithmetic operators ) | C ++ implementation of smallest perfect power of 2 greater than n ; Function to find smallest perfect power of 2 greater than n ; To store perfect power of 2 ; bitwise left shift by 1 ; bitwise right shift by 1 ; Required perfect power of 2 ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned int perfectPowerOf2 ( unsigned int n ) { unsigned int per_pow = 1 ; while ( n > 0 ) { per_pow = per_pow << 1 ; n = n >> 1 ; } return per_pow ; } int main ( ) { unsigned int n = 128 ; cout << " Perfect ▁ power ▁ of ▁ 2 ▁ greater ▁ than ▁ " << n << " : ▁ " << perfectPowerOf2 ( n ) ; return 0 ; }
Find Unique pair in an array with pairs of numbers | C program to find a unique pair in an array of pairs . ; XOR each element and get XOR of two unique elements ( ans ) ; Get a set bit of XOR ( We get the rightmost set bit ) ; Now divide elements in two sets by comparing rightmost set bit of XOR with bit at same position in each element . int x = 0 , y = 0 ; Initialize missing numbers ; XOR of first set in arr [ ] ; XOR of second set in arr [ ] ; Driver code
#include <stdio.h> NEW_LINE void findUniquePair ( int arr [ ] , int n ) { int XOR = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) XOR = XOR ^ arr [ i ] ; int set_bit_no = XOR & ~ ( XOR - 1 ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] & set_bit_no ) x = x ^ arr [ i ] ; else y = y ^ arr [ i ] ; } printf ( " The ▁ unique ▁ pair ▁ is ▁ ( % d , ▁ % d ) " , x , y ) ; } int main ( ) { int a [ ] = { 6 , 1 , 3 , 5 , 1 , 3 , 7 , 6 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; findUniquePair ( a , n ) ; return 0 ; }
M | C ++ implementation to find the mth smallest number having k number of set bits ; function to find the next higher number with same number of set bits as in ' x ' ; the approach is same as discussed in ; function to find the mth smallest number having k number of set bits ; smallest number having ' k ' number of set bits ; finding the mth smallest number having k set bits ; required number ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; typedef unsigned int uint_t ; uint_t nxtHighWithNumOfSetBits ( uint_t x ) { uint_t rightOne ; uint_t nextHigherOneBit ; uint_t rightOnesPattern ; uint_t next = 0 ; if ( x ) { rightOne = x & - ( signed ) x ; nextHigherOneBit = x + rightOne ; rightOnesPattern = x ^ nextHigherOneBit ; rightOnesPattern = ( rightOnesPattern ) / rightOne ; rightOnesPattern >>= 2 ; next = nextHigherOneBit | rightOnesPattern ; } return next ; } int mthSmallestWithKSetBits ( uint_t m , uint_t k ) { uint_t num = ( 1 << k ) - 1 ; for ( int i = 1 ; i < m ; i ++ ) num = nxtHighWithNumOfSetBits ( num ) ; return num ; } int main ( ) { uint_t m = 6 , k = 4 ; cout << mthSmallestWithKSetBits ( m , k ) ; return 0 ; }
Count unset bits of a number | An optimized C ++ program to count unset bits in an integer . ; This makes sure two bits ( From MSB and including MSB ) are set ; This makes sure 4 bits ( From MSB and including MSB ) are set ; Count set bits in toggled number ; Driver code
#include <iostream> NEW_LINE using namespace std ; int countUnsetBits ( int n ) { int x = n ; n |= n >> 1 ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; return __builtin_popcount ( x ^ n ) ; } int main ( ) { int n = 17 ; cout << countUnsetBits ( n ) ; return 0 ; }
Toggle all bits after most significant bit | CPP program to toggle set bits starting from MSB ; Function to toggle bits starting from MSB ; temporary variable to use XOR with one of a n ; Run loop until the only set bit in temp crosses MST of n . ; Toggle bit of n corresponding to current set bit in temp . ; Move set bit to next higher position . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void toggle ( int & n ) { int temp = 1 ; while ( temp <= n ) { n = n ^ temp ; temp = temp << 1 ; } } int main ( ) { int n = 10 ; toggle ( n ) ; cout << n ; return 0 ; }
Find the n | C ++ program to find n - th number whose binary representation is palindrome . ; Finds if the kth bit is set in the binary representation ; Returns the position of leftmost set bit in the binary representation ; Finds whether the integer in binary representation is palindrome or not ; One by one compare bits ; Compare left and right bits and converge ; Start from 1 , traverse through all the integers ; If we reach n , break the loop ; Driver code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int isKthBitSet ( int x , int k ) { return ( x & ( 1 << ( k - 1 ) ) ) ? 1 : 0 ; } int leftmostSetBit ( int x ) { int count = 0 ; while ( x ) { count ++ ; x = x >> 1 ; } return count ; } int isBinPalindrome ( int x ) { int l = leftmostSetBit ( x ) ; int r = 1 ; while ( l > r ) { if ( isKthBitSet ( x , l ) != isKthBitSet ( x , r ) ) return 0 ; l -- ; r ++ ; } return 1 ; } int findNthPalindrome ( int n ) { int pal_count = 0 ; int i = 0 ; for ( i = 1 ; i <= INT_MAX ; i ++ ) { if ( isBinPalindrome ( i ) ) { pal_count ++ ; } if ( pal_count == n ) break ; } return i ; } int main ( ) { int n = 9 ; cout << findNthPalindrome ( n ) ; }
Print ' K ' th least significant bit of a number | CPP code to print ' K ' th LSB ; Function returns 1 if set , 0 if not ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool LSB ( int num , int K ) { return ( num & ( 1 << ( K - 1 ) ) ) ; } int main ( ) { int num = 10 , K = 4 ; cout << LSB ( num , K ) ; return 0 ; }
Check if two numbers are equal without using comparison operators | CPP code to check if 2 numbers are same ; Finds if a and b are same ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void areSame ( int a , int b ) { if ( ! ( a - b ) ) cout << " Same " ; else cout << " Not ▁ Same " ; } int main ( ) { areSame ( 10 , 20 ) ; return 0 ; }
Position of rightmost different bit | C ++ implementation to find the position of rightmost different bit ; Function to find the position of rightmost set bit in ' n ' returns 0 if there is no set bit . ; to handle edge case when n = 0. ; Function to find the position of rightmost different bit in the binary representations of ' m ' and ' n ' returns 0 if there is no rightmost different bit . ; position of rightmost different bit ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getRightMostSetBit ( int n ) { if ( n == 0 ) return 0 ; return log2 ( n & - n ) + 1 ; } int posOfRightMostDiffBit ( int m , int n ) { return getRightMostSetBit ( m ^ n ) ; } int main ( ) { int m = 52 , n = 24 ; cout << " Position ▁ of ▁ rightmost ▁ different ▁ bit : " << posOfRightMostDiffBit ( m , n ) << endl ; return 0 ; }
Closest ( or Next ) smaller and greater numbers with same number of set bits | C ++ Implementation of getNext with Same number of bits 1 's is below ; Main Function to find next smallest number bigger than n ; Compute c0 and c1 ; If there is no bigger number with the same no . of 1 's ; Driver Code ; input 1 ; input 2
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getNext ( int n ) { int c = n ; int c0 = 0 ; int c1 = 0 ; while ( ( ( c & 1 ) == 0 ) && ( c != 0 ) ) { c0 ++ ; c >>= 1 ; } while ( ( c & 1 ) == 1 ) { c1 ++ ; c >>= 1 ; } if ( c0 + c1 == 31 c0 + c1 == 0 ) return -1 ; return n + ( 1 << c0 ) + ( 1 << ( c1 - 1 ) ) - 1 ; } int main ( ) { int n = 5 ; cout << getNext ( n ) ; n = 8 ; cout << endl ; cout << getNext ( n ) ; return 0 ; }
Count minimum bits to flip such that XOR of A and B equal to C | C ++ code to count the Minimum bits in A and B ; If both A [ i ] and B [ i ] are equal ; If Both A and B are unequal ; Driver Code ; N represent total count of Bits
#include <bits/stdc++.h> NEW_LINE using namespace std ; int totalFlips ( char * A , char * B , char * C , int N ) { int count = 0 ; for ( int i = 0 ; i < N ; ++ i ) { if ( A [ i ] == B [ i ] && C [ i ] == '1' ) ++ count ; else if ( A [ i ] != B [ i ] && C [ i ] == '0' ) ++ count ; } return count ; } int main ( ) { int N = 5 ; char a [ ] = "10100" ; char b [ ] = "00010" ; char c [ ] = "10011" ; cout << totalFlips ( a , b , c , N ) ; return 0 ; }
Swap three variables without using temporary variable | C ++ program to swap three variables without using temporary variable ; Assign c ' s ▁ value ▁ to ▁ a , ▁ a ' s value to b and b 's value to c. ; Store XOR of all in a ; After this , b has value of a ; After this , c has value of b ; After this , a has value of c ; Driver code ; Calling Function
#include <iostream> NEW_LINE using namespace std ; void swapThree ( int & a , int & b , int & c ) { a = a ^ b ^ c ; b = a ^ b ^ c ; c = a ^ b ^ c ; a = a ^ b ^ c ; } int main ( ) { int a = 10 , b = 20 , c = 30 ; cout << " Before ▁ swapping ▁ a ▁ = ▁ " << a << " , ▁ b ▁ = ▁ " << b << " , ▁ c ▁ = ▁ " << c << endl ; swapThree ( a , b , c ) ; cout << " After ▁ swapping ▁ a ▁ = ▁ " << a << " , ▁ b ▁ = ▁ " << b << " , ▁ c ▁ = ▁ " << c << endl ; return 0 ; }
Find Two Missing Numbers | Set 2 ( XOR based solution ) | C ++ Program to find 2 Missing Numbers using O ( 1 ) extra space and no overflow . ; Function to find two missing numbers in range [ 1 , n ] . This function assumes that size of array is n - 2 and all array elements are distinct ; Get the XOR of all elements in arr [ ] and { 1 , 2 . . n } ; Get a set bit of XOR ( We get the rightmost set bit ) ; Now divide elements in two sets by comparing rightmost set bit of XOR with bit at same position in each element . int x = 0 , y = 0 ; Initialize missing numbers ; XOR of first set in arr [ ] ; XOR of second set in arr [ ] ; XOR of first set in arr [ ] and { 1 , 2 , ... n } ; XOR of second set in arr [ ] and { 1 , 2 , ... n } ; Driver program to test above function ; Range of numbers is 2 plus size of array
#include <bits/stdc++.h> NEW_LINE void findTwoMissingNumbers ( int arr [ ] , int n ) { int XOR = arr [ 0 ] ; for ( int i = 1 ; i < n - 2 ; i ++ ) XOR ^= arr [ i ] ; for ( int i = 1 ; i <= n ; i ++ ) XOR ^= i ; int set_bit_no = XOR & ~ ( XOR - 1 ) ; for ( int i = 0 ; i < n - 2 ; i ++ ) { if ( arr [ i ] & set_bit_no ) x = x ^ arr [ i ] ; else y = y ^ arr [ i ] ; } for ( int i = 1 ; i <= n ; i ++ ) { if ( i & set_bit_no ) x = x ^ i ; else y = y ^ i ; } printf ( " Two ▁ Missing ▁ Numbers ▁ are % d % d " , x , y ) ; } int main ( ) { int arr [ ] = { 1 , 3 , 5 , 6 } ; int n = 2 + sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findTwoMissingNumbers ( arr , n ) ; return 0 ; }
Find profession in a special family | C ++ program to find profession of a person at given level and position . ; Function to get no of set bits in binary representation of passed binary no . ; Returns ' e ' if profession of node at given level and position is engineer . Else doctor . The function assumes that given position and level have valid values . ; Count set bits in ' pos - 1' ; If set bit count is odd , then doctor , else engineer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSetBits ( int n ) { int count = 0 ; while ( n ) { n &= ( n - 1 ) ; count ++ ; } return count ; } char findProffesion ( int level , int pos ) { int c = countSetBits ( pos - 1 ) ; return ( c % 2 ) ? ' d ' : ' e ' ; } int main ( void ) { int level = 3 , pos = 4 ; ( findProffesion ( level , pos ) == ' e ' ) ? cout << " Engineer " : cout << " Doctor " ; return 0 ; }
Find XOR of two number without using XOR operator | C ++ program to find XOR without using ^ ; Returns XOR of x and y ; Driver program to test above function
#include <iostream> NEW_LINE using namespace std ; int myXOR ( int x , int y ) { return ( x & ( ~ y ) ) | ( ( ~ x ) & y ) ; } int main ( ) { int x = 3 , y = 5 ; cout << " XOR ▁ is ▁ " << myXOR ( x , y ) ; return 0 ; }
Find maximum xor of k elements in an array | C ++ implementation of the approach ; Function to return the maximum xor for a subset of size k from the given array ; Initialize result ; Traverse all subsets of the array ; __builtin_popcount ( ) returns the number of sets bits in an integer ; Initialize current xor as 0 ; If jth bit is set in i then include jth element in the current xor ; Update maximum xor so far ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Max_Xor ( int arr [ ] , int n , int k ) { int maxXor = INT_MIN ; for ( int i = 0 ; i < ( 1 << n ) ; i ++ ) { if ( __builtin_popcount ( i ) == k ) { int cur_xor = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( i & ( 1 << j ) ) cur_xor = cur_xor ^ arr [ j ] ; } maxXor = max ( maxXor , cur_xor ) ; } } return maxXor ; } int main ( ) { int arr [ ] = { 2 , 5 , 4 , 1 , 3 , 7 , 6 , 8 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int k = 3 ; cout << Max_Xor ( arr , n , k ) ; return 0 ; }
Bitwise Operators in C / C ++ | CPP Program to demonstrate use of bitwise operators ; a = 5 ( 00000101 ) , b = 9 ( 00001001 ) ; The result is 00000001 ; The result is 00001101 ; The result is 00001100 ; The result is 11111010 ; The result is 00010010 ; The result is 00000100
#include <iostream> NEW_LINE using namespace std ; int main ( ) { int a = 5 , b = 9 ; cout << " a ▁ = ▁ " << a << " , " << " ▁ b ▁ = ▁ " << b << endl ; cout << " a ▁ & ▁ b ▁ = ▁ " << ( a & b ) << endl ; cout << " a ▁ | ▁ b ▁ = ▁ " << ( a b ) << endl ; cout << " a ▁ ^ ▁ b ▁ = ▁ " << ( a ^ b ) << endl ; cout << " ~ ( " << a << " ) ▁ = ▁ " << ( ~ a ) << endl ; cout << " b ▁ < < ▁ 1" << " ▁ = ▁ " << ( b << 1 ) << endl ; cout << " b ▁ > > ▁ 1 ▁ " << " = ▁ " << ( b >> 1 ) << endl ; return 0 ; }
Convert a given temperature to another system based on given boiling and freezing points | C ++ program for above approach ; Function to return temperature in the second thermometer ; Calculate the temperature ; Driver Code
#include <iostream> NEW_LINE using namespace std ; double temp_convert ( int F1 , int B1 , int F2 , int B2 , int T ) { float t2 ; t2 = F2 + ( float ) ( B2 - F2 ) / ( B1 - F1 ) * ( T - F1 ) ; return t2 ; } int main ( ) { int F1 = 0 , B1 = 100 ; int F2 = 32 , B2 = 212 ; int T = 37 ; float t2 ; cout << temp_convert ( F1 , B1 , F2 , B2 , T ) ; return 0 ; }
Maximum possible elements which are divisible by 2 | CPP program to find maximum possible elements which divisible by 2 ; Function to find maximum possible elements which divisible by 2 ; To store count of even numbers ; All even numbers and half of odd numbers ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Divisible ( int arr [ ] , int n ) { int count_even = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] % 2 == 0 ) count_even ++ ; return count_even + ( n - count_even ) / 2 ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << Divisible ( arr , n ) ; return 0 ; }
Select a Random Node from a tree with equal probability | CPP program to Select a Random Node from a tree ; This is used to fill children counts . ; Inserts Children count for each node ; returns number of children for root ; Helper Function to return a random node ; Returns Random node ; Driver code ; Creating Above Tree
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; int children ; Node * left , * right ; } ; Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; temp -> children = 0 ; return temp ; } int getElements ( Node * root ) { if ( ! root ) return 0 ; return getElements ( root -> left ) + getElements ( root -> right ) + 1 ; } void insertChildrenCount ( Node * & root ) { if ( ! root ) return ; root -> children = getElements ( root ) - 1 ; insertChildrenCount ( root -> left ) ; insertChildrenCount ( root -> right ) ; } int children ( Node * root ) { if ( ! root ) return 0 ; return root -> children + 1 ; } int randomNodeUtil ( Node * root , int count ) { if ( ! root ) return 0 ; if ( count == children ( root -> left ) ) return root -> data ; if ( count < children ( root -> left ) ) return randomNodeUtil ( root -> left , count ) ; return randomNodeUtil ( root -> right , count - children ( root -> left ) - 1 ) ; } int randomNode ( Node * root ) { srand ( time ( 0 ) ) ; int count = rand ( ) % ( root -> children + 1 ) ; return randomNodeUtil ( root , count ) ; } int main ( ) { Node * root = newNode ( 10 ) ; root -> left = newNode ( 20 ) ; root -> right = newNode ( 30 ) ; root -> left -> right = newNode ( 40 ) ; root -> left -> right = newNode ( 50 ) ; root -> right -> left = newNode ( 60 ) ; root -> right -> right = newNode ( 70 ) ; insertChildrenCount ( root ) ; cout << " A ▁ Random ▁ Node ▁ From ▁ Tree ▁ : ▁ " << randomNode ( root ) << endl ; return 0 ; }
Implement rand3 ( ) using rand2 ( ) | C ++ Program to print 0 , 1 or 2 with equal probability ; Random Function to that returns 0 or 1 with equal probability ; rand ( ) function will generate odd or even number with equal probability . If rand ( ) generates odd number , the function will return 1 else it will return 0. ; Random Function to that returns 0 , 1 or 2 with equal probability 1 with 75 % ; returns 0 , 1 , 2 or 3 with 25 % probability ; Driver code to test above functions
#include <iostream> NEW_LINE using namespace std ; int rand2 ( ) { return rand ( ) & 1 ; } int rand3 ( ) { int r = 2 * rand2 ( ) + rand2 ( ) ; if ( r < 3 ) return r ; return rand3 ( ) ; } int main ( ) { srand ( time ( NULL ) ) ; for ( int i = 0 ; i < 100 ; i ++ ) cout << rand3 ( ) ; return 0 ; }
Delete leaf nodes with value as x | CPP code to delete all leaves with given value . ; A binary tree node ; A utility function to allocate a new node ; deleteleaves ( ) ; inorder ( ) ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; struct Node * newNode ( int data ) { struct Node * newNode = new Node ; newNode -> data = data ; newNode -> left = newNode -> right = NULL ; return ( newNode ) ; } Node * deleteLeaves ( Node * root , int x ) { if ( root == NULL ) return nullptr ; root -> left = deleteLeaves ( root -> left , x ) ; root -> right = deleteLeaves ( root -> right , x ) ; if ( root -> data == x && root -> left == NULL && root -> right == NULL ) { return nullptr ; } return root ; } void inorder ( Node * root ) { if ( root == NULL ) return ; inorder ( root -> left ) ; cout << root -> data << " ▁ " ; inorder ( root -> right ) ; } int main ( void ) { struct Node * root = newNode ( 10 ) ; root -> left = newNode ( 3 ) ; root -> right = newNode ( 10 ) ; root -> left -> left = newNode ( 3 ) ; root -> left -> right = newNode ( 1 ) ; root -> right -> right = newNode ( 3 ) ; root -> right -> right -> left = newNode ( 3 ) ; root -> right -> right -> right = newNode ( 3 ) ; deleteLeaves ( root , 3 ) ; cout << " Inorder ▁ traversal ▁ after ▁ deletion ▁ : ▁ " ; inorder ( root ) ; return 0 ; }
Non | Non - Recursive Program to delete an entire binary tree . ; A Binary Tree Node ; Non - recursive function to delete an entire binary tree . ; Base Case ; Create an empty queue for level order traversal ; Do level order traversal starting from root ; Deletes a tree and sets the root as NULL ; Utility function to create a new tree Node ; Driver program to test above functions ; create a binary tree ; delete entire binary tree
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; void _deleteTree ( Node * root ) { if ( root == NULL ) return ; queue < Node * > q ; q . push ( root ) ; while ( ! q . empty ( ) ) { Node * node = q . front ( ) ; q . pop ( ) ; if ( node -> left != NULL ) q . push ( node -> left ) ; if ( node -> right != NULL ) q . push ( node -> right ) ; free ( node ) ; } } void deleteTree ( Node * * node_ref ) { _deleteTree ( * node_ref ) ; * node_ref = NULL ; } Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } int main ( ) { Node * root = newNode ( 15 ) ; root -> left = newNode ( 10 ) ; root -> right = newNode ( 20 ) ; root -> left -> left = newNode ( 8 ) ; root -> left -> right = newNode ( 12 ) ; root -> right -> left = newNode ( 16 ) ; root -> right -> right = newNode ( 25 ) ; deleteTree ( & root ) ; return 0 ; }
Iterative program to Calculate Size of a tree | C ++ program to print size of tree in iterative ; Node Structure ; A utility function to create a new Binary Tree Node ; return size of tree ; if tree is empty it will return 0 ; Using level order Traversal . ; when the queue is empty : the poll ( ) method returns null . ; Increment count ; Enqueue left child ; Increment count ; Enqueue right child ; Driver Code ; creating a binary tree and entering the nodes
#include <iostream> NEW_LINE #include <queue> 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 = NULL ; temp -> right = NULL ; return temp ; } int sizeoftree ( Node * root ) { if ( root == NULL ) return 0 ; queue < Node * > q ; int count = 1 ; q . push ( root ) ; while ( ! q . empty ( ) ) { Node * temp = q . front ( ) ; if ( temp -> left ) { count ++ ; q . push ( temp -> left ) ; } if ( temp -> right ) { count ++ ; q . push ( temp -> right ) ; } q . pop ( ) ; } return count ; } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; cout << " Size ▁ of ▁ the ▁ tree ▁ is ▁ " << sizeoftree ( root ) << endl ; return 0 ; }
Write a Program to Find the Maximum Depth or Height of a Tree | C ++ program to find height of tree ; A binary tree node has data , pointer to left child and a pointer to right child ; Compute the " maxDepth " of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node . ; compute the depth of each subtree ; use the larger one ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int data ; node * left ; node * right ; } ; int maxDepth ( node * node ) { if ( node == NULL ) return 0 ; else { int lDepth = maxDepth ( node -> left ) ; int rDepth = maxDepth ( node -> right ) ; if ( lDepth > rDepth ) return ( lDepth + 1 ) ; else return ( rDepth + 1 ) ; } } node * newNode ( int data ) { node * Node = new node ( ) ; Node -> data = data ; Node -> left = NULL ; Node -> right = NULL ; return ( Node ) ; } int main ( ) { node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; cout << " Height ▁ of ▁ tree ▁ is ▁ " << maxDepth ( root ) ; return 0 ; }
Find postorder traversal of BST from preorder traversal | C ++ program for finding postorder traversal of BST from preorder traversal ; Function to find postorder traversal from preorder traversal . ; If entire preorder array is traversed then return as no more element is left to be added to post order array . ; If array element does not lie in range specified , then it is not part of current subtree . ; Store current value , to be printed later , after printing left and right subtrees . Increment preIndex to find left and right subtrees , and pass this updated value to recursive calls . ; All elements with value between minval and val lie in left subtree . ; All elements with value between val and maxval lie in right subtree . ; Function to find postorder traversal . ; To store index of element to be traversed next in preorder array . This is passed by reference to utility function . ; Driver code ; Calling function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findPostOrderUtil ( int pre [ ] , int n , int minval , int maxval , int & preIndex ) { if ( preIndex == n ) return ; if ( pre [ preIndex ] < minval pre [ preIndex ] > maxval ) { return ; } int val = pre [ preIndex ] ; preIndex ++ ; findPostOrderUtil ( pre , n , minval , val , preIndex ) ; findPostOrderUtil ( pre , n , val , maxval , preIndex ) ; cout << val << " ▁ " ; } void findPostOrder ( int pre [ ] , int n ) { int preIndex = 0 ; findPostOrderUtil ( pre , n , INT_MIN , INT_MAX , preIndex ) ; } int main ( ) { int pre [ ] = { 40 , 30 , 35 , 80 , 100 } ; int n = sizeof ( pre ) / sizeof ( pre [ 0 ] ) ; findPostOrder ( pre , n ) ; return 0 ; }
Height of binary tree considering even level leaves only | Program to find height of the tree considering only even level leaves . ; A binary tree node has data , pointer to left child and a pointer to right child ; Base Case ; left stores the result of left subtree , and right stores the result of right subtree ; If both left and right returns 0 , it means there is no valid path till leaf node ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver program to test above functions ; Let us create binary tree shown in above diagram
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left ; struct Node * right ; } ; int heightOfTreeUtil ( Node * root , bool isEven ) { if ( ! root ) return 0 ; if ( ! root -> left && ! root -> right ) { if ( isEven ) return 1 ; else return 0 ; } int left = heightOfTreeUtil ( root -> left , ! isEven ) ; int right = heightOfTreeUtil ( root -> right , ! isEven ) ; if ( left == 0 && right == 0 ) return 0 ; return ( 1 + max ( left , right ) ) ; } 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 heightOfTree ( Node * root ) { return heightOfTreeUtil ( root , false ) ; } 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 -> right -> left = newNode ( 6 ) ; cout << " Height ▁ of ▁ tree ▁ is ▁ " << heightOfTree ( root ) ; return 0 ; }
Find Height of Binary Tree represented by Parent array | C ++ program to find height using parent array ; This function fills depth of i 'th element in parent[]. The depth is filled in depth[i]. ; If depth [ i ] is already filled ; If node at index i is root ; If depth of parent is not evaluated before , then evaluate depth of parent first ; Depth of this node is depth of parent plus 1 ; This function returns height of binary tree represented by parent array ; Create an array to store depth of all nodes / and initialize depth of every node as 0 ( an invalid value ) . Depth of root is 1 ; fill depth of all nodes ; The height of binary tree is maximum of all depths . Find the maximum value in depth [ ] and assign it to ht . ; Driver program to test above functions ; int parent [ ] = { 1 , 5 , 5 , 2 , 2 , - 1 , 3 } ;
#include <bits/stdc++.h> NEW_LINE using namespace std ; void fillDepth ( int parent [ ] , int i , int depth [ ] ) { if ( depth [ i ] ) return ; if ( parent [ i ] == -1 ) { depth [ i ] = 1 ; return ; } if ( depth [ parent [ i ] ] == 0 ) fillDepth ( parent , parent [ i ] , depth ) ; depth [ i ] = depth [ parent [ i ] ] + 1 ; } int findHeight ( int parent [ ] , int n ) { int depth [ n ] ; for ( int i = 0 ; i < n ; i ++ ) depth [ i ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) fillDepth ( parent , i , depth ) ; int ht = depth [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) if ( ht < depth [ i ] ) ht = depth [ i ] ; return ht ; } int main ( ) { int parent [ ] = { -1 , 0 , 0 , 1 , 1 , 3 , 5 } ; int n = sizeof ( parent ) / sizeof ( parent [ 0 ] ) ; cout << " Height ▁ is ▁ " << findHeight ( parent , n ) ; return 0 ; }
How to determine if a binary tree is height | CPP program to check if a tree is height - balanced or not ; A binary tree node has data , pointer to left child and a pointer to right child ; Returns the height of a binary tree ; Returns true if binary tree with root as root is height - balanced ; for height of left subtree ; for height of right subtree ; If tree is empty then return true ; Get the height of left and right sub trees ; If we reach here then tree is not height - balanced ; returns maximum of two integers ; The function Compute the " height " of a tree . Height is the number of nodes along the longest path from the root node down to the farthest leaf node . ; base case tree is empty ; If tree is not empty then height = 1 + max of left height and right heights ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int data ; node * left ; node * right ; } ; int height ( node * node ) ; bool isBalanced ( node * root ) { int lh ; int rh ; if ( root == NULL ) return 1 ; lh = height ( root -> left ) ; rh = height ( root -> right ) ; if ( abs ( lh - rh ) <= 1 && isBalanced ( root -> left ) && isBalanced ( root -> right ) ) return 1 ; return 0 ; } int max ( int a , int b ) { return ( a >= b ) ? a : b ; } int height ( node * node ) { if ( node == NULL ) return 0 ; return 1 + max ( height ( node -> left ) , height ( node -> right ) ) ; } node * newNode ( int data ) { node * Node = new node ( ) ; Node -> data = data ; Node -> left = NULL ; Node -> right = NULL ; return ( Node ) ; } 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 -> left -> left -> left = newNode ( 8 ) ; if ( isBalanced ( root ) ) cout << " Tree ▁ is ▁ balanced " ; else cout << " Tree ▁ is ▁ not ▁ balanced " ; return 0 ; }
Find height of a special binary tree whose leaf nodes are connected | C ++ program to calculate height of a special tree whose leaf nodes forms a circular doubly linked list ; A binary tree Node ; Helper function that allocates a new tree node ; function to check if given node is a leaf node or node ; If given node ' s ▁ left ' s right is pointing to given node and its right ' s ▁ left ▁ is ▁ pointing ▁ to ▁ the ▁ node ▁ ▁ itself ▁ then ▁ it ' s a leaf ; Compute the height of a tree -- the number of Nodes along the longest path from the root node down to the farthest leaf node . ; if node is NULL , return 0 ; if node is a leaf node , return 1 ; compute the depth of each subtree and take maximum ; Driver code ; Given tree contains 3 leaf nodes ; create circular doubly linked list out of leaf nodes of the tree set next pointer of linked list ; set prev pointer of linked list ; calculate height of the tree
#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 = NULL ; node -> right = NULL ; return node ; } bool isLeaf ( Node * node ) { return node -> left && node -> left -> right == node && node -> right && node -> right -> left == node ; } int maxDepth ( Node * node ) { if ( node == NULL ) return 0 ; if ( isLeaf ( node ) ) return 1 ; return 1 + max ( maxDepth ( node -> left ) , maxDepth ( node -> right ) ) ; } 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 -> left -> left -> left = newNode ( 6 ) ; Node * L1 = root -> left -> left -> left ; Node * L2 = root -> left -> right ; Node * L3 = root -> right ; L1 -> right = L2 , L2 -> right = L3 , L3 -> right = L1 ; L3 -> left = L2 , L2 -> left = L1 , L1 -> left = L3 ; cout << " Height ▁ of ▁ tree ▁ is ▁ " << maxDepth ( root ) ; return 0 ; }
Diameter of a Binary Tree | Recursive optimized C program to find the diameter of a Binary Tree ; 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 . ; returns max of two integers ; The function Compute the " height " of a tree . Height is the number f nodes along the longest path from the root node down to the farthest leaf node . ; base case tree is empty ; If tree is not empty then height = 1 + max of left height and right heights ; Function to get diameter of a binary tree ; base case where tree is empty ; get the height of left and right sub - trees ; get the diameter of left and right sub - trees ; Return max of following three 1 ) Diameter of left subtree 2 ) Diameter of right subtree 3 ) Height of left subtree + height of right subtree + 1 ; Driver Code ; Constructed binary tree is 1 / \ 2 3 / \ 4 5 ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int data ; struct node * left , * right ; } ; 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 max ( int a , int b ) { return ( a > b ) ? a : b ; } int height ( struct node * node ) { if ( node == NULL ) return 0 ; return 1 + max ( height ( node -> left ) , height ( node -> right ) ) ; } int diameter ( struct node * tree ) { if ( tree == NULL ) return 0 ; int lheight = height ( tree -> left ) ; int rheight = height ( tree -> right ) ; int ldiameter = diameter ( tree -> left ) ; int rdiameter = diameter ( tree -> right ) ; return max ( lheight + rheight + 1 , max ( ldiameter , rdiameter ) ) ; } 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 ) ; cout << " Diameter ▁ of ▁ the ▁ given ▁ binary ▁ tree ▁ is ▁ " << diameter ( root ) ; return 0 ; }
Find if possible to visit every nodes in given Graph exactly once based on given conditions | C ++ program for above approach . ; Function to find print path ; If a [ 0 ] is 1 ; Printing path ; Seeking for a [ i ] = 0 and a [ i + 1 ] = 1 ; Printing path ; If a [ N - 1 ] = 0 ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findpath ( int N , int a [ ] ) { if ( a [ 0 ] ) { cout << " ▁ " << N + 1 ; for ( int i = 1 ; i <= N ; i ++ ) cout << " ▁ " << i ; return ; } for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( ! a [ i ] && a [ i + 1 ] ) { for ( int j = 1 ; j <= i ; j ++ ) cout << " ▁ " << j ; cout << " ▁ " << N + 1 ; for ( int j = i + 1 ; j <= N ; j ++ ) cout << " ▁ " << j ; return ; } } for ( int i = 1 ; i <= N ; i ++ ) cout << " ▁ " << i ; cout << " ▁ " << N + 1 ; } int main ( ) { int N = 3 , arr [ ] = { 0 , 1 , 0 } ; findpath ( N , arr ) ; }
Modify a numeric string to a balanced parentheses by replacements | C ++ program for the above approach ; Function to check if the given string can be converted to a balanced bracket sequence or not ; Check if the first and last characters are equal ; Initialize two variables to store the count of open and closed brackets ; If the current character is same as the first character ; If the current character is same as the last character ; If count of open brackets becomes less than 0 ; Print the new string ; If the current character is same as the first character ; If bracket sequence is not balanced ; Check for unbalanced bracket sequence ; Print the sequence ; Driver Code ; Given Input ; Function Call
#include <iostream> NEW_LINE using namespace std ; void balBracketSequence ( string str ) { int n = str . size ( ) ; if ( str [ 0 ] == str [ n - 1 ] ) { cout << " No " << endl ; } else { int cntForOpen = 0 , cntForClose = 0 ; int check = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == str [ 0 ] ) cntForOpen ++ ; else if ( str [ i ] == str [ n - 1 ] ) cntForOpen -- ; else cntForOpen ++ ; if ( cntForOpen < 0 ) { check = 0 ; break ; } } if ( check && cntForOpen == 0 ) { cout << " Yes , ▁ " ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == str [ n - 1 ] ) cout << ' ) ' ; else cout << ' ( ' ; } return ; } else { for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == str [ 0 ] ) cntForClose ++ ; else cntForClose -- ; if ( cntForClose < 0 ) { check = 0 ; break ; } } if ( check && cntForClose == 0 ) { cout << " Yes , ▁ " ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == str [ 0 ] ) cout << ' ( ' ; else cout << ' ) ' ; } return ; } } cout << " No " ; } } int main ( ) { string str = "123122" ; balBracketSequence ( str ) ; return 0 ; }
Diameter of a Binary Tree | Recursive optimized C ++ program to find the diameter of a Binary Tree ; 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 . ; define height = 0 globally and call diameterOpt ( root , height ) from main ; lh -- > Height of left subtree rh -- > Height of right subtree ; ldiameter -- > diameter of left subtree rdiameter -- > Diameter of right subtree ; base condition - when binary tree is empty ; diameter is also 0 ; Get the heights of left and right subtrees in lh and rh And store the returned values in ldiameter and ldiameter ; Height of current node is max of heights of left and right subtrees plus 1 ; Driver Code ; Constructed binary tree is 1 / \ 2 3 / \ 4 5 ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int data ; struct node * left , * right ; } ; 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 diameterOpt ( struct node * root , int * height ) { int lh = 0 , rh = 0 ; int ldiameter = 0 , rdiameter = 0 ; if ( root == NULL ) { * height = 0 ; return 0 ; } ldiameter = diameterOpt ( root -> left , & lh ) ; rdiameter = diameterOpt ( root -> right , & rh ) ; * height = max ( lh , rh ) + 1 ; return max ( lh + rh + 1 , max ( ldiameter , rdiameter ) ) ; } 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 ) ; int height = 0 ; cout << " Diameter ▁ of ▁ the ▁ given ▁ binary ▁ tree ▁ is ▁ " << diameterOpt ( root , & height ) ; return 0 ; }
Diameter of a Binary Tree in O ( n ) [ A new method ] | Simple C ++ program to find diameter of a binary tree . ; Tree node structure used in the program ; Function to find height of a tree ; update the answer , because diameter of a tree is nothing but maximum value of ( left_height + right_height + 1 ) for each node ; Computes the diameter of binary tree with given root . ; This will store the final answer ; A utility function to create a new Binary Tree Node ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; int height ( Node * root , int & ans ) { if ( root == NULL ) return 0 ; int left_height = height ( root -> left , ans ) ; int right_height = height ( root -> right , ans ) ; ans = max ( ans , 1 + left_height + right_height ) ; return 1 + max ( left_height , right_height ) ; } int diameter ( Node * root ) { if ( root == NULL ) return 0 ; int ans = INT_MIN ; height ( root , ans ) ; return ans ; } 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 ) ; printf ( " Diameter ▁ is ▁ % d STRNEWLINE " , diameter ( root ) ) ; return 0 ; }
Find postorder traversal of BST from preorder traversal | Run loop from 1 to length of pre ; Print from pivot length - 1 to zero ; Print from end to pivot length ; Driver Code
#include <iostream> NEW_LINE using namespace std ; void getPostOrderBST ( int pre [ ] , int N ) { int pivotPoint = 0 ; for ( int i = 1 ; i < N ; i ++ ) { if ( pre [ 0 ] <= pre [ i ] ) { pivotPoint = i ; break ; } } for ( int i = pivotPoint - 1 ; i > 0 ; i -- ) { cout << pre [ i ] << " ▁ " ; } for ( int i = N - 1 ; i >= pivotPoint ; i -- ) { cout << pre [ i ] << " ▁ " ; } cout << pre [ 0 ] ; }
Count substrings made up of a single distinct character | ; Function to count the number of substrings made up of a single distinct character ; Stores the required count ; Stores the count of substrings possible by using current character ; Stores the previous character ; Traverse the string ; If current character is same as the previous character ; Increase count of substrings possible with current character ; Reset count of substrings possible with current character ; Update count of substrings ; Update previous character ; Driver code
#include <iostream> NEW_LINE using namespace std ; void countSubstrings ( string s ) { int ans = 0 ; int subs = 1 ; char pre = '0' ; for ( auto & i : s ) { if ( pre == i ) { subs += 1 ; } else { subs = 1 ; } ans += subs ; pre = i ; } cout << ans << endl ; } int main ( ) { string s = " geeksforgeeks " ; countSubstrings ( s ) ; return 0 ; }
Generate an array from given pairs of adjacent elements | C ++ program of the above approach ; Utility function to find original array ; Map to store all neighbors for each element ; Vector to store original elements ; Stotrs which array elements are visited ; Adjacency list to store neighbors of each array element ; Find the first corner element ; Stores first element of the original array ; Push it into the original array ; Mark as visited ; Traversing the neighbors and check if the elements are visited or not ; Traverse adjacent elements ; If element is not visited ; Push it into res ; Mark as visited ; Update the next adjacent ; Print original array ; Driver Code ; Given pairs of adjacent elements
#include <bits/stdc++.h> NEW_LINE using namespace std ; void find_original_array ( vector < pair < int , int > > & A ) { unordered_map < int , vector < int > > mp ; vector < int > res ; unordered_map < int , bool > visited ; for ( auto & it : A ) { mp [ it . first ] . push_back ( it . second ) ; mp [ it . second ] . push_back ( it . first ) ; } auto it = mp . begin ( ) ; for ( ; it != mp . end ( ) ; it ++ ) { if ( it -> second . size ( ) == 1 ) { break ; } } int adjacent = it -> first ; res . push_back ( it -> first ) ; visited [ it -> first ] = true ; while ( res . size ( ) != A . size ( ) + 1 ) { for ( auto & elements : mp [ adjacent ] ) { if ( ! visited [ elements ] ) { res . push_back ( elements ) ; visited [ elements ] = true ; adjacent = elements ; } } } for ( auto it : res ) { cout << it << " ▁ " ; } } int main ( ) { vector < pair < int , int > > A = { { 5 , 1 } , { 3 , 4 } , { 3 , 5 } } ; find_original_array ( A ) ; return 0 ; }
Possible edges of a tree for given diameter , height and vertices | C ++ program to construct tree for given count width and height . ; Function to construct the tree ; Special case when d == 2 , only one edge ; Tree is not possible ; Satisfy the height condition by add edges up to h ; Add d - h edges from 1 to satisfy diameter condition ; Remaining edges at vertex 1 or 2 ( d == h ) ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void constructTree ( int n , int d , int h ) { if ( d == 1 ) { if ( n == 2 && h == 1 ) { cout << "1 ▁ 2" << endl ; return ; } cout << " - 1" << endl ; return ; } if ( d > 2 * h ) { cout << " - 1" << endl ; return ; } for ( int i = 1 ; i <= h ; i ++ ) cout << i << " ▁ " << i + 1 << endl ; if ( d > h ) { cout << "1" << " ▁ " << h + 2 << endl ; for ( int i = h + 2 ; i <= d ; i ++ ) { cout << i << " ▁ " << i + 1 << endl ; } } for ( int i = d + 1 ; i < n ; i ++ ) { int k = 1 ; if ( d == h ) k = 2 ; cout << k << " ▁ " << i + 1 << endl ; } } int main ( ) { int n = 5 , d = 3 , h = 2 ; constructTree ( n , d , h ) ; return 0 ; }
Query to find length of the longest subarray consisting only of 1 s | C ++ Program for the above approach ; Function to calculate the longest subarray consisting of 1 s only ; Stores the maximum length of subarray containing 1 s only ; Traverse the array ; If current element is '1' ; Increment length ; Otherwise ; Reset length ; Update maximum subarray length ; Function to perform given queries ; Stores count of queries ; Traverse each query ; Flip the character ; Driver Code ; Size of array ; Given array ; Given queries ; Number of queries
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longestsubarray ( int a [ ] , int N ) { int maxlength = 0 , sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( a [ i ] == 1 ) { sum ++ ; } else { sum = 0 ; } maxlength = max ( maxlength , sum ) ; } return maxlength ; } void solveQueries ( int arr [ ] , int n , vector < vector < int > > Q , int k ) { int cntQuery = Q . size ( ) ; for ( int i = 0 ; i < cntQuery ; i ++ ) { if ( Q [ i ] [ 0 ] == 1 ) { cout << longestsubarray ( arr , n ) << " ▁ " ; } else { arr [ Q [ i ] [ 1 ] - 1 ] ^= 1 ; } } } int main ( ) { int N = 10 ; int arr [ ] = { 1 , 1 , 0 , 1 , 1 , 1 , 0 , 0 , 1 , 1 } ; vector < vector < int > > Q = { { 1 } , { 2 , 3 } , { 1 } } ; int K = 3 ; solveQueries ( arr , N , Q , K ) ; }
Smallest element present in every subarray of all possible lengths | C ++ program for the above approach ; Function to add count of numbers in the map for a subarray of length k ; Set to store unique elements ; Add elements to the set ; Iterator of the set ; Adding count in map ; Function to check if there is any number which repeats itself in every subarray of length K ; Check all number starting from 1 ; Check if i occurred n - k + 1 times ; Print the smallest number ; Print - 1 , if no such number found ; Function to count frequency of each number in each subarray of length K ; Traverse all subarrays of length K ; Check and print the smallest number present in every subarray and print it ; Function to generate the value of K ; Function call ; Driver Code ; Given array ; Size of array ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void uniqueElements ( int arr [ ] , int start , int K , map < int , int > & mp ) { set < int > st ; for ( int i = 0 ; i < K ; i ++ ) st . insert ( arr [ start + i ] ) ; set < int > :: iterator itr = st . begin ( ) ; for ( ; itr != st . end ( ) ; itr ++ ) mp [ * itr ] ++ ; } void checkAnswer ( map < int , int > & mp , int N , int K ) { for ( int i = 1 ; i <= N ; i ++ ) { if ( mp [ i ] == ( N - K + 1 ) ) { cout << i << " ▁ " ; return ; } } cout << -1 << " ▁ " ; } void smallestPresentNumber ( int arr [ ] , int N , int K ) { map < int , int > mp ; for ( int i = 0 ; i <= N - K ; i ++ ) { uniqueElements ( arr , i , K , mp ) ; } checkAnswer ( mp , N , K ) ; } void generateK ( int arr [ ] , int N ) { for ( int k = 1 ; k <= N ; k ++ ) smallestPresentNumber ( arr , N , k ) ; } int main ( ) { int arr [ ] = { 2 , 3 , 5 , 3 , 2 , 3 , 1 , 3 , 2 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; generateK ( arr , N ) ; return ( 0 ) ; }
Deepest right leaf node in a binary tree | Iterative approach | CPP program to find deepest right leaf node of binary tree ; tree node ; returns a new tree Node ; return the deepest right leaf node of binary tree ; create a queue for level order traversal ; traverse until the queue is empty ; Since we go level by level , the last stored right leaf node is deepest one ; 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 ; } Node * getDeepestRightLeafNode ( Node * root ) { if ( ! root ) return NULL ; queue < Node * > q ; q . push ( root ) ; Node * result = NULL ; while ( ! q . empty ( ) ) { Node * temp = q . front ( ) ; q . pop ( ) ; if ( temp -> left ) { q . push ( temp -> left ) ; } if ( temp -> right ) { q . push ( temp -> right ) ; if ( ! temp -> right -> left && ! temp -> right -> right ) result = temp -> right ; } } return result ; } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> right = newNode ( 4 ) ; root -> right -> left = newNode ( 5 ) ; root -> right -> right = newNode ( 6 ) ; root -> right -> left -> right = newNode ( 7 ) ; root -> right -> right -> right = newNode ( 8 ) ; root -> right -> left -> right -> left = newNode ( 9 ) ; root -> right -> right -> right -> right = newNode ( 10 ) ; Node * result = getDeepestRightLeafNode ( root ) ; if ( result ) cout << " Deepest ▁ Right ▁ Leaf ▁ Node ▁ : : ▁ " << result -> data << endl ; else cout << " No ▁ result , ▁ right ▁ leaf ▁ not ▁ found STRNEWLINE " ; return 0 ; }
Check if two strings can be made equal by reversing a substring of one of the strings | C ++ program for the above approach ; Function to check if the strings can be made equal or not by reversing a substring of X ; Store the first index from the left which contains unequal characters in both the strings ; Store the first element from the right which contains unequal characters in both the strings ; Checks for the first index from left in which characters in both the strings are unequal ; Store the current index ; Break out of the loop ; Checks for the first index from right in which characters in both the strings are unequal ; Store the current index ; Break out of the loop ; Reverse the substring X [ L , R ] ; If X and Y are equal ; Otherwise ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkString ( string X , string Y ) { int L = -1 ; int R = -1 ; for ( int i = 0 ; i < X . length ( ) ; ++ i ) { if ( X [ i ] != Y [ i ] ) { L = i ; break ; } } for ( int i = X . length ( ) - 1 ; i > 0 ; -- i ) { if ( X [ i ] != Y [ i ] ) { R = i ; break ; } } reverse ( X . begin ( ) + L , X . begin ( ) + R + 1 ) ; if ( X == Y ) { cout << " Yes " ; } else { cout << " No " ; } } int main ( ) { string X = " adcbef " , Y = " abcdef " ; checkString ( X , Y ) ; return 0 ; }
Maximum length of same indexed subarrays from two given arrays satisfying the given condition | C ++ program for the above approach ; Stores the segment tree node values ; Function to find maximum length of subarray such that sum of maximum element in subarray in brr [ ] and sum of subarray in arr [ ] * K is at most C ; Base Case ; Let maximum length be 0 ; Perform Binary search ; Find mid value ; Check if the current mid satisfy the given condition ; If yes , then store length ; Otherwise ; Return maximum length stored ; Function to check if it is possible to have such a subarray of length K ; Check for first window of size K ; Calculate the total cost and check if less than equal to c ; If it satisfy the condition ; Find the sum of current subarray and calculate total cost ; Include the new element of current subarray ; Discard the element of last subarray ; Calculate total cost and check <= c ; If possible , then return true ; If it is not possible ; Function that builds segment Tree ; If there is only one element ; Find the value of mid ; Build left and right parts of segment tree recursively ; Update the value at current index ; Function to find maximum element in the given range ; If the query is out of bounds ; If the segment is completely inside the query range ; Calculate the mid ; Return maximum in left & right of the segment tree recursively ; Function that initializes the segment Tree ; Driver Code ; Initialize and Build the Segment Tree ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int seg [ 10000 ] ; int maxLength ( int a [ ] , int b [ ] , int n , int c ) { if ( n == 0 ) return 0 ; int max_length = 0 ; int low = 0 , high = n ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( possible ( a , b , n , c , mid ) != false ) { max_length = mid ; low = mid + 1 ; } else high = mid - 1 ; } return max_length ; } bool possible ( int a [ ] , int b [ ] , int n , int c , int k ) { int sum = 0 ; for ( int i = 0 ; i < k ; i ++ ) { sum += a [ i ] ; } int total_cost = sum * k + getMax ( b , 0 , n - 1 , 0 , k - 1 , 0 ) ; if ( total_cost <= c ) return true ; for ( int i = k ; i < n ; i ++ ) { sum += a [ i ] ; sum -= a [ i - k ] ; total_cost = sum * k + getMax ( b , 0 , n - 1 , i - k + 1 , i , 0 ) ; if ( total_cost <= c ) return true ; } return false ; } void build ( int b [ ] , int index , int s , int e ) { if ( s == e ) { seg [ index ] = b [ s ] ; return ; } int mid = s + ( e - s ) / 2 ; build ( b , 2 * index + 1 , s , mid ) ; build ( b , 2 * index + 2 , mid + 1 , e ) ; seg [ index ] = max ( seg [ 2 * index + 1 ] , seg [ 2 * index + 2 ] ) ; } int getMax ( int b [ ] , int ss , int se , int qs , int qe , int index ) { if ( se < qs ss > qe ) return INT_MIN / 2 ; if ( ss >= qs && se <= qe ) return seg [ index ] ; int mid = ss + ( se - ss ) / 2 ; return max ( getMax ( b , ss , mid , qs , qe , 2 * index + 1 ) , getMax ( b , mid + 1 , se , qs , qe , 2 * index + 2 ) ) ; } void initialiseSegmentTree ( int N ) { int seg [ 4 * N ] ; } int main ( ) { int A [ ] = { 1 , 2 , 1 , 6 , 5 , 5 , 6 , 1 } ; int B [ ] = { 14 , 8 , 15 , 15 , 9 , 10 , 7 , 12 } ; int C = 40 ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; initialiseSegmentTree ( N ) ; build ( B , 0 , 0 , N - 1 ) ; cout << ( maxLength ( A , B , N , C ) ) ; }
Maximum length of same indexed subarrays from two given arrays satisfying the given condition | C ++ program for the above approach ; Function to find maximum length of subarray such that sum of maximum element in subarray in brr [ ] and sum of subarray in arr [ ] * K is at most C ; Base Case ; Let maximum length be 0 ; Perform Binary search ; Find mid value ; Check if the current mid satisfy the given condition ; If yes , then store length ; Otherwise ; Return maximum length stored ; Function to check if it is possible to have such a subarray of length K ; Finds the maximum element in each window of size k ; Check for window of size K ; For all possible subarrays of length k ; Until deque is empty ; Calculate the total cost and check if less than equal to c ; Find sum of current subarray and the total cost ; Include the new element of current subarray ; Discard the element of last subarray ; Remove all the elements in the old window ; Calculate total cost and check <= c ; If current subarray length satisfies ; If it is not possible ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxLength ( int a [ ] , int b [ ] , int n , int c ) { if ( n == 0 ) return 0 ; int max_length = 0 ; int low = 0 , high = n ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( possible ( a , b , n , c , mid ) ) { max_length = mid ; low = mid + 1 ; } else high = mid - 1 ; } return max_length ; } bool possible ( int a [ ] , int b [ ] , int n , int c , int k ) { deque < int > dq ; int sum = 0 ; for ( int i = 0 ; i < k ; i ++ ) { sum += a [ i ] ; while ( dq . size ( ) > 0 && b [ i ] > b [ dq . back ( ) ] ) dq . pop_back ( ) ; dq . push_back ( i ) ; } int total_cost = sum * k + b [ dq . front ( ) ] ; if ( total_cost <= c ) return true ; for ( int i = k ; i < n ; i ++ ) { sum += a [ i ] ; sum -= a [ i - k ] ; while ( dq . size ( ) > 0 && dq . front ( ) <= i - k ) dq . pop_front ( ) ; while ( dq . size ( ) > 0 && b [ i ] > b [ dq . back ( ) ] ) dq . pop_back ( ) ; dq . push_back ( i ) ; total_cost = sum * k + b [ dq . front ( ) ] ; if ( total_cost <= c ) return true ; } return false ; } int main ( ) { int A [ ] = { 1 , 2 , 1 , 6 , 5 , 5 , 6 , 1 } ; int B [ ] = { 14 , 8 , 15 , 15 , 9 , 10 , 7 , 12 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int C = 40 ; cout << maxLength ( A , B , N , C ) ; return 0 ; }
Program to find the Nth natural number with exactly two bits set | Set 2 | C ++ program for the above approach ; Function to find the Nth number with exactly two bits set ; Initialize variables ; Initialize the range in which the value of ' a ' is present ; Perform Binary Search ; Find the mid value ; Update the range using the mid value t ; Find b value using a and N ; Print the value 2 ^ a + 2 ^ b ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findNthNum ( long long int N ) { long long int a , b , left ; long long int right , mid ; long long int t , last_num = 0 ; left = 1 , right = N ; while ( left <= right ) { mid = left + ( right - left ) / 2 ; t = ( mid * ( mid + 1 ) ) / 2 ; if ( t < N ) { left = mid + 1 ; } else if ( t == N ) { a = mid ; break ; } else { a = mid ; right = mid - 1 ; } } t = a - 1 ; b = N - ( t * ( t + 1 ) ) / 2 - 1 ; cout << ( 1 << a ) + ( 1 << b ) ; } int main ( ) { long long int N = 15 ; findNthNum ( N ) ; return 0 ; }
Longest subsequence having maximum sum | C ++ program to implement the above approach ; Function to find the longest subsequence from the given array with maximum sum ; Stores the largest element of the array ; If Max is less than 0 ; Print the largest element of the array ; Traverse the array ; If arr [ i ] is greater than or equal to 0 ; Print elements of the subsequence ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void longestSubWithMaxSum ( int arr [ ] , int N ) { int Max = * max_element ( arr , arr + N ) ; if ( Max < 0 ) { cout << Max ; return ; } for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] >= 0 ) { cout << arr [ i ] << " ▁ " ; } } } int main ( ) { int arr [ ] = { 1 , 2 , -4 , -2 , 3 , 0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; longestSubWithMaxSum ( arr , N ) ; return 0 ; }
Check if string S2 can be obtained by appending subsequences of string S1 | C ++ Program to implement the above approach ; Function for finding minimum number of operations ; Stores the length of strings ; Stores frequency of characters in string s ; Update frequencies of character in s ; Traverse string s1 ; If any character in s1 is not present in s ; Stores the indices of each character in s ; Traverse string s ; Store indices of characters ; Stores index of last appended character ; Traverse string s1 ; Find the index of next character that can be appended ; Check if the current character be included in the current subsequence ; Otherwise ; Start a new subsequence ; Update index of last character appended ; Driver Code ; If S2 cannot be obtained from subsequences of S1 ; Otherwise
#include " bits / stdc + + . h " NEW_LINE using namespace std ; int findMinimumOperations ( string s , string s1 ) { int n = s . length ( ) , m = s1 . length ( ) ; int frequency [ 26 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) frequency [ s [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < m ; i ++ ) { if ( frequency [ s1 [ i ] - ' a ' ] == 0 ) { return -1 ; } } set < int > indices [ 26 ] ; for ( int i = 0 ; i < n ; i ++ ) { indices [ s [ i ] - ' a ' ] . insert ( i ) ; } int ans = 1 ; int last = ( * indices [ s1 [ 0 ] - ' a ' ] . begin ( ) ) ; for ( int i = 1 ; i < m ; i ++ ) { int ch = s1 [ i ] - ' a ' ; auto it = indices [ ch ] . upper_bound ( last ) ; if ( it != indices [ ch ] . end ( ) ) { last = ( * it ) ; } else { ans ++ ; last = ( * indices [ ch ] . begin ( ) ) ; } } return ans ; } int main ( ) { string S1 = " acebcd " , S2 = " acbcde " ; int ans = findMinimumOperations ( S1 , S2 ) ; if ( ans == -1 ) { cout << " NO STRNEWLINE " ; } else { cout << " YES STRNEWLINE " << ans ; } return 0 ; }
Sink Odd nodes in Binary Tree | Program to sink odd nodes to the bottom of binary tree ; A binary tree node ; Helper function to allocates a new node ; Helper function to check if node is leaf node ; A recursive method to sink a tree with odd root This method assumes that the subtrees are already sinked . This method is similar to Heapify of Heap - Sort ; If NULL or is a leaf , do nothing ; if left subtree exists and left child is even ; swap root 's data with left child and fix left subtree ; if right subtree exists and right child is even ; swap root 's data with right child and fix right subtree ; Function to sink all odd nodes to the bottom of binary tree . It does a postorder traversal and calls sink ( ) if any odd node is found ; If NULL or is a leaf , do nothing ; Process left and right subtrees before this node ; If root is odd , sink it ; Helper function to do Level Order Traversal of Binary Tree level by level . This function is used here only for showing modified tree . ; Do Level order traversal ; Print one level at a time ; Line separator for levels ; Driver program to test above functions ; Constructed binary tree is 1 / \ 5 8 / \ / \ 2 4 9 10
#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 ; } bool isLeaf ( Node * root ) { return ( root -> left == NULL && root -> right == NULL ) ; } void sink ( Node * & root ) { if ( root == NULL || isLeaf ( root ) ) return ; if ( root -> left && ! ( root -> left -> data & 1 ) ) { swap ( root -> data , root -> left -> data ) ; sink ( root -> left ) ; } else if ( root -> right && ! ( root -> right -> data & 1 ) ) { swap ( root -> data , root -> right -> data ) ; sink ( root -> right ) ; } } void sinkOddNodes ( Node * & root ) { if ( root == NULL || isLeaf ( root ) ) return ; sinkOddNodes ( root -> left ) ; sinkOddNodes ( root -> right ) ; if ( root -> data & 1 ) sink ( root ) ; } void printLevelOrder ( Node * root ) { queue < Node * > q ; q . push ( root ) ; while ( ! q . empty ( ) ) { int nodeCount = q . size ( ) ; while ( nodeCount ) { Node * node = q . front ( ) ; printf ( " % d ▁ " , node -> data ) ; q . pop ( ) ; if ( node -> left != NULL ) q . push ( node -> left ) ; if ( node -> right != NULL ) q . push ( node -> right ) ; nodeCount -- ; } printf ( " STRNEWLINE " ) ; } } int main ( ) { Node * root = newnode ( 1 ) ; root -> left = newnode ( 5 ) ; root -> right = newnode ( 8 ) ; root -> left -> left = newnode ( 2 ) ; root -> left -> right = newnode ( 4 ) ; root -> right -> left = newnode ( 9 ) ; root -> right -> right = newnode ( 10 ) ; sinkOddNodes ( root ) ; printf ( " Level ▁ order ▁ traversal ▁ of ▁ modified ▁ tree STRNEWLINE " ) ; printLevelOrder ( root ) ; return 0 ; }
Print first K distinct Moran numbers from a given array | ; Function to calculate the sum of digits of a number ; Stores the sum of digits ; Add the digit to sum ; Remove digit ; Returns the sum of digits ; Function to check if a number is prime or not ; If r has any divisor ; Set r as non - prime ; Function to check if a number is moran number ; Calculate sum of digits ; Check if n is divisible by the sum of digits ; Calculate the quotient ; If the quotient is prime ; Function to print the first K Moran numbers from the array ; Sort the given array ; Initialise a set ; Traverse the array from the end ; If the current array element is a Moran number ; Insert into the set ; Driver Code
#include <algorithm> NEW_LINE #include <iostream> NEW_LINE #include <set> NEW_LINE using namespace std ; int digiSum ( int a ) { int sum = 0 ; while ( a ) { sum += a % 10 ; a = a / 10 ; } return sum ; } bool isPrime ( int r ) { bool s = true ; for ( int i = 2 ; i * i <= r ; i ++ ) { if ( r % i == 0 ) { s = false ; break ; } } return s ; } bool isMorannumber ( int n ) { int dup = n ; int sum = digiSum ( dup ) ; if ( n % sum == 0 ) { int c = n / sum ; if ( isPrime ( c ) ) { return true ; } } return false ; } void FirstKMorannumber ( int a [ ] , int n , int k ) { int X = k ; sort ( a , a + n ) ; set < int > s ; for ( int i = n - 1 ; i >= 0 && k > 0 ; i -- ) { if ( isMorannumber ( a [ i ] ) ) { s . insert ( a [ i ] ) ; k -- ; } } if ( k > 0 ) { cout << X << " ▁ Moran ▁ numbers ▁ are " << " ▁ not ▁ present ▁ in ▁ the ▁ array " << endl ; return ; } set < int > :: iterator it ; for ( it = s . begin ( ) ; it != s . end ( ) ; ++ it ) { cout << * it << " , ▁ " ; } cout << endl ; } int main ( ) { int A [ ] = { 34 , 198 , 21 , 42 , 63 , 45 , 22 , 44 , 43 } ; int K = 4 ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; FirstKMorannumber ( A , N , K ) ; return 0 ; }
Number of pairs whose sum is a power of 2 | Set 2 | C ++ program to implement the above approach ; Function to count all pairs whose sum is a power of two ; Stores the frequency of each element of the array ; Update frequency of array elements ; Stores count of required pairs ; Current power of 2 ; Traverse the array ; If pair does not exist ; Increment count of pairs ; Return the count of pairs ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPair ( int arr [ ] , int n ) { map < int , int > m ; for ( int i = 0 ; i < n ; i ++ ) m [ arr [ i ] ] ++ ; int ans = 0 ; for ( int i = 0 ; i < 31 ; i ++ ) { int key = pow ( 2 , i ) ; for ( int j = 0 ; j < n ; j ++ ) { int k = key - arr [ j ] ; if ( m . find ( k ) == m . end ( ) ) continue ; else ans += m [ k ] ; if ( k == arr [ j ] ) ans ++ ; } } return ans / 2 ; } int main ( ) { int arr [ ] = { 1 , 8 , 2 , 10 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPair ( arr , n ) << endl ; return 0 ; }
Longest Subsequence from a numeric String divisible by K | C ++ program for the above approach ; Function to if the integer representation of the current string is divisible by K ; Stores the integer representation of the string ; Check if the num is divisible by K ; Function to find the longest subsequence which is divisible by K ; If the number is divisible by K ; If current number is the maximum obtained so far ; Include the digit at current index ; Exclude the digit at current index ; Driver Code ; Printing the largest number which is divisible by K ; If no number is found to be divisible by K
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isdivisible ( string & newstr , long long K ) { long long num = 0 ; for ( int i = 0 ; i < newstr . size ( ) ; i ++ ) { num = num * 10 + newstr [ i ] - '0' ; } if ( num % K == 0 ) return true ; else return false ; } void findLargestNo ( string & str , string & newstr , string & ans , int index , long long K ) { if ( index == ( int ) str . length ( ) ) { if ( isdivisible ( newstr , K ) ) { if ( ( ans < newstr && ans . length ( ) == newstr . length ( ) ) || newstr . length ( ) > ans . length ( ) ) { ans = newstr ; } } return ; } string x = newstr + str [ index ] ; findLargestNo ( str , x , ans , index + 1 , K ) ; findLargestNo ( str , newstr , ans , index + 1 , K ) ; } int main ( ) { string str = "121400" ; string ans = " " , newstr = " " ; long long K = 8 ; findLargestNo ( str , newstr , ans , 0 , K ) ; if ( ans != " " ) cout << ans << endl ; else cout << -1 << endl ; }
Counting Rock Samples | TCS Codevita 2020 | C ++ program of the above approach ; Function to find the rock samples in the ranges ; Iterate over the ranges ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findRockSample ( vector < vector < int > > ranges , int n , int r , vector < int > arr ) { vector < int > a ; for ( int i = 0 ; i < r ; i ++ ) { int c = 0 ; int l = ranges [ i ] [ 0 ] ; int h = ranges [ i ] [ 1 ] ; for ( int j = 0 ; j < arr . size ( ) ; j ++ ) { if ( l <= arr [ j ] && arr [ j ] <= h ) c += 1 ; } a . push_back ( c ) ; } for ( auto i : a ) cout << i << " ▁ " ; } int main ( ) { int n = 5 ; int r = 2 ; vector < int > arr = { 400 , 567 , 890 , 765 , 987 } ; vector < vector < int > > ranges = { { 300 , 380 } , { 800 , 1000 } } ; findRockSample ( ranges , n , r , arr ) ; }
Depth of the deepest odd level node in Binary Tree | C ++ program to find depth of the deepest odd level node ; A Tree node ; Utility function to create a new node ; Utility function which returns whether the current node is a leaf or not ; function to return the longest odd level depth if it exists otherwise 0 ; Base case return from here ; increment current level ; if curr_level is odd and its a leaf node ; A wrapper over deepestOddLevelDepth ( ) ; 10 / \ 28 13 / \ 14 15 / \ 23 24 Let us create Binary Tree shown in above example
#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 ) ; } bool isleaf ( Node * curr_node ) { return ( curr_node -> left == NULL && curr_node -> right == NULL ) ; } int deepestOddLevelDepthUtil ( Node * curr_node , int curr_level ) { if ( curr_node == NULL ) return 0 ; curr_level += 1 ; if ( curr_level % 2 != 0 && isleaf ( curr_node ) ) return curr_level ; return max ( deepestOddLevelDepthUtil ( curr_node -> left , curr_level ) , deepestOddLevelDepthUtil ( curr_node -> right , curr_level ) ) ; } int deepestOddLevelDepth ( Node * curr_node ) { return deepestOddLevelDepthUtil ( curr_node , 0 ) ; } int main ( ) { Node * root = newNode ( 10 ) ; root -> left = newNode ( 28 ) ; root -> right = newNode ( 13 ) ; root -> right -> left = newNode ( 14 ) ; root -> right -> right = newNode ( 15 ) ; root -> right -> right -> left = newNode ( 23 ) ; root -> right -> right -> right = newNode ( 24 ) ; cout << deepestOddLevelDepth ( root ) << endl ; return 0 ; }
N digit numbers having difference between the first and last digits as K | C ++ program for the above approach ; Function to store and check the difference of digits ; Base Case ; Last digit of the number to check the difference from the first digit ; Condition to avoid repeated values ; Update the string pt ; Recursive Call ; Update the string pt ; Recursive Call ; Any number can come in between first and last except the zero ; Recursive Call ; Function to place digit of the number ; When N is 1 and K > 0 , then the single number will be the first and last digit it cannot have difference greater than 0 ; This loop place the digit at the starting ; Recursive Call ; Vector to store results ; Generate all the resultant number ; Print the result ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findNumbers ( string st , vector < int > & result , int prev , int n , int K ) { if ( st . length ( ) == n ) { result . push_back ( stoi ( st ) ) ; return ; } if ( st . size ( ) == n - 1 ) { if ( prev - K >= 0 ) { string pt = " " ; pt += prev - K + 48 ; findNumbers ( st + pt , result , prev - K , n , K ) ; } if ( K != 0 && prev + K < 10 ) { string pt = " " ; pt += prev + K + 48 ; findNumbers ( st + pt , result , prev + K , n , K ) ; } } else { for ( int j = 1 ; j <= 9 ; j ++ ) { string pt = " " ; pt += j + 48 ; findNumbers ( st + pt , result , prev , n , K ) ; } } } vector < int > numDifference ( int N , int K ) { vector < int > res ; string st = " " ; if ( N == 1 && K == 0 ) { res . push_back ( 0 ) ; } else if ( N == 1 && K > 0 ) { return res ; } for ( int i = 1 ; i < 10 ; i ++ ) { string temp = " " ; temp += 48 + i ; findNumbers ( st + temp , res , i , N , K ) ; st = " " ; } return res ; } void numDifferenceUtil ( int N , int K ) { vector < int > res ; res = numDifference ( N , K ) ; for ( int i = 0 ; i < res . size ( ) ; i ++ ) { cout << res [ i ] << " ▁ " ; } } int main ( ) { int N = 2 , K = 9 ; numDifferenceUtil ( N , K ) ; return 0 ; }