codeparrot/xlcost-text-to-code huggingface dataset:
Node having maximum number of nodes less than its value in its subtree | C ++ program for the above approach ; Stores the nodes to be deleted ; Structure of a Tree node ; Function to create a new node ; Function to compare the current node key with keys received from it left & right tree by Post Order traversal ; Base Case ; Find nodes lesser than the current root in the left subtree ; Find nodes lesser than the current root in the right subtree ; Stores all the nodes less than the current node 's ; Add the nodes which are less than current node in left [ ] ; Add the nodes which are less than current node in right [ ] ; Create a combined vector for pass to it 's parent ; Stores key that has maximum nodes ; Return the vector of nodes ; Driver Code ; Given Tree ; Function Call ; Print the node value
#include <bits/stdc++.h> NEW_LINE using namespace std ; unordered_map < int , bool > mp ; struct Node { int key ; struct Node * left , * right ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return ( temp ) ; } vector < int > findNodes ( Node * root , int & max_v , int & rootIndex ) { if ( ! root ) { return vector < int > { } ; } vector < int > left = findNodes ( root -> left , max_v , rootIndex ) ; vector < int > right = findNodes ( root -> right , max_v , rootIndex ) ; vector < int > combined ; int count = 0 ; for ( int i = 0 ; i < left . size ( ) ; i ++ ) { if ( left [ i ] < root -> key ) { count += 1 ; } combined . push_back ( left [ i ] ) ; } for ( int i = 0 ; i < right . size ( ) ; i ++ ) { if ( right [ i ] < root -> key ) { count += 1 ; } combined . push_back ( right [ i ] ) ; } combined . push_back ( root -> key ) ; if ( count > max_v ) { rootIndex = root -> key ; max_v = count ; } return combined ; } int main ( ) { Node * root = newNode ( 3 ) ; root -> left = newNode ( 4 ) ; root -> right = newNode ( 6 ) ; root -> right -> left = newNode ( 4 ) ; root -> right -> right = newNode ( 5 ) ; root -> left -> left = newNode ( 10 ) ; root -> left -> right = newNode ( 2 ) ; int max_v = 0 ; int rootIndex = -1 ; findNodes ( root , max_v , rootIndex ) ; cout << rootIndex ; }
Maximum sum path in a matrix from top | C ++ program for the above approach ; Function to find the maximum sum path in the grid ; Dimensions of grid [ ] [ ] ; Stores maximum sum at each cell sum [ i ] [ j ] from cell sum [ 0 ] [ 0 ] ; Iterate to compute the maximum sum path in the grid ; Update the maximum path sum ; Return the maximum sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MaximumPath ( vector < vector < int > > & grid ) { int N = grid . size ( ) ; int M = grid [ 0 ] . size ( ) ; vector < vector < int > > sum ; sum . resize ( N + 1 , vector < int > ( M + 1 ) ) ; for ( int i = 1 ; i <= N ; i ++ ) { for ( int j = 1 ; j <= M ; j ++ ) { sum [ i ] [ j ] = max ( sum [ i - 1 ] [ j ] , sum [ i ] [ j - 1 ] ) + grid [ i - 1 ] [ j - 1 ] ; } } return sum [ N ] [ M ] ; } int main ( ) { vector < vector < int > > grid = { { 1 , 2 } , { 3 , 5 } } ; cout << MaximumPath ( grid ) ; return 0 ; }
Maximize cost of deletions to obtain string having no pair of similar adjacent characters | C ++ program for the above approach ; Function to find maximum cost to remove consecutive characters ; Initialize the count ; Maximum cost ; Traverse from 0 to len ( s ) - 2 ; If characters are identical ; Add cost [ i ] if its maximum ; Add cost [ i + 1 ] if its maximum ; Increment i ; Return the final max count ; Driver Code ; Given string s ; Given cost of removal ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Maxcost ( string s , int cost [ ] ) { int count = 0 ; int maxcost = 0 , i = 0 ; while ( i < s . size ( ) - 1 ) { if ( s [ i ] == s [ i + 1 ] ) { if ( cost [ i ] > cost [ i + 1 ] ) maxcost += cost [ i ] ; else { maxcost += cost [ i + 1 ] ; cost [ i + 1 ] = cost [ i ] ; } } i += 1 ; } return maxcost ; } int main ( ) { string s = " abaac " ; int cost [ ] = { 1 , 2 , 3 , 4 , 5 } ; cout << Maxcost ( s , cost ) ; return 0 ; }
Maximum count of values of S modulo M lying in a range [ L , R ] after performing given operations on the array | C ++ program for the above approach ; Lookup table ; Function to count the value of S after adding arr [ i ] or arr [ i - 1 ] to the sum S at each time ; Base Case ; Store the mod value ; If the mod value lies in the range then return 1 ; Else return 0 ; Store the current state ; If already computed , return the computed value ; Recursively adding the elements to the sum adding ai value ; Adding arr [ i ] - 1 value ; Return the maximum count to check for root value as well ; Avoid counting idx = 0 as possible solution we are using idx != 0 ; Return the value of current state ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; map < pair < int , int > , int > dp ; int countMagicNumbers ( int idx , int sum , int a [ ] , int n , int m , int l , int r ) { if ( idx == n ) { int temp = sum % m ; if ( temp == l || temp == r || ( temp > l && temp < r ) ) return dp [ { idx , sum } ] = 1 ; else return dp [ { idx , sum } ] = 0 ; } pair < int , int > curr = make_pair ( idx , sum ) ; if ( dp . find ( curr ) != dp . end ( ) ) return dp [ curr ] ; int ls = countMagicNumbers ( idx + 1 , sum + a [ idx ] , a , n , m , l , r ) ; int rs = countMagicNumbers ( idx + 1 , sum + ( a [ idx ] - 1 ) , a , n , m , l , r ) ; int temp1 = max ( ls , rs ) ; int temp = sum % m ; if ( ( temp == l || temp == r || ( temp > l && temp < r ) ) && idx != 0 ) { temp1 += 1 ; } return dp [ { idx , sum } ] = temp1 ; } int main ( ) { int N = 5 , M = 22 , L = 14 , R = 16 ; int arr [ ] = { 17 , 11 , 10 , 8 , 15 } ; cout << countMagicNumbers ( 0 , 0 , arr , N , M , L , R ) ; return 0 ; }
Check if a path exists for a cell valued 1 to reach the bottom right corner of a Matrix before any cell valued 2 | C ++ program for the above approach ; Function to check if cell with value 1 doesn 't reaches the bottom right cell or not ; Number of rows and columns ; Initialise the deque ; Traverse the matrix ; Push 1 to front of queue ; Push 2 to back of queue ; Store all the possible direction of the current cell ; Run multi - source BFS ; Get the front element ; Pop the front element ; If 1 reached corner first ; Insert new point in queue ; If 1 can 't reach the bottom  right then return false ; Driver Code ; Given matrix ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool reachesBottom ( vector < vector < int > > & a ) { int n = a . size ( ) ; int m = a [ 0 ] . size ( ) ; deque < vector < int > > q ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( a [ i ] [ j ] == 1 ) { q . push_front ( { i , j , 1 } ) ; } else if ( a [ i ] [ j ] == 2 ) { q . push_back ( { i , j , 2 } ) ; } a [ i ] [ j ] = 0 ; } } int dx [ ] = { -1 , 0 , 1 , 0 } ; int dy [ ] = { 0 , 1 , 0 , -1 } ; while ( ! q . empty ( ) ) { auto front = q . front ( ) ; q . pop_front ( ) ; int i = front [ 0 ] , j = front [ 1 ] ; int t = front [ 2 ] ; if ( a [ i ] [ j ] ) continue ; a [ i ] [ j ] = 1 ; if ( t == 1 and ( i == n - 1 && j == m - 1 ) ) { return true ; } for ( int d = 0 ; d < 4 ; d ++ ) { int ni = i + dx [ d ] ; int nj = j + dy [ d ] ; if ( ni >= 0 and ni < n and nj > = 0 and nj < m ) { q . push_back ( { ni , nj , t } ) ; } } } return false ; } int main ( ) { vector < vector < int > > matrix { { 0 , 2 , 0 } , { 0 , 1 , 0 } , { 0 , 2 , 0 } } ; if ( reachesBottom ( matrix ) ) { cout << " YES " ; } else { cout << " NO " ; } return 0 ; }
Smallest element from all square submatrices of size K from a given Matrix | C ++ Program for the above approach ; Function to returns a smallest elements of all KxK submatrices of a given NxM matrix ; Stores the dimensions of the given matrix ; Stores the required smallest elements ; Update the smallest elements row - wise ; Update the minimum column - wise ; Store the final submatrix with required minimum values ; Return the resultant matrix ; Function Call ; Print resultant matrix with the minimum values of KxK sub - matrix ; Driver Code ; Given matrix ; Given K
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < vector < int > > matrixMinimum ( vector < vector < int > > nums , int K ) { int N = nums . size ( ) ; int M = nums [ 0 ] . size ( ) ; vector < vector < int > > res ( N - K + 1 , vector < int > ( M - K + 1 ) ) ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M - K + 1 ; j ++ ) { int mini = INT_MAX ; for ( int k = j ; k < j + K ; k ++ ) { mini = min ( mini , nums [ i ] [ k ] ) ; } nums [ i ] [ j ] = mini ; } } for ( int j = 0 ; j < M ; j ++ ) { for ( int i = 0 ; i < N - K + 1 ; i ++ ) { int mini = INT_MAX ; for ( int k = i ; k < i + K ; k ++ ) { mini = min ( mini , nums [ k ] [ j ] ) ; } nums [ i ] [ j ] = mini ; } } for ( int i = 0 ; i < N - K + 1 ; i ++ ) for ( int j = 0 ; j < M - K + 1 ; j ++ ) res [ i ] [ j ] = nums [ i ] [ j ] ; return res ; } void smallestinKsubmatrices ( vector < vector < int > > arr , int K ) { vector < vector < int > > res = matrixMinimum ( arr , K ) ; for ( int i = 0 ; i < res . size ( ) ; i ++ ) { for ( int j = 0 ; j < res [ 0 ] . size ( ) ; j ++ ) { cout << res [ i ] [ j ] << " ▁ " ; } cout << endl ; } } int main ( ) { vector < vector < int > > arr = { { -1 , 5 , 4 , 1 , -3 } , { 4 , 3 , 1 , 1 , 6 } , { 2 , -2 , 5 , 3 , 1 } , { 8 , 5 , 1 , 9 , -4 } , { 12 , 3 , 5 , 8 , 1 } } ; int K = 3 ; smallestinKsubmatrices ( arr , K ) ; }
Queries to find Kth greatest character in a range [ L , R ] from a string with updates | C ++ Program to implement the above approach ; Function to find the kth greatest character from the strijng ; Sorting the string in non - increasing Order ; Function to print the K - th character from the substring S [ l ] . . S [ r ] ; 0 - based indexing ; Substring of str from the indices l to r . ; Extract kth Largest character ; Function to replace character at pos of str by the character s ; Index of S to be updated . ; Character to be replaced at index in S ; Driver Code ; Given string ; Count of queries ; Queries
#include " bits / stdc + + . h " NEW_LINE using namespace std ; char find_kth_largest ( string str , int k ) { sort ( str . begin ( ) , str . end ( ) , greater < char > ( ) ) ; return str [ k - 1 ] ; } char printCharacter ( string str , int l , int r , int k ) { l = l - 1 ; r = r - 1 ; string temp = str . substr ( l , r - l + 1 ) ; char ans = find_kth_largest ( temp , k ) ; return ans ; } void updateString ( string str , int pos , char s ) { int index = pos - 1 ; char c = s ; str [ index ] = c ; } int main ( ) { string str = " abcddef " ; int Q = 3 ; cout << printCharacter ( str , 1 , 2 , 2 ) << endl ; updateString ( str , 4 , ' g ' ) ; cout << printCharacter ( str , 1 , 5 , 4 ) << endl ; return 0 ; }
Split array into two subarrays such that difference of their sum is minimum | C ++ program for above approach ; Function to return minimum difference between sum of two subarrays ; To store total sum of array ; Calculate the total sum of the array ; Stores the prefix sum ; Stores the minimum difference ; Traverse the given array ; To store minimum difference ; Update minDiff ; Return minDiff ; Driver code ; Given array ; Length of the array
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minDiffSubArray ( int arr [ ] , int n ) { int total_sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) total_sum += arr [ i ] ; int prefix_sum = 0 ; int minDiff = INT_MAX ; for ( int i = 0 ; i < n - 1 ; i ++ ) { prefix_sum += arr [ i ] ; int diff = abs ( ( total_sum - prefix_sum ) - prefix_sum ) ; if ( diff < minDiff ) minDiff = diff ; } return minDiff ; } int main ( ) { int arr [ ] = { 7 , 9 , 5 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minDiffSubArray ( arr , n ) << endl ; return 0 ; }
Maximize count of non | C ++ Program to implement the above approach ; Function to count the maximum number of subarrays with sum K ; Stores all the distinct prefixSums obtained ; Stores the prefix sum of the current subarray ; Stores the count of subarrays with sum K ; If a subarray with sum K is already found ; Increase count ; Reset prefix sum ; Clear the set ; Insert the prefix sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int CtSubarr ( int arr [ ] , int N , int K ) { unordered_set < int > st ; int prefixSum = 0 ; st . insert ( prefixSum ) ; int res = 0 ; for ( int i = 0 ; i < N ; i ++ ) { prefixSum += arr [ i ] ; if ( st . count ( prefixSum - K ) ) { res += 1 ; prefixSum = 0 ; st . clear ( ) ; st . insert ( 0 ) ; } st . insert ( prefixSum ) ; } return res ; } int main ( ) { int arr [ ] = { -2 , 6 , 6 , 3 , 5 , 4 , 1 , 2 , 8 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 10 ; cout << CtSubarr ( arr , N , K ) ; }
Count of subarrays consisting of only prime numbers | C ++ Program to implement the above approach ; Function to check if a number is prime or not . ; If n has any factor other than 1 , then n is non - prime . ; Function to return the count of subarrays made up of prime numbers only ; Stores the answer ; Stores the count of continuous prime numbers in an array ; If the current array element is prime ; Increase the count ; Update count of subarrays ; If the array ended with a continuous prime sequence ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool is_prime ( int n ) { if ( n <= 1 ) return 0 ; for ( int i = 2 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) return 0 ; } return 1 ; } int count_prime_subarrays ( int ar [ ] , int n ) { int ans = 0 ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( is_prime ( ar [ i ] ) ) count ++ ; else { if ( count ) { ans += count * ( count + 1 ) / 2 ; count = 0 ; } } } if ( count ) ans += count * ( count + 1 ) / 2 ; return ans ; } int main ( ) { int N = 10 ; int ar [ ] = { 2 , 3 , 5 , 6 , 7 , 11 , 3 , 5 , 9 , 3 } ; cout << count_prime_subarrays ( ar , N ) ; }
Minimum Subarray flips required to convert all elements of a Binary Array to K | C ++ 14 Program to implement the above approach ; Function to count the minimum number of subarray flips required ; Iterate the array ; If arr [ i ] and flag are equal ; Return the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minSteps ( int arr [ ] , int n , int k ) { int i , cnt = 0 ; int flag ; if ( k == 1 ) flag = 0 ; else flag = 1 ; for ( i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == flag ) { cnt ++ ; flag = ( flag + 1 ) % 2 ; } } return cnt ; } int main ( ) { int arr [ ] = { 1 , 0 , 1 , 0 , 0 , 1 , 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 1 ; cout << minSteps ( arr , n , k ) ; return 0 ; }
Minimize Sum of an Array by at most K reductions | C ++ program to implement the above approach ; Function to obtain the minimum possible sum from the array by K reductions ; Implements the MaxHeap ; Insert elements into the MaxHeap ; Remove the maximum ; Insert maximum / 2 ; Stores the sum of remaining elements ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minSum ( int a [ ] , int n , int k ) { priority_queue < int > q ; for ( int i = 0 ; i < n ; i ++ ) { q . push ( a [ i ] ) ; } while ( ! q . empty ( ) && k > 0 ) { int top = q . top ( ) / 2 ; q . pop ( ) ; q . push ( top ) ; k -= 1 ; } int sum = 0 ; while ( ! q . empty ( ) ) { sum += q . top ( ) ; q . pop ( ) ; } return sum ; } int main ( ) { int n = 4 ; int k = 3 ; int a [ ] = { 20 , 7 , 5 , 4 } ; cout << ( minSum ( a , n , k ) ) ; return 0 ; }
Sum of indices of Characters removed to obtain an Empty String based on given conditions | C ++ Program to implement the above approach ; Function to add index of the deleted character ; If index is beyond the range ; Insert the index of the deleted characeter ; Search over the subtrees to find the desired index ; Function to return count of deleted indices which are to the left of the current index ; Function to generate the sum of indices ; Stores the original index of the characters in sorted order of key ; Traverse the map ; Extract smallest index of smallest character ; Delete the character from the map if it has no remaining occurrence ; Stores the original index ; Count of elements removed to the left of current character ; Current index of the current character ; For 1 - based indexing ; Insert the deleted index in the segment tree ; Final answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void add_seg ( int seg [ ] , int start , int end , int current , int index ) { if ( index > end or index < start ) return ; if ( start == end ) { seg [ current ] = 1 ; return ; } int mid = ( start + end ) / 2 ; add_seg ( seg , start , mid , 2 * current + 1 , index ) ; add_seg ( seg , mid + 1 , end , 2 * current + 2 , index ) ; seg [ current ] = seg [ 2 * current + 1 ] + seg [ 2 * current + 2 ] ; } int deleted ( int seg [ ] , int l , int r , int start , int end , int current ) { if ( end < l or start > r ) return 0 ; if ( start >= l and end <= r ) return seg [ current ] ; int mid = ( start + end ) / 2 ; return deleted ( seg , l , r , start , mid , 2 * current + 1 ) + deleted ( seg , l , r , mid + 1 , end , 2 * current + 2 ) ; } void sumOfIndices ( string s ) { int N = s . size ( ) ; int x = int ( ceil ( log2 ( N ) ) ) ; int seg_size = 2 * ( int ) pow ( 2 , x ) - 1 ; int segment [ seg_size ] = { 0 } ; int count = 0 ; map < int , queue < int > > fre ; for ( int i = 0 ; i < N ; i ++ ) { fre [ s [ i ] ] . push ( i ) ; } while ( fre . empty ( ) == false ) { auto it = fre . begin ( ) ; if ( it -> second . empty ( ) == true ) fre . erase ( it -> first ) ; else { int original_index = it -> second . front ( ) ; int curr_index = deleted ( segment , 0 , original_index - 1 , 0 , N - 1 , 0 ) ; int new_index = original_index - curr_index ; count += new_index + 1 ; add_seg ( segment , 0 , N - 1 , 0 , original_index ) ; it -> second . pop ( ) ; } } cout << count << endl ; } int main ( ) { string s = " geeksforgeeks " ; sumOfIndices ( s ) ; }
Maximum Length of Sequence of Sums of prime factors generated by the given operations | C ++ Program to implement the above approach ; Smallest prime factor array ; Stores if a number is prime or not ; Function to compute all primes using Sieve of Eratosthenes ; Function for finding smallest prime factors for every integer ; Function to find the sum of prime factors of number ; Add smallest prime factor to the sum ; Reduce N ; Return the answer ; Function to return the length of sequence of for the given number ; If the number is prime ; If a previously computed subproblem occurred ; Calculate the sum of prime factors ; Function to return the maximum length of sequence for the given range ; Pre - calculate primes ; Precalculate smallest prime factors ; Iterate over the range ; Update maximum length ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int spf [ 100005 ] ; bool prime [ 100005 ] ; int dp [ 100005 ] ; void sieve ( ) { prime [ 0 ] = prime [ 1 ] = false ; for ( int i = 2 ; i < 100005 ; i ++ ) prime [ i ] = true ; for ( int i = 2 ; i * i < 100005 ; i ++ ) { if ( prime [ i ] ) { for ( int j = i * i ; j < 100005 ; j += i ) { prime [ j ] = false ; } } } } void smallestPrimeFactors ( ) { for ( int i = 0 ; i < 100005 ; i ++ ) spf [ i ] = -1 ; for ( int i = 2 ; i * i < 100005 ; i ++ ) { for ( int j = i ; j < 100005 ; j += i ) { if ( spf [ j ] == -1 ) { spf [ j ] = i ; } } } } int sumOfPrimeFactors ( int n ) { int ans = 0 ; while ( n > 1 ) { ans += spf [ n ] ; n /= spf [ n ] ; } return ans ; } int findLength ( int n ) { if ( prime [ n ] ) { return 1 ; } if ( dp [ n ] ) { return dp [ n ] ; } int sum = sumOfPrimeFactors ( n ) ; return dp [ n ] = 1 + findLength ( sum ) ; } int maxLength ( int n , int m ) { sieve ( ) ; smallestPrimeFactors ( ) ; int ans = INT_MIN ; for ( int i = n ; i <= m ; i ++ ) { if ( i == 4 ) { continue ; } ans = max ( ans , findLength ( i ) ) ; } return ans ; } int main ( ) { int n = 2 , m = 14 ; cout << maxLength ( n , m ) ; }
Longest Subarray consisting of unique elements from an Array | C ++ program to implement the above approach ; Function to find largest subarray with no duplicates ; Stores index of array elements ; Update j based on previous occurrence of a [ i ] ; Update ans to store maximum length of subarray ; Store the index of current occurrence of a [ i ] ; Return final ans ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int largest_subarray ( int a [ ] , int n ) { unordered_map < int , int > index ; int ans = 0 ; for ( int i = 0 , j = 0 ; i < n ; i ++ ) { j = max ( index [ a [ i ] ] , j ) ; ans = max ( ans , i - j + 1 ) ; index [ a [ i ] ] = i + 1 ; } return ans ; } int32_t main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 1 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << largest_subarray ( arr , n ) ; }
Count of Ways to obtain given Sum from the given Array elements | C ++ program to implement the above approach ; Function to count the number of ways ; Base Case : Reached the end of the array ; Sum is equal to the required sum ; Recursively check if required sum can be obtained by adding current element or by subtracting the current index element ; Function to call dfs ( ) to calculate the number of ways ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dfs ( int nums [ ] , int S , int curr_sum , int index , int n ) { if ( index == n ) { if ( S == curr_sum ) return 1 ; else return 0 ; } return dfs ( nums , S , curr_sum + nums [ index ] , index + 1 , n ) + dfs ( nums , S , curr_sum - nums [ index ] , index + 1 , n ) ; } int findWays ( int nums [ ] , int S , int n ) { return dfs ( nums , S , 0 , 0 , n ) ; } int main ( ) { int S = 3 ; int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int answer = findWays ( arr , S , n ) ; cout << ( answer ) ; return 0 ; }
Check if all the Nodes in a Binary Tree having common values are at least D distance apart | C ++ program to implement the above approach ; Structure of a Tree node ; Function to create a new node ; Function to count the frequency of node value present in the tree ; Function that returns the max distance between the nodes that have the same key ; If right and left subtree did not have node whose key is value ; Check if the current node is equal to value ; If the left subtree has no node whose key is equal to value ; If the right subtree has no node whose key is equal to value ; Function that finds if the distance between any same nodes is at most K ; Create the map to look for same value of nodes ; Counting the frequency of nodes ; If the returned value of distance is exceeds dist ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * left , * right ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return ( temp ) ; } void frequencyCounts ( unordered_map < int , int > & map , Node * root ) { if ( root == NULL ) return ; map [ root -> key ] ++ ; frequencyCounts ( map , root -> left ) ; frequencyCounts ( map , root -> right ) ; } int computeDistance ( Node * root , int value ) { if ( root == NULL ) { return -1 ; } int left = computeDistance ( root -> left , value ) ; int right = computeDistance ( root -> right , value ) ; if ( left == -1 && right == -1 ) { if ( root -> key == value ) { return 1 ; } else return -1 ; } if ( left == -1 ) { return right + 1 ; } if ( right == -1 ) { return left + 1 ; } else { return 1 + max ( left , right ) ; } return -1 ; } void solve ( Node * root , int dist ) { unordered_map < int , int > map ; frequencyCounts ( map , root ) ; int flag = 0 ; for ( auto it = map . begin ( ) ; it != map . end ( ) ; it ++ ) { if ( it -> second > 1 ) { int result = computeDistance ( root , it -> first ) ; if ( result > dist result == -1 ) { flag = 1 ; break ; } } } flag == 0 ? cout << " Yes STRNEWLINE " : cout << " No STRNEWLINE " ; } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 3 ) ; root -> right -> right = newNode ( 4 ) ; root -> right -> left = newNode ( 4 ) ; int dist = 7 ; solve ( root , dist ) ; return 0 ; }