text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Twin Prime Numbers between 1 and n | C ++ program print all twin primes using Sieve of Eratosthenes . ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; to check for twin prime numbers display the twin primes ; Driver Program to test above function ; Calling the function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printTwinPrime ( int n ) { bool prime [ n + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= n ; i += p ) prime [ i ] = false ; } } for ( int p = 2 ; p <= n - 2 ; p ++ ) if ( prime [ p ] && prime [ p + 2 ] ) cout << " ( " << p << " , ▁ " << p + 2 << " ) " ; } int main ( ) { int n = 25 ; printTwinPrime ( n ) ; return 0 ; }
Cube Free Numbers smaller than n | Simple C ++ Program to print all cube free numbers smaller than or equal to n . ; Returns true if n is a cube free number , else returns false . ; check for all possible divisible cubes ; Print all cube free numbers smaller than n . ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isCubeFree ( int n ) { if ( n == 1 ) return false ; for ( int i = 2 ; i * i * i <= n ; i ++ ) if ( n % ( i * i * i ) == 0 ) return false ; return true ; } void printCubeFree ( int n ) { for ( int i = 2 ; i <= n ; i ++ ) if ( isCubeFree ( i ) ) cout << i << " ▁ " ; } int main ( ) { int n = 20 ; printCubeFree ( n ) ; return 0 ; }
Decimal Equivalent of Gray Code and its Inverse | CPP Program to convert given decimal number of gray code into its inverse in decimal form ; Function to convert given decimal number of gray code into its inverse in decimal form ; Taking xor until n becomes zero ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int inversegrayCode ( int n ) { int inv = 0 ; for ( ; n ; n = n >> 1 ) inv ^= n ; return inv ; } int main ( ) { int n = 15 ; cout << inversegrayCode ( n ) << endl ; return 0 ; }
Product of unique prime factors of a number | C ++ program to find product of unique prime factors of a number ; A function to print all prime factors of a given number n ; Handle prime factor 2 explicitly so that can optimally handle other prime factors . ; n must be odd at this point . So we can skip one element ( Note i = i + 2 ) ; While i divides n , print i and divide n ; This condition is to handle the case when n is a prime number greater than 2 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long int productPrimeFactors ( int n ) { long long int product = 1 ; if ( n % 2 == 0 ) { product *= 2 ; while ( n % 2 == 0 ) n = n / 2 ; } for ( int i = 3 ; i <= sqrt ( n ) ; i = i + 2 ) { if ( n % i == 0 ) { product = product * i ; while ( n % i == 0 ) n = n / i ; } } if ( n > 2 ) product = product * n ; return product ; } int main ( ) { int n = 44 ; cout << productPrimeFactors ( n ) ; return 0 ; }
Maximizing Probability of one type from N containers | CPP program to find maximum probability of getting a copy ' A ' from N ; Returns the Maximum probability for Drawing 1 copy of number A from N containers with N copies each of numbers A and B ; Pmax = N / ( N + 1 ) ; Driver code ; 1. N = 1 ; 2. N = 2 ; 3. N = 10
#include <bits/stdc++.h> NEW_LINE using namespace std ; double calculateProbability ( int N ) { double probability = ( double ) N / ( N + 1 ) ; return probability ; } int main ( ) { int N ; double probabilityMax ; N = 1 ; probabilityMax = calculateProbability ( N ) ; cout << " Maximum ▁ Probability ▁ for ▁ N ▁ = ▁ " << N << " ▁ is , ▁ " << setprecision ( 4 ) << fixed << probabilityMax << endl ; N = 2 ; probabilityMax = calculateProbability ( N ) ; cout << " Maximum ▁ Probability ▁ for ▁ N ▁ = ▁ " << N << " ▁ is , ▁ " << setprecision ( 4 ) << fixed << probabilityMax << endl ; N = 10 ; probabilityMax = calculateProbability ( N ) ; cout << " Maximum ▁ Probability ▁ for ▁ N ▁ = ▁ " << N << " ▁ is , ▁ " << setprecision ( 4 ) << fixed << probabilityMax << endl ; return 0 ; }
Program to implement standard deviation of grouped data | CPP Program to implement standard deviation of grouped data . ; Function to find mean of grouped data . ; Function to find standard deviation of grouped data . ; Formula to find standard deviation of grouped data . ; Driver function . ; Declare and initialize the lower limit of interval . ; Declare and initialize the upper limit of interval . ; Calculating the size of array .
#include <bits/stdc++.h> NEW_LINE using namespace std ; float mean ( float mid [ ] , int freq [ ] , int n ) { float sum = 0 , freqSum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum = sum + mid [ i ] * freq [ i ] ; freqSum = freqSum + freq [ i ] ; } return sum / freqSum ; } float groupedSD ( float lower_limit [ ] , float upper_limit [ ] , int freq [ ] , int n ) { float mid [ n ] , sum = 0 , freqSum = 0 , sd ; for ( int i = 0 ; i < n ; i ++ ) { mid [ i ] = ( lower_limit [ i ] + upper_limit [ i ] ) / 2 ; sum = sum + freq [ i ] * mid [ i ] * mid [ i ] ; freqSum = freqSum + freq [ i ] ; } sd = sqrt ( ( sum - freqSum * mean ( mid , freq , n ) * mean ( mid , freq , n ) ) / ( freqSum - 1 ) ) ; return sd ; } int main ( ) { float lower_limit [ ] = { 50 , 61 , 71 , 86 , 96 } ; float upper_limit [ ] = { 60 , 70 , 85 , 95 , 100 } ; int freq [ ] = { 9 , 7 , 9 , 12 , 8 } ; int n = sizeof ( lower_limit ) / sizeof ( lower_limit [ 0 ] ) ; cout << groupedSD ( lower_limit , upper_limit , freq , n ) ; return 0 ; }
Average of first n even natural numbers | C ++ implementation to find Average of sum of first n natural even numbers ; function to find average of sum of first n even numbers ; sum of first n even numbers ; calculating Average ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int avg_of_even_num ( int n ) { int sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) sum += 2 * i ; return sum / n ; } int main ( ) { int n = 9 ; cout << avg_of_even_num ( n ) ; return 0 ; }
Average of first n even natural numbers | CPP Program to find the average of sum of first n even numbers ; Return the average of sum of first n even numbers ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int avg_of_even_num ( int n ) { return n + 1 ; } int main ( ) { int n = 8 ; cout << avg_of_even_num ( n ) << endl ; return 0 ; }
Sum of square of first n odd numbers | Efficient C ++ method to find sum of square of first n odd numbers . ; driver code
#include <iostream> NEW_LINE using namespace std ; int squareSum ( int n ) { return n * ( 4 * n * n - 1 ) / 3 ; } int main ( ) { cout << squareSum ( 8 ) ; return 0 ; }
Check whether given three numbers are adjacent primes | CPP program to check given three numbers are primes are not . ; checks weather given number is prime or not . ; check if n is a multiple of 2 ; if not , then just check the odds ; return next prime number ; start with next number . ; breaks after finding next prime number ; check given three numbers are adjacent primes are not . ; check given three numbers are primes are not . ; find next prime of a ; If next is not same as ' a ' ; If next next is not same as ' c ' ; Driver code for above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int n ) { if ( n % 2 == 0 ) return false ; for ( int i = 3 ; i * i <= n ; i += 2 ) if ( n % i == 0 ) return false ; return true ; } int nextPrime ( int start ) { int next = start + 1 ; while ( ! isPrime ( next ) ) next ++ ; return next ; } bool areAdjacentPrimes ( int a , int b , int c ) { if ( ! isPrime ( a ) || ! isPrime ( b ) || ! isPrime ( c ) ) return false ; int next = nextPrime ( a ) ; if ( next != b ) return false ; if ( nextPrime ( b ) != c ) return false ; return true ; } int main ( ) { if ( areAdjacentPrimes ( 11 , 13 , 19 ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Check whether a number is semiprime or not | C ++ Program to check whether number is semiprime or not ; Utility function to check whether number is semiprime or not ; If number is greater than 1 , add it to the count variable as it indicates the number remain is prime number ; Return '1' if count is equal to '2' else return '0' ; Function to print ' True ' or ' False ' according to condition of semiprime ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int checkSemiprime ( int num ) { int cnt = 0 ; for ( int i = 2 ; cnt < 2 && i * i <= num ; ++ i ) while ( num % i == 0 ) num /= i , ++ cnt ; if ( num > 1 ) ++ cnt ; return cnt == 2 ; } void semiprime ( int n ) { if ( checkSemiprime ( n ) ) cout << " True STRNEWLINE " ; else cout << " False STRNEWLINE " ; } int main ( ) { int n = 6 ; semiprime ( n ) ; n = 8 ; semiprime ( n ) ; return 0 ; }
Program to find sum of series 1 + 2 + 2 + 3 + 3 + 3 + . . . + n | Program to find sum of series 1 + 2 + 2 + 3 + . . . + n ; Function to find sum of series . ; Driver function . ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfSeries ( int n ) { int sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) sum = sum + i * i ; return sum ; } int main ( ) { int n = 10 ; cout << sumOfSeries ( n ) ; return 0 ; }
Program to find sum of series 1 + 2 + 2 + 3 + 3 + 3 + . . . + n | C ++ Program to find sum of series 1 + 2 + 2 + 3 + . . . + n ; Function to find sum of series . ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfSeries ( int n ) { return ( n * ( n + 1 ) * ( 2 * n + 1 ) ) / 6 ; } int main ( ) { int n = 10 ; cout << sumOfSeries ( n ) ; return 0 ; }
Maximum binomial coefficient term value | CPP Program to find maximum binomial coefficient term ; Returns value of Binomial Coefficient C ( n , k ) ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Return maximum binomial coefficient term value . ; if n is even ; if n is odd ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int binomialCoeff ( int n , int k ) { int C [ n + 1 ] [ k + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) { for ( int j = 0 ; j <= min ( i , k ) ; j ++ ) { if ( j == 0 j == i ) C [ i ] [ j ] = 1 ; else C [ i ] [ j ] = C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] ; } } return C [ n ] [ k ] ; } int maxcoefficientvalue ( int n ) { if ( n % 2 == 0 ) return binomialCoeff ( n , n / 2 ) ; else return binomialCoeff ( n , ( n + 1 ) / 2 ) ; } int main ( ) { int n = 4 ; cout << maxcoefficientvalue ( n ) << endl ; return 0 ; }
Smallest n digit number divisible by given three numbers | C ++ program to find smallest n digit number which is divisible by x , y and z . ; LCM for x , y , z ; returns smallest n digit number divisible by x , y and z ; find the LCM ; find power of 10 for least number ; reminder after ; If smallest number itself divides lcm . ; add lcm - reminder number for next n digit number ; this condition check the n digit number is possible or not if it is possible it return the number else return 0 ; driver code ; if number is possible then it print the number
#include <bits/stdc++.h> NEW_LINE using namespace std ; int LCM ( int x , int y , int z ) { int ans = ( ( x * y ) / ( __gcd ( x , y ) ) ) ; return ( ( z * ans ) / ( __gcd ( ans , z ) ) ) ; } int findDivisible ( int n , int x , int y , int z ) { int lcm = LCM ( x , y , z ) ; int ndigitnumber = pow ( 10 , n - 1 ) ; int reminder = ndigitnumber % lcm ; if ( reminder == 0 ) return ndigitnumber ; ndigitnumber += lcm - reminder ; if ( ndigitnumber < pow ( 10 , n ) ) return ndigitnumber ; else return 0 ; } int main ( ) { int n = 4 , x = 2 , y = 3 , z = 5 ; int res = findDivisible ( n , x , y , z ) ; if ( res != 0 ) cout << res ; else cout << " Not ▁ possible " ; return 0 ; }
Sum of squares of first n natural numbers | CPP Program to find sum of square of first n natural numbers . This program avoids overflow upto some extent for large value of n . ; Return the sum of square of first n natural numbers ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int squaresum ( int n ) { return ( n * ( n + 1 ) / 2 ) * ( 2 * n + 1 ) / 3 ; } int main ( ) { int n = 4 ; cout << squaresum ( n ) << endl ; return 0 ; }
Program to calculate distance between two points | C ++ code to compute distance ; Function to calculate distance ; Calculating distance ; Drivers Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; float distance ( int x1 , int y1 , int x2 , int y2 ) { return sqrt ( pow ( x2 - x1 , 2 ) + pow ( y2 - y1 , 2 ) * 1.0 ) ; } int main ( ) { cout << distance ( 3 , 4 , 4 , 3 ) ; return 0 ; }
Check if a large number is divisibility by 15 | CPP program to check if a large number is divisible by 15 ; function to check if a large number is divisible by 15 ; length of string ; check divisibility by 5 ; Sum of digits ; if divisible by 3 ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isDivisible ( string s ) { int n = s . length ( ) ; if ( s [ n - 1 ] != '5' and s [ n - 1 ] != '0' ) return false ; int sum = accumulate ( begin ( s ) , end ( s ) , 0 ) - '0' * n ; return ( sum % 3 == 0 ) ; } int main ( ) { string s = "15645746327462384723984023940239" ; isDivisible ( s ) ? cout << " Yes STRNEWLINE " : cout << " No STRNEWLINE " ; string s1 = "15645746327462384723984023940235" ; isDivisible ( s1 ) ? cout << " Yes STRNEWLINE " : cout << " No STRNEWLINE " ; return 0 ; }
Shortest path with exactly k edges in a directed and weighted graph | C ++ program to find shortest path with exactly k edges ; Define number of vertices in the graph and inifinite value ; A naive recursive function to count walks from u to v with k edges ; Base cases ; Initialize result ; Go to all adjacents of u and recur ; driver program to test above function ; Let us create the graph shown in above diagram
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define V 4 NEW_LINE #define INF INT_MAX NEW_LINE int shortestPath ( int graph [ ] [ V ] , int u , int v , int k ) { if ( k == 0 && u == v ) return 0 ; if ( k == 1 && graph [ u ] [ v ] != INF ) return graph [ u ] [ v ] ; if ( k <= 0 ) return INF ; int res = INF ; for ( int i = 0 ; i < V ; i ++ ) { if ( graph [ u ] [ i ] != INF && u != i && v != i ) { int rec_res = shortestPath ( graph , i , v , k - 1 ) ; if ( rec_res != INF ) res = min ( res , graph [ u ] [ i ] + rec_res ) ; } } return res ; } int main ( ) { int graph [ V ] [ V ] = { { 0 , 10 , 3 , 2 } , { INF , 0 , INF , 7 } , { INF , INF , 0 , 6 } , { INF , INF , INF , 0 } } ; int u = 0 , v = 3 , k = 2 ; cout << " Weight ▁ of ▁ the ▁ shortest ▁ path ▁ is ▁ " << shortestPath ( graph , u , v , k ) ; return 0 ; }
Shortest path with exactly k edges in a directed and weighted graph | Dynamic Programming based C ++ program to find shortest path with exactly k edges ; Define number of vertices in the graph and inifinite value ; A Dynamic programming based function to find the shortest path from u to v with exactly k edges . ; Table to be filled up using DP . The value sp [ i ] [ j ] [ e ] will store weight of the shortest path from i to j with exactly k edges ; Loop for number of edges from 0 to k ; for source ; for destination ; initialize value ; from base cases ; go to adjacent only when number of edges is more than 1 ; There should be an edge from i to a and a should not be same as either i or j ; driver program to test above function ; Let us create the graph shown in above diagram
#include <iostream> NEW_LINE #include <climits> NEW_LINE using namespace std ; #define V 4 NEW_LINE #define INF INT_MAX NEW_LINE int shortestPath ( int graph [ ] [ V ] , int u , int v , int k ) { int sp [ V ] [ V ] [ k + 1 ] ; for ( int e = 0 ; e <= k ; e ++ ) { for ( int i = 0 ; i < V ; i ++ ) { for ( int j = 0 ; j < V ; j ++ ) { sp [ i ] [ j ] [ e ] = INF ; if ( e == 0 && i == j ) sp [ i ] [ j ] [ e ] = 0 ; if ( e == 1 && graph [ i ] [ j ] != INF ) sp [ i ] [ j ] [ e ] = graph [ i ] [ j ] ; if ( e > 1 ) { for ( int a = 0 ; a < V ; a ++ ) { if ( graph [ i ] [ a ] != INF && i != a && j != a && sp [ a ] [ j ] [ e - 1 ] != INF ) sp [ i ] [ j ] [ e ] = min ( sp [ i ] [ j ] [ e ] , graph [ i ] [ a ] + sp [ a ] [ j ] [ e - 1 ] ) ; } } } } } return sp [ u ] [ v ] [ k ] ; } int main ( ) { int graph [ V ] [ V ] = { { 0 , 10 , 3 , 2 } , { INF , 0 , INF , 7 } , { INF , INF , 0 , 6 } , { INF , INF , INF , 0 } } ; int u = 0 , v = 3 , k = 2 ; cout << shortestPath ( graph , u , v , k ) ; return 0 ; }
Multistage Graph ( Shortest Path ) | CPP program to find shortest distance in a multistage graph . ; Returns shortest distance from 0 to N - 1. ; dist [ i ] is going to store shortest distance from node i to node N - 1. ; Calculating shortest path for rest of the nodes ; Initialize distance from i to destination ( N - 1 ) ; Check all nodes of next stages to find shortest distance from i to N - 1. ; Reject if no edge exists ; We apply recursive equation to distance to target through j . and compare with minimum distance so far . ; Driver code ; Graph stored in the form of an adjacency Matrix
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 8 NEW_LINE #define INF INT_MAX NEW_LINE int shortestDist ( int graph [ N ] [ N ] ) { int dist [ N ] ; dist [ N - 1 ] = 0 ; for ( int i = N - 2 ; i >= 0 ; i -- ) { dist [ i ] = INF ; for ( int j = i ; j < N ; j ++ ) { if ( graph [ i ] [ j ] == INF ) continue ; dist [ i ] = min ( dist [ i ] , graph [ i ] [ j ] + dist [ j ] ) ; } } return dist [ 0 ] ; } int main ( ) { int graph [ N ] [ N ] = { { INF , 1 , 2 , 5 , INF , INF , INF , INF } , { INF , INF , INF , INF , 4 , 11 , INF , INF } , { INF , INF , INF , INF , 9 , 5 , 16 , INF } , { INF , INF , INF , INF , INF , INF , 2 , INF } , { INF , INF , INF , INF , INF , INF , INF , 18 } , { INF , INF , INF , INF , INF , INF , INF , 13 } , { INF , INF , INF , INF , INF , INF , INF , 2 } , { INF , INF , INF , INF , INF , INF , INF , INF } } ; cout << shortestDist ( graph ) ; return 0 ; }
Reverse Level Order Traversal | A recursive C ++ program to print REVERSE level order traversal ; A binary tree node has data , pointer to left and right child ; Function protoypes ; Function to print REVERSE level order traversal a tree ; Print nodes at a given level ; Compute the " height " of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node . ; compute the height 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 ; Let us create trees shown in above diagram
#include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int data ; node * left ; node * right ; } ; void printGivenLevel ( node * root , int level ) ; int height ( node * node ) ; node * newNode ( int data ) ; void reverseLevelOrder ( node * root ) { int h = height ( root ) ; int i ; for ( i = h ; i >= 1 ; i -- ) printGivenLevel ( root , i ) ; } void printGivenLevel ( node * root , int level ) { if ( root == NULL ) return ; if ( level == 1 ) cout << root -> data << " ▁ " ; else if ( level > 1 ) { printGivenLevel ( root -> left , level - 1 ) ; printGivenLevel ( root -> right , level - 1 ) ; } } int height ( node * node ) { if ( node == NULL ) return 0 ; else { int lheight = height ( node -> left ) ; int rheight = height ( node -> right ) ; if ( lheight > rheight ) return ( lheight + 1 ) ; else return ( rheight + 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 << " Level ▁ Order ▁ traversal ▁ of ▁ binary ▁ tree ▁ is ▁ STRNEWLINE " ; reverseLevelOrder ( root ) ; return 0 ; }
Minimize the number of weakly connected nodes | C ++ code to minimize the number of weakly connected nodes ; Set of nodes which are traversed in each launch of the DFS ; Function traversing the graph using DFS approach and updating the set of nodes ; building a undirected graph ; computes the minimum number of disconnected components when a bi - directed graph is converted to a undirected graph ; Declaring and initializing a visited array ; We check if each node is visited once or not ; We only launch DFS from a node iff it is unvisited . ; Clearing the set of nodes on every relaunch of DFS ; relaunching DFS from an unvisited node . ; iterating over the node set to count the number of nodes visited after making the graph directed and storing it in the variable count . If count / 2 == number of nodes - 1 , then increment count by 1. ; Driver function ; Building graph in the form of a adjacency list
#include <bits/stdc++.h> NEW_LINE using namespace std ; set < int > node ; vector < int > Graph [ 10001 ] ; void dfs ( bool visit [ ] , int src ) { visit [ src ] = true ; node . insert ( src ) ; int len = Graph [ src ] . size ( ) ; for ( int i = 0 ; i < len ; i ++ ) if ( ! visit [ Graph [ src ] [ i ] ] ) dfs ( visit , Graph [ src ] [ i ] ) ; } void buildGraph ( int x [ ] , int y [ ] , int len ) { for ( int i = 0 ; i < len ; i ++ ) { int p = x [ i ] ; int q = y [ i ] ; Graph [ p ] . push_back ( q ) ; Graph [ q ] . push_back ( p ) ; } } int compute ( int n ) { bool visit [ n + 5 ] ; memset ( visit , false , sizeof ( visit ) ) ; int number_of_nodes = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! visit [ i ] ) { node . clear ( ) ; dfs ( visit , i ) ; int count = 0 ; for ( auto it = node . begin ( ) ; it != node . end ( ) ; ++ it ) count += Graph [ ( * it ) ] . size ( ) ; count /= 2 ; if ( count == node . size ( ) - 1 ) number_of_nodes ++ ; } } return number_of_nodes ; } int main ( ) { int n = 6 , m = 4 ; int x [ m + 5 ] = { 1 , 1 , 4 , 4 } ; int y [ m + 5 ] = { 2 , 3 , 5 , 6 } ; buildGraph ( x , y , n ) ; cout << compute ( n ) << " ▁ weakly ▁ connected ▁ nodes " ; return 0 ; }
Karp 's minimum mean (or average) weight cycle algorithm | C ++ program to find minimum average weight of a cycle in connected and directed graph . ; a struct to represent edges ; vector to store edges ; calculates the shortest path ; initializing all distances as - 1 ; shortest distance from first vertex to in tself consisting of 0 edges ; filling up the dp table ; Returns minimum value of average weight of a cycle in graph . ; array to store the avg values ; Compute average values for all vertices using weights of shortest paths store in dp . ; Find minimum value in avg [ ] ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int V = 4 ; struct edge { int from , weight ; } ; vector < edge > edges [ V ] ; void addedge ( int u , int v , int w ) { edges [ v ] . push_back ( { u , w } ) ; } void shortestpath ( int dp [ ] [ V ] ) { for ( int i = 0 ; i <= V ; i ++ ) for ( int j = 0 ; j < V ; j ++ ) dp [ i ] [ j ] = -1 ; dp [ 0 ] [ 0 ] = 0 ; for ( int i = 1 ; i <= V ; i ++ ) { for ( int j = 0 ; j < V ; j ++ ) { for ( int k = 0 ; k < edges [ j ] . size ( ) ; k ++ ) { if ( dp [ i - 1 ] [ edges [ j ] [ k ] . from ] != -1 ) { int curr_wt = dp [ i - 1 ] [ edges [ j ] [ k ] . from ] + edges [ j ] [ k ] . weight ; if ( dp [ i ] [ j ] == -1 ) dp [ i ] [ j ] = curr_wt ; else dp [ i ] [ j ] = min ( dp [ i ] [ j ] , curr_wt ) ; } } } } } double minAvgWeight ( ) { int dp [ V + 1 ] [ V ] ; shortestpath ( dp ) ; double avg [ V ] ; for ( int i = 0 ; i < V ; i ++ ) avg [ i ] = -1 ; for ( int i = 0 ; i < V ; i ++ ) { if ( dp [ V ] [ i ] != -1 ) { for ( int j = 0 ; j < V ; j ++ ) if ( dp [ j ] [ i ] != -1 ) avg [ i ] = max ( avg [ i ] , ( ( double ) dp [ V ] [ i ] - dp [ j ] [ i ] ) / ( V - j ) ) ; } } double result = avg [ 0 ] ; for ( int i = 0 ; i < V ; i ++ ) if ( avg [ i ] != -1 && avg [ i ] < result ) result = avg [ i ] ; return result ; } int main ( ) { addedge ( 0 , 1 , 1 ) ; addedge ( 0 , 2 , 10 ) ; addedge ( 1 , 2 , 3 ) ; addedge ( 2 , 3 , 2 ) ; addedge ( 3 , 1 , 0 ) ; addedge ( 3 , 0 , 8 ) ; cout << minAvgWeight ( ) ; return 0 ; }
Frequency of maximum occurring subsequence in given string | C ++ program for the above approach ; Function to find the frequency ; freq stores frequency of each english lowercase character ; dp [ i ] [ j ] stores the count of subsequence with ' a ' + i and ' a ' + j character ; Increment the count of subsequence j and s [ i ] ; Update the frequency array ; For 1 length subsequence ; For 2 length subsequence ; Return the final result ; Driver Code ; Given string str ; Function Call
#include <bits/stdc++.h> NEW_LINE #define ll long long NEW_LINE using namespace std ; ll findCount ( string s ) { ll freq [ 26 ] ; ll dp [ 26 ] [ 26 ] ; memset ( freq , 0 , sizeof freq ) ; memset ( dp , 0 , sizeof dp ) ; for ( int i = 0 ; i < s . size ( ) ; ++ i ) { for ( int j = 0 ; j < 26 ; j ++ ) { dp [ j ] [ s [ i ] - ' a ' ] += freq [ j ] ; } freq [ s [ i ] - ' a ' ] ++ ; } ll ans = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) ans = max ( freq [ i ] , ans ) ; for ( int i = 0 ; i < 26 ; i ++ ) { for ( int j = 0 ; j < 26 ; j ++ ) { ans = max ( dp [ i ] [ j ] , ans ) ; } } return ans ; } int main ( ) { string str = " acbab " ; cout << findCount ( str ) ; return 0 ; }
Create an array such that XOR of subarrays of length K is X | C ++ implementation to Create an array in which the XOR of all elements of each contiguous sub - array of length K is X ; Function to construct the array ; Creating a vector of size K , initialised with 0 ; Initialising the first element with the given XOR ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void constructArray ( int N , int K , int X ) { vector < int > ans ( K , 0 ) ; ans [ 0 ] = X ; for ( int i = 0 ; i < N ; ++ i ) { cout << ans [ i % K ] << " ▁ " ; } cout << endl ; } int main ( ) { int N = 5 , K = 2 , X = 4 ; constructArray ( N , K , X ) ; return 0 ; }
Two player game in which a player can remove all occurrences of a number | C ++ implementation for Two player game in which a player can remove all occurrences of a number ; Function that print whether player1 can wins or loses ; storing the number of occurrence of elements in unordered map ; variable to check if the occurrence of repeated elements is >= 4 and multiple of 2 or not ; count elements which occur more than once ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void game ( int v [ ] , int n ) { unordered_map < int , int > m ; for ( int i = 0 ; i < n ; i ++ ) { if ( m . find ( v [ i ] ) == m . end ( ) ) m [ v [ i ] ] = 1 ; else m [ v [ i ] ] ++ ; } int count = 0 ; int check = 0 ; for ( auto i : m ) { if ( i . second > 1 ) { if ( i . second >= 4 && i . second % 2 == 0 ) check ++ ; count ++ ; } } if ( check % 2 != 0 ) bool flag = false ; if ( check % 2 != 0 ) cout << " Yes " << endl ; else if ( n % 2 == 0 && count % 2 == 0 ) cout << " No " << endl ; else cout << " Yes " << endl ; } int main ( ) { int arr [ ] = { 3 , 2 , 2 , 3 , 3 , 5 } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; game ( arr , size ) ; return 0 ; }
Count of elements which form a loop in an Array according to given constraints | C ++ program to number of elements which form a cycle in an array ; Function to count number of elements forming a cycle ; Array to store parent node of traversal . ; Array to determine whether current node is already counted in the cycle . ; Initialize the arrays . ; Check if current node is already traversed or not . If node is not traversed yet then parent value will be - 1. ; Traverse the graph until an already visited node is not found . ; Check parent value to ensure a cycle is present . ; Count number of nodes in the cycle . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define mp make_pair NEW_LINE #define pb push_back NEW_LINE #define mod 1000000007 NEW_LINE int solve ( int A [ ] , int n ) { int i , cnt = 0 , j ; int parent [ n ] ; int vis [ n ] ; memset ( parent , -1 , sizeof ( parent ) ) ; memset ( vis , 0 , sizeof ( vis ) ) ; for ( i = 0 ; i < n ; i ++ ) { j = i ; if ( parent [ j ] == -1 ) { while ( parent [ j ] == -1 ) { parent [ j ] = i ; j = __gcd ( j , A [ j ] ) % n ; } if ( parent [ j ] == i ) { while ( ! vis [ j ] ) { vis [ j ] = 1 ; cnt ++ ; j = __gcd ( j , A [ j ] ) % n ; } } } } return cnt ; } int main ( ) { int A [ ] = { 1 , 1 , 6 , 2 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << solve ( A , n ) ; return 0 ; }
Find farthest node from each node in Tree | C ++ implementation to find the farthest node from each vertex of the tree ; Adjacency list to store edges ; Add edge between U and V in tree ; Edge from U to V ; Edge from V to U ; DFS to find the first End Node of diameter ; Calculating level of nodes ; Go in opposite direction of parent ; Function to clear the levels of the nodes ; set all value of lvl [ ] to 0 for next dfs ; Set maximum with 0 ; DFS will calculate second end of the diameter ; Calculating level of nodes ; Store the node with maximum depth from end1 ; Go in opposite direction of parent ; Function to find the distance of the farthest distant node ; Storing distance from end1 to node u ; Function to find the distance of nodes from second end of diameter ; storing distance from end2 to node u ; Joining Edge between two nodes of the tree ; Find the one end of the diameter of tree ; Find the other end of the diameter of tree ; Find the distance to each node from end1 ; Find the distance to each node from end2 ; Comparing distance between the two ends of diameter ; Driver code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 10000 NEW_LINE vector < int > adj [ N ] ; int lvl [ N ] , dist1 [ N ] , dist2 [ N ] ; void AddEdge ( int u , int v ) { adj [ u ] . push_back ( v ) ; adj [ v ] . push_back ( u ) ; } int end1 , end2 , maxi ; void findFirstEnd ( int u , int p ) { lvl [ u ] = 1 + lvl [ p ] ; if ( lvl [ u ] > maxi ) { maxi = lvl [ u ] ; end1 = u ; } for ( int i = 0 ; i < adj [ u ] . size ( ) ; i ++ ) { if ( adj [ u ] [ i ] != p ) { findFirstEnd ( adj [ u ] [ i ] , u ) ; } } } void clear ( int n ) { for ( int i = 0 ; i <= n ; i ++ ) { lvl [ i ] = 0 ; } maxi = 0 ; dist1 [ 0 ] = dist2 [ 0 ] = -1 ; } void findSecondEnd ( int u , int p ) { lvl [ u ] = 1 + lvl [ p ] ; if ( lvl [ u ] > maxi ) { maxi = lvl [ u ] ; end2 = u ; } for ( int i = 0 ; i < adj [ u ] . size ( ) ; i ++ ) { if ( adj [ u ] [ i ] != p ) { findSecondEnd ( adj [ u ] [ i ] , u ) ; } } } void findDistancefromFirst ( int u , int p ) { dist1 [ u ] = 1 + dist1 [ p ] ; for ( int i = 0 ; i < adj [ u ] . size ( ) ; i ++ ) { if ( adj [ u ] [ i ] != p ) { findDistancefromFirst ( adj [ u ] [ i ] , u ) ; } } } void findDistancefromSecond ( int u , int p ) { dist2 [ u ] = 1 + dist2 [ p ] ; for ( int i = 0 ; i < adj [ u ] . size ( ) ; i ++ ) { if ( adj [ u ] [ i ] != p ) { findDistancefromSecond ( adj [ u ] [ i ] , u ) ; } } } void findNodes ( ) { int n = 5 ; AddEdge ( 1 , 2 ) ; AddEdge ( 1 , 3 ) ; AddEdge ( 3 , 4 ) ; AddEdge ( 3 , 5 ) ; findFirstEnd ( 1 , 0 ) ; clear ( n ) ; findSecondEnd ( end1 , 0 ) ; findDistancefromFirst ( end1 , 0 ) ; findDistancefromSecond ( end2 , 0 ) ; for ( int i = 1 ; i <= n ; i ++ ) { int x = dist1 [ i ] ; int y = dist2 [ i ] ; if ( x >= y ) { cout << end1 << ' ▁ ' ; } else { cout << end2 << ' ▁ ' ; } } } int main ( ) { findNodes ( ) ; return 0 ; }
Sum and Product of all even digit sum Nodes of a Singly Linked List | C ++ program for the above approach ; Node of Linked List ; Function to insert a node at the beginning of the singly Linked List ; Allocate new node ; Insert the data ; Link old list to the new node ; Move head to point the new node ; Function to find the digit sum for a number ; Return the sum ; Function to find the required sum and product ; Initialise the sum and product to 0 and 1 respectively ; Traverse the given linked list ; If current node has even digit sum then include it in resultant sum and product ; Find the sum and the product ; Print the final Sum and Product ; Driver Code ; Head of the linked list ; Create the linked list 15 -> 16 -> 8 -> 6 -> 13 ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * next ; } ; void push ( Node * * head_ref , int new_data ) { Node * new_node = ( Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } int digitSum ( int num ) { int sum = 0 ; while ( num ) { sum += ( num % 10 ) ; num /= 10 ; } return sum ; } void sumAndProduct ( Node * head_ref ) { int prod = 1 ; int sum = 0 ; Node * ptr = head_ref ; while ( ptr != NULL ) { if ( ! ( digitSum ( ptr -> data ) & 1 ) ) { prod *= ptr -> data ; sum += ptr -> data ; } ptr = ptr -> next ; } cout << " Sum ▁ = ▁ " << sum << endl ; cout << " Product ▁ = ▁ " << prod ; } int main ( ) { Node * head = NULL ; push ( & head , 13 ) ; push ( & head , 6 ) ; push ( & head , 8 ) ; push ( & head , 16 ) ; push ( & head , 15 ) ; sumAndProduct ( head ) ; return 0 ; }
Shortest Palindromic Substring | C ++ program to find the shortest palindromic substring ; Function return the shortest palindromic substring ; One by one consider every character as center point of even and length palindromes ; Find the longest odd length palindrome with center point as i ; Find the even length palindrome with center points as i - 1 and i . ; Smallest substring which is not empty ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string ShortestPalindrome ( string s ) { int n = s . length ( ) ; vector < string > v ; for ( int i = 0 ; i < n ; i ++ ) { int l = i ; int r = i ; string ans1 = " " ; string ans2 = " " ; while ( l >= 0 && r < n && s [ l ] == s [ r ] ) { ans1 += s [ l ] ; l -- ; r ++ ; } l = i - 1 ; r = i ; while ( l >= 0 && r < n && s [ l ] == s [ r ] ) { ans2 += s [ l ] ; l -- ; r ++ ; } v . push_back ( ans1 ) ; v . push_back ( ans2 ) ; } string ans = v [ 0 ] ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { if ( v [ i ] != " " ) { ans = min ( ans , v [ i ] ) ; } } return ans ; } int main ( ) { string s = " geeksforgeeks " ; cout << ShortestPalindrome ( s ) ; return 0 ; }
Minimum increment or decrement operations required to make the array sorted | C ++ implementation of the approach ; Function to return the minimum number of given operations required to sort the array ; Number of elements in the array ; Smallest element in the array ; Largest element in the array ; dp ( i , j ) represents the minimum number of operations needed to make the array [ 0 . . i ] sorted in non - decreasing order given that ith element is j ; Fill the dp [ ] ] [ array for base cases ; Using results for the first ( i - 1 ) elements , calculate the result for the ith element ; If the ith element is j then we can have any value from small to j for the i - 1 th element We choose the one that requires the minimum operations ; If we made the ( n - 1 ) th element equal to j we required dp ( n - 1 , j ) operations We choose the minimum among all possible dp ( n - 1 , j ) where j goes from small to large ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMinimumOps ( vector < int > ar ) { int n = ar . size ( ) ; int small = * min_element ( ar . begin ( ) , ar . end ( ) ) ; int large = * max_element ( ar . begin ( ) , ar . end ( ) ) ; int dp [ n ] [ large + 1 ] ; for ( int j = small ; j <= large ; j ++ ) { dp [ 0 ] [ j ] = abs ( ar [ 0 ] - j ) ; } for ( int i = 1 ; i < n ; i ++ ) { int minimum = INT_MAX ; for ( int j = small ; j <= large ; j ++ ) { minimum = min ( minimum , dp [ i - 1 ] [ j ] ) ; dp [ i ] [ j ] = minimum + abs ( ar [ i ] - j ) ; } } int ans = INT_MAX ; for ( int j = small ; j <= large ; j ++ ) { ans = min ( ans , dp [ n - 1 ] [ j ] ) ; } return ans ; } int main ( ) { vector < int > ar = { 1 , 2 , 1 , 4 , 3 } ; cout << getMinimumOps ( ar ) ; return 0 ; }
Minimize the cost of partitioning an array into K groups | C ++ implementation of the approach ; Function to return the minimum number of operations needed to partition the array in k contiguous groups such that all elements of a given group are identical ; n is the size of the array ; dp ( i , j ) represents the minimum cost for partitioning the array [ 0. . i ] into j groups ; Base case , cost is 0 for parititoning the array [ 0. .0 ] into 1 group ; Fill dp ( i , j ) and the answer will be stored at dp ( n - 1 , k ) ; The maximum groups that the segment 0. . i can be divided in is represented by maxGroups ; Initialize dp ( i , j ) to infinity ; Divide segment 0. . i in 1 group ; map and freqOfMode are together used to keep track of the frequency of the most occurring element in [ 0. . i ] ; Change all the elements in the range 0. . i to the most frequent element in this range ; If the jth group is the segment from it . . i , we change all the elements in this range to this range 's most occurring element ; Number of elements we need to change in the jth group i . e . the range it . . i ; For all the possible sizes of the jth group that end at the ith element we pick the size that gives us the minimum cost for dp ( i , j ) elementsToChange is the cost of making all the elements in the jth group identical and we make use of dp ( it - 1 , j - 1 ) to find the overall minimal cost ; Return the minimum cost for partitioning array [ 0. . n - 1 ] into k groups which is stored at dp ( n - 1 , k ) ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMinimumOps ( vector < int > ar , int k ) { int n = ar . size ( ) ; int dp [ n ] [ k + 1 ] ; dp [ 0 ] [ 1 ] = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int maxGroups = min ( k , i + 1 ) ; for ( int j = 1 ; j <= maxGroups ; j ++ ) { dp [ i ] [ j ] = INT_MAX ; if ( j == 1 ) { unordered_map < int , int > freq ; int freqOfMode = 0 ; for ( int it = 0 ; it <= i ; it ++ ) { freq [ ar [ it ] ] ++ ; int newElementFreq = freq [ ar [ it ] ] ; if ( newElementFreq > freqOfMode ) freqOfMode = newElementFreq ; } dp [ i ] [ 1 ] = ( i + 1 ) - freqOfMode ; } else { unordered_map < int , int > freq ; int freqOfMode = 0 ; for ( int it = i ; it >= j - 1 ; it -- ) { freq [ ar [ it ] ] ++ ; int newElementFreq = freq [ ar [ it ] ] ; if ( newElementFreq > freqOfMode ) freqOfMode = newElementFreq ; int elementsToChange = i - it + 1 ; elementsToChange -= freqOfMode ; dp [ i ] [ j ] = min ( dp [ it - 1 ] [ j - 1 ] + elementsToChange , dp [ i ] [ j ] ) ; } } } } return dp [ n - 1 ] [ k ] ; } int main ( ) { int k = 3 ; vector < int > ar = { 3 , 1 , 3 , 3 , 2 , 1 , 8 , 5 } ; cout << getMinimumOps ( ar , k ) ; return 0 ; }
Find numbers which are multiples of first array and factors of second array | C ++ implementation of the approach ; Function to return the LCM of two numbers ; Function to print the required numbers ; To store the lcm of array a [ ] elements and the gcd of array b [ ] elements ; Finding LCM of first array ; Finding GCD of second array ; No such element exists ; All the multiples of lcmA which are less than or equal to gcdB and evenly divide gcdB will satisfy the conditions ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int lcm ( int x , int y ) { int temp = ( x * y ) / __gcd ( x , y ) ; return temp ; } void findNumbers ( int a [ ] , int n , int b [ ] , int m ) { int lcmA = 1 , gcdB = 0 ; for ( int i = 0 ; i < n ; i ++ ) lcmA = lcm ( lcmA , a [ i ] ) ; for ( int i = 0 ; i < m ; i ++ ) gcdB = __gcd ( gcdB , b [ i ] ) ; if ( gcdB % lcmA != 0 ) { cout << " - 1" ; return ; } int num = lcmA ; while ( num <= gcdB ) { if ( gcdB % num == 0 ) cout << num << " ▁ " ; num += lcmA ; } } int main ( ) { int a [ ] = { 1 , 2 , 2 , 4 } ; int b [ ] = { 16 , 32 , 64 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int m = sizeof ( b ) / sizeof ( b [ 0 ] ) ; findNumbers ( a , n , b , m ) ; return 0 ; }
Probability such that two subset contains same number of elements | C ++ implementation of the above approach ; Returns value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate value of ; Iterative Function to calculate ( x ^ y ) in O ( log y ) ; Initialize result ; If y is odd , multiply x with result ; y must be even now y = y / 2 ; Change x to x ^ 2 ; Function to find probability ; Calculate total possible ways and favourable ways . ; Divide by gcd such that they become relatively coprime ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int binomialCoeff ( int n , int k ) { int res = 1 ; if ( k > n - k ) k = n - k ; for ( int i = 0 ; i < k ; ++ i ) { res *= ( n - i ) ; res /= ( i + 1 ) ; } return res ; } int power ( int x , unsigned int y ) { int res = 1 ; while ( y > 0 ) { if ( y & 1 ) res = res * x ; y = y >> 1 ; x = x * x ; } return res ; } void FindProbability ( int n ) { int up = binomialCoeff ( 2 * n , n ) ; int down = power ( 2 , 2 * n ) ; int g = __gcd ( up , down ) ; up /= g , down /= g ; cout << up << " / " << down << endl ; } int main ( ) { int N = 8 ; FindProbability ( N ) ; return 0 ; }
How to learn Pattern printing easily ? | C ++ implementation of the approach
#include <iostream> NEW_LINE using namespace std ; int main ( ) { int N = 4 , i , j , min ; cout << " Value ▁ of ▁ N : ▁ " << N << endl ; for ( i = 1 ; i <= N ; i ++ ) { for ( j = 1 ; j <= N ; j ++ ) { min = i < j ? i : j ; cout << N - min + 1 ; } for ( j = N - 1 ; j >= 1 ; j -- ) { min = i < j ? i : j ; cout << N - min + 1 ; } cout << endl ; } for ( i = N - 1 ; i >= 1 ; i -- ) { for ( j = 1 ; j <= N ; j ++ ) { min = i < j ? i : j ; cout << N - min + 1 ; } for ( j = N - 1 ; j >= 1 ; j -- ) { min = i < j ? i : j ; cout << N - min + 1 ; } cout << endl ; } return 0 ; }
Largest perfect square number in an Array | CPP program to find the largest perfect square number among n numbers ; Function to check if a number is perfect square number or not ; takes the sqrt of the number ; checks if it is a perfect square number ; Function to find the largest perfect square number in the array ; stores the maximum of all perfect square numbers ; Traverse all elements in the array ; store the maximum if current element is a perfect square ; Driver Code
#include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; bool checkPerfectSquare ( double n ) { double d = sqrt ( n ) ; if ( d * d == n ) return true ; return false ; } int largestPerfectSquareNumber ( int a [ ] , double n ) { int maxi = -1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( checkPerfectSquare ( a [ i ] ) ) maxi = max ( a [ i ] , maxi ) ; } return maxi ; } int main ( ) { int a [ ] = { 16 , 20 , 25 , 2 , 3 , 10 } ; double n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << largestPerfectSquareNumber ( a , n ) ; return 0 ; }
Maximum number of parallelograms that can be made using the given length of line segments | Function to find the maximum number of parallelograms can be made ; Finding the length of the frequency array ; Increasing the occurrence of each segment ; To store the count of parallelograms ; Counting parallelograms that can be made using 4 similar sides ; counting segments which have occurrence left >= 2 ; Adding parallelograms that can be made using 2 similar sides ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void convert ( int n , int a [ ] ) { int z = a [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { if ( a [ i ] > z ) z = a [ i ] ; } z = z + 1 ; int ff [ z ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { ff [ a [ i ] ] += 1 ; } int cc = 0 ; for ( int i = 0 ; i < z ; i ++ ) { cc += int ( ff [ i ] / 4 ) ; ff [ i ] = ff [ i ] % 4 ; } int vv = 0 ; for ( int i = 0 ; i < z ; i ++ ) { if ( ff [ i ] >= 2 ) vv += 1 ; } cc += int ( vv / 2 ) ; cout << ( cc ) ; } int main ( ) { int n = 4 ; int a [ ] = { 1 , 2 , 1 , 2 } ; convert ( n , a ) ; }
Count pairs ( i , j ) such that ( i + j ) is divisible by A and B both | C ++ implementation of above approach ; Function to find the LCM ; Function to count the pairs ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find_LCM ( int x , int y ) { return ( x * y ) / __gcd ( x , y ) ; } int CountPairs ( int n , int m , int A , int B ) { int cnt = 0 ; int lcm = find_LCM ( A , B ) ; for ( int i = 1 ; i <= n ; i ++ ) cnt += ( m + ( i % lcm ) ) / lcm ; return cnt ; } int main ( ) { int n = 60 , m = 90 , A = 5 , B = 10 ; cout << CountPairs ( n , m , A , B ) ; return 0 ; }
Sorting without comparison of elements | C ++ program to sort an array without comparison operator . ; Represents node of a doubly linked list ; Count of elements in given range ; Count frequencies of all elements ; Traverse through range . For every element , print it its count times . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sortArr ( int arr [ ] , int n , int min , int max ) { int m = max - min + 1 ; vector < int > c ( m , 0 ) ; for ( int i = 0 ; i < n ; i ++ ) c [ arr [ i ] - min ] ++ ; for ( int i = 0 ; i < m ; i ++ ) for ( int j = 0 ; j < c [ i ] ; j ++ ) cout << ( i + min ) << " ▁ " ; } int main ( ) { int arr [ ] = { 10 , 10 , 1 , 4 , 4 , 100 , 0 } ; int min = 0 , max = 100 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortArr ( arr , n , min , max ) ; return 0 ; }
Check if given Array can be divided into subsequences of K increasing consecutive integers | C ++ program for the above approach ; Function to check if the array can be divided into subsequences of K consecutive integers in increasing order ; If N is not divisible by K or K > N , no possible set of required subsequences exist ; Stores the indices of each element in a set ; Stores the index of each number ; Stores if the integer at current index is already included in a subsequence ; Stores the count of total visited elements ; If current integer is already in a subsequence ; Stores the value of last element of the current subsequence ; Stores the index of last element of the current subsequence ; Mark Visited ; Increment the visited count ; Find the next K - 1 elements of the subsequence starting from index i ; No valid index found ; Find index of j such that it is greater than last_index ; if no such index found , return false ; Update last_index ; Mark current index as visited ; Increment total_visited by 1 ; Remove the index from set because it has been already used ; Return the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPossible ( vector < int > nums , int K ) { int N = nums . size ( ) ; if ( N % K != 0 K > N ) { return false ; } map < int , set < int > > idx ; for ( int i = 0 ; i < nums . size ( ) ; i ++ ) { idx [ nums [ i ] ] . insert ( i ) ; } int visited [ N ] = { 0 } ; int total_visited = 0 ; for ( int i = 0 ; i < nums . size ( ) ; i ++ ) { if ( visited [ i ] ) { continue ; } int num = nums [ i ] ; int last_index = i ; visited [ i ] = 1 ; total_visited ++ ; for ( int j = num + 1 ; j < num + K ; j ++ ) { if ( idx [ j ] . size ( ) == 0 ) { return false ; } auto it = idx [ j ] . upper_bound ( last_index ) ; if ( it == idx [ j ] . end ( ) * it <= last_index ) { return false ; } last_index = * it ; visited [ last_index ] = 1 ; total_visited ++ ; idx [ j ] . erase ( it ) ; } } return total_visited == N ; } int main ( ) { vector < int > arr = { 4 , 3 , 1 , 2 } ; int K = 2 ; cout << ( isPossible ( arr , K ) ? " Yes " : " No " ) ; return 0 ; }
Minimize the maximum distance between adjacent points after adding K points anywhere in between | C ++ program for the above approach ; Function to check if it is possible to add K points such that the maximum distance between adjacent points is D ; Stores the count of point used ; Iterate over all given points ; Add number of points required to be placed between ith and ( i + 1 ) th point ; Return answer ; Function to find the minimum value of maximum distance between adjacent points after adding K points any where between ; Stores the lower bound and upper bound of the given range ; Perform binary search ; Find the middle value ; Update the current range to lower half ; Update the current range to upper half ; Driver Code
#include <iostream> NEW_LINE using namespace std ; bool isPossible ( double D , int arr [ ] , int N , int K ) { int used = 0 ; for ( int i = 0 ; i < N - 1 ; ++ i ) { used += ( int ) ( ( arr [ i + 1 ] - arr [ i ] ) / D ) ; } return used <= K ; } double minMaxDist ( int stations [ ] , int N , int K ) { double low = 0 , high = 1e8 ; while ( high - low > 1e-6 ) { double mid = ( low + high ) / 2.0 ; if ( isPossible ( mid , stations , N , K ) ) { high = mid ; } else { low = mid ; } } return low ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 } ; int K = 9 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minMaxDist ( arr , N , K ) ; return 0 ; }
Find Binary permutations of given size not present in the Array | C ++ program for the above approach ; Function to find a Binary String of same length other than the Strings present in the array ; Map all the strings present in the array ; Find all the substring that can be made ; If num already exists then increase counter ; If not found print ; If all the substrings are present then print - 1 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMissingBinaryString ( vector < string > & nums , int N ) { unordered_set < string > s ; int counter = 0 ; for ( string str : nums ) { s . insert ( str ) ; } int total = ( int ) pow ( 2 , N ) ; string ans = " " ; for ( int i = 0 ; i < total ; i ++ ) { string num = " " ; for ( int j = N - 1 ; j >= 0 ; j -- ) { if ( i & ( 1 << j ) ) { num += '1' ; } else { num += '0' ; } } if ( s . find ( num ) != s . end ( ) ) { continue ; counter ++ ; } else { cout << num << " , ▁ " ; } } if ( counter == total ) { cout << " - 1" ; } } int main ( ) { int N = 3 ; vector < string > arr = { "101" , "111" , "001" , "011" , "100" , "110" } ; findMissingBinaryString ( arr , N ) ; return 0 ; }
Queries to find number of connected grid components of given sizes in a Matrix | C ++ implementation for the above approach ; stores information about which cell are already visited in a particular BFS ; Stores the count of cells in the largest connected component ; Function checks if a cell is valid , i . e . it is inside the grid and equal to 1 ; Map to count the frequency of each connected component ; function to calculate the largest connected component ; Iterate over every cell ; Stores the indices of the matrix cells ; Mark the starting cell as visited and push it into the queue ; Iterate while the queue is not empty ; Go to the adjacent cells ; Drivers Code ; Given input array of 1 s and 0 s ; queries array ; sizeof queries array ; Count the frequency of each connected component ; Iterate over the given queries array and And answer the queries
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int n = 6 ; const int m = 6 ; const int dx [ ] = { 0 , 1 , -1 , 0 } ; const int dy [ ] = { 1 , 0 , 0 , -1 } ; int visited [ n ] [ m ] ; int COUNT ; bool is_valid ( int x , int y , int matrix [ n ] [ m ] ) { if ( x < n && y < m && x >= 0 && y >= 0 ) { if ( visited [ x ] [ y ] == false && matrix [ x ] [ y ] == 1 ) return true ; else return false ; } else return false ; } map < int , int > mp ; void findComponentSize ( int matrix [ n ] [ m ] ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( ! visited [ i ] [ j ] && matrix [ i ] [ j ] == 1 ) { COUNT = 0 ; queue < pair < int , int > > q ; q . push ( { i , j } ) ; visited [ i ] [ j ] = true ; while ( ! q . empty ( ) ) { pair < int , int > p = q . front ( ) ; q . pop ( ) ; int x = p . first , y = p . second ; COUNT ++ ; for ( int i = 0 ; i < 4 ; i ++ ) { int newX = x + dx [ i ] ; int newY = y + dy [ i ] ; if ( is_valid ( newX , newY , matrix ) ) { q . push ( { newX , newY } ) ; visited [ newX ] [ newY ] = true ; } } } mp [ COUNT ] ++ ; } } } } int main ( ) { int matrix [ n ] [ m ] = { { 1 , 1 , 1 , 1 , 1 , 1 } , { 1 , 1 , 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 1 , 1 , 1 } , { 0 , 0 , 0 , 1 , 1 , 1 } , { 0 , 0 , 1 , 0 , 0 , 0 } , { 1 , 0 , 0 , 0 , 0 , 0 } } ; int queries [ ] = { 6 , 1 , 8 , 2 } ; int N = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; memset ( visited , false , sizeof visited ) ; findComponentSize ( matrix ) ; for ( int i = 0 ; i < N ; i ++ ) cout << mp [ queries [ i ] ] << " ▁ " ; return 0 ; }
Minimum value of X such that sum of arr [ i ] | C ++ program for the above approach ; Function to check if there exists an X that satisfies the given conditions ; Find the required value of the given expression ; Function to find the minimum value of X using binary search . ; Boundaries of the Binary Search ; Find the middle value ; Check for the middle value ; Update the upper ; Update the lower ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int a [ ] , int b [ ] , int k , int n , int x ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum = sum + pow ( max ( a [ i ] - x , 0 ) , b [ i ] ) ; } if ( sum <= k ) return true ; else return false ; } int findMin ( int a [ ] , int b [ ] , int n , int k ) { int l = 0 , u = * max_element ( a , a + n ) ; while ( l < u ) { int m = ( l + u ) / 2 ; if ( check ( a , b , k , n , m ) ) { u = m ; } else { l = m + 1 ; } } return l ; } int main ( ) { int arr [ ] = { 2 , 1 , 4 , 3 , 5 } ; int brr [ ] = { 4 , 3 , 2 , 3 , 1 } ; int K = 12 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findMin ( arr , brr , N , K ) ; return 0 ; }
Count of indices pairs such that product of elements at these indices is equal to absolute difference of indices | C ++ program for the above approach ; Function to count the number of pairs ( i , j ) such that arr [ i ] * arr [ j ] is equal to abs ( i - j ) ; Stores the resultant number of pairs ; Iterate over the range [ 0 , N ) ; Now , iterate from the value arr [ i ] - ( i % arr [ i ] ) till N with an increment of arr [ i ] ; If the given criteria satisfy then increment the value of count ; Return the resultant count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getPairsCount ( int arr [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = arr [ i ] - ( i % arr [ i ] ) ; j < n ; j += arr [ i ] ) { if ( i < j && ( arr [ i ] * arr [ j ] ) == abs ( i - j ) ) { count ++ ; } } } return count ; } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << getPairsCount ( arr , N ) ; return 0 ; }
Find frequency of each character with positions in given Array of Strings | C ++ program for the above approach ; Function to print every occurence of every characters in every string ; Iterate over the vector arr [ ] ; Traverse the string arr [ i ] ; Push the pair of { i + 1 , j + 1 } in mp [ arr [ i ] [ j ] ] ; Print the occurences of every character ; Driver Code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printOccurences ( vector < string > arr , int N ) { map < char , vector < pair < int , int > > > mp ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < arr [ i ] . length ( ) ; j ++ ) { mp [ arr [ i ] [ j ] ] . push_back ( make_pair ( i + 1 , j + 1 ) ) ; } } for ( auto it : mp ) { cout << " Occurences ▁ of : ▁ " << it . first << " ▁ = ▁ " ; for ( int j = 0 ; j < ( it . second ) . size ( ) ; j ++ ) { cout << " [ " << ( it . second ) [ j ] . first << " ▁ " << ( it . second ) [ j ] . second << " ] ▁ " ; } cout << endl ; } } int main ( ) { vector < string > arr = { " geeksforgeeks " , " gfg " } ; int N = arr . size ( ) ; printOccurences ( arr , N ) ; }
Count of subarrays with X as the most frequent element , for each value of X from 1 to N | C ++ program for the above approach ; Function to calculate the number of subarrays where X ( 1 <= X <= N ) is the most frequent element ; array to store the final answers ; Array to store current frequencies ; Initialise count ; Variable to store the current most frequent element ; Update frequency array ; Update answer ; Print answer ; Driver code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int mostFrequent ( int arr [ ] , int N ) { int ans [ N ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { int count [ N ] ; memset ( count , 0 , sizeof ( count ) ) ; int best = 0 ; for ( int j = i ; j < N ; j ++ ) { count [ arr [ j ] - 1 ] ++ ; if ( count [ arr [ j ] - 1 ] > count [ best - 1 ] || ( count [ arr [ j ] - 1 ] == count [ best - 1 ] && arr [ j ] < best ) ) { best = arr [ j ] ; } ans [ best - 1 ] ++ ; } } for ( int i = 0 ; i < N ; i ++ ) cout << ans [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 2 , 1 , 2 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; mostFrequent ( arr , N ) ; return 0 ; }
Count array elements whose highest power of 2 less than or equal to that number is present in the given array | C ++ program for the above approach ; Function to count array elements whose highest power of 2 is less than or equal to that number is present in the given array ; Stores the resultant count of array elements ; Stores frequency of visited array elements ; Traverse the array ; Calculate log base 2 of the element arr [ i ] ; Highest power of 2 whose value is at most arr [ i ] ; Increment the count by 1 ; Return the resultant count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countElement ( int arr [ ] , int N ) { int count = 0 ; unordered_map < int , int > m ; for ( int i = 0 ; i < N ; i ++ ) { m [ arr [ i ] ] ++ ; } for ( int i = 0 ; i < N ; i ++ ) { int lg = log2 ( arr [ i ] ) ; int p = pow ( 2 , lg ) ; if ( m [ p ] ) { count ++ ; } } return count ; } int main ( ) { int arr [ ] = { 3 , 4 , 6 , 9 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countElement ( arr , N ) ; return 0 ; }
Maximum number of intersections possible for any of the N given segments | C ++ program for the above approach ; Function to find the maximum number of intersections one segment has with all the other given segments ; Stores the resultant maximum count ; Stores the starting and the ending points ; Sort arrays points in the ascending order ; Traverse the array arr [ ] ; Find the count of segments on left of ith segment ; Find the count of segments on right of ith segment ; Find the total segments not intersecting with the current segment ; Store the count of segments that intersect with the ith segment ; Update the value of count ; Return the resultant count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumIntersections ( int arr [ ] [ 2 ] , int N ) { int count = 0 ; int L [ N ] , R [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { L [ i ] = arr [ i ] [ 0 ] ; R [ i ] = arr [ i ] [ 1 ] ; } sort ( L , L + N ) ; sort ( R , R + N ) ; for ( int i = 0 ; i < N ; i ++ ) { int l = arr [ i ] [ 0 ] ; int r = arr [ i ] [ 1 ] ; int x = lower_bound ( R , R + N , l ) - R ; int y = N - ( upper_bound ( L , L + N , r ) - L ) ; int cnt = x + y ; cnt = N - cnt - 1 ; count = max ( count , cnt ) ; } return count ; } int main ( ) { int arr [ ] [ 2 ] = { { 1 , 6 } , { 5 , 5 } , { 2 , 3 } } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maximumIntersections ( arr , N ) ; return 0 ; }
Program to find the Nth Composite Number | C ++ program for the above approach ; Function to find the Nth Composite Numbers using Sieve of Eratosthenes ; Sieve of prime numbers ; Initialize the array to true ; Iterate over the range [ 2 , MAX_SIZE ] ; If IsPrime [ p ] is true ; Iterate over the range [ p * p , MAX_SIZE ] ; Stores the list of composite numbers ; Iterate over the range [ 4 , MAX_SIZE ] ; If i is not prime ; Return Nth Composite Number ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX_SIZE 1000005 NEW_LINE int NthComposite ( int N ) { bool IsPrime [ MAX_SIZE ] ; memset ( IsPrime , true , sizeof ( IsPrime ) ) ; for ( int p = 2 ; p * p < MAX_SIZE ; p ++ ) { if ( IsPrime [ p ] == true ) { for ( int i = p * p ; i < MAX_SIZE ; i += p ) IsPrime [ i ] = false ; } } vector < int > Composites ; for ( int p = 4 ; p < MAX_SIZE ; p ++ ) if ( ! IsPrime [ p ] ) Composites . push_back ( p ) ; return Composites [ N - 1 ] ; } int main ( ) { int N = 4 ; cout << NthComposite ( N ) ; return 0 ; }
Intersection point of two Linked Lists | Set 3 | C ++ program for the above approach ; Structure of a node of a Linked List ; Constructor ; Function to find the intersection point of the two Linked Lists ; Traverse the first linked list and multiply all values by - 1 ; Update a -> data ; Update a ; Traverse the second Linked List and find the value of the first node having negative value ; Intersection point ; Update b ; Function to create linked lists ; Linked List L1 ; Linked List L2 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * next ; Node ( int x ) { data = x ; next = NULL ; } } ; Node * intersectingNode ( Node * headA , Node * headB ) { Node * a = headA ; while ( a ) { a -> data *= -1 ; a = a -> next ; } Node * b = headB ; while ( b ) { if ( b -> data < 0 ) break ; b = b -> next ; } return b ; } void formLinkList ( Node * & head1 , Node * & head2 ) { head1 = new Node ( 3 ) ; head1 -> next = new Node ( 6 ) ; head1 -> next -> next = new Node ( 9 ) ; head1 -> next -> next -> next = new Node ( 15 ) ; head1 -> next -> next -> next -> next = new Node ( 30 ) ; head2 = new Node ( 10 ) ; head2 -> next = head1 -> next -> next -> next ; return ; } int main ( ) { Node * head1 ; Node * head2 ; formLinkList ( head1 , head2 ) ; cout << abs ( intersectingNode ( head1 , head2 ) -> data ) ; return 0 ; }
Left rotate digits of node values of all levels of a Binary Tree in increasing order | C ++ program for the above approach ; TreeNode class ; Function to check if the nodes are in increasing order or not ; Perform Level Order Traversal ; Current length of queue ; If queue is empty ; Level order traversal ; Pop element from front of the queue ; If previous value exceeds current value , return false ; Function to print the Tree after modification ; Performs level order traversal ; Calculate size of the queue ; Iterate until queue is empty ; Function to arrange node values of each level in increasing order ; Perform level order traversal ; Calculate length of queue ; If queue is empty ; Level order traversal ; Pop element from front of the queue ; Initialize the optimal element by the initial element ; Check for all left shift operations ; Left shift ; If the current shifting gives optimal solution ; Replacing initial element by the optimal element ; Push the LST ; Push the RST ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct TreeNode { int val ; TreeNode * left , * right ; TreeNode ( int v ) { val = v ; left = NULL ; right = NULL ; } } ; bool isInc ( TreeNode * root ) { queue < TreeNode * > que ; que . push ( root ) ; while ( true ) { int length = que . size ( ) ; if ( length == 0 ) break ; auto pre = que . front ( ) ; while ( length > 0 ) { auto temp = que . front ( ) ; que . pop ( ) ; if ( pre -> val > temp -> val ) return false ; pre = temp ; if ( temp -> left ) que . push ( temp -> left ) ; if ( temp -> right ) que . push ( temp -> right ) ; length -= 1 ; } } return true ; } void levelOrder ( TreeNode * root ) { queue < TreeNode * > que ; que . push ( root ) ; while ( true ) { int length = que . size ( ) ; if ( length == 0 ) break ; while ( length ) { auto temp = que . front ( ) ; que . pop ( ) ; cout << temp -> val << " ▁ " ; if ( temp -> left ) que . push ( temp -> left ) ; if ( temp -> right ) que . push ( temp -> right ) ; length -= 1 ; } cout << endl ; } cout << endl ; } void makeInc ( TreeNode * root ) { queue < TreeNode * > que ; que . push ( root ) ; while ( true ) { int length = que . size ( ) ; if ( length == 0 ) break ; int prev = -1 ; while ( length > 0 ) { auto temp = que . front ( ) ; que . pop ( ) ; auto optEle = temp -> val ; auto strEle = to_string ( temp -> val ) ; bool flag = true ; int yy = strEle . size ( ) ; for ( int idx = 0 ; idx < strEle . size ( ) ; idx ++ ) { int ls = stoi ( strEle . substr ( idx , yy ) + strEle . substr ( 0 , idx ) ) ; if ( ls >= prev and flag ) { optEle = ls ; flag = false ; } if ( ls >= prev ) optEle = min ( optEle , ls ) ; } temp -> val = optEle ; prev = temp -> val ; if ( temp -> left ) que . push ( temp -> left ) ; if ( temp -> right ) que . push ( temp -> right ) ; length -= 1 ; } } if ( isInc ( root ) ) levelOrder ( root ) ; else cout << ( -1 ) ; } int main ( ) { TreeNode * root = new TreeNode ( 341 ) ; root -> left = new TreeNode ( 241 ) ; root -> right = new TreeNode ( 123 ) ; root -> left -> left = new TreeNode ( 324 ) ; root -> left -> right = new TreeNode ( 235 ) ; root -> right -> right = new TreeNode ( 161 ) ; makeInc ( root ) ; }
Reverse Level Order Traversal | A C ++ program to print REVERSE level order traversal using stack and queue This approach is adopted from following link tech - queries . blogspot . in / 2008 / 12 / level - order - tree - traversal - in - reverse . html http : ; A binary tree node has data , pointer to left and right children ; Given a binary tree , print its nodes in reverse level order ; Do something like normal level order traversal order . Following are the differences with normal level order traversal 1 ) Instead of printing a node , we push the node to stack 2 ) Right subtree is visited before left subtree ; Dequeue node and make it root ; Enqueue right child ; NOTE : RIGHT CHILD IS ENQUEUED BEFORE LEFT ; Enqueue left child ; Now pop all items from stack one by one and print them ; 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 trees shown in above diagram
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int data ; struct node * left ; struct node * right ; } ; void reverseLevelOrder ( node * root ) { stack < node * > S ; queue < node * > Q ; Q . push ( root ) ; while ( Q . empty ( ) == false ) { root = Q . front ( ) ; Q . pop ( ) ; S . push ( root ) ; if ( root -> right ) Q . push ( root -> right ) ; if ( root -> left ) Q . push ( root -> left ) ; } while ( S . empty ( ) == false ) { root = S . top ( ) ; cout << root -> data << " ▁ " ; S . pop ( ) ; } } node * newNode ( int data ) { node * temp = new node ; temp -> data = data ; temp -> left = NULL ; temp -> right = NULL ; return ( temp ) ; } int main ( ) { struct node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> left = newNode ( 6 ) ; root -> right -> right = newNode ( 7 ) ; cout << " Level ▁ Order ▁ traversal ▁ of ▁ binary ▁ tree ▁ is ▁ STRNEWLINE " ; reverseLevelOrder ( root ) ; return 0 ; }
Modify array of strings by replacing characters repeating in the same or remaining strings | C ++ program for the above approach ; Function to remove duplicate characters across the strings ; Stores distinct characters ; Size of the array ; Stores the list of modified strings ; Traverse the array ; Stores the modified string ; Iterate over the characters of the modified string ; If character is already present ; Insert character into the Set ; Print the list of modified strings ; Print each string ; Driver Code ; Given array of strings ; Function Call to modify the given array of strings
#include <bits/stdc++.h> NEW_LINE using namespace std ; void removeDuplicateCharacters ( vector < string > arr ) { unordered_set < char > cset ; int n = arr . size ( ) ; vector < string > out ; for ( auto str : arr ) { string out_curr = " " ; for ( auto ch : str ) { if ( cset . find ( ch ) != cset . end ( ) ) continue ; out_curr += ch ; cset . insert ( ch ) ; } if ( out_curr . size ( ) ) out . push_back ( out_curr ) ; } for ( int i = 0 ; i < out . size ( ) ; i ++ ) { cout << out [ i ] << " ▁ " ; } } int main ( ) { vector < string > arr = { " Geeks " , " For " , " Geeks " , " Post " } ; removeDuplicateCharacters ( arr ) ; }
Sum of array elements which are prime factors of a given number | C ++ program for the above approach ; Function to check if a number is prime or not ; Corner cases ; Check if n is a multiple of 2 or 3 ; Above condition allows to check only for every 6 th number , starting from 5 ; If n is a multiple of i and i + 2 ; Function to find the sum of array elements which are prime factors of K ; Stores the required sum ; Traverse the given array ; If current element is a prime factor of k , add it to the sum ; Print the result ; Driver Code ; Given arr [ ] ; Store the size of the array
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; return true ; } void primeFactorSum ( int arr [ ] , int n , int k ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( k % arr [ i ] == 0 && isPrime ( arr [ i ] ) ) { sum = sum + arr [ i ] ; } } cout << sum ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 5 , 6 , 7 , 15 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 35 ; primeFactorSum ( arr , N , K ) ; return 0 ; }
Minimum number of array elements from either ends required to be subtracted from X to reduce X to 0 | C ++ program to implement the above approach ; Function to count the minimum number of operations required to reduce x to 0 ; If sum of the array is less than x ; Stores the count of operations ; Two pointers to traverse the array ; Reduce x by the sum of the entire array ; Iterate until l reaches the front of the array ; If sum of elements from the front exceeds x ; Shift towards left ; If sum exceeds 0 ; Reduce x by elements from the right ; If x is reduced to 0 ; Update the minimum count of operations required ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; static int minOperations ( int nums [ ] , int N , int x ) { int sum = 0 ; for ( int i = 0 ; i < x ; i ++ ) sum += nums [ i ] ; if ( sum < x ) return -1 ; int ans = INT_MAX ; int l = N - 1 , r = N ; x -= sum ; while ( l >= 0 ) { if ( x <= 0 ) { x += nums [ l ] ; l -= 1 ; } if ( x > 0 ) { r -= 1 ; x -= nums [ r ] ; } if ( x == 0 ) { ans = min ( ans , ( l + 1 ) + ( N - r ) ) ; } } if ( ans < INT_MAX ) return ans ; else return -1 ; } int main ( ) { int nums [ ] = { 1 , 1 , 4 , 2 , 3 } ; int N = sizeof ( nums ) / sizeof ( nums [ 0 ] ) ; int x = 5 ; cout << minOperations ( nums , N , x ) ; return 0 ; }
Count of subarrays having product as a perfect cube | C ++ program for the above approach ; Function to store the prime factorization of a number ; If N is divisible by i ; Increment v [ i ] by 1 and calculate it modulo by 3 ; Divide the number by i ; If the number is not equal to 1 ; Increment v [ n ] by 1 ; Calculate it modulo 3 ; Function to count the number of subarrays whose product is a perfect cube ; Store the required result ; Stores the prime factors modulo 3 ; Stores the occurrences of the prime factors ; Traverse the array , arr [ ] ; Store the prime factors and update the vector v ; Update the answer ; Increment current state of the prime factors by 1 ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1e5 NEW_LINE void primeFactors ( vector < int > & v , int n ) { for ( int i = 2 ; i * i <= n ; i ++ ) { while ( n % i == 0 ) { v [ i ] ++ ; v [ i ] %= 3 ; n /= i ; } } if ( n != 1 ) { v [ n ] ++ ; v [ n ] %= 3 ; } } void countSubarrays ( int arr [ ] , int n ) { int ans = 0 ; vector < int > v ( MAX , 0 ) ; map < vector < int > , int > mp ; mp [ v ] ++ ; for ( int i = 0 ; i < n ; i ++ ) { primeFactors ( v , arr [ i ] ) ; ans += mp [ v ] ; mp [ v ] ++ ; } cout << ans ; } int main ( ) { int arr [ ] = { 1 , 8 , 4 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countSubarrays ( arr , N ) ; return 0 ; }
Number of subarrays having even product | Function to count subarrays with even product ; Total number of subarrays ; Counter variables ; Traverse the array ; If current element is odd ; Update count of subarrays with odd product up to index i ; Print count of subarrays with even product ; Driver code ; Input ; Length of an array ; Function call to count even product subarrays
#include <iostream> NEW_LINE using namespace std ; void evenproduct ( int arr [ ] , int length ) { int total_subarray = length * ( length + 1 ) / 2 ; int total_odd = 0 ; int count_odd = 0 ; for ( int i = 0 ; i < length ; ++ i ) { if ( arr [ i ] % 2 == 0 ) { count_odd = 0 ; } else { ++ count_odd ; total_odd += count_odd ; } } cout << ( total_subarray - total_odd ) << endl ; } int main ( ) { int arr [ ] = { 7 , 5 , 4 , 9 } ; int length = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; evenproduct ( arr , length ) ; return 0 ; }
Check if all rows of a Binary Matrix have all ones placed adjacently or not | C ++ program for the above approach ; Function to check if all 1 s are placed adjacently in an array or not ; Base Case ; Stores the sum of XOR of all pair of adjacent elements ; Calculate sum of XOR of all pair of adjacent elements ; Check for corner cases ; Return true ; Function to check if all the rows have all 1 s grouped together or not ; Traverse each row ; Check if all 1 s are placed together in the ith row or not ; Function to check if all 1 s in a row are grouped together in a matrix or not ; Print the result ; Driver Code ; Given matrix ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkGroup ( vector < int > arr ) { if ( arr . size ( ) <= 2 ) return true ; int corner = arr [ 0 ] + arr [ ( int ) arr . size ( ) - 1 ] ; int xorSum = 0 ; for ( int i = 0 ; i < arr . size ( ) - 1 ; i ++ ) xorSum += ( arr [ i ] ^ arr [ i + 1 ] ) ; if ( ! corner ) if ( xorSum > 2 ) return false ; else if ( corner == 1 ) if ( xorSum > 1 ) return false ; else if ( xorSum > 0 ) return false ; return true ; } bool isInGroupUtil ( vector < vector < int > > mat ) { for ( auto i : mat ) { if ( ! checkGroup ( i ) ) return false ; } return true ; } void isInGroup ( vector < vector < int > > mat ) { bool ans = isInGroupUtil ( mat ) ; if ( ans ) printf ( " Yes " ) ; else printf ( " No " ) ; } int main ( ) { vector < vector < int > > mat = { { 0 , 1 , 1 , 0 } , { 1 , 1 , 0 , 0 } , { 0 , 0 , 0 , 1 } , { 1 , 1 , 1 , 0 } } ; isInGroup ( mat ) ; }
Print all numbers up to N having product of digits equal to K | C ++ program for the above approach ; Function to find the product of digits of a number ; Stores the product of digits of a number ; Return the product ; Function to print all numbers upto N having product of digits equal to K ; Stores whether any number satisfying the given conditions exists or not ; Iterate over the range [ 1 , N ] ; If product of digits of arr [ i ] is equal to K or not ; Print that number ; If no numbers are found ; Driver Code ; Given value of N & K ; Function call to print all numbers from [ 1 , N ] with product of digits K
#include <bits/stdc++.h> NEW_LINE using namespace std ; int productOfDigits ( int N ) { int product = 1 ; while ( N != 0 ) { product = product * ( N % 10 ) ; N = N / 10 ; } return product ; } void productOfDigitsK ( int N , int K ) { int flag = 0 ; for ( int i = 1 ; i <= N ; ++ i ) { if ( K == productOfDigits ( i ) ) { cout << i << " ▁ " ; flag = 1 ; } } if ( flag == 0 ) cout << " - 1" ; } int main ( ) { int N = 500 , K = 10 ; productOfDigitsK ( N , K ) ; }
Minimize difference between maximum and minimum array elements by removing a K | C ++ program for the above approach ; Function to minimize difference between maximum and minimum array elements by removing a K - length subarray ; Size of array ; Stores the maximum and minimum in the suffix subarray [ i . . N - 1 ] ; Traverse the array ; Stores the maximum and minimum in the prefix subarray [ 0 . . i - 1 ] ; Store the minimum difference ; Traverse the array ; If the suffix doesn 't exceed the end of the array ; Store the maximum element in array after removing subarray of size K ; Stores the maximum element in array after removing subarray of size K ; Update minimum difference ; Updating the maxPrefix and minPrefix with current element ; Print the minimum difference ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimiseDifference ( vector < int > & arr , int K ) { int N = arr . size ( ) ; int maxSuffix [ N + 1 ] , minSuffix [ N + 1 ] ; maxSuffix [ N ] = -1e9 ; minSuffix [ N ] = 1e9 ; maxSuffix [ N - 1 ] = arr [ N - 1 ] ; minSuffix [ N - 1 ] = arr [ N - 1 ] ; for ( int i = N - 2 ; i >= 0 ; -- i ) { maxSuffix [ i ] = max ( maxSuffix [ i + 1 ] , arr [ i ] ) ; minSuffix [ i ] = min ( minSuffix [ i + 1 ] , arr [ i ] ) ; } int maxPrefix = arr [ 0 ] ; int minPrefix = arr [ 0 ] ; int minDiff = maxSuffix [ K ] - minSuffix [ K ] ; for ( int i = 1 ; i < N ; ++ i ) { if ( i + K <= N ) { int maximum = max ( maxSuffix [ i + K ] , maxPrefix ) ; int minimum = min ( minSuffix [ i + K ] , minPrefix ) ; minDiff = min ( minDiff , maximum - minimum ) ; } maxPrefix = max ( maxPrefix , arr [ i ] ) ; minPrefix = min ( minPrefix , arr [ i ] ) ; } cout << minDiff << " STRNEWLINE " ; } int main ( ) { vector < int > arr = { 4 , 5 , 8 , 9 , 1 , 2 } ; int K = 2 ; minimiseDifference ( arr , K ) ; return 0 ; }
Minimize segments required to be removed such that at least one segment intersects with all remaining segments | C ++ program for the above approach ; Function to find the minimum number of segments required to be deleted ; Stores the start and end points ; Traverse segments and fill the startPoints and endPoints ; Sort the startPoints ; Sort the startPoints ; Store the minimum number of deletions required and initialize with ( N - 1 ) ; Traverse the array segments [ ] ; Store the starting point ; Store the ending point ; Store the number of segments satisfying the first condition of non - intersection ; Store the number of segments satisfying the second condition of non - intersection ; Update answer ; Print the answer ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minSegments ( pair < int , int > segments [ ] , int n ) { int startPoints [ n ] , endPoints [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { startPoints [ i ] = segments [ i ] . first ; endPoints [ i ] = segments [ i ] . second ; } sort ( startPoints , startPoints + n ) ; sort ( endPoints , endPoints + n ) ; int ans = n - 1 ; for ( int i = 0 ; i < n ; i ++ ) { int f = segments [ i ] . first ; int s = segments [ i ] . second ; int leftDelete = lower_bound ( endPoints , endPoints + n , f ) - endPoints ; int rightDelete = max ( 0 , n - ( int ) ( upper_bound ( startPoints , startPoints + n , s ) - startPoints ) ) ; ans = min ( ans , leftDelete + rightDelete ) ; } cout << ans ; } int main ( ) { pair < int , int > arr [ ] = { { 1 , 2 } , { 5 , 6 } , { 6 , 7 } , { 7 , 10 } , { 8 , 9 } } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minSegments ( arr , N ) ; return 0 ; }
Longest substring where all the characters appear at least K times | Set 3 | C ++ program for the above approach ; Function to find the length of the longest substring ; Store the required answer ; Create a frequency map of the characters of the string ; Store the length of the string ; Traverse the string , s ; Increment the frequency of the current character by 1 ; Stores count of unique characters ; Find the number of unique characters in string ; Iterate in range [ 1 , unique ] ; Initialize frequency of all characters as 0 ; Stores the start and the end of the window ; Stores the current number of unique characters and characters occuring atleast K times ; New unique character ; New character which occurs atleast k times ; Expand window by incrementing end by 1 ; Check if this character is present atleast k times ; Check if this character is unique ; Shrink the window by incrementing start by 1 ; If there are curr_unique characters and each character is atleast k times ; Update the overall maximum length ; Print the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longestSubstring ( string s , int k ) { int ans = 0 ; int freq [ 26 ] = { 0 } ; int n = s . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) freq [ s [ i ] - ' a ' ] ++ ; int unique = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) if ( freq [ i ] != 0 ) unique ++ ; for ( int curr_unique = 1 ; curr_unique <= unique ; curr_unique ++ ) { memset ( freq , 0 , sizeof ( freq ) ) ; int start = 0 , end = 0 ; int cnt = 0 , count_k = 0 ; while ( end < n ) { if ( cnt <= curr_unique ) { int ind = s [ end ] - ' a ' ; if ( freq [ ind ] == 0 ) cnt ++ ; freq [ ind ] ++ ; if ( freq [ ind ] == k ) count_k ++ ; end ++ ; } else { int ind = s [ start ] - ' a ' ; if ( freq [ ind ] == k ) count_k -- ; freq [ ind ] -- ; if ( freq [ ind ] == 0 ) cnt -- ; start ++ ; } if ( cnt == curr_unique && count_k == curr_unique ) ans = max ( ans , end - start ) ; } } cout << ans ; } int main ( ) { string S = " aabbba " ; int K = 3 ; longestSubstring ( S , K ) ; return 0 ; }
Maximum number of intervals that an interval can intersect | C ++ program for the above approach ; Comparator function to sort in increasing order of second values in each pair ; Function to count maximum number of intervals that an interval can intersect ; Create a hashmap ; Sort by starting position ; Traverse all the intervals ; Initialize um [ v [ i ] ] as 0 ; Store the starting and ending point of the ith interval ; Set low and high ; Store the required number of intervals ; Apply binary search to find the number of intervals completely lying to the right of the ith interval ; Find the mid ; Condition for searching in the first half ; Otherwise search in the second half ; Increment um [ v [ i ] ] by n - ans if ans != - 1 ; Sort by ending position ; Traverse all the intervals ; Store the starting and ending point of the ith interval ; Set low and high ; Store the required number of intervals ; Apply binary search to find the number of intervals completely lying to the left of the ith interval ; Increment um [ v [ i ] ] by ans + 1 if ans != - 1 ; Store the answer ; Traverse the map ; Update the overall answer ; Print the answer ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool compare ( pair < int , int > f , pair < int , int > s ) { return f . second < s . second ; } struct hash_pair { template < class T1 , class T2 > size_t operator() ( const pair < T1 , T2 > & p ) const { auto hash1 = hash < T1 > { } ( p . first ) ; auto hash2 = hash < T2 > { } ( p . second ) ; return hash1 ^ hash2 ; } } ; void findMaxIntervals ( vector < pair < int , int > > v , int n ) { unordered_map < pair < int , int > , int , hash_pair > um ; sort ( v . begin ( ) , v . end ( ) ) ; for ( int i = 0 ; i < n ; i ++ ) { um [ v [ i ] ] = 0 ; int start = v [ i ] . first ; int end = v [ i ] . second ; int low = i + 1 ; int high = n - 1 ; int ans = -1 ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( v [ mid ] . first > end ) { ans = mid ; high = mid - 1 ; } else { low = mid + 1 ; } } if ( ans != -1 ) um [ v [ i ] ] = n - ans ; } sort ( v . begin ( ) , v . end ( ) , compare ) ; for ( int i = 0 ; i < n ; i ++ ) { int start = v [ i ] . first ; int end = v [ i ] . second ; int low = 0 ; int high = i - 1 ; int ans = -1 ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( v [ mid ] . second < start ) { ans = mid ; low = mid + 1 ; } else { high = mid - 1 ; } } if ( ans != -1 ) um [ v [ i ] ] += ( ans + 1 ) ; } int res = 0 ; for ( auto it = um . begin ( ) ; it != um . end ( ) ; it ++ ) { res = max ( res , n - it -> second ) ; } cout << res ; } int main ( ) { vector < pair < int , int > > arr = { { 1 , 2 } , { 3 , 4 } , { 2 , 5 } } ; int N = arr . size ( ) ; findMaxIntervals ( arr , N ) ; return 0 ; }
Print matrix elements using DFS traversal | C ++ program for the above approach ; Direction vectors ; Function to check if current position is valid or not ; Check if the cell is out of bounds ; Check if the cell is visited or not ; Utility function to print matrix elements using DFS Traversal ; Mark the current cell visited ; Print the element at the cell ; Traverse all four adjacent cells of the current element ; Check if x and y is valid index or not ; Function to print the matrix elements ; Initialize a visiting matrix ; Function call to print matrix elements by DFS traversal ; Driver Code ; Given matrix ; Row of the matrix ; Column of the matrix
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dRow [ ] = { -1 , 0 , 1 , 0 } ; int dCol [ ] = { 0 , 1 , 0 , -1 } ; bool isValid ( vector < vector < bool > > & vis , int row , int col , int COL , int ROW ) { if ( row < 0 col < 0 col > COL - 1 row > ROW - 1 ) return false ; if ( vis [ row ] [ col ] == true ) return false ; return true ; } void DFSUtil ( int row , int col , vector < vector < int > > grid , vector < vector < bool > > & vis , int M , int N ) { vis [ row ] [ col ] = true ; cout << grid [ row ] [ col ] << " ▁ " ; for ( int i = 0 ; i < 4 ; i ++ ) { int x = row + dRow [ i ] ; int y = col + dCol [ i ] ; if ( isValid ( vis , x , y , M , N ) ) DFSUtil ( x , y , grid , vis , M , N ) ; } } void DFS ( int row , int col , vector < vector < int > > grid , int M , int N ) { vector < vector < bool > > vis ( M + 1 , vector < bool > ( N + 1 , false ) ) ; DFSUtil ( 0 , 0 , grid , vis , M , N ) ; } int main ( ) { vector < vector < int > > grid { { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 16 } } ; int M = grid . size ( ) ; int N = grid [ 0 ] . size ( ) ; DFS ( 0 , 0 , grid , M , N ) ; return 0 ; }
Print matrix elements using DFS traversal | C ++ program for the above approach ; Direction vectors ; Function to check if curruent position is valid or not ; Check if the cell is out of bounds ; Check if the cell is visited ; Function to print the matrix elements ; Stores if a position in the matrix been visited or not ; Initialize stack to implement DFS ; Push the first position of grid [ ] [ ] in the stack ; Mark the cell ( 0 , 0 ) visited ; Stores top element of stack ; Delete the top ( ) element of stack ; Print element at the cell ; Traverse in all four adjacent sides of current positions ; Check if x and y is valid position and then push the position of current cell in the stack ; Push the current cell ; Mark current cell visited ; Driver Code ; Given matrix ; Row of the matrix ; Column of the matrix
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dRow [ ] = { -1 , 0 , 1 , 0 } ; int dCol [ ] = { 0 , 1 , 0 , -1 } ; bool isValid ( vector < vector < bool > > & vis , int row , int col , int COL , int ROW ) { if ( row < 0 col < 0 col > COL - 1 row > ROW - 1 ) return false ; if ( vis [ row ] [ col ] == true ) return false ; return true ; } void DFS_iterative ( vector < vector < int > > grid , int M , int N ) { vector < vector < bool > > vis ( M + 5 , vector < bool > ( N + 5 , false ) ) ; stack < pair < int , int > > st ; st . push ( { 0 , 0 } ) ; vis [ 0 ] [ 0 ] = true ; while ( ! st . empty ( ) ) { pair < int , int > p = st . top ( ) ; st . pop ( ) ; int row = p . first ; int col = p . second ; cout << grid [ row ] [ col ] << " ▁ " ; for ( int i = 0 ; i < 4 ; i ++ ) { int x = row + dRow [ i ] ; int y = col + dCol [ i ] ; if ( isValid ( vis , x , y , M , N ) ) { st . push ( { x , y } ) ; vis [ x ] [ y ] = true ; } } } } int main ( ) { vector < vector < int > > grid { { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 16 } } ; int M = grid . size ( ) ; int N = grid [ 0 ] . size ( ) ; DFS_iterative ( grid , M , N ) ; return 0 ; }
Segregate 1 s and 0 s in separate halves of a Binary String | C ++ program for the above approach ; Function to count the minimum number of operations required to segregate all 1 s and 0 s in a binary string ; Stores the count of unequal pair of adjacent characters ; If an unequal pair of adjacent characters occurs ; For odd count ; For even count ; Driver Code ; Given string ; Length of the string ; Prints the minimum count of operations required
#include <bits/stdc++.h> NEW_LINE using namespace std ; #include <bits/stdc++.h> NEW_LINE using namespace std ; void minOps ( string s , int N ) { int ans = 0 ; for ( int i = 1 ; i < N ; i ++ ) { if ( s [ i ] != s [ i - 1 ] ) { ans ++ ; } } if ( ans % 2 == 1 ) { cout << ( ans - 1 ) / 2 << endl ; return ; } cout << ( ans / 2 ) ; } int main ( ) { string str = "01011100" ; int N = str . size ( ) ; minOps ( str , N ) ; return 0 ; }
Count prime triplets upto N having sum of first two elements equal to the third number | C ++ program for the above approach ; Boolean array to mark prime numbers ; To count the prime triplets having the sum of the first two numbers equal to the third element ; Function to count prime triplets having sum of the first two elements equal to the third element ; Sieve of Eratosthenes ; Checks for the prime numbers having difference equal to2 ; Update count of triplets ; Print the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1000001 NEW_LINE bool prime [ MAX ] ; int cntTriplet [ MAX ] ; void primeTriplet ( long N ) { memset ( prime , true , sizeof ( prime ) ) ; prime [ 0 ] = prime [ 1 ] = false ; for ( int i = 2 ; i * i <= N ; i ++ ) { if ( prime [ i ] ) { for ( int j = i * i ; j <= N ; j += i ) { prime [ j ] = false ; } } } for ( int i = 3 ; i <= N ; i ++ ) { if ( prime [ i ] && prime [ i - 2 ] ) { cntTriplet [ i ] = cntTriplet [ i - 1 ] + 1 ; } else { cntTriplet [ i ] = cntTriplet [ i - 1 ] ; } } cout << cntTriplet [ N ] ; } int main ( ) { long N = 7 ; primeTriplet ( N ) ; return 0 ; }
Find index of the element differing in parity with all other array elements | C ++ program for the above approach ; Function to print the array element which differs in parity with the remaining array elements ; Multimaps to store even and odd numbers along with their indices ; Traverse the array ; If array element is even ; Otherwise ; If only one even element is present in the array ; If only one odd element is present in the array ; Driver Code ; Given array ; Size of the array
#include <bits/stdc++.h> NEW_LINE using namespace std ; int OddOneOut ( int arr [ ] , int N ) { multimap < int , int > e , o ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] % 2 == 0 ) { e . insert ( { arr [ i ] , i } ) ; } else { o . insert ( { arr [ i ] , i } ) ; } } if ( e . size ( ) == 1 ) { cout << e . begin ( ) -> second ; } else { cout << o . begin ( ) -> second ; } } int main ( ) { int arr [ ] = { 2 , 4 , 7 , 8 , 10 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; OddOneOut ( arr , N ) ; return 0 ; }
Count indices where the maximum in the prefix array is less than that in the suffix array | C ++ program for the above approach ; Function to print the count of indices in which the maximum in prefix arrays is less than that in the suffix array ; If size of array is 1 ; pre [ ] : Prefix array suf [ ] : Suffix array ; Stores the required count ; Find the maximum in prefix array ; Find the maximum in suffix array ; Traverse the array ; If maximum in prefix array is less than maximum in the suffix array ; Print the answer ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void count ( int a [ ] , int n ) { if ( n == 1 ) { cout << 0 ; return ; } int pre [ n - 1 ] , suf [ n - 1 ] ; int max = a [ 0 ] ; int ans = 0 , i ; pre [ 0 ] = a [ 0 ] ; for ( i = 1 ; i < n - 1 ; i ++ ) { if ( a [ i ] > max ) max = a [ i ] ; pre [ i ] = max ; } max = a [ n - 1 ] ; suf [ n - 2 ] = a [ n - 1 ] ; for ( i = n - 2 ; i >= 1 ; i -- ) { if ( a [ i ] > max ) max = a [ i ] ; suf [ i - 1 ] = max ; } for ( i = 0 ; i < n - 1 ; i ++ ) { if ( pre [ i ] < suf [ i ] ) ans ++ ; } cout << ans ; } int main ( ) { int arr [ ] = { 2 , 3 , 4 , 8 , 1 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; count ( arr , N ) ; return 0 ; }
Length of the longest subsequence such that XOR of adjacent elements is equal to K | C ++ program for above approach ; Function to find maximum length of subsequence ; Stores maximum length of subsequence ; Dictionary to store the longest length of subsequence ending at an integer , say X ; Stores the maximum length of subsequence ending at index i ; Base case ; Iterate over the range [ 1 , N - 1 ] ; Retrieve the longest length of subsequence ending at integer [ ] a ^ K ; If dpj is not NULL ; Update dp [ i ] ; Update ans ; Update the maximum length of subsequence ending at element is a [ i ] in Dictionary ; Return the ans if ans >= 2. Otherwise , return 0 ; Input ; Print the length of the longest subsequence
#include <bits/stdc++.h> NEW_LINE using namespace std ; int xorSubsequence ( int a [ ] , int n , int k ) { int ans = 0 ; map < int , int > map ; int dp [ n ] = { 0 } ; map [ a [ 0 ] ] = 1 ; dp [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { int dpj ; if ( map . find ( a [ i ] ^ k ) != map . end ( ) ) { dpj = map [ a [ i ] ^ k ] ; } else { dpj = -1 ; } if ( dpj != 0 ) dp [ i ] = max ( dp [ i ] , dpj + 1 ) ; ans = max ( ans , dp [ i ] ) ; if ( map . find ( a [ i ] ) != map . end ( ) ) { map [ a [ i ] ] = max ( map [ a [ i ] ] + 1 , dp [ i ] ) ; } else { map [ a [ i ] ] = max ( 1 , dp [ i ] ) ; } } return ans >= 2 ? ans : 0 ; } int main ( ) { int arr [ ] = { 3 , 2 , 4 , 3 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 1 ; cout << ( xorSubsequence ( arr , N , K ) ) ; return 0 ; }
Sum of subtree depths for every node of a given Binary Tree | C ++ program for the above approach ; Binary tree node ; Function to allocate a new node with the given data and NULL in its left and right pointers ; DFS function to calculate the sum of depths of all subtrees depth sum ; Store total number of node in its subtree and total sum of depth in its subtree ; Check if left is not NULL ; Call recursively the DFS function for left child ; Increment the sum of depths by ptemp . first + p . temp . first ; Increment p . first by count of noded in left subtree ; Check if right is not NULL ; Call recursively the DFS function for right child ; Increment the sum of depths by ptemp . first + p . temp . first ; Increment p . first by count of nodes in right subtree ; Increment the result by total sum of depth in current subtree ; Return p ; Driver Code ; Given Tree ; Print the result
#include <bits/stdc++.h> NEW_LINE using namespace std ; class TreeNode { public : int data ; TreeNode * left ; TreeNode * right ; } ; TreeNode * newNode ( int data ) { TreeNode * Node = new TreeNode ( ) ; Node -> data = data ; Node -> left = NULL ; Node -> right = NULL ; return ( Node ) ; } pair < int , int > sumofsubtree ( TreeNode * root , int & ans ) { pair < int , int > p = make_pair ( 1 , 0 ) ; if ( root -> left ) { pair < int , int > ptemp = sumofsubtree ( root -> left , ans ) ; p . second += ptemp . first + ptemp . second ; p . first += ptemp . first ; } if ( root -> right ) { pair < int , int > ptemp = sumofsubtree ( root -> right , ans ) ; p . second += ptemp . first + ptemp . second ; p . first += ptemp . first ; } ans += p . second ; return p ; } int main ( ) { TreeNode * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> left = newNode ( 6 ) ; root -> right -> right = newNode ( 7 ) ; root -> left -> left -> left = newNode ( 8 ) ; root -> left -> left -> right = newNode ( 9 ) ; int ans = 0 ; sumofsubtree ( root , ans ) ; cout << ans ; return 0 ; }
Minimum time required to fill given N slots | C ++ program for the above approach ; Function to return the minimum time to fill all the slots ; Stores visited slots ; Checks if a slot is visited or not ; Insert all filled slots ; Iterate until queue is not empty ; Iterate through all slots in the queue ; Front index ; If previous slot is present and not visited ; If next slot is present and not visited ; Increment the time at each level ; Print the answer ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minTime ( vector < int > arr , int N , int K ) { queue < int > q ; vector < bool > vis ( N + 1 , false ) ; int time = 0 ; for ( int i = 0 ; i < K ; i ++ ) { q . push ( arr [ i ] ) ; vis [ arr [ i ] ] = true ; } while ( q . size ( ) > 0 ) { for ( int i = 0 ; i < q . size ( ) ; i ++ ) { int curr = q . front ( ) ; q . pop ( ) ; if ( curr - 1 >= 1 && ! vis [ curr - 1 ] ) { vis [ curr - 1 ] = true ; q . push ( curr - 1 ) ; } if ( curr + 1 <= N && ! vis [ curr + 1 ] ) { vis [ curr + 1 ] = true ; q . push ( curr + 1 ) ; } } time ++ ; } cout << ( time - 1 ) ; } int main ( ) { int N = 6 ; vector < int > arr = { 2 , 6 } ; int K = arr . size ( ) ; minTime ( arr , N , K ) ; }
Search for an element in a Mountain Array | CPP program for the above approach ; Function to find the index of the peak element in the array ; Stores left most index in which the peak element can be found ; Stores right most index in which the peak element can be found ; Stores mid of left and right ; If element at mid is less than element at ( mid + 1 ) ; Update left ; Update right ; Function to perform binary search in an a subarray if elements of the subarray are in an ascending order ; Stores mid of left and right ; If X found at mid ; If X is greater than mid ; Update left ; Update right ; Function to perform binary search in an a subarray if elements of the subarray are in an ascending order ; Stores mid of left and right ; If X found at mid ; Update right ; Update left ; Function to find the smallest index of X ; Stores index of peak element in array ; Stores index of X in the array ; If X greater than or equal to first element of array and less than the peak element ; Update res ; If element not found on left side of peak element ; Update res ; Print res ; Driver Code ; Given X ; Given array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findPeak ( vector < int > arr ) { int left = 0 ; int right = arr . size ( ) - 1 ; while ( left < right ) { int mid = left + ( right - left ) / 2 ; if ( arr [ mid ] < arr [ mid + 1 ] ) { left = mid + 1 ; } else { right = mid ; } } return left ; } int BS ( int X , int left , int right , vector < int > arr ) { while ( left <= right ) { int mid = left + ( right - left ) / 2 ; if ( arr [ mid ] == X ) { return mid ; } else if ( X > arr [ mid ] ) { left = mid + 1 ; } else { right = mid - 1 ; } } return -1 ; } int reverseBS ( int X , int left , int right , vector < int > arr ) { while ( left <= right ) { int mid = left + ( right - left ) / 2 ; if ( arr [ mid ] == X ) { return mid ; } else if ( X > arr [ mid ] ) { right = mid - 1 ; } else { left = mid + 1 ; } } return -1 ; } void findInMA ( int X , vector < int > mountainArr ) { int peakIndex = findPeak ( mountainArr ) ; int res = -1 ; if ( X >= mountainArr [ 0 ] && X <= mountainArr [ peakIndex ] ) { res = BS ( X , 0 , peakIndex , mountainArr ) ; } if ( res == -1 ) { res = reverseBS ( X , peakIndex + 1 , mountainArr . size ( ) - 1 , mountainArr ) ; } cout << res << endl ; } int main ( ) { int X = 3 ; vector < int > list { 1 , 2 , 3 , 4 , 5 , 3 , 1 } ; findInMA ( X , list ) ; }
Rearrange given array to obtain positive prefix sums at exactly X indices | C ++ program for the above approach ; Function to rearrange the array according to the given condition ; Using 2 nd operation making all values positive ; Sort the array ; Assign K = N - K ; Count number of zeros ; If number of zeros if greater ; Using 2 nd operation convert it into one negative ; Using 2 nd operation convert it into one negative ; Print the array ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void rearrange ( int * a , int n , int x ) { for ( int i = 0 ; i < n ; i ++ ) a [ i ] = abs ( a [ i ] ) ; sort ( a , a + n ) ; x = n - x ; int z = count ( a , a + n , 0 ) ; if ( x > n - z ) { cout << " - 1 STRNEWLINE " ; return ; } for ( int i = 0 ; i < n && x > 0 ; i += 2 ) { a [ i ] = - a [ i ] ; x -- ; } for ( int i = n - 1 ; i >= 0 && x > 0 ; i -- ) { if ( a [ i ] > 0 ) { a [ i ] = - a [ i ] ; x -- ; } } for ( int i = 0 ; i < n ; i ++ ) { cout << a [ i ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 0 , -2 , 4 , 5 , -3 } ; int K = 3 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; rearrange ( arr , N , K ) ; return 0 ; }
Maximize product of a strictly increasing or decreasing subarray | C ++ program to implement the above approach ; Function to find the maximum product of subarray in the array , arr [ ] ; Maximum positive product ending at the i - th index ; Minimum negative product ending at the current index ; Maximum product up to i - th index ; Check if an array element is positive or not ; Traverse the array ; If current element is positive ; Update max_ending_here ; Update min_ending_here ; Update flag ; If current element is 0 , reset the start index of subarray ; Update max_ending_here ; Update min_ending_here ; If current element is negative ; Stores max_ending_here ; Update max_ending_here ; Update min_ending_here ; Update max_so_far , if needed ; If no array elements is positive and max_so_far is 0 ; Function to find the maximum product of either increasing subarray or the decreasing subarray ; Stores start index of either increasing subarray or the decreasing subarray ; Initially assume maxProd to be 1 ; Traverse the array ; Store the longest either increasing subarray or the decreasing subarray whose start index is i ; Check for increasing subarray ; Insert elements of increasing subarray ; Check for decreasing subarray ; Insert elements of decreasing subarray ; Stores maximum subarray product of current increasing or decreasing subarray ; Update maxProd ; Update i ; Finally print maxProd ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSubarrayProduct ( vector < int > arr , int n ) { int max_ending_here = 1 ; int min_ending_here = 1 ; int max_so_far = 0 ; int flag = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > 0 ) { max_ending_here = max_ending_here * arr [ i ] ; min_ending_here = min ( min_ending_here * arr [ i ] , 1 ) ; flag = 1 ; } else if ( arr [ i ] == 0 ) { max_ending_here = 1 ; min_ending_here = 1 ; } else { int temp = max_ending_here ; max_ending_here = max ( min_ending_here * arr [ i ] , 1 ) ; min_ending_here = temp * arr [ i ] ; } if ( max_so_far < max_ending_here ) max_so_far = max_ending_here ; } if ( flag == 0 && max_so_far == 0 ) return 0 ; return max_so_far ; } int findMaxProduct ( int * a , int n ) { int i = 0 ; int maxProd = -1e9 ; while ( i < n ) { vector < int > v ; v . push_back ( a [ i ] ) ; if ( i < n - 1 && a [ i ] < a [ i + 1 ] ) { while ( i < n - 1 && a [ i ] < a [ i + 1 ] ) { v . push_back ( a [ i + 1 ] ) ; i += 1 ; } } else if ( i < n - 1 && a [ i ] > a [ i + 1 ] ) { while ( i < n - 1 && a [ i ] > a [ i + 1 ] ) { v . push_back ( a [ i + 1 ] ) ; i += 1 ; } } int prod = maxSubarrayProduct ( v , v . size ( ) ) ; maxProd = max ( maxProd , prod ) ; i ++ ; } return maxProd ; } int main ( ) { int arr [ ] = { 1 , 2 , 10 , 8 , 1 , 100 , 101 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findMaxProduct ( arr , N ) ; return 0 ; }
Number of connected components of a graph ( using Disjoint Set Union ) | C ++ program for the above approach ; Stores the parent of each vertex ; Function to find the topmost parent of vertex a ; If current vertex is the topmost vertex ; Otherwise , set topmost vertex of its parent as its topmost vertex ; Function to connect the component having vertex a with the component having vertex b ; Connect edges ; Function to find unique top most parents ; Traverse all vertices ; Insert all topmost vertices obtained ; Print count of connected components ; Function to print answer ; Setting parent to itself ; Traverse all edges ; Print answer ; Driver Code ; Given N ; Given edges ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int parent [ 1000000 ] ; int root ( int a ) { if ( a == parent [ a ] ) { return a ; } return parent [ a ] = root ( parent [ a ] ) ; } void connect ( int a , int b ) { a = root ( a ) ; b = root ( b ) ; if ( a != b ) { parent [ b ] = a ; } } void connectedComponents ( int n ) { set < int > s ; for ( int i = 0 ; i < n ; i ++ ) { s . insert ( root ( parent [ i ] ) ) ; } cout << s . size ( ) << ' ' ; } void printAnswer ( int N , vector < vector < int > > edges ) { for ( int i = 0 ; i <= N ; i ++ ) { parent [ i ] = i ; } for ( int i = 0 ; i < edges . size ( ) ; i ++ ) { connect ( edges [ i ] [ 0 ] , edges [ i ] [ 1 ] ) ; } connectedComponents ( N ) ; } int main ( ) { int N = 8 ; vector < vector < int > > edges = { { 1 , 0 } , { 0 , 2 } , { 5 , 3 } , { 3 , 4 } , { 6 , 7 } } ; printAnswer ( N , edges ) ; return 0 ; }
Remove all zero | C ++ program for the above approach ; Function to remove the rows or columns from the matrix which contains all 0 s elements ; Stores count of rows ; col [ i ] : Stores count of 0 s in current column ; row [ i ] : Stores count of 0 s in current row ; Traverse the matrix ; Stores count of 0 s in current row ; Update col [ j ] ; Update count ; Update row [ i ] ; Traverse the matrix ; If all elements of current row is 0 ; If all elements of current column is 0 ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void removeZeroRowCol ( vector < vector < int > > & arr ) { int n = arr . size ( ) ; int col [ n + 1 ] = { 0 } ; int row [ n + 1 ] = { 0 } ; for ( int i = 0 ; i < n ; ++ i ) { int count = 0 ; for ( int j = 0 ; j < n ; ++ j ) { col [ j ] += ( arr [ i ] [ j ] == 1 ) ; count += ( arr [ i ] [ j ] == 1 ) ; } row [ i ] = count ; } for ( int i = 0 ; i < n ; ++ i ) { if ( row [ i ] == 0 ) { continue ; } for ( int j = 0 ; j < n ; ++ j ) { if ( col [ j ] != 0 ) cout << arr [ i ] [ j ] ; } cout << " STRNEWLINE " ; } } int main ( ) { vector < vector < int > > arr = { { 1 , 1 , 0 , 1 } , { 0 , 0 , 0 , 0 } , { 1 , 1 , 0 , 1 } , { 0 , 1 , 0 , 1 } } ; removeZeroRowCol ( arr ) ; return 0 ; }
Find a pair of overlapping intervals from a given Set | C ++ program to implement the above approach ; Function to find a pair ( i , j ) such that i - th interval lies within the j - th interval ; Store interval and index of the interval in the form of { { l , r } , index } ; Traverse the array , arr [ ] [ ] ; Stores l - value of the interval ; Stores r - value of the interval ; Push current interval and index into tup ; Sort the vector based on l - value of the intervals ; Stores r - value of current interval ; Stores index of current interval ; Traverse the vector , tup [ ] ; Stores l - value of previous interval ; Stores l - value of current interval ; If Q and R are equal ; Print the index of interval ; Stores r - value of current interval ; If T is less than or equal to curr ; Update curr ; Update currPos ; If such intervals found ; Driver Code ; Given l - value of segments ; Given r - value of segments ; Given size ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findOverlapSegement ( int N , int a [ ] , int b [ ] ) { vector < pair < pair < int , int > , int > > tup ; for ( int i = 0 ; i < N ; i ++ ) { int x , y ; x = a [ i ] ; y = b [ i ] ; tup . push_back ( pair < pair < int , int > , int > ( pair < int , int > ( x , y ) , i ) ) ; } sort ( tup . begin ( ) , tup . end ( ) ) ; int curr = tup [ 0 ] . first . second ; int currPos = tup [ 0 ] . second ; for ( int i = 1 ; i < N ; i ++ ) { int Q = tup [ i - 1 ] . first . first ; int R = tup [ i ] . first . first ; if ( Q == R ) { if ( tup [ i - 1 ] . first . second < tup [ i ] . first . second ) cout << tup [ i - 1 ] . second << ' ▁ ' << tup [ i ] . second ; else cout << tup [ i ] . second << ' ▁ ' << tup [ i - 1 ] . second ; return ; } int T = tup [ i ] . first . second ; if ( T <= curr ) { cout << tup [ i ] . second << ' ▁ ' << currPos ; return ; } else { curr = T ; currPos = tup [ i ] . second ; } } cout << " - 1 ▁ - 1" ; } int main ( ) { int a [ ] = { 1 , 2 , 3 , 2 , 2 } ; int b [ ] = { 5 , 10 , 10 , 2 , 15 } ; int N = sizeof ( a ) / sizeof ( int ) ; findOverlapSegement ( N , a , b ) ; }
Replace each node of a Binary Tree with the sum of all the nodes present in its diagonal | CPP program to implement the above approach ; Structure of a tree node ; Function to replace each node with the sum of nodes at the same diagonal ; IF root is NULL ; Replace nodes ; Traverse the left subtree ; Traverse the right subtree ; Function to find the sum of all the nodes at each diagonal of the tree ; If root is not NULL ; If update sum of nodes at current diagonal ; Traverse the left subtree ; Traverse the right subtree ; Function to print the nodes of the tree using level order traversal ; Stores node at each level of the tree ; Stores count of nodes at current level ; Stores front element of the queue ; Insert left subtree ; Insert right subtree ; Update length ; Driver Code ; Build tree ; Store sum of nodes at each diagonal of the tree ; Find sum of nodes at each diagonal of the tree ; Replace nodes with the sum of nodes at the same diagonal ; Print tree
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct TreeNode { int val ; struct TreeNode * left , * right ; TreeNode ( int x ) { val = x ; left = NULL ; right = NULL ; } } ; void replaceDiag ( TreeNode * root , int d , unordered_map < int , int > & diagMap ) { if ( ! root ) return ; root -> val = diagMap [ d ] ; replaceDiag ( root -> left , d + 1 , diagMap ) ; replaceDiag ( root -> right , d , diagMap ) ; } void getDiagSum ( TreeNode * root , int d , unordered_map < int , int > & diagMap ) { if ( ! root ) return ; if ( diagMap [ d ] > 0 ) diagMap [ d ] += root -> val ; else diagMap [ d ] = root -> val ; getDiagSum ( root -> left , d + 1 , diagMap ) ; getDiagSum ( root -> right , d , diagMap ) ; } void levelOrder ( TreeNode * root ) { queue < TreeNode * > q ; q . push ( root ) ; while ( true ) { int length = q . size ( ) ; if ( ! length ) break ; while ( length ) { auto temp = q . front ( ) ; q . pop ( ) ; cout << temp -> val << " ▁ " ; if ( temp -> left ) q . push ( temp -> left ) ; if ( temp -> right ) q . push ( temp -> right ) ; length -= 1 ; } } } int main ( ) { TreeNode * root = new TreeNode ( 5 ) ; root -> left = new TreeNode ( 6 ) ; root -> right = new TreeNode ( 3 ) ; root -> left -> left = new TreeNode ( 4 ) ; root -> left -> right = new TreeNode ( 9 ) ; root -> right -> right = new TreeNode ( 2 ) ; unordered_map < int , int > diagMap ; getDiagSum ( root , 0 , diagMap ) ; replaceDiag ( root , 0 , diagMap ) ; levelOrder ( root ) ; return 0 ; }
Count maximum concatenation of pairs from given array that are divisible by 3 | C ++ program to implement the above approach ; Function to count pairs whose concatenation is divisible by 3 and each element can be present in at most one pair ; Stores count pairs whose concatenation is divisible by 3 and each element can be present in at most one pair ; Check if an element present in any pair or not ; Generate all possible pairs ; If the element already present in a pair ; If the element already present in a pair ; If concatenation of elements is divisible by 3 ; Update ans ; Mark i is True ; Mark j is True ; Driver Code ; To display the result
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countDivBy3InArray ( int arr [ ] , int N ) { int ans = 0 ; bool taken [ N ] ; memset ( taken , false , sizeof ( taken ) ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( taken [ i ] == true ) { continue ; } for ( int j = i + 1 ; j < N ; j ++ ) { if ( taken [ j ] == true ) { continue ; } if ( stoi ( to_string ( arr [ i ] ) + to_string ( arr [ j ] ) ) % 3 == 0 || stoi ( to_string ( arr [ j ] ) + to_string ( arr [ i ] ) ) % 3 == 0 ) { ans += 1 ; taken [ i ] = true ; taken [ j ] = true ; } } } return ans ; } int main ( ) { int arr [ ] = { 5 , 3 , 2 , 8 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countDivBy3InArray ( arr , N ) ; return 0 ; }
Longest increasing sequence possible by the boundary elements of an Array | C ++ program for the above approach ; Function to find longest strictly increasing sequence using boundary elements ; Maintains rightmost element in the sequence ; Pointer to start of array ; Pointer to end of array ; Stores the required sequence ; Traverse the array ; If arr [ i ] > arr [ j ] ; If arr [ j ] is greater than rightmost element of the sequence ; Push arr [ j ] into the sequence ; Update rightmost element ; Push arr [ i ] into the sequence ; Update rightmost element ; If arr [ i ] < arr [ j ] ; If arr [ i ] > rightmost element ; Push arr [ i ] into the sequence ; Update rightmost element ; If arr [ j ] > rightmost element ; Push arr [ j ] into the sequence ; Update rightmost element ; If arr [ i ] is equal to arr [ j ] ; If i and j are at the same element ; If arr [ i ] > rightmostelement ; Push arr [ j ] into the sequence ; Update rightmost element ; Traverse array from left to right ; Stores the increasing sequence from the left end ; Traverse array from left to right ; Push arr [ k ] to max_left vector ; Traverse the array from right to left ; Stores the increasing sequence from the right end ; Traverse array from right to left ; Push arr [ k ] to max_right vector ; If size of max_left is greater than max_right ; Push max_left elements to the original sequence ; Otherwise ; Push max_right elements to the original sequence ; Print the sequence ; Driver Code ; Print the longest increasing sequence using boundary elements
#include <iostream> NEW_LINE #include <vector> NEW_LINE using namespace std ; void findMaxLengthSequence ( int N , int arr [ 4 ] ) { int rightmost_element = -1 ; int i = 0 ; int j = N - 1 ; vector < int > sequence ; while ( i <= j ) { if ( arr [ i ] > arr [ j ] ) { if ( arr [ j ] > rightmost_element ) { sequence . push_back ( arr [ j ] ) ; rightmost_element = arr [ j ] ; j -- ; } else if ( arr [ i ] > rightmost_element ) { sequence . push_back ( arr [ i ] ) ; rightmost_element = arr [ i ] ; i ++ ; } else break ; } else if ( arr [ i ] < arr [ j ] ) { if ( arr [ i ] > rightmost_element ) { sequence . push_back ( arr [ i ] ) ; rightmost_element = arr [ i ] ; i ++ ; } else if ( arr [ j ] > rightmost_element ) { sequence . push_back ( arr [ j ] ) ; rightmost_element = arr [ j ] ; j -- ; } else break ; } else if ( arr [ i ] == arr [ j ] ) { if ( i == j ) { if ( arr [ i ] > rightmost_element ) { sequence . push_back ( arr [ i ] ) ; rightmost_element = arr [ i ] ; i ++ ; } break ; } else { sequence . push_back ( arr [ i ] ) ; int k = i + 1 ; vector < int > max_left ; while ( k < j && arr [ k ] > arr [ k - 1 ] ) { max_left . push_back ( arr [ k ] ) ; k ++ ; } int l = j - 1 ; vector < int > max_right ; while ( l > i && arr [ l ] > arr [ l + 1 ] ) { max_right . push_back ( arr [ l ] ) ; l -- ; } if ( max_left . size ( ) > max_right . size ( ) ) for ( int element : max_left ) sequence . push_back ( element ) ; else for ( int element : max_right ) sequence . push_back ( element ) ; break ; } } } for ( int element : sequence ) printf ( " % d ▁ " , element ) ; } int main ( ) { int N = 4 ; int arr [ ] = { 1 , 3 , 2 , 1 } ; findMaxLengthSequence ( N , arr ) ; }
Maximum average of subtree values in a given Binary Tree | C ++ program for the above approach ; Structure of the Tree node ; Stores the result ; Function for finding maximum subtree average ; Checks if current node is not NULL and doesn 't have any children ; Stores sum of its subtree in index 0 and count number of nodes in index 1 ; Traverse all children of the current node ; Recursively calculate max average of subtrees among its children ; Increment sum by sum of its child 's subtree ; Increment number of nodes by its child 's node ; Increment sum by current node 's value ; Increment number of nodes by one ; Take maximum of ans and current node 's average ; Finally return pair of { sum , count } ; Driver Code ; Given tree ; Function call ; Print answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct TreeNode { int val ; vector < TreeNode * > children ; TreeNode ( int v ) { val = v ; } } ; double ans = 0.0 ; vector < int > MaxAverage ( TreeNode * root ) { if ( root != NULL && root -> children . size ( ) == 0 ) { ans = max ( ans , ( root -> val ) * ( 1.0 ) ) ; return { root -> val , 1 } ; } vector < int > childResult ( 2 ) ; for ( TreeNode * child : root -> children ) { vector < int > childTotal = MaxAverage ( child ) ; childResult [ 0 ] = childResult [ 0 ] + childTotal [ 0 ] ; childResult [ 1 ] = childResult [ 1 ] + childTotal [ 1 ] ; } int sum = childResult [ 0 ] + root -> val ; int count = childResult [ 1 ] + 1 ; ans = max ( ans , sum / count * 1.0 ) ; return { sum , count } ; } int main ( ) { TreeNode * root = new TreeNode ( 20 ) ; TreeNode * left = new TreeNode ( 12 ) ; TreeNode * right = new TreeNode ( 18 ) ; root -> children . push_back ( left ) ; root -> children . push_back ( right ) ; left -> children . push_back ( new TreeNode ( 11 ) ) ; left -> children . push_back ( new TreeNode ( 3 ) ) ; right -> children . push_back ( new TreeNode ( 15 ) ) ; right -> children . push_back ( new TreeNode ( 8 ) ) ; MaxAverage ( root ) ; printf ( " % 0.1f STRNEWLINE " , ans ) ; }
Check if a Binary String can be converted to another by reversing substrings consisting of even number of 1 s | C ++ program for the above approach ; Function to check if string A can be transformed to string B by reversing substrings of A having even number of 1 s ; Store the size of string A ; Store the size of string B ; Store the count of 1 s in A and B ; Stores cntA for string A and cntB for string B ; Traverse the string A ; If current character is 1 ; Increment 1 s count ; Otherwise , update odd1A or even1A depending whether count1A is odd or even ; Traverse the string B ; If current character is 1 ; Increment 1 s count ; Otherwise , update odd1B or even1B depending whether count1B is odd or even ; If the condition is satisfied ; If true , print Yes ; Otherwise , print No ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void canTransformStrings ( string A , string B ) { int n1 = A . size ( ) ; int n2 = B . size ( ) ; int count1A = 0 , count1B = 0 ; int odd1A = 0 , odd1B = 0 ; int even1A = 0 , even1B = 0 ; for ( int i = 0 ; i < n1 ; i ++ ) { if ( A [ i ] == '1' ) count1A ++ ; else { if ( count1A & 1 ) odd1A ++ ; else even1A ++ ; } } for ( int i = 0 ; i < n2 ; i ++ ) { if ( B [ i ] == '1' ) count1B ++ ; else { if ( count1B & 1 ) odd1B ++ ; else even1B ++ ; } } if ( count1A == count1B && odd1A == odd1B && even1A == even1B ) { cout << " Yes " ; } else cout << " No " ; } int main ( ) { string A = "10011" , B = "11100" ; canTransformStrings ( A , B ) ; return 0 ; }
Smallest element present in every subarray of all possible lengths | C ++ program of the above approach ; Function to print the common elements for all subarray lengths ; Function to find and store the minimum element present in all subarrays of all lengths from 1 to n ; Skip lengths for which answer [ i ] is - 1 ; Initialize minimum as the first element where answer [ i ] is not - 1 ; Updating the answer array ; If answer [ i ] is - 1 , then minimum can be substituted in that place ; Find minimum answer ; Function to find the minimum number corresponding to every subarray of length K , for every K from 1 to N ; Stores the minimum common elements for all subarray lengths ; Initialize with - 1. ; Find for every element , the minimum length such that the number is present in every subsequence of that particular length or more ; To store first occurence and gaps between occurences ; To cover the distance between last occurence and the end of the array ; To find the distance between any two occurences ; Update and store the answer ; Print the required answer ; Function to find the smallest element common in all subarrays for every possible subarray lengths ; Initializing indices array ; Store the numbers present in the array ; Push the index in the indices [ A [ i ] ] and also store the numbers in set to get the numbers present in input array ; Function call to calculate length of subarray for which a number is present in every subarray of that length ; Driver Code ; Given array ; Size of array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printAnswer ( int answer [ ] , int N ) { for ( int i = 1 ; i <= N ; i ++ ) { cout << answer [ i ] << " ▁ " ; } } void updateAnswerArray ( int answer [ ] , int N ) { int i = 0 ; while ( answer [ i ] == -1 ) i ++ ; int minimum = answer [ i ] ; while ( i <= N ) { if ( answer [ i ] == -1 ) answer [ i ] = minimum ; else answer [ i ] = min ( minimum , answer [ i ] ) ; minimum = min ( minimum , answer [ i ] ) ; i ++ ; } } void lengthOfSubarray ( vector < int > indices [ ] , set < int > st , int N ) { int answer [ N + 1 ] ; memset ( answer , -1 , sizeof ( answer ) ) ; for ( auto itr : st ) { int start = -1 ; int gap = -1 ; indices [ itr ] . push_back ( N ) ; for ( int i = 0 ; i < indices [ itr ] . size ( ) ; i ++ ) { gap = max ( gap , indices [ itr ] [ i ] - start ) ; start = indices [ itr ] [ i ] ; } if ( answer [ gap ] == -1 ) answer [ gap ] = itr ; } updateAnswerArray ( answer , N ) ; printAnswer ( answer , N ) ; } void smallestPresentNumber ( int arr [ ] , int N ) { vector < int > indices [ N + 1 ] ; set < int > elements ; for ( int i = 0 ; i < N ; i ++ ) { indices [ arr [ i ] ] . push_back ( i ) ; elements . insert ( arr [ i ] ) ; } lengthOfSubarray ( indices , elements , N ) ; } int main ( ) { int arr [ ] = { 2 , 3 , 5 , 3 , 2 , 3 , 1 , 3 , 2 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; smallestPresentNumber ( arr , N ) ; return ( 0 ) ; }
Minimize remaining array element by removing pairs and replacing them by their absolute difference | C ++ program to implement the above approach ; Function to find the smallest element left in the array by the given operations ; Base Case ; If this subproblem has occurred previously ; Including i - th array element into the first subset ; If i - th array element is not selected ; Update dp [ i ] [ sum ] ; Utility function to find smallest element left in the array by the given operations ; Stores sum of the array elements ; Traverse the array ; Update total ; Stores overlapping subproblems ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int smallestLeft ( int arr [ ] , int total , int sum , int i , vector < vector < int > > & dp ) { if ( i == 0 ) { return abs ( total - 2 * sum ) ; } if ( dp [ i ] [ sum ] != -1 ) return dp [ i ] [ sum ] ; int X = smallestLeft ( arr , total , sum + arr [ i - 1 ] , i - 1 , dp ) ; int Y = smallestLeft ( arr , total , sum , i - 1 , dp ) ; return dp [ i ] [ sum ] = min ( X , Y ) ; } int UtilSmallestElement ( int arr [ ] , int N ) { int total = 0 ; for ( int i = 0 ; i < N ; i ++ ) { total += arr [ i ] ; } vector < vector < int > > dp ( N + 1 , vector < int > ( total , -1 ) ) ; cout << smallestLeft ( arr , total , 0 , N , dp ) ; } int main ( ) { int arr [ ] = { 2 , 7 , 4 , 1 , 8 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; UtilSmallestElement ( arr , N ) ; return 0 ; }
Minimize remaining array element by removing pairs and replacing them by their absolute difference | C ++ program to implement the above approach ; Function to find minimize the remaining array element by removing pairs and replacing them by their absolute difference ; Stores sum of array elements ; Traverse the array ; Update totalSum ; Stores half of totalSum ; dp [ i ] : True if sum i can be obtained as a subset sum ; Base case ; Stores closest sum that can be obtained as a subset sum ; Traverse the array ; Iterate over all possible value of sum ; Update dp [ j ] ; If sum i can be obtained from array elements ; Update reach ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int SmallestElementLeft ( int arr [ ] , int N ) { int totalSum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { totalSum += arr [ i ] ; } int req = totalSum / 2 ; bool dp [ req + 1 ] ; memset ( dp , false , sizeof ( dp ) ) ; dp [ 0 ] = true ; int reach = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = req ; j - arr [ i ] >= 0 ; j -- ) { dp [ j ] = dp [ j ] || dp [ j - arr [ i ] ] ; if ( dp [ j ] ) { reach = max ( reach , j ) ; } } } return totalSum - ( 2 * reach ) ; } int main ( ) { int arr [ ] = { 2 , 2 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << SmallestElementLeft ( arr , N ) ; return 0 ; }
Replace even | C ++ program to implement the above approach ; Function to count the minimum number of substrings of str1 such that replacing even - indexed characters of those substrings converts the string str1 to str2 ; Stores length of str1 ; Stores minimum count of operations to convert str1 to str2 ; Traverse both the given string ; If current character in both the strings are equal ; Stores current index of the string ; If current character in both the strings are not equal ; Replace str1 [ ptr ] by str2 [ ptr ] ; Update ptr ; Update cntOp ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperationsReq ( string str1 , string str2 ) { int N = str1 . length ( ) ; int cntOp = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( str1 [ i ] == str2 [ i ] ) { continue ; } int ptr = i ; while ( ptr < N && str1 [ ptr ] != str2 [ ptr ] ) { str1 [ ptr ] = str2 [ ptr ] ; ptr += 2 ; } cntOp ++ ; } return cntOp ; } int main ( ) { string str1 = " abcdef " ; string str2 = " ffffff " ; cout << minOperationsReq ( str1 , str2 ) ; return 0 ; }
Check if GCD of all Composite Numbers in an array divisible by K is a Fibonacci Number or not | C ++ Program for the above approach ; Function to check if a number is composite or not ; Corner cases ; Check if the number is divisible by 2 or 3 or not ; Check if n is a multiple of any other prime number ; Function to check if a number is a Perfect Square or not ; Function to check if a number is a Fibonacci number or not ; If 5 * n ^ 2 + 4 or 5 * n ^ 2 - 4 or both are perfect square ; Function to check if GCD of composite numbers from the array a [ ] which are divisible by k is a Fibonacci number or not ; Traverse the array ; If array element is composite and divisible by k ; Calculate GCD of all elements in compositeset ; If GCD is Fibonacci ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isComposite ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return false ; if ( n % 2 == 0 n % 3 == 0 ) return true ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return true ; return false ; } bool isPerfectSquare ( int x ) { int s = sqrt ( x ) ; return ( s * s == x ) ; } bool isFibonacci ( int n ) { return isPerfectSquare ( 5 * n * n + 4 ) || isPerfectSquare ( 5 * n * n - 4 ) ; } void ifgcdFibonacci ( int a [ ] , int n , int k ) { vector < int > compositeset ; for ( int i = 0 ; i < n ; i ++ ) { if ( isComposite ( a [ i ] ) && a [ i ] % k == 0 ) { compositeset . push_back ( a [ i ] ) ; } } int gcd = compositeset [ 0 ] ; for ( int i = 1 ; i < compositeset . size ( ) ; i ++ ) { gcd = __gcd ( gcd , compositeset [ i ] ) ; if ( gcd == 1 ) { break ; } } if ( isFibonacci ( gcd ) ) { cout << " Yes " ; return ; } cout << " No " ; return ; } int main ( ) { int arr [ ] = { 34 , 2 , 4 , 8 , 5 , 7 , 11 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 2 ; ifgcdFibonacci ( arr , n , k ) ; return 0 ; }
Longest subarray in which all elements are a factor of K | C ++ program to implement the above approach ; Function to find the length of the longest subarray in which all elements are a factor of K ; Stores length of the longest subarray in which all elements are a factor of K ; Stores length of the current subarray ; Traverse the array arr [ ] ; If A [ i ] is a factor of K ; Update Len ; Update MaxLen ; If A [ i ] is not a factor of K ; Update Len ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find_longest_subarray ( int A [ ] , int N , int K ) { int MaxLen = 0 ; int Len = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( K % A [ i ] == 0 ) { Len ++ ; MaxLen = max ( MaxLen , Len ) ; } else { Len = 0 ; } } return MaxLen ; } int main ( ) { int A [ ] = { 2 , 8 , 3 , 10 , 6 , 7 , 4 , 9 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; ; int K = 60 ; cout << find_longest_subarray ( A , N , K ) ; return 0 ; }
Length of smallest meeting that can be attended | C ++ program to implement the above approach ; Function to find the minimum time to attend exactly one meeting ; Stores minimum time to attend exactly one meeting ; Sort entrance [ ] array ; Sort exit [ ] time ; Traverse meeting [ ] [ ] ; Stores start time of current meeting ; Stores end time of current meeting ; Find just greater value of u in entrance [ ] ; Find just greater or equal value of u in entrance [ ] ; Stores enter time to attend the current meeting ; Stores exist time after attending the meeting ; Update start lies in range [ 0 , m - 1 ] and end lies in the range [ 0 , p - 1 ] ; Update ans ; Return answer ; Driver Code ; Stores interval of meeting ; Stores entrance timings ; Stores exit timings ; Stores total count of meetings ; Stores total entrance timings ; Stores total exit timings ; Minimum time
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minTime ( int meeting [ ] [ 2 ] , int n , vector < int > entrance , int m , vector < int > & exit , int p ) { int ans = INT_MAX ; sort ( entrance . begin ( ) , entrance . end ( ) ) ; sort ( exit . begin ( ) , exit . end ( ) ) ; for ( int i = 0 ; i < n ; i ++ ) { int u = meeting [ i ] [ 0 ] ; int v = meeting [ i ] [ 1 ] ; auto it1 = upper_bound ( entrance . begin ( ) , entrance . end ( ) , u ) ; auto it2 = lower_bound ( exit . begin ( ) , exit . end ( ) , v ) ; int start = it1 - entrance . begin ( ) - 1 ; int end = it2 - exit . begin ( ) ; if ( start >= 0 && start < m && end >= 0 && end < p ) ans = min ( ans , exit [ end ] - entrance [ start ] ) ; } return ans >= INT_MAX ? -1 : ans ; } int main ( ) { int meeting [ ] [ 2 ] = { { 15 , 19 } , { 5 , 10 } , { 7 , 25 } } ; vector < int > entrance = { 4 , 13 , 25 , 2 } ; vector < int > exit = { 10 , 25 } ; int n = ( sizeof ( meeting ) ) / sizeof ( meeting [ 0 ] ) ; int m = entrance . size ( ) ; int p = exit . size ( ) ; cout << minTime ( meeting , n , entrance , m , exit , p ) << endl ; return 0 ; }
Divide array into two arrays which does not contain any pair with sum K | C ++ program for the above approach ; Function to split the given array into two separate arrays satisfying given condition ; Stores resultant arrays ; Traverse the array ; If a [ i ] is smaller than or equal to k / 2 ; Print first array ; Print second array ; Driver Code ; Given K ; Given array ; Given size
#include <bits/stdc++.h> NEW_LINE using namespace std ; void splitArray ( int a [ ] , int n , int k ) { vector < int > first , second ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] <= k / 2 ) first . push_back ( a [ i ] ) ; else second . push_back ( a [ i ] ) ; } for ( int i = 0 ; i < first . size ( ) ; i ++ ) { cout << first [ i ] << " ▁ " ; } cout << " STRNEWLINE " ; for ( int i = 0 ; i < second . size ( ) ; i ++ ) { cout << second [ i ] << " ▁ " ; } } int main ( ) { int k = 5 ; int a [ ] = { 0 , 1 , 3 , 2 , 4 , 5 , 6 , 7 , 8 , 9 , 10 } ; int n = sizeof ( a ) / sizeof ( int ) ; splitArray ( a , n , k ) ; return 0 ; }
Find all the queens attacking the king in a chessboard | C ++ Program to implement the above approach ; Function to find the queen closest to king in an attacking position ; Function to find all the queens attacking the king in the chessboard ; Iterating over the coordinates of the queens ; If king is horizontally on the right of current queen ; If no attacker is present in that direction ; Or if the current queen is closest in that direction ; Set current queen as the attacker ; If king is horizontally on the left of current queen ; If no attacker is present in that direction ; Or if the current queen is closest in that direction ; Set current queen as the attacker ; If the king is attacked by a queen from the left by a queen diagonal above ; If no attacker is present in that direction ; Or the current queen is the closest attacker in that direction ; Set current queen as the attacker ; If the king is attacked by a queen from the left by a queen diagonally below ; If no attacker is present in that direction ; Or the current queen is the closest attacker in that direction ; Set current queen as the attacker ; If the king is attacked by a queen from the right by a queen diagonally above ; If no attacker is present in that direction ; Or the current queen is the closest attacker in that direction ; Set current queen as the attacker ; If the king is attacked by a queen from the right by a queen diagonally below ; If no attacker is present in that direction ; Or the current queen is the closest attacker in that direction ; Set current queen as the attacker ; If a king is vertically below the current queen ; If no attacker is present in that direction ; Or the current queen is the closest attacker in that direction ; Set current queen as the attacker ; If a king is vertically above the current queen ; If no attacker is present in that direction ; Or the current queen is the closest attacker in that direction ; Set current queen as the attacker ; Return the coordinates ; Print all the coordinates of the queens attacking the king ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dis ( vector < int > ans , vector < int > attacker ) { return abs ( ans [ 0 ] - attacker [ 0 ] ) + abs ( ans [ 1 ] - attacker [ 1 ] ) ; } vector < vector < int > > findQueens ( vector < vector < int > > & queens , vector < int > & king ) { vector < vector < int > > sol ; vector < vector < int > > attackers ( 8 ) ; for ( int i = 0 ; i < queens . size ( ) ; i ++ ) { if ( king [ 0 ] == queens [ i ] [ 0 ] && king [ 1 ] > queens [ i ] [ 1 ] ) { if ( ( attackers [ 3 ] . size ( ) == 0 ) || ( dis ( attackers [ 3 ] , king ) > dis ( queens [ i ] , king ) ) ) attackers [ 3 ] = queens [ i ] ; } if ( king [ 0 ] == queens [ i ] [ 0 ] && king [ 1 ] < queens [ i ] [ 1 ] ) { if ( ( attackers [ 4 ] . size ( ) == 0 ) || ( dis ( attackers [ 4 ] , king ) > dis ( queens [ i ] , king ) ) ) attackers [ 4 ] = queens [ i ] ; } if ( king [ 0 ] - queens [ i ] [ 0 ] == king [ 1 ] - queens [ i ] [ 1 ] && king [ 0 ] > queens [ i ] [ 0 ] ) { if ( ( attackers [ 0 ] . size ( ) == 0 ) || ( dis ( attackers [ 0 ] , king ) > dis ( queens [ i ] , king ) ) ) attackers [ 0 ] = queens [ i ] ; } if ( king [ 0 ] - queens [ i ] [ 0 ] == king [ 1 ] - queens [ i ] [ 1 ] && king [ 0 ] < queens [ i ] [ 0 ] ) { if ( ( attackers [ 7 ] . size ( ) == 0 ) || ( dis ( attackers [ 7 ] , king ) > dis ( queens [ i ] , king ) ) ) attackers [ 7 ] = queens [ i ] ; } if ( king [ 1 ] - queens [ i ] [ 1 ] == 0 && king [ 0 ] > queens [ i ] [ 0 ] ) { if ( ( attackers [ 1 ] . size ( ) == 0 ) || ( dis ( attackers [ 1 ] , king ) > dis ( queens [ i ] , king ) ) ) attackers [ 1 ] = queens [ i ] ; } if ( king [ 1 ] - queens [ i ] [ 1 ] == 0 && king [ 0 ] < queens [ i ] [ 0 ] ) { if ( ( attackers [ 6 ] . size ( ) == 0 ) || ( dis ( attackers [ 6 ] , king ) > dis ( queens [ i ] , king ) ) ) attackers [ 6 ] = queens [ i ] ; } if ( king [ 0 ] - queens [ i ] [ 0 ] == - ( king [ 1 ] - queens [ i ] [ 1 ] ) && king [ 0 ] > queens [ i ] [ 0 ] ) { if ( ( attackers [ 2 ] . size ( ) == 0 ) || ( dis ( attackers [ 2 ] , king ) > dis ( queens [ i ] , king ) ) ) attackers [ 2 ] = queens [ i ] ; } if ( king [ 0 ] - queens [ i ] [ 0 ] == - ( king [ 1 ] - queens [ i ] [ 1 ] ) && king [ 0 ] < queens [ i ] [ 0 ] ) { if ( ( attackers [ 5 ] . size ( ) == 0 ) || ( dis ( attackers [ 5 ] , king ) > dis ( queens [ i ] , king ) ) ) attackers [ 5 ] = queens [ i ] ; } } for ( int i = 0 ; i < 8 ; i ++ ) if ( attackers [ i ] . size ( ) ) sol . push_back ( attackers [ i ] ) ; return sol ; } void print ( vector < vector < int > > ans ) { for ( int i = 0 ; i < ans . size ( ) ; i ++ ) { for ( int j = 0 ; j < 2 ; j ++ ) cout << ans [ i ] [ j ] << " ▁ " ; cout << " STRNEWLINE " ; } } int main ( ) { vector < int > king = { 2 , 3 } ; vector < vector < int > > queens = { { 0 , 1 } , { 1 , 0 } , { 4 , 0 } , { 0 , 4 } , { 3 , 3 } , { 2 , 4 } } ; vector < vector < int > > ans = findQueens ( queens , king ) ; print ( ans ) ; }
Count numbers in a given range whose count of prime factors is a Prime Number | C ++ program to implement the above approach ; Function to find the smallest prime factor of all the numbers in range [ 0 , MAX ] ; Stores smallest prime factor of all the numbers in the range [ 0 , MAX ] ; No smallest prime factor of 0 and 1 exists ; Traverse all the numbers in the range [ 1 , MAX ] ; Update spf [ i ] ; Update all the numbers whose smallest prime factor is 2 ; Traverse all the numbers in the range [ 1 , sqrt ( MAX ) ] ; Check if i is a prime number ; Update all the numbers whose smallest prime factor is i ; Check if j is a prime number ; Function to find count of prime factor of num ; Stores count of prime factor of num ; Calculate count of prime factor ; Update count ; Update num ; Function to precalculate the count of numbers in the range [ 0 , i ] whose count of prime factors is a prime number ; Stores the sum of all the numbers in the range [ 0 , i ] count of prime factor is a prime number ; Update sum [ 0 ] ; Traverse all the numbers in the range [ 1 , MAX ] ; Stores count of prime factor of i ; If count of prime factor is a prime number ; Update sum [ i ] ; Update sum [ i ] ; Driver Code ; Stores smallest prime factor of all the numbers in the range [ 0 , MAX ] ; Stores the sum of all the numbers in the range [ 0 , i ] count of prime factor is a prime number ; int N = sizeof ( Q ) / sizeof ( Q [ 0 ] ) ;
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1001 NEW_LINE vector < int > sieve ( ) { vector < int > spf ( MAX ) ; spf [ 0 ] = spf [ 1 ] = -1 ; for ( int i = 2 ; i < MAX ; i ++ ) { spf [ i ] = i ; } for ( int i = 4 ; i < MAX ; i = i + 2 ) { spf [ i ] = 2 ; } for ( int i = 3 ; i * i < MAX ; i ++ ) { if ( spf [ i ] == i ) { for ( int j = i * i ; j < MAX ; j = j + i ) { if ( spf [ j ] == j ) { spf [ j ] = i ; } } } } return spf ; } int countFactors ( vector < int > & spf , int num ) { int count = 0 ; while ( num > 1 ) { count ++ ; num = num / spf [ num ] ; } return count ; } vector < int > precalculateSum ( vector < int > & spf ) { vector < int > sum ( MAX ) ; sum [ 0 ] = 0 ; for ( int i = 1 ; i < MAX ; i ++ ) { int prime_factor = countFactors ( spf , i ) ; if ( spf [ prime_factor ] == prime_factor ) { sum [ i ] = sum [ i - 1 ] + 1 ; } else { sum [ i ] = sum [ i - 1 ] ; } } return sum ; } int main ( ) { vector < int > spf = sieve ( ) ; vector < int > sum = precalculateSum ( spf ) ; int Q [ ] [ 2 ] = { { 4 , 8 } , { 30 , 32 } } ; for ( int i = 0 ; i < 2 ; i ++ ) { cout << ( sum [ Q [ i ] [ 1 ] ] - sum [ Q [ i ] [ 0 ] - 1 ] ) << " ▁ " ; } return 0 ; }
Maximum number of Perfect Numbers present in a subarray of size K | C ++ program for the above approach ; Function to check a number is Perfect Number or not ; Stores sum of divisors ; Find all divisors and add them ; If sum of divisors is equal to N ; Function to return maximum sum of a subarray of size K ; If k is greater than N ; Compute sum of first window of size K ; Compute sums of remaining windows by removing first element of previous window and adding last element of current window ; return the answer ; Function to find all the perfect numbers in the array ; The given array is converted into binary array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int isPerfect ( int N ) { int sum = 1 ; for ( int i = 2 ; i < sqrt ( N ) ; i ++ ) { if ( N % i == 0 ) { if ( i == N / i ) { sum += i ; } else { sum += i + N / i ; } } } if ( sum == N && N != 1 ) return 1 ; return 0 ; } int maxSum ( int arr [ ] , int N , int K ) { if ( N < K ) { cout << " Invalid " ; return -1 ; } int res = 0 ; for ( int i = 0 ; i < K ; i ++ ) { res += arr [ i ] ; } int curr_sum = res ; for ( int i = K ; i < N ; i ++ ) { curr_sum += arr [ i ] - arr [ i - K ] ; res = max ( res , curr_sum ) ; } return res ; } int max_PerfectNumbers ( int arr [ ] , int N , int K ) { for ( int i = 0 ; i < N ; i ++ ) { arr [ i ] = isPerfect ( arr [ i ] ) ? 1 : 0 ; } return maxSum ( arr , N , K ) ; } int main ( ) { int arr [ ] = { 28 , 2 , 3 , 6 , 496 , 99 , 8128 , 24 } ; int K = 4 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << max_PerfectNumbers ( arr , N , K ) ; return 0 ; }
Count greater elements on the left side of every array element | C ++ program to implement the above approach ; Function to print the count of greater elements on left of each array element ; Function to get the count of greater elements on left of each array element ; Store distinct array elements in sorted order ; Stores the count of greater elements on the left side ; Traverse the array ; Insert array elements into the set ; Find previous greater element ; Find the distance between the previous greater element of arr [ i ] and last element of the set ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void display ( int countLeftGreater [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { cout << countLeftGreater [ i ] << " ▁ " ; } } void countGreater ( int arr [ ] , int N ) { set < int > St ; int countLeftGreater [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { St . insert ( arr [ i ] ) ; auto it = St . upper_bound ( arr [ i ] ) ; countLeftGreater [ i ] = distance ( it , St . end ( ) ) ; } display ( countLeftGreater , N ) ; } int main ( ) { int arr [ ] = { 12 , 1 , 2 , 3 , 0 , 11 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countGreater ( arr , N ) ; }
Count characters to be shifted from the start or end of a string to obtain another string | C ++ 14 program for the above approach ; Function to find the minimum cost to convert string A to string B ; Length of string ; Initialize maxlen as 0 ; Traverse the string A ; Stores the length of substrings of string A ; Traversing string B for each character of A ; Shift i pointer towards right and increment length , if A [ i ] equals B [ j ] ; If traverse till end ; Update maxlen ; Return minimum cost ; Driver Code ; Given two strings A and B ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minCost ( string A , string B ) { int n = A . size ( ) ; int i = 0 ; int maxlen = 0 ; while ( i < n ) { int length = 0 ; for ( int j = 0 ; j < n ; ++ j ) { if ( A [ i ] == B [ j ] ) { ++ i ; ++ length ; if ( i == n ) break ; } } maxlen = max ( maxlen , length ) ; } return n - maxlen ; } int main ( ) { string A = " edacb " ; string B = " abcde " ; cout << minCost ( A , B ) << endl ; }
Lexicographic rank of a string among all its substrings | C ++ program for the above approach ; Function to find lexicographic rank of string among all its substring ; Length of string ; Traverse the given string and store the indices of each character ; Extract the index ; Store it in the vector ; Traverse the alphaIndex array lesser than the index of first character of given string ; If alphaIndex [ i ] size exceeds 0 ; Traverse over the indices ; Add count of substring equal to n - alphaIndex [ i ] [ j ] ; Store all substrings in a vector str starting with the first character of the given string ; Insert the current character to substring ; Store the substring formed ; Sort the substring in the lexicographical order ; Find the rank of given string ; increase the rank until the given string is same ; If substring is same as the given string ; Add 1 to rank of the given string ; Driver Code ; Given string ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int lexicographicRank ( string s ) { int n = s . length ( ) ; vector < int > alphaIndex [ 26 ] ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int x = s [ i ] - ' a ' ; alphaIndex [ x ] . push_back ( i ) ; } int rank = 0 ; for ( int i = 0 ; i < 26 && ' a ' + i < s [ 0 ] ; i ++ ) { if ( alphaIndex [ i ] . size ( ) > 0 ) { for ( int j = 0 ; j < alphaIndex [ i ] . size ( ) ; j ++ ) { rank = rank + ( n - alphaIndex [ i ] [ j ] ) ; } } } vector < string > str ; for ( int i = 0 ; i < alphaIndex [ s [ 0 ] - ' a ' ] . size ( ) ; i ++ ) { string substring ; int j = alphaIndex [ s [ 0 ] - ' a ' ] [ i ] ; for ( ; j < n ; j ++ ) { substring . push_back ( s [ j ] ) ; str . push_back ( substring ) ; } } sort ( str . begin ( ) , str . end ( ) ) ; for ( int i = 0 ; i < str . size ( ) ; i ++ ) { if ( str [ i ] != s ) { rank ++ ; } else { break ; } } return rank + 1 ; } int main ( ) { string str = " enren " ; cout << lexicographicRank ( str ) ; return 0 ; }
Find H | C ++ implementation of the above approach ; Function to find the H - index ; Set the range for binary search ; Check if current citations is possible ; Check to the right of mid ; Update h - index ; Since current value is not possible , check to the left of mid ; Print the h - index ; Driver Code ; citations
#include <bits/stdc++.h> NEW_LINE using namespace std ; int hIndex ( vector < int > citations , int n ) { int hindex = 0 ; int low = 0 , high = n - 1 ; while ( low <= high ) { int mid = ( low + high ) / 2 ; if ( citations [ mid ] >= ( mid + 1 ) ) { low = mid + 1 ; hindex = mid + 1 ; } else { high = mid - 1 ; } } cout << hindex << endl ; return hindex ; } int main ( ) { int n = 5 ; vector < int > citations = { 5 , 3 , 3 , 2 , 2 } ; hIndex ( citations , n ) ; }