text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Search insert position of K in a sorted array | C ++ program for the above approach ; Function to find insert position of K ; Lower and upper bounds ; Traverse the search space ; If K is found ; Return insert position ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find_index ( int arr [ ] , int n , int K ) { int start = 0 ; int end = n - 1 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; if ( arr [ mid ] == K ) return mid ; else if ( arr [ mid ] < K ) start = mid + 1 ; else end = mid - 1 ; } return end + 1 ; } int main ( ) { int arr [ ] = { 1 , 3 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 2 ; cout << find_index ( arr , n , K ) << endl ; return 0 ; }
Queries to find minimum swaps required to sort given array with updates | C ++ program for the above approach ; Function to return the position of the given value using binary search ; Return 0 if every value is greater than the given value ; Return N - 1 if every value is smaller than the given value ; Perform Binary Search ; Iterate till start < end ; Find the mid ; Update start and end ; Return the position of the given value ; Function to return the number of make the array sorted ; Index x to update ; Increment value by y ; Set newElement equals to x + y ; Compute the new index ; Print the minimum number of swaps ; Driver Code ; Given array arr [ ] ; Given Queries ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int computePos ( int arr [ ] , int n , int value ) { if ( value < arr [ 0 ] ) return 0 ; if ( value > arr [ n - 1 ] ) return n - 1 ; int start = 0 ; int end = n - 1 ; while ( start < end ) { int mid = ( start + end + 1 ) / 2 ; if ( arr [ mid ] >= value ) end = mid - 1 ; else start = mid ; } return start ; } void countShift ( int arr [ ] , int n , vector < vector < int > > & queries ) { for ( auto q : queries ) { int index = q [ 0 ] ; int update = q [ 1 ] ; int newElement = arr [ index ] + update ; int newIndex = computePos ( arr , n , newElement ) ; cout << abs ( newIndex - index ) << " ▁ " ; } } int main ( ) { int arr [ ] = { 2 , 3 , 4 , 5 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; vector < vector < int > > queries = { { 0 , -1 } , { 4 , -11 } } ; countShift ( arr , N , queries ) ; return 0 ; }
Count nodes having smallest value in the path from root to itself in a Binary Tree | C ++ program for the above approach ; Structure of a tree node ; Function to create new tree node ; Function to find the total number of required nodes ; If current node is null then return to the parent node ; Check if current node value is less than or equal to minNodeVal ; Update the value of minNodeVal ; Update the count ; Go to the left subtree ; Go to the right subtree ; Driver Code ; Binary Tree creation 8 / \ / \ 6 5 / \ / \ / \ / \ 6 7 3 9 ; Function Call ; Print the result
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; Node * left , * right ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return temp ; } void countReqNodes ( Node * root , int minNodeVal , int & ans ) { if ( root == NULL ) return ; if ( root -> key <= minNodeVal ) { minNodeVal = root -> key ; ans ++ ; } countReqNodes ( root -> left , minNodeVal , ans ) ; countReqNodes ( root -> right , minNodeVal , ans ) ; } int main ( ) { Node * root = newNode ( 8 ) ; root -> left = newNode ( 6 ) ; root -> right = newNode ( 5 ) ; root -> left -> left = newNode ( 6 ) ; root -> left -> right = newNode ( 7 ) ; root -> right -> left = newNode ( 3 ) ; root -> right -> right = newNode ( 9 ) ; int ans = 0 , minNodeVal = INT_MAX ; countReqNodes ( root , minNodeVal , ans ) ; cout << ans ; return 0 ; }
Check if a palindromic string can be obtained by concatenating substrings split from same indices of two given strings | C ++ Program to implement the above approach ; Function to check if a string is palindrome or not ; Start and end of the string ; Iterate the string until i > j ; If there is a mismatch ; Increment first pointer and decrement the other ; Given string is a palindrome ; Function two check if the strings can be combined to form a palindrome ; Initialize array of characters ; Stores character of string in the character array ; Find left and right parts of strings a and b ; Substring a [ j ... i - 1 ] ; Substring b [ j ... i - 1 ] ; Substring a [ i ... n ] ; Substring b [ i ... n ] ; Check is left part of a + right part of b or vice versa is a palindrome ; Print the result ; Otherwise ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( string str ) { int i = 0 , j = str . size ( ) - 1 ; while ( i < j ) { if ( str [ i ] != str [ j ] ) return false ; i ++ ; j -- ; } return true ; } void formPalindrome ( string a , string b , int n ) { char aa [ n + 2 ] ; char bb [ n + 2 ] ; for ( int i = 0 ; i < n + 2 ; i ++ ) { aa [ i ] = ' ▁ ' ; bb [ i ] = ' ▁ ' ; } for ( int i = 1 ; i <= n ; i ++ ) { aa [ i ] = a [ i - 1 ] ; bb [ i ] = b [ i - 1 ] ; } bool ok = false ; for ( int i = 0 ; i <= n + 1 ; i ++ ) { string la = " " ; string ra = " " ; string lb = " " ; string rb = " " ; for ( int j = 1 ; j <= i - 1 ; j ++ ) { if ( aa [ j ] == ' ▁ ' ) la += " " ; else la += aa [ j ] ; if ( bb [ j ] == ' ▁ ' ) lb += " " ; else lb += bb [ j ] ; } for ( int j = i ; j <= n + 1 ; j ++ ) { if ( aa [ j ] == ' ▁ ' ) ra += " " ; else ra += aa [ j ] ; if ( bb [ j ] == ' ▁ ' ) rb += " " ; else rb += bb [ j ] ; } if ( isPalindrome ( la + rb ) || isPalindrome ( lb + ra ) ) { ok = true ; break ; } } if ( ok ) cout << ( " Yes " ) ; else cout << ( " No " ) ; } int main ( ) { string A = " bdea " ; string B = " abbb " ; int N = 4 ; formPalindrome ( A , B , N ) ; }
Minimize elements to be added to a given array such that it contains another given array as its subsequence | Set 2 | C ++ program for the above approach ; Function to return minimum element to be added in array B so that array A become subsequence of array B ; Stores indices of the array elements ; Iterate over the array ; Store the indices of the array elements ; Stores the LIS ; Check if element B [ i ] is in array A [ ] ; Perform Binary Search ; Find the value of mid m ; Update l and r ; If found better element ' e ' for pos r + 1 ; Otherwise , extend the current subsequence ; Return the answer ; Driver code ; Given arrays ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minElements ( int A [ ] , int B [ ] , int N , int M ) { map < int , int > map ; for ( int i = 0 ; i < N ; i ++ ) { map [ A [ i ] ] = i ; } vector < int > subseq ; int l = 0 , r = -1 ; for ( int i = 0 ; i < M ; i ++ ) { if ( map . find ( B [ i ] ) != map . end ( ) ) { int e = map [ B [ i ] ] ; while ( l <= r ) { int m = l + ( r - l ) / 2 ; if ( subseq [ m ] < e ) l = m + 1 ; else r = m - 1 ; } if ( r + 1 < subseq . size ( ) ) { subseq [ r + 1 ] = e ; } else { subseq . push_back ( e ) ; } l = 0 ; r = subseq . size ( ) - 1 ; } } return N - subseq . size ( ) ; } int main ( ) { int A [ ] = { 1 , 2 , 3 , 4 , 5 } ; int B [ ] = { 2 , 5 , 6 , 4 , 9 , 12 } ; int M = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int N = sizeof ( B ) / sizeof ( B [ 0 ] ) ; cout << minElements ( A , B , M , N ) ; return 0 ; }
Detect a negative cycle in a Graph using Shortest Path Faster Algorithm | C ++ program for the above approach ; Stores the adjacency list of the given graph ; Create Adjacency List ; Stores the distance of all reachable vertex from source ; Check if vertex is present in queue or not ; Counts the relaxation for each vertex ; Distance from src to src is 0 ; Create a queue ; Push source in the queue ; Mark source as visited ; Front vertex of Queue ; Relaxing all edges of vertex from the Queue ; Update the dist [ v ] to minimum distance ; If vertex v is in Queue ; Negative cycle ; No cycle found ; Driver Code ; Number of vertices ; Given source node src ; Number of Edges ; Given Edges with weight ; If cycle is present
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool sfpa ( int V , int src , int Edges [ ] [ 3 ] , int M ) { vector < pair < int , int > > g [ V ] ; for ( int i = 0 ; i < M ; i ++ ) { int u = Edges [ i ] [ 0 ] ; int v = Edges [ i ] [ 1 ] ; int w = Edges [ i ] [ 2 ] ; g [ u ] . push_back ( { v , w } ) ; } vector < int > dist ( V , INT_MAX ) ; vector < bool > inQueue ( V , false ) ; vector < int > cnt ( V , 0 ) ; dist [ src ] = 0 ; queue < int > q ; q . push ( src ) ; inQueue [ src ] = true ; while ( ! q . empty ( ) ) { int u = q . front ( ) ; q . pop ( ) ; inQueue [ u ] = false ; for ( pair < int , int > x : g [ u ] ) { int v = x . first ; int cost = x . second ; if ( dist [ v ] > dist [ u ] + cost ) { dist [ v ] = dist [ u ] + cost ; if ( ! inQueue [ v ] ) { q . push ( v ) ; inQueue [ v ] = true ; cnt [ v ] ++ ; if ( cnt [ v ] >= V ) return true ; } } } } return false ; } int main ( ) { int N = 4 ; int src = 0 ; int M = 4 ; int Edges [ ] [ 3 ] = { { 0 , 1 , 1 } , { 1 , 2 , -1 } , { 2 , 3 , -1 } , { 3 , 0 , -1 } } ; if ( sfpa ( N , src , Edges , M ) == true ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; }
Sum of all pair shortest paths in a Tree | C ++ program for the above approach ; Function that performs the Floyd Warshall to find all shortest paths ; Initialize the distance matrix ; Pick all vertices as source one by one ; Pick all vertices as destination for the above picked source ; If vertex k is on the shortest path from i to j then update dist [ i ] [ j ] ; Sum the upper diagonal of the shortest distance matrix ; Traverse the given dist [ ] [ ] ; Add the distance ; Return the final sum ; Function to generate the tree ; Add edges ; Get source and destination with weight ; Add the edges ; Perform Floyd Warshal Algorithm ; Driver code ; Number of Vertices ; Number of Edges ; Given Edges with weight ; Function Call
#include <iostream> NEW_LINE using namespace std ; #define INF 99999 NEW_LINE int floyd_warshall ( int * graph , int V ) { int dist [ V ] [ V ] , i , j , k ; for ( i = 0 ; i < V ; i ++ ) { for ( j = 0 ; j < V ; j ++ ) { dist [ i ] [ j ] = * ( ( graph + i * V ) + j ) ; } } for ( k = 0 ; k < V ; k ++ ) { for ( i = 0 ; i < V ; i ++ ) { for ( j = 0 ; j < V ; j ++ ) { if ( dist [ i ] [ k ] + dist [ k ] [ j ] < dist [ i ] [ j ] ) { dist [ i ] [ j ] = dist [ i ] [ k ] + dist [ k ] [ j ] ; } } } } int sum = 0 ; for ( i = 0 ; i < V ; i ++ ) { for ( j = i + 1 ; j < V ; j ++ ) { sum += dist [ i ] [ j ] ; } } return sum ; } int sumOfshortestPath ( int N , int E , int edges [ ] [ 3 ] ) { int g [ N ] [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { g [ i ] [ j ] = INF ; } } for ( int i = 0 ; i < E ; i ++ ) { int u = edges [ i ] [ 0 ] ; int v = edges [ i ] [ 1 ] ; int w = edges [ i ] [ 2 ] ; g [ u ] [ v ] = w ; g [ v ] [ u ] = w ; } return floyd_warshall ( ( int * ) g , N ) ; } int main ( ) { int N = 4 ; int E = 3 ; int Edges [ ] [ 3 ] = { { 0 , 1 , 1 } , { 1 , 2 , 2 } , { 2 , 3 , 3 } } ; cout << sumOfshortestPath ( N , E , Edges ) ; return 0 ; }
Kth space | C ++ Program for the above approach ; Function to print kth integer in a given string ; Size of the string ; Pointer for iteration ; If space char found decrement K ; If K becomes 1 , the next string is the required one ; Print the required number ; Driver Code ; Given string ; Given K ; Function call
#include <iostream> NEW_LINE using namespace std ; void print_kth_string ( string s , int K ) { int N = s . length ( ) ; int i ; for ( i = 0 ; i < N ; i ++ ) { if ( s [ i ] == ' ▁ ' ) K -- ; if ( K == 1 ) break ; } while ( i ++ < N && s [ i ] != ' ▁ ' ) cout << s [ i ] ; } int main ( ) { string s ( "10 ▁ 20 ▁ 30 ▁ 40" ) ; int K = 4 ; print_kth_string ( s , K ) ; }
Minimum peak elements from an array by their repeated removal at every iteration of the array | C ++ program for the above approach ; Function to return the list of minimum peak elements ; Length of original list ; Initialize resultant list ; Traverse each element of list ; Length of original list after removing the peak element ; Traverse new list after removal of previous min peak element ; Update min and index , if first element of list > next element ; Update min and index , if last element of list > previous one ; Update min and index , if list has single element ; Update min and index , if current element > adjacent elements ; Remove current min peak element from list ; Insert min peak into resultant list ; Print resultant list ; Driver Code ; Given array arr [ ] ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minPeaks ( vector < int > list ) { int n = list . size ( ) ; vector < int > result ; for ( int i = 0 ; i < n ; i ++ ) { int min = INT_MAX ; int index = -1 ; int size = list . size ( ) ; for ( int j = 0 ; j < size ; j ++ ) { if ( j == 0 && j + 1 < size ) { if ( list [ j ] > list [ j + 1 ] && min > list [ j ] ) { min = list [ j ] ; index = j ; } } else if ( j == size - 1 && j - 1 >= 0 ) { if ( list [ j ] > list [ j - 1 ] && min > list [ j ] ) { min = list [ j ] ; index = j ; } } else if ( size == 1 ) { min = list [ j ] ; index = j ; } else if ( list [ j ] > list [ j - 1 ] && list [ j ] > list [ j + 1 ] && min > list [ j ] ) { min = list [ j ] ; index = j ; } } list . erase ( list . begin ( ) + index ) ; result . push_back ( min ) ; } cout << " [ " ; for ( int i = 0 ; i < result . size ( ) ; i ++ ) { cout << result [ i ] << " , ▁ " ; } cout << " ] " ; } int main ( ) { vector < int > arr = { 1 , 9 , 7 , 8 , 2 , 6 } ; minPeaks ( arr ) ; }
Search an element in a reverse sorted array | C ++ program to implement the above approach ; Function to search if element X is present in reverse sorted array ; Store the first index of the subarray in which X lies ; Store the last index of the subarray in which X lies ; Store the middle index of the subarray ; Check if value at middle index of the subarray equal to X ; Element is found ; If X is smaller than the value at middle index of the subarray ; Search in right half of subarray ; Search in left half of subarray ; If X not found ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int binarySearch ( int arr [ ] , int N , int X ) { int start = 0 ; int end = N ; while ( start <= end ) { int mid = start + ( end - start ) / 2 ; if ( X == arr [ mid ] ) { return mid ; } else if ( X < arr [ mid ] ) { start = mid + 1 ; } else { end = mid - 1 ; } } return -1 ; } int main ( ) { int arr [ ] = { 5 , 4 , 3 , 2 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int X = 5 ; cout << binarySearch ( arr , N , X ) ; return 0 ; }
Construct an AP series consisting of A and B having minimum possible Nth term | C ++ program for the above approach ; Function to check if both a and b are present in the AP series or not ; Iterate over the array arr [ ] ; If a is present ; If b is present ; If both are present ; Otherwise ; Function to print all the elements of the Arithmetic Progression ; Function to construct AP series consisting of A and B with minimum Nth term ; Stores the resultant series ; Initialise ans [ i ] as INT_MAX ; Maintain a smaller than b ; swap ( a and b ) ; Difference between a and b ; Check for all possible combination of start and common difference d ; Initialise arr [ 0 ] as start ; Check if both a and b are present or not and the Nth term is the minimum or not ; Update the answer ; Print the resultant array ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check_both_present ( int arr [ ] , int N , int a , int b ) { bool f1 = false , f2 = false ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == a ) { f1 = true ; } if ( arr [ i ] == b ) { f2 = true ; } } if ( f1 && f2 ) { return true ; } else { return false ; } } void print_array ( int ans [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { cout << ans [ i ] << " ▁ " ; } } void build_AP ( int N , int a , int b ) { int arr [ N ] , ans [ N ] ; for ( int i = 0 ; i < N ; i ++ ) ans [ i ] = INT_MAX ; int flag = 0 ; if ( a > b ) { swap ( a , b ) ; } int diff = b - a ; for ( int start = 1 ; start <= a ; start ++ ) { for ( int d = 1 ; d <= diff ; d ++ ) { arr [ 0 ] = start ; for ( int i = 1 ; i < N ; i ++ ) { arr [ i ] = arr [ i - 1 ] + d ; } if ( check_both_present ( arr , N , a , b ) && arr [ N - 1 ] < ans [ N - 1 ] ) { for ( int i = 0 ; i < N ; i ++ ) { ans [ i ] = arr [ i ] ; } } } } print_array ( ans , N ) ; } int main ( ) { int N = 5 , A = 20 , B = 50 ; build_AP ( N , A , B ) ; return 0 ; }
Find the word from a given sentence having given word as prefix | C ++ program for the above approach ; Function to find the position of the string having word as prefix ; Initialize a vector ; Extract words from the sentence ; Traverse each word ; Traverse the characters of word ; If prefix does not match ; Otherwise ; Return the word ; Return - 1 if not present ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string isPrefixOfWord ( string sentence , string Word ) { stringstream ss ( sentence ) ; vector < string > v ; string temp ; while ( ss >> temp ) { v . push_back ( temp ) ; } for ( int i = 0 ; i < v . size ( ) ; i ++ ) { for ( int j = 0 ; j < v [ i ] . size ( ) ; j ++ ) { if ( v [ i ] [ j ] != Word [ j ] ) break ; else if ( j == Word . size ( ) - 1 ) return v [ i ] ; } } return " - 1" ; } int main ( ) { string s = " Welcome ▁ to ▁ Geeksforgeeks " ; string word = " Gee " ; cout << isPrefixOfWord ( s , word ) << endl ; return 0 ; }
Paths requiring minimum number of jumps to reach end of array | C ++ program to implement the above approach ; Pair Struct ; Stores the current index ; Stores the path travelled so far ; Stores the minimum jumps required to reach the last index from current index ; Minimum jumps required to reach end of the array ; Stores the maximum number of steps that can be taken from the current index ; Checking if index stays within bounds ; Stores the minimum number of jumps required to jump from ( i + j ) - th index ; Function to find all possible paths to reach end of array requiring minimum number of steps ; Storing the neighbours of current index element ; Function to find the minimum steps and corresponding paths to reach end of an array ; dp [ ] array stores the minimum jumps from each position to last position ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Pair { int idx ; string psf ; int jmps ; } ; void minJumps ( int arr [ ] , int dp [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) dp [ i ] = INT_MAX ; dp [ n - 1 ] = 0 ; for ( int i = n - 2 ; i >= 0 ; i -- ) { int steps = arr [ i ] ; int min = INT_MAX ; for ( int j = 1 ; j <= steps && i + j < n ; j ++ ) { if ( dp [ i + j ] != INT_MAX && dp [ i + j ] < min ) { min = dp [ i + j ] ; } } if ( min != INT_MAX ) dp [ i ] = min + 1 ; } } void possiblePath ( int arr [ ] , int dp [ ] , int n ) { queue < Pair > Queue ; Pair p1 = { 0 , "0" , dp [ 0 ] } ; Queue . push ( p1 ) ; while ( Queue . size ( ) > 0 ) { Pair tmp = Queue . front ( ) ; Queue . pop ( ) ; if ( tmp . jmps == 0 ) { cout << tmp . psf << " STRNEWLINE " ; continue ; } for ( int step = 1 ; step <= arr [ tmp . idx ] ; step ++ ) { if ( tmp . idx + step < n && tmp . jmps - 1 == dp [ tmp . idx + step ] ) { string s1 = tmp . psf + " ▁ - > ▁ " + to_string ( ( tmp . idx + step ) ) ; Pair p2 = { tmp . idx + step , s1 , tmp . jmps - 1 } ; Queue . push ( p2 ) ; } } } } void Solution ( int arr [ ] , int dp [ ] , int size ) { minJumps ( arr , dp , size ) ; possiblePath ( arr , dp , size ) ; } int main ( ) { int arr [ ] = { 3 , 3 , 0 , 2 , 1 , 2 , 4 , 2 , 0 , 0 } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int dp [ size ] ; Solution ( arr , dp , size ) ; }
Length of longest increasing absolute even subsequence | C ++ 14 program for the above approach ; Function to find the longest increasing absolute even subsequence ; Stores length of required subsequence ; Traverse the array ; Traverse prefix of current array element ; Check if the subsequence is LIS and have even absolute difference of adjacent pairs ; Update lis [ ] ; Stores maximum length ; Find the length of longest absolute even subsequence ; Return the maximum length of absolute even subsequence ; Driver code ; Given array arr [ ] and brr [ ] ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void EvenLIS ( int arr [ ] , int n ) { int lis [ n ] ; for ( int i = 0 ; i < n ; i ++ ) lis [ i ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { if ( abs ( arr [ i ] ) > abs ( arr [ j ] ) && abs ( arr [ i ] ) % 2 == 0 && abs ( arr [ j ] ) % 2 == 0 && lis [ i ] < lis [ j ] + 1 ) lis [ i ] = lis [ j ] + 1 ; } } int maxlen = 0 ; for ( int i = 0 ; i < n ; i ++ ) maxlen = max ( maxlen , lis [ i ] ) ; cout << maxlen << endl ; } int main ( ) { int arr [ ] = { 11 , -22 , 43 , -54 , 66 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; EvenLIS ( arr , N ) ; }
Count balanced nodes present in a binary tree | C ++ program to implement the above approach ; Structure of a Tree Node ; Function to get the sum of left subtree and right subtree ; Base case ; Store the sum of left subtree ; Store the sum of right subtree ; Check if node is balanced or not ; Increase count of balanced nodes ; Return subtree sum ; Driver Code ; Insert nodes in tree ; Store the count of balanced nodes
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left ; Node * right ; Node ( int val ) { data = val ; left = right = NULL ; } } ; int Sum ( Node * root , int & res ) { if ( root == NULL ) { return 0 ; } int leftSubSum = Sum ( root -> left , res ) ; int rightSubSum = Sum ( root -> right , res ) ; if ( root -> left and root -> right && leftSubSum == rightSubSum ) res += 1 ; return root -> data + leftSubSum + rightSubSum ; } int main ( ) { Node * root = new Node ( 9 ) ; root -> left = new Node ( 2 ) ; root -> left -> left = new Node ( -1 ) ; root -> left -> right = new Node ( 3 ) ; root -> right = new Node ( 4 ) ; root -> right -> right = new Node ( 0 ) ; int res = 0 ; Sum ( root , res ) ; cout << res ; }
Print alternate nodes from all levels of a Binary Tree | C ++ program to implement the above approach ; Structure of a Node ; Print alternate nodes of a binary tree ; Store nodes of each level ; Store count of nodes of current level ; Print alternate nodes of the current level ; If left child exists ; Store left child ; If right child exists ; Store right child ; Driver Code ; Create a tree
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left ; Node * right ; Node ( int val ) { data = val ; left = right = NULL ; } } ; void PrintAlternate ( Node * root ) { queue < Node * > Q ; Q . push ( root ) ; while ( ! Q . empty ( ) ) { int N = Q . size ( ) ; for ( int i = 0 ; i < N ; i ++ ) { Node * temp = Q . front ( ) ; Q . pop ( ) ; if ( i % 2 == 0 ) { cout << temp -> data << " ▁ " ; } if ( temp -> left ) { Q . push ( temp -> left ) ; } if ( temp -> right ) { Q . push ( temp -> right ) ; } } cout << endl ; } } int main ( ) { Node * root ; root = new Node ( 71 ) ; root -> left = new Node ( 88 ) ; root -> right = new Node ( 99 ) ; root -> left -> left = new Node ( 4 ) ; root -> left -> right = new Node ( 5 ) ; root -> right -> left = new Node ( 6 ) ; root -> right -> right = new Node ( 7 ) ; root -> left -> left -> left = new Node ( 8 ) ; root -> left -> left -> right = new Node ( 9 ) ; root -> left -> right -> left = new Node ( 10 ) ; root -> left -> right -> right = new Node ( 11 ) ; root -> right -> left -> right = new Node ( 13 ) ; root -> right -> right -> left = new Node ( 14 ) ; PrintAlternate ( root ) ; }
Count subarrays for every array element in which they are the minimum | C ++ implementation of the above approach ; Function to required count subarrays ; For storing count of subarrays ; For finding next smaller element left to a element if there is no next smaller element left to it than taking - 1. ; For finding next smaller element right to a element if there is no next smaller element right to it than taking n . ; Taking exact boundaries in which arr [ i ] is minimum ; Similarly for right side ; Driver Code ; Given array arr [ ] ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > countingSubarray ( vector < int > arr , int n ) { vector < int > a ( n ) ; vector < int > nsml ( n , -1 ) ; vector < int > nsmr ( n , n ) ; stack < int > st ; for ( int i = n - 1 ; i >= 0 ; i -- ) { while ( ! st . empty ( ) && arr [ st . top ( ) ] >= arr [ i ] ) st . pop ( ) ; nsmr [ i ] = ( ! st . empty ( ) ) ? st . top ( ) : n ; st . push ( i ) ; } while ( ! st . empty ( ) ) st . pop ( ) ; for ( int i = 0 ; i < n ; i ++ ) { while ( ! st . empty ( ) && arr [ st . top ( ) ] >= arr [ i ] ) st . pop ( ) ; nsml [ i ] = ( ! st . empty ( ) ) ? st . top ( ) : -1 ; st . push ( i ) ; } for ( int i = 0 ; i < n ; i ++ ) { nsml [ i ] ++ ; nsmr [ i ] -- ; int r = nsmr [ i ] - i + 1 ; int l = i - nsml [ i ] + 1 ; a [ i ] = r * l ; } return a ; } int main ( ) { int N = 5 ; vector < int > arr = { 3 , 2 , 4 , 1 , 5 } ; auto a = countingSubarray ( arr , N ) ; cout << " [ " ; int n = a . size ( ) - 1 ; for ( int i = 0 ; i < n ; i ++ ) cout << a [ i ] << " , ▁ " ; cout << a [ n ] << " ] " ; return 0 ; }
Lexicographically smallest permutation of a string that contains all substrings of another string | C ++ program for the above approach ; Function to reorder the string B to contain all the substrings of A ; Find length of strings ; Initialize array to count the frequencies of the character ; Counting frequencies of character in B ; Find remaining character in B ; Declare the reordered string ; Loop until freq [ j ] > 0 ; Decrement the value from freq array ; Check if A [ j ] > A [ 0 ] ; Check if A [ j ] < A [ 0 ] ; Append the remaining characters to the end of the result ; Push all the values from frequency array in the answer ; Return the answer ; Driver Code ; Given strings A and B ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string reorderString ( string A , string B ) { int size_a = A . length ( ) ; int size_b = B . length ( ) ; int freq [ 300 ] = { 0 } ; for ( int i = 0 ; i < size_b ; i ++ ) freq [ B [ i ] ] ++ ; for ( int i = 0 ; i < size_a ; i ++ ) freq [ A [ i ] ] -- ; for ( int j = ' a ' ; j <= ' z ' ; j ++ ) { if ( freq [ j ] < 0 ) return " - 1" ; } string answer ; for ( int j = ' a ' ; j < A [ 0 ] ; j ++ ) while ( freq [ j ] > 0 ) { answer . push_back ( j ) ; freq [ j ] -- ; } int first = A [ 0 ] ; for ( int j = 0 ; j < size_a ; j ++ ) { if ( A [ j ] > A [ 0 ] ) break ; if ( A [ j ] < A [ 0 ] ) { answer += A ; A . clear ( ) ; break ; } } while ( freq [ first ] > 0 ) { answer . push_back ( first ) ; -- freq [ first ] ; } answer += A ; for ( int j = ' a ' ; j <= ' z ' ; j ++ ) while ( freq [ j ] -- ) answer . push_back ( j ) ; return answer ; } int main ( ) { string A = " aa " ; string B = " ababab " ; cout << reorderString ( A , B ) ; return 0 ; }
Find the interval which contains maximum number of concurrent meetings | C ++ 14 implementation of the above approach ; Function to find time slot of maximum concurrent meeting ; Sort array by start time of meeting ; Declare Minheap ; Insert first meeting end time ; Initialize max_len , max_start and max_end ; Traverse over sorted array to find required slot ; Pop all meetings that end before current meeting ; Push current meeting end time ; Update max_len , max_start and max_end if size of queue is greater than max_len ; Print slot of maximum concurrent meeting ; Driver Code ; Given array of meetings ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool cmp ( vector < int > a , vector < int > b ) { if ( a [ 0 ] != b [ 0 ] ) return a [ 0 ] < b [ 0 ] ; return a [ 1 ] - b [ 1 ] ; } void maxConcurrentMeetingSlot ( vector < vector < int > > meetings ) { sort ( meetings . begin ( ) , meetings . end ( ) , cmp ) ; priority_queue < int , vector < int > , greater < int > > pq ; pq . push ( meetings [ 0 ] [ 1 ] ) ; int max_len = 0 , max_start = 0 ; int max_end = 0 ; for ( auto k : meetings ) { while ( pq . size ( ) > 0 && k [ 0 ] >= pq . top ( ) ) pq . pop ( ) ; pq . push ( k [ 1 ] ) ; if ( pq . size ( ) > max_len ) { max_len = pq . size ( ) ; max_start = k [ 0 ] ; max_end = pq . top ( ) ; } } cout << max_start << " ▁ " << max_end ; } int main ( ) { vector < vector < int > > meetings = { { 100 , 200 } , { 50 , 300 } , { 300 , 400 } } ; maxConcurrentMeetingSlot ( meetings ) ; }
Number from a range [ L , R ] having Kth minimum cost of conversion to 1 by given operations | C ++ 14 implementation of the above approach ; Function to calculate the cost ; Base case ; Even condition ; Odd condition ; Return cost ; Function to find Kth element ; Array to store the costs ; Sort the array based on cost ; Driver Code ; Given range and6 K ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int func ( int n ) { int count = 0 ; if ( n == 2 or n == 1 ) return 1 ; if ( n % 2 == 0 ) count = 1 + func ( n / 2 ) ; if ( n % 2 != 0 ) count = 1 + func ( n * 3 + 1 ) ; return count ; } void findKthElement ( int l , int r , int k ) { vector < int > arr ; for ( int i = l ; i <= r ; i ++ ) arr . push_back ( i ) ; vector < vector < int > > result ; for ( int i : arr ) result . push_back ( { i , func ( i ) } ) ; sort ( result . begin ( ) , result . end ( ) ) ; cout << ( result [ k - 1 ] [ 0 ] ) ; } int main ( ) { int l = 12 ; int r = 15 ; int k = 2 ; findKthElement ( l , r , k ) ; return 0 ; }
Check if a string represents a hexadecimal number or not | C ++ implementation of the above approach ; Function to check if the string represents a hexadecimal number ; Size of string ; Iterate over string ; Check if the character is invalid ; Print true if all characters are valid ; Driver code ; Given string ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void checkHex ( string s ) { int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { char ch = s [ i ] ; if ( ( ch < '0' ch > '9' ) && ( ch < ' A ' ch > ' F ' ) ) { cout << " No " << endl ; return ; } } cout << " Yes " << endl ; } int main ( ) { string s = " BF57C " ; checkHex ( s ) ; return 0 ; }
Longest subsequence forming an Arithmetic Progression ( AP ) | C ++ program for the above approach ; Function that finds the longest arithmetic subsequence having the same absolute difference ; Stores the length of sequences having same difference ; Stores the resultant length ; Iterate over the array ; Update length of subsequence ; Return res ; Driver Code ; Given array arr [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int lenghtOfLongestAP ( int A [ ] , int n ) { unordered_map < int , unordered_map < int , int > > dp ; int res = 2 ; for ( int i = 0 ; i < n ; ++ i ) { for ( int j = i + 1 ; j < n ; ++ j ) { int d = A [ j ] - A [ i ] ; dp [ d ] [ j ] = dp [ d ] . count ( i ) ? dp [ d ] [ i ] + 1 : 2 ; res = max ( res , dp [ d ] [ j ] ) ; } } return res ; } int main ( ) { int arr [ ] = { 20 , 1 , 15 , 3 , 10 , 5 , 8 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << lenghtOfLongestAP ( arr , N ) ; return 0 ; }
Length of longest increasing prime subsequence from a given array | C ++ program for the above approach ; Function to find the prime numbers till 10 ^ 5 using Sieve of Eratosthenes ; False here indicates that it is not prime ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p , set them to non - prime ; Function which computes the length of the LIS of Prime Numbers ; Create an array of size n ; Create boolean array to mark prime numbers ; Initialize all values to true ; Precompute N primes ; Compute optimized LIS having prime numbers in bottom up manner ; Check for LIS and prime ; Return maximum value in lis [ ] ; Driver Code ; Given array ; Size of array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 100005 NEW_LINE void SieveOfEratosthenes ( bool prime [ ] , int p_size ) { prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= p_size ; p ++ ) { if ( prime [ p ] ) { for ( int i = p * 2 ; i <= p_size ; i += p ) prime [ i ] = false ; } } } int LISPrime ( int arr [ ] , int n ) { int lisp [ n ] ; bool prime [ N + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; SieveOfEratosthenes ( prime , N ) ; lisp [ 0 ] = prime [ arr [ 0 ] ] ? 1 : 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( ! prime [ arr [ i ] ] ) { lisp [ i ] = 0 ; continue ; } lisp [ i ] = 1 ; for ( int j = 0 ; j < i ; j ++ ) { if ( prime [ arr [ j ] ] && arr [ i ] > arr [ j ] && lisp [ i ] < lisp [ j ] + 1 ) { lisp [ i ] = lisp [ j ] + 1 ; } } } return * max_element ( lisp , lisp + n ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 5 , 3 , 2 , 5 , 1 , 7 } ; int M = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << LISPrime ( arr , M ) ; return 0 ; }
Check if a given number can be expressed as pair | C ++ program of the above approach ; Function to check if the number is pair - sum of sum of first X natural numbers ; Check if the given number is sum of pair of special numbers ; X is the sum of first i natural numbers ; t = 2 * Y ; Condition to check if Y is a special number ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void checkSumOfNatural ( int n ) { int i = 1 ; bool flag = false ; while ( i * ( i + 1 ) < n * 2 ) { int X = i * ( i + 1 ) ; int t = n * 2 - X ; int k = sqrt ( t ) ; if ( k * ( k + 1 ) == t ) { flag = true ; break ; } i += 1 ; } if ( flag ) cout << " YES " ; else cout << " NO " ; } int main ( ) { int n = 25 ; checkSumOfNatural ( n ) ; return 0 ; }
Count distinct regular bracket sequences which are not N periodic | C ++ program for the above approach ; Function that finds the value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate the value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; Return the C ( n , k ) ; Binomial coefficient based function to find nth catalan number in O ( n ) time ; Calculate value of 2 nCn ; Return C ( 2 n , n ) / ( n + 1 ) ; Function to find possible ways to put balanced parenthesis in an expression of length n ; If n is odd , not possible to create any valid parentheses ; Otherwise return n / 2 th Catalan Number ; Difference between counting ways of 2 * N and N is the result ; Driver Code ; Given value of N ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned long int binomialCoeff ( unsigned int n , unsigned int k ) { unsigned long 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 ; } unsigned long int catalan ( unsigned int n ) { unsigned long int c = binomialCoeff ( 2 * n , n ) ; return c / ( n + 1 ) ; } unsigned long int findWays ( unsigned n ) { if ( n & 1 ) return 0 ; return catalan ( n / 2 ) ; } void countNonNPeriodic ( int N ) { cout << findWays ( 2 * N ) - findWays ( N ) ; } int main ( ) { int N = 4 ; countNonNPeriodic ( N ) ; return 0 ; }
Check if two elements of a matrix are on the same diagonal or not | C ++ program for the above approach ; Function to check if two integers are on the same diagonal of the matrix ; Storing indexes of x in I , J ; Storing Indexes of y in P , Q ; Condition to check if the both the elements are in same diagonal of a matrix ; Driver code ; Dimensions of Matrix ; Given Matrix ; Elements to be checked ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void checkSameDiag ( int li [ 6 ] [ 5 ] , int x , int y , int m , int n ) { int I = 0 , J = 0 ; int P = 0 , Q = 0 ; for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( li [ i ] [ j ] == x ) { I = i ; J = j ; } if ( li [ i ] [ j ] == y ) { P = i ; Q = j ; } } } if ( P - Q == I - J P + Q == I + J ) { cout << " YES " ; } else cout << " NO " ; } int main ( ) { int m = 6 ; int n = 5 ; int li [ 6 ] [ 5 ] = { { 32 , 94 , 99 , 26 , 82 } , { 51 , 69 , 52 , 63 , 17 } , { 90 , 36 , 88 , 55 , 33 } , { 93 , 42 , 73 , 39 , 28 } , { 81 , 31 , 83 , 53 , 10 } , { 12 , 29 , 85 , 80 , 87 } } ; int x = 42 ; int y = 80 ; checkSameDiag ( li , x , y , m , n ) ; return 0 ; }
Count of decrement operations required to obtain K in N steps | C ++ program for the above approach ; Function to check whether m number of steps of type 1 are valid or not ; If m and n are the count of operations of type 1 and type 2 respectively , then n - m operations are performed ; Find the value of S after step 2 ; If m steps of type 1 is valid ; Function to find the number of operations of type 1 required ; Iterate over the range ; Find the value of mid ; Check if m steps of type 1 are valid or not ; If mid is the valid number of steps ; If no valid number of steps exist ; Driver Code ; Given and N , K ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int isValid ( int n , int m , int k ) { int step2 = n - m ; int cnt = ( step2 * ( step2 + 1 ) ) / 2 ; if ( cnt - m == k ) return 0 ; if ( cnt - m > k ) return 1 ; return -1 ; } void countOfOperations ( int n , int k ) { int start = 0 , end = n ; bool ok = 1 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; int temp = isValid ( n , mid , k ) ; if ( temp == 0 ) { ok = 0 ; cout << mid ; break ; } else if ( temp == 1 ) { start = mid + 1 ; } else { end = mid - 1 ; } } if ( ok ) cout << " - 1" ; } int main ( ) { int N = 5 , K = 4 ; countOfOperations ( N , K ) ; return 0 ; }
Print all Possible Decodings of a given Digit Sequence | C ++ program for the above approach ; Function to check if all the characters are lowercase or not ; Traverse the string ; If any character is not found to be in lowerCase ; Function to print the decodings ; If all characters are not in lowercase ; Function to return the character corresponding to given integer ; Function to return the decodings ; Base case ; Recursive call ; Stores the characters of two digit numbers ; Extract first digit and first two digits ; Check if it lies in the range of alphabets ; Next recursive call ; Combine both the output in a single final output array ; Index of final output array ; Store the elements of output1 in final output array ; Store the elements of output2 in final output array ; Result the result ; Driver Code ; Function call ; Print function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool nonLower ( string s ) { for ( int i = 0 ; i < s . size ( ) ; i ++ ) { if ( ! islower ( s [ i ] ) ) { return true ; } } return false ; } void printCodes ( vector < string > output ) { for ( int i = 0 ; i < output . size ( ) ; i ++ ) { if ( nonLower ( output [ i ] ) ) continue ; cout << ( output [ i ] ) << endl ; } } char getChar ( int n ) { return ( char ) ( n + 96 ) ; } vector < string > getCode ( string str ) { if ( str . size ( ) == 0 ) { vector < string > ans ; ans . push_back ( " " ) ; return ans ; } vector < string > output1 = getCode ( str . substr ( 1 ) ) ; vector < string > output2 ( 0 ) ; int firstDigit = ( str [ 0 ] - '0' ) ; int firstTwoDigit = 0 ; if ( str . size ( ) >= 2 ) { firstTwoDigit = ( str [ 0 ] - '0' ) * 10 + ( str [ 1 ] - '0' ) ; if ( firstTwoDigit >= 10 && firstTwoDigit <= 26 ) { output2 = getCode ( str . substr ( 2 ) ) ; } } vector < string > output ( output1 . size ( ) + output2 . size ( ) ) ; int k = 0 ; for ( int i = 0 ; i < output1 . size ( ) ; i ++ ) { char ch = getChar ( firstDigit ) ; output [ i ] = ch + output1 [ i ] ; k ++ ; } for ( int i = 0 ; i < output2 . size ( ) ; i ++ ) { char ch = getChar ( firstTwoDigit ) ; output [ k ] = ch + output2 [ i ] ; k ++ ; } return output ; } int main ( ) { string input = "101" ; vector < string > output = getCode ( input ) ; printCodes ( output ) ; }
Count prime numbers that can be expressed as sum of consecutive prime numbers | C ++ program for the above approach ; Function to check if a number is prime or not ; Base Case ; Iterate till [ 5 , sqrt ( N ) ] to detect primality of numbers ; If N is divisible by i or i + 2 ; Return 1 if N is prime ; Function to count the prime numbers which can be expressed as sum of consecutive prime numbers ; Initialize count as 0 ; Stores prime numbers ; If i is prime ; Initialize the sum ; Find all required primes upto N ; Add it to the sum ; Return the final count ; Driver Code ; Given number N ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int isprm ( int n ) { if ( n <= 1 ) return 0 ; if ( n <= 3 ) return 1 ; if ( n % 2 == 0 n % 3 == 0 ) return 0 ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) { if ( n % i == 0 || n % ( i + 2 ) == 0 ) return 0 ; } return 1 ; } int countprime ( int n ) { int count = 0 ; vector < int > primevector ; for ( int i = 2 ; i <= n ; i ++ ) { if ( isprm ( i ) == 1 ) { primevector . push_back ( i ) ; } } int sum = primevector [ 0 ] ; for ( int i = 1 ; i < primevector . size ( ) ; i ++ ) { sum += primevector [ i ] ; if ( sum > n ) break ; if ( isprm ( sum ) == 1 ) { count ++ ; } } return count ; } int main ( ) { int N = 45 ; cout << countprime ( N ) ; return 0 ; }
Find a subarray of size K whose sum is a perfect square | C ++ program for the above approach ; Function to check if a given number is a perfect square or not ; Find square root of n ; Check if the square root is an integer or not ; Function to print the subarray whose sum is a perfect square ; Sum of first K elements ; If the first k elements have a sum as perfect square ; Iterate through the array ; If sum is perfect square ; If subarray not found ; Driver Code ; Given array ; Given subarray size K ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPerfectSquare ( int n ) { double sr = sqrt ( n ) ; return ( ( sr - floor ( sr ) ) == 0 ) ; } void SubarrayHavingPerfectSquare ( vector < int > arr , int k ) { pair < int , int > ans ; int sum = 0 , i ; for ( i = 0 ; i < k ; i ++ ) { sum += arr [ i ] ; } bool found = false ; if ( isPerfectSquare ( sum ) ) { ans . first = 0 ; ans . second = i - 1 ; } else { for ( int j = i ; j < arr . size ( ) ; j ++ ) { sum = sum + arr [ j ] - arr [ j - k ] ; if ( isPerfectSquare ( sum ) ) { found = true ; ans . first = j - k + 1 ; ans . second = j ; } } for ( int k = ans . first ; k <= ans . second ; k ++ ) { cout << arr [ k ] << " ▁ " ; } } if ( found == false ) { cout << " - 1" ; } } int main ( ) { vector < int > arr ; arr = { 20 , 34 , 51 , 10 , 99 , 87 , 23 , 45 } ; int K = 3 ; SubarrayHavingPerfectSquare ( arr , K ) ; return 0 ; }
Check if any permutation of a number without any leading zeros is a power of 2 or not | C ++ program for the above approach ; Function to update the frequency array such that freq [ i ] stores the frequency of digit i to n ; While there are digits left to process ; Update the frequency of the current digit ; Remove the last digit ; Function that returns true if a and b are anagrams of each other ; To store the frequencies of the digits in a and b ; Update the frequency of the digits in a ; Update the frequency of the digits in b ; Match the frequencies of the common digits ; If frequency differs for any digit then the numbers are not anagrams of each other ; Function to check if any permutation of a number is a power of 2 or not ; Iterate over all possible perfect power of 2 ; Print that number ; Driver Code ; Given Number N ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int TEN = 10 ; void updateFreq ( int n , int freq [ ] ) { while ( n ) { int digit = n % TEN ; freq [ digit ] ++ ; n /= TEN ; } } bool areAnagrams ( int a , int b ) { int freqA [ TEN ] = { 0 } ; int freqB [ TEN ] = { 0 } ; updateFreq ( a , freqA ) ; updateFreq ( b , freqB ) ; for ( int i = 0 ; i < TEN ; i ++ ) { if ( freqA [ i ] != freqB [ i ] ) return false ; } return true ; } bool isPowerOf2 ( int N ) { for ( int i = 0 ; i < 32 ; i ++ ) { if ( areAnagrams ( 1 << i , N ) ) { cout << ( 1 << i ) ; return true ; } } return false ; } int main ( ) { int N = 46 ; if ( ! isPowerOf2 ( N ) ) { cout << " No " ; } return 0 ; }
Count number of triangles possible with length of sides not exceeding N | C ++ implementation of the above approach ; Function to count total number of right angled triangle ; Initialise count with 0 ; Run three nested loops and check all combinations of sides ; Condition for right angled triangle ; Increment count ; Driver Code ; Given N ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int right_angled ( int n ) { int count = 0 ; for ( int z = 1 ; z <= n ; z ++ ) { for ( int y = 1 ; y <= z ; y ++ ) { for ( int x = 1 ; x <= y ; x ++ ) { if ( ( x * x ) + ( y * y ) == ( z * z ) ) { count ++ ; } } } } return count ; } int main ( ) { int n = 5 ; cout << right_angled ( n ) ; return 0 ; }
Check if the given two matrices are mirror images of one another | C ++ implementation of the above approach ; Function to check whether the two matrices are mirror of each other ; Initialising row and column of second matrix ; Iterating over the matrices ; Check row of first matrix with reversed row of second matrix ; If the element is not equal ; Increment column ; Reset column to 0 for new row ; Increment row ; Driver code ; Given 2 matrices ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void mirrorMatrix ( int mat1 [ ] [ 4 ] , int mat2 [ ] [ 4 ] , int N ) { int row = 0 ; int col = 0 ; bool isMirrorImage = true ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = N - 1 ; j >= 0 ; j -- ) { if ( mat2 [ row ] [ col ] != mat1 [ i ] [ j ] ) { isMirrorImage = false ; } col ++ ; } col = 0 ; row ++ ; } if ( isMirrorImage ) cout << " Yes " ; else cout << " No " ; } int main ( ) { int N = 4 ; int mat1 [ ] [ 4 ] = { { 1 , 2 , 3 , 4 } , { 0 , 6 , 7 , 8 } , { 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 16 } } ; int mat2 [ ] [ 4 ] = { { 4 , 3 , 2 , 1 } , { 8 , 7 , 6 , 0 } , { 12 , 11 , 10 , 9 } , { 16 , 15 , 14 , 13 } } ; mirrorMatrix ( mat1 , mat2 , N ) ; }
Calculate number of nodes between two vertices in an acyclic Graph by DFS method | C ++ program for the above approach ; Function to return the count of nodes in the path from source to destination ; Mark the node visited ; If dest is reached ; Traverse all adjacent nodes ; If not already visited ; If there is path , then include the current node ; Return 0 if there is no path between src and dest through the current node ; Function to return the count of nodes between two given vertices of the acyclic Graph ; Initialize an adjacency list ; Populate the edges in the list ; Mark all the nodes as not visited ; Count nodes in the path from src to dest ; Return the nodes between src and dest ; Driver Code ; Given number of vertices and edges ; Given source and destination vertices ; Given edges
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dfs ( int src , int dest , int * vis , vector < int > * adj ) { vis [ src ] = 1 ; if ( src == dest ) { return 1 ; } for ( int u : adj [ src ] ) { if ( ! vis [ u ] ) { int temp = dfs ( u , dest , vis , adj ) ; if ( temp != 0 ) { return temp + 1 ; } } } return 0 ; } int countNodes ( int V , int E , int src , int dest , int edges [ ] [ 2 ] ) { vector < int > adj [ V + 1 ] ; for ( int i = 0 ; i < E ; i ++ ) { adj [ edges [ i ] [ 0 ] ] . push_back ( edges [ i ] [ 1 ] ) ; adj [ edges [ i ] [ 1 ] ] . push_back ( edges [ i ] [ 0 ] ) ; } int vis [ V + 1 ] = { 0 } ; int count = dfs ( src , dest , vis , adj ) ; return count - 2 ; } int main ( ) { int V = 8 , E = 7 ; int src = 5 , dest = 2 ; int edges [ ] [ 2 ] = { { 1 , 4 } , { 4 , 5 } , { 4 , 2 } , { 2 , 6 } , { 6 , 3 } , { 2 , 7 } , { 3 , 8 } } ; cout << countNodes ( V , E , src , dest , edges ) ; return 0 ; }
Check if all array elements are pairwise co | C ++ Program for the above approach ; Function to calculate GCD ; Function to calculate LCM ; Function to check if all elements in the array are pairwise coprime ; Initialize variables ; Iterate over the array ; Calculate product of array elements ; Calculate LCM of array elements ; If the product of array elements is equal to LCM of the array ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE ll GCD ( ll a , ll b ) { if ( a == 0 ) return b ; return GCD ( b % a , a ) ; } ll LCM ( ll a , ll b ) { return ( a * b ) / GCD ( a , b ) ; } void checkPairwiseCoPrime ( int A [ ] , int n ) { ll prod = 1 ; ll lcm = 1 ; for ( int i = 0 ; i < n ; i ++ ) { prod *= A [ i ] ; lcm = LCM ( A [ i ] , lcm ) ; } if ( prod == lcm ) cout << " Yes " << endl ; else cout << " No " << endl ; } int main ( ) { int A [ ] = { 2 , 3 , 5 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; checkPairwiseCoPrime ( A , n ) ; }
Partition a set into two non | C ++ Program for above approach ; Function to return the maximum difference between the subset sums ; Stores the total sum of the array ; Checks for positive and negative elements ; Stores the minimum element from the given array ; Traverse the array ; Calculate total sum ; Mark positive element present in the set ; Mark negative element present in the set ; Find the minimum element of the set ; If the array contains both positive and negative elements ; Otherwise ; Driver Code ; Given the array ; Length of the array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxDiffSubsets ( int arr [ ] , int N ) { int totalSum = 0 ; bool pos = false , neg = false ; int min = INT_MAX ; for ( int i = 0 ; i < N ; i ++ ) { totalSum += abs ( arr [ i ] ) ; if ( arr [ i ] > 0 ) pos = true ; if ( arr [ i ] < 0 ) neg = true ; if ( arr [ i ] < min ) min = arr [ i ] ; } if ( pos && neg ) return totalSum ; else return totalSum - 2 * min ; } int main ( ) { int S [ ] = { 1 , 2 , 1 } ; int N = sizeof ( S ) / sizeof ( S [ 0 ] ) ; if ( N < 2 ) cout << ( " Not ▁ Possible " ) ; else cout << ( maxDiffSubsets ( S , N ) ) ; }
Split array into two subarrays such that difference of their sum is minimum | C ++ program for the above approach ; Function to return minimum difference between two subarray sums ; To store prefix sums ; Generate prefix sum array ; To store suffix sums ; Generate suffix sum array ; Stores the minimum difference ; Traverse the given array ; Calculate the 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 prefix_sum [ n ] ; prefix_sum [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) prefix_sum [ i ] = prefix_sum [ i - 1 ] + arr [ i ] ; int suffix_sum [ n ] ; suffix_sum [ n - 1 ] = arr [ n - 1 ] ; for ( int i = n - 2 ; i >= 0 ; i -- ) suffix_sum [ i ] = suffix_sum [ i + 1 ] + arr [ i ] ; int minDiff = INT_MAX ; for ( int i = 0 ; i < n - 1 ; i ++ ) { int diff = abs ( prefix_sum [ i ] - suffix_sum [ i + 1 ] ) ; 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 ) ; }
Count of days remaining for the next day with higher temperature | C ++ program for the above approach ; Function to determine how many days required to wait for the next warmer temperature ; To store the answer ; Traverse all the temperatures ; Check if current index is the next warmer temperature of any previous indexes ; Pop the element ; Push the current index ; Print waiting days ; Driver Code ; Given temperatures ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void dailyTemperatures ( vector < int > & T ) { int n = T . size ( ) ; vector < int > daysOfWait ( n , -1 ) ; stack < int > s ; for ( int i = 0 ; i < n ; i ++ ) { while ( ! s . empty ( ) && T [ s . top ( ) ] < T [ i ] ) { daysOfWait [ s . top ( ) ] = i - s . top ( ) ; s . pop ( ) ; } s . push ( i ) ; } for ( int i = 0 ; i < n ; i ++ ) { cout << daysOfWait [ i ] << " ▁ " ; } } int main ( ) { vector < int > arr { 73 , 74 , 75 , 71 , 69 , 72 , 76 , 73 } ; dailyTemperatures ( arr ) ; return 0 ; }
Find node U containing all nodes from a set V at atmost distance 1 from the path from root to U | C ++ program for the above approach ; To store the time ; Function to perform DFS to store times , distance and parent of each node ; Update the distance of node u ; Update parent of node u ; Increment time timeT ; Discovery time of node u ; Traverse the adjacency list of current node and recursively call DFS for each vertex ; If current node Adj [ u ] [ i ] is unvisited ; Update the finishing time ; Function to add edges between nodes u and v ; Function to find the node U such that path from root to U contains nodes in V [ ] ; Initialise vis , dis , parent , preTime , and postTime ; Store Adjacency List ; Create adjacency List ; Perform DFS Traversal ; Stores the distance of deepest vertex ' u ' ; Update the deepest node by traversing the qu [ ] ; Find deepest vertex ; Replace each vertex with it 's corresponding parent except the root vertex ; Checks if the ancestor with respect to deepest vertex u ; Update ans ; Print the result ; Driver Code ; Total vertices ; Given set of vertices ; Given edges ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int timeT = 0 ; void dfs ( int u , int p , int dis , vector < int > & vis , vector < int > & distance , vector < int > & parent , vector < int > & preTime , vector < int > & postTime , vector < int > Adj [ ] ) { distance [ u ] = dis ; parent [ u ] = p ; vis [ u ] = 1 ; timeT ++ ; preTime [ u ] = timeT ; for ( int i = 0 ; i < Adj [ u ] . size ( ) ; i ++ ) { if ( vis [ Adj [ u ] [ i ] ] == 0 ) { dfs ( Adj [ u ] [ i ] , u , dis + 1 , vis , distance , parent , preTime , postTime , Adj ) ; } } timeT ++ ; postTime [ u ] = timeT ; } void addEdge ( vector < int > Adj [ ] , int u , int v ) { Adj [ u ] . push_back ( v ) ; Adj [ v ] . push_back ( u ) ; } void findNodeU ( int N , int V , int Vertices [ ] , int Edges [ ] [ 2 ] ) { vector < int > vis ( N + 1 , 0 ) ; vector < int > distance ( N + 1 , 0 ) ; vector < int > parent ( N + 1 , 0 ) ; vector < int > preTime ( N + 1 , 0 ) ; vector < int > postTime ( N + 1 , 0 ) ; vector < int > Adj [ N + 1 ] ; int u , v ; for ( int i = 0 ; i < N - 1 ; i ++ ) { addEdge ( Adj , Edges [ i ] [ 0 ] , Edges [ i ] [ 1 ] ) ; } dfs ( 1 , 0 , 0 , vis , distance , parent , preTime , postTime , Adj ) ; int maximumDistance = 0 ; maximumDistance = 0 ; for ( int k = 0 ; k < V ; k ++ ) { if ( maximumDistance < distance [ Vertices [ k ] ] ) { maximumDistance = distance [ Vertices [ k ] ] ; u = Vertices [ k ] ; } if ( parent [ Vertices [ k ] ] != 0 ) { Vertices [ k ] = parent [ Vertices [ k ] ] ; } } bool ans = true ; bool flag ; for ( int k = 0 ; k < V ; k ++ ) { if ( preTime [ Vertices [ k ] ] <= preTime [ u ] && postTime [ Vertices [ k ] ] >= postTime [ u ] ) flag = true ; else flag = false ; ans = ans & flag ; } if ( ans ) cout << u ; else cout << " NO " ; } int main ( ) { int N = 10 ; int V = 5 ; int Vertices [ ] = { 4 , 3 , 8 , 9 , 10 } ; int Edges [ ] [ 2 ] = { { 1 , 2 } , { 1 , 3 } , { 1 , 4 } , { 2 , 5 } , { 2 , 6 } , { 3 , 7 } , { 7 , 8 } , { 7 , 9 } , { 9 , 10 } } ; findNodeU ( N , V , Vertices , Edges ) ; return 0 ; }
Check if an array contains only one distinct element | C ++ program for the above approach ; Function to find if the array contains only one distinct element ; Create a set ; Traversing the array ; Compare and print the result ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void uniqueElement ( int arr [ ] , int n ) { unordered_set < int > set ; for ( int i = 0 ; i < n ; i ++ ) { set . insert ( arr [ i ] ) ; } if ( set . size ( ) == 1 ) { cout << " YES " << endl ; } else { cout << " NO " << endl ; } } int main ( ) { int arr [ ] = { 9 , 9 , 9 , 9 , 9 , 9 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; uniqueElement ( arr , n ) ; return 0 ; }
Maximum cost of splitting given Binary Tree into two halves | C ++ program for the above approach ; To store the results and sum of all nodes in the array ; To create adjacency list ; Function to add edges into the adjacency list ; Recursive function that calculate the value of the cost of splitting the tree recursively ; Fetch the child of node - r ; Neglect if cur node is parent ; Add all values of nodes which are decendents of r ; The two trees formed are rooted at ' r ' with its decendents ; Check and replace if current product t1 * t2 is large ; Function to find the maximum cost after splitting the tree in 2 halves ; Find sum of values in all nodes ; Traverse edges to create adjacency list ; Function Call ; Driver Code ; Values in each node ; Given Edges
#include <bits/stdc++.h> NEW_LINE using namespace std ; int ans = 0 , allsum = 0 ; vector < int > edges [ 100001 ] ; void addedge ( int a , int b ) { edges [ a ] . push_back ( b ) ; edges [ b ] . push_back ( a ) ; } void findCost ( int r , int p , int arr [ ] ) { int i , cur ; for ( i = 0 ; i < edges [ r ] . size ( ) ; i ++ ) { cur = edges [ r ] . at ( i ) ; if ( cur == p ) continue ; findCost ( cur , r , arr ) ; arr [ r ] += arr [ cur ] ; } int t1 = arr [ r ] ; int t2 = allsum - t1 ; if ( t1 * t2 > ans ) { ans = t1 * t2 ; } } void maximumCost ( int r , int p , int N , int M , int arr [ ] , int Edges [ ] [ 2 ] ) { for ( int i = 0 ; i < N ; i ++ ) { allsum += arr [ i ] ; } for ( int i = 0 ; i < M ; i ++ ) { addedge ( Edges [ i ] [ 0 ] , Edges [ i ] [ 1 ] ) ; } findCost ( r , p , arr ) ; } int main ( ) { int a , b , N = 6 ; int arr [ ] = { 13 , 8 , 7 , 4 , 5 , 9 } ; int M = 5 ; int Edges [ ] [ 2 ] = { { 0 , 1 } , { 1 , 2 } , { 1 , 4 } , { 3 , 4 } , { 4 , 5 } } ; maximumCost ( 1 , -1 , N , M , arr , Edges ) ; cout << ans ; return 0 ; }
Diameters for each node of Tree after connecting it with given disconnected component | C ++ Program to implement the above approach ; Keeps track of the farthest end of the diameter ; Keeps track of the length of the diameter ; Stores the nodes which are at ends of the diameter ; Perform DFS on the given tree ; Update diameter and X ; If current node is an end of diameter ; Traverse its neighbors ; Function to call DFS for the required purposes ; DFS from a random node and find the node farthest from it ; DFS from X to calculate diameter ; DFS from farthest_node to find the farthest node ( s ) from it ; DFS from X ( other end of diameter ) and check the farthest node ( s ) from it ; If node i is the end of a diameter ; Increase diameter by 1 ; Otherwise ; Remains unchanged ; Driver Code ; constructed tree is 1 / \ 2 3 7 / | \ / | \ 4 5 6 ; creating undirected edges
#include <bits/stdc++.h> NEW_LINE using namespace std ; int X = 1 ; int diameter = 0 ; map < int , bool > mp ; void dfs ( int current_node , int prev_node , int len , bool add_to_map , vector < vector < int > > & adj ) { if ( len > diameter ) { diameter = len ; X = current_node ; } if ( add_to_map && len == diameter ) { mp [ current_node ] = 1 ; } for ( auto & it : adj [ current_node ] ) { if ( it != prev_node ) dfs ( it , current_node , len + 1 , add_to_map , adj ) ; } } void dfsUtility ( vector < vector < int > > & adj ) { dfs ( 1 , -1 , 0 , 0 , adj ) ; int farthest_node = X ; dfs ( farthest_node , -1 , 0 , 0 , adj ) ; dfs ( farthest_node , -1 , 0 , 1 , adj ) ; dfs ( X , -1 , 0 , 1 , adj ) ; } void printDiameters ( vector < vector < int > > & adj ) { dfsUtility ( adj ) ; for ( int i = 1 ; i <= 6 ; i ++ ) { if ( mp [ i ] == 1 ) cout << diameter + 1 << " , ▁ " ; else cout << diameter << " , ▁ " ; } } int main ( ) { vector < vector < int > > adj ( 7 ) ; adj [ 1 ] . push_back ( 2 ) ; adj [ 2 ] . push_back ( 1 ) ; adj [ 1 ] . push_back ( 3 ) ; adj [ 3 ] . push_back ( 1 ) ; adj [ 2 ] . push_back ( 4 ) ; adj [ 4 ] . push_back ( 2 ) ; adj [ 2 ] . push_back ( 5 ) ; adj [ 5 ] . push_back ( 2 ) ; adj [ 2 ] . push_back ( 6 ) ; adj [ 6 ] . push_back ( 2 ) ; printDiameters ( adj ) ; return 0 ; }
Count of replacements required to make the sum of all Pairs of given type from the Array equal | C ++ Program to implement the above approach ; Function to find the minimum replacements required ; Stores the maximum and minimum values for every pair of the form arr [ i ] , arr [ n - i - 1 ] ; Map for storing frequencies of every sum formed by pairs ; Minimum element in the pair ; Maximum element in the pair ; Incrementing the frequency of sum encountered ; Insert minimum and maximum values ; Sorting the vectors ; Iterate over all possible values of x ; Count of pairs for which x > x + k ; Count of pairs for which x < mn + 1 ; Count of pairs requiring 2 replacements ; Count of pairs requiring no replacements ; Count of pairs requiring 1 replacement ; Update the answer ; Return the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE #define int long long int NEW_LINE using namespace std ; const int inf = 1e18 ; int minimumReplacement ( int * arr , int N , int K ) { int ans = inf ; vector < int > max_values ; vector < int > min_values ; map < int , int > sum_equal_to_x ; for ( int i = 0 ; i < N / 2 ; i ++ ) { int mn = min ( arr [ i ] , arr [ N - i - 1 ] ) ; int mx = max ( arr [ i ] , arr [ N - i - 1 ] ) ; sum_equal_to_x [ arr [ i ] + arr [ N - i - 1 ] ] ++ ; min_values . push_back ( mn ) ; max_values . push_back ( mx ) ; } sort ( max_values . begin ( ) , max_values . end ( ) ) ; sort ( min_values . begin ( ) , min_values . end ( ) ) ; for ( int x = 2 ; x <= 2 * K ; x ++ ) { int mp1 = lower_bound ( max_values . begin ( ) , max_values . end ( ) , x - K ) - max_values . begin ( ) ; int mp2 = lower_bound ( min_values . begin ( ) , min_values . end ( ) , x ) - min_values . begin ( ) ; int rep2 = mp1 + ( N / 2 - mp2 ) ; int rep0 = sum_equal_to_x [ x ] ; int rep1 = ( N / 2 - rep2 - rep0 ) ; ans = min ( ans , rep2 * 2 + rep1 ) ; } return ans ; } int32_t main ( ) { int N = 4 ; int K = 3 ; int arr [ ] = { 1 , 2 , 2 , 1 } ; cout << minimumReplacement ( arr , N , K ) ; return 0 ; }
Print the Forests of a Binary Tree after removal of given Nodes | C ++ Program to implement the above approach ; Stores the nodes to be deleted ; Structure of a Tree node ; Function to create a new node ; Function to check whether the node needs to be deleted or not ; Function to perform tree pruning by performing post order traversal ; If the node needs to be deleted ; Store the its subtree ; Perform Inorder Traversal ; Function to print the forests ; Stores the remaining nodes ; Print the inorder traversal of Forests ; Driver Code
#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 ) ; } bool deleteNode ( int nodeVal ) { return mp . find ( nodeVal ) != mp . end ( ) ; } Node * treePruning ( Node * root , vector < Node * > & result ) { if ( root == NULL ) return NULL ; root -> left = treePruning ( root -> left , result ) ; root -> right = treePruning ( root -> right , result ) ; if ( deleteNode ( root -> key ) ) { if ( root -> left ) { result . push_back ( root -> left ) ; } if ( root -> right ) { result . push_back ( root -> right ) ; } return NULL ; } return root ; } void printInorderTree ( Node * root ) { if ( root == NULL ) return ; printInorderTree ( root -> left ) ; cout << root -> key << " ▁ " ; printInorderTree ( root -> right ) ; } void printForests ( Node * root , int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { mp [ arr [ i ] ] = true ; } vector < Node * > result ; if ( treePruning ( root , result ) ) result . push_back ( root ) ; for ( int i = 0 ; i < result . size ( ) ; i ++ ) { printInorderTree ( result [ i ] ) ; cout << endl ; } } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 12 ) ; root -> right = newNode ( 13 ) ; root -> right -> left = newNode ( 14 ) ; root -> right -> right = newNode ( 15 ) ; root -> right -> left -> left = newNode ( 21 ) ; root -> right -> left -> right = newNode ( 22 ) ; root -> right -> right -> left = newNode ( 23 ) ; root -> right -> right -> right = newNode ( 24 ) ; int arr [ ] = { 14 , 23 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printForests ( root , arr , n ) ; }
Count of Ways to obtain given Sum from the given Array elements | C ++ program to implement the above approach ; Function to call dfs to calculate the number of ways ; If target + sum is odd or S exceeds sum ; No sultion exists ; Return the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int knapSack ( int nums [ ] , int S , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += nums [ i ] ; if ( sum < S || - sum > - S || ( S + sum ) % 2 == 1 ) return 0 ; int dp [ ( S + sum ) / 2 + 1 ] ; for ( int i = 0 ; i <= ( S + sum ) / 2 ; i ++ ) dp [ i ] = 0 ; dp [ 0 ] = 1 ; for ( int j = 0 ; j < n ; j ++ ) { for ( int i = ( S + sum ) / 2 ; i >= nums [ j ] ; i -- ) { dp [ i ] += dp [ i - nums [ j ] ] ; } } return dp [ ( S + sum ) / 2 ] ; } int main ( ) { int S = 3 ; int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int answer = knapSack ( arr , S , 5 ) ; cout << answer << endl ; }
Maximum distance between two elements whose absolute difference is K | C ++ program for the above approach ; Function that find maximum distance between two elements whose absolute difference is K ; To store the first index ; Traverse elements and find maximum distance between 2 elements whose absolute difference is K ; If this is first occurrence of element then insert its index in map ; If next element present in map then update max distance ; If previous element present in map then update max distance ; Return the answer ; Driver code ; Given array arr [ ] ; Given difference K ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxDistance ( int arr [ ] , int K , int N ) { map < int , int > Map ; int maxDist = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( Map . find ( arr [ i ] ) == Map . end ( ) ) Map [ arr [ i ] ] = i ; if ( Map . find ( arr [ i ] + K ) != Map . end ( ) ) { maxDist = max ( maxDist , i - Map [ arr [ i ] + K ] ) ; } if ( Map . find ( arr [ i ] - K ) != Map . end ( ) ) { maxDist = max ( maxDist , i - Map [ arr [ i ] - K ] ) ; } } if ( maxDist == 0 ) return -1 ; else return maxDist ; } int main ( ) { int arr [ ] = { 11 , 2 , 3 , 8 , 5 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 2 ; cout << maxDistance ( arr , K , N ) ; return 0 ; }
Count of Substrings with at least K pairwise Distinct Characters having same Frequency | C ++ Program for the above approach ; Function to find the substring with K pairwise distinct characters and with same frequency ; Stores the occurrence of each character in the substring ; Length of the string ; Iterate over the string ; Set all values at each index to zero ; Stores the count of unique characters ; Moving the substring ending at j ; Calculate the index of character in frequency array ; Increment the frequency ; Update the maximum index ; Check for both the conditions ; Return the answer ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int no_of_substring ( string s , int N ) { int fre [ 26 ] ; int str_len ; str_len = ( int ) s . length ( ) ; int count = 0 ; for ( int i = 0 ; i < str_len ; i ++ ) { memset ( fre , 0 , sizeof ( fre ) ) ; int max_index = 0 ; int dist = 0 ; for ( int j = i ; j < str_len ; j ++ ) { int x = s [ j ] - ' a ' ; if ( fre [ x ] == 0 ) dist ++ ; fre [ x ] ++ ; max_index = max ( max_index , fre [ x ] ) ; if ( dist >= N && ( ( max_index * dist ) == ( j - i + 1 ) ) ) count ++ ; } } return count ; } int main ( ) { string s = " abhay " ; int N = 3 ; cout << no_of_substring ( s , N ) ; return 0 ; }
Count of Ordered Pairs ( X , Y ) satisfying the Equation 1 / X + 1 / Y = 1 / N | C ++ Program for the above approach ; Function to find number of ordered positive integer pairs ( x , y ) such that they satisfy the equation ; Initialize answer variable ; Iterate over all possible values of y ; For valid x and y , ( n * n ) % ( y - n ) has to be 0 ; Increment count of ordered pairs ; Print the answer ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( int n ) { int ans = 0 ; for ( int y = n + 1 ; y <= n * n + n ; y ++ ) { if ( ( n * n ) % ( y - n ) == 0 ) { ans += 1 ; } } cout << ans ; } int main ( ) { int n = 5 ; solve ( n ) ; return 0 ; }
Count of Root to Leaf Paths consisting of at most M consecutive Nodes having value K | C ++ Program to implement the above approach ; Initialize the adjacency list and visited array ; Function to find the number of root to leaf paths that contain atmost m consecutive nodes with value k ; Mark the current node as visited ; If value at current node is k ; Increment counter ; If count is greater than m return from that path ; Path is allowed if size of present node becomes 0 i . e it has no child root and no more than m consecutive 1 's ; Driver Code ; Desigining the tree ; Counter counts no . of consecutive nodes
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > adj [ 100005 ] ; int visited [ 100005 ] = { 0 } ; int ans = 0 ; void dfs ( int node , int count , int m , int arr [ ] , int k ) { visited [ node ] = 1 ; if ( arr [ node - 1 ] == k ) { count ++ ; } else { count = 0 ; } if ( count > m ) { return ; } if ( adj [ node ] . size ( ) == 1 && node != 1 ) { ans ++ ; } for ( auto x : adj [ node ] ) { if ( ! visited [ x ] ) { dfs ( x , count , m , arr , k ) ; } } } int main ( ) { int arr [ ] = { 2 , 1 , 3 , 2 , 1 , 2 , 1 } ; int N = 7 , K = 2 , M = 2 ; adj [ 1 ] . push_back ( 2 ) ; adj [ 2 ] . push_back ( 1 ) ; adj [ 1 ] . push_back ( 3 ) ; adj [ 3 ] . push_back ( 1 ) ; adj [ 2 ] . push_back ( 4 ) ; adj [ 4 ] . push_back ( 2 ) ; adj [ 2 ] . push_back ( 5 ) ; adj [ 5 ] . push_back ( 2 ) ; adj [ 3 ] . push_back ( 6 ) ; adj [ 6 ] . push_back ( 3 ) ; adj [ 3 ] . push_back ( 7 ) ; adj [ 7 ] . push_back ( 3 ) ; int counter = 0 ; dfs ( 1 , counter , M , arr , K ) ; cout << ans << " STRNEWLINE " ; return 0 ; }
Count of N | C ++ program to implement the above approach ; Function to calculate and return the reverse of the number ; Function to calculate the total count of N - digit numbers satisfying the necessary conditions ; Initialize two variables ; Calculate the sum of odd and even positions ; Check for divisibility ; Return the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long reverse ( long num ) { long rev = 0 ; while ( num > 0 ) { int r = ( int ) ( num % 10 ) ; rev = rev * 10 + r ; num /= 10 ; } return rev ; } long count ( int N , int A , int B ) { long l = ( long ) pow ( 10 , N - 1 ) , r = ( long ) pow ( 10 , N ) - 1 ; if ( l == 1 ) l = 0 ; long ans = 0 ; for ( long i = l ; i <= r ; i ++ ) { int even_sum = 0 , odd_sum = 0 ; long itr = 0 , num = reverse ( i ) ; while ( num > 0 ) { if ( itr % 2 == 0 ) odd_sum += num % 10 ; else even_sum += num % 10 ; num /= 10 ; itr ++ ; } if ( even_sum % A == 0 && odd_sum % B == 0 ) ans ++ ; } return ans ; } int main ( ) { int N = 2 , A = 5 , B = 3 ; cout << ( count ( N , A , B ) ) ; }
Distance Traveled by Two Trains together in the same Direction | C ++ Program to find the distance traveled together by the two trains ; Function to find the distance traveled together ; Stores distance travelled by A ; Stpres distance travelled by B ; Stores the total distance travelled together ; Sum of distance travelled ; Condition for traveling together ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int calc_distance ( int A [ ] , int B [ ] , int n ) { int distance_traveled_A = 0 ; int distance_traveled_B = 0 ; int answer = 0 ; for ( int i = 0 ; i < 5 ; i ++ ) { distance_traveled_A += A [ i ] ; distance_traveled_B += B [ i ] ; if ( ( distance_traveled_A == distance_traveled_B ) && ( A [ i ] == B [ i ] ) ) { answer += A [ i ] ; } } return answer ; } int main ( ) { int A [ 5 ] = { 1 , 2 , 3 , 2 , 4 } ; int B [ 5 ] = { 2 , 1 , 3 , 1 , 4 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << calc_distance ( A , B , N ) ; return 0 ; }
Sum of Nodes and respective Neighbors on the path from root to a vertex V | C ++ Program to implement the above approach ; Creating Adjacency list ; Function to perform DFS traversal ; Initializing parent of each node to p ; Iterate over the children ; Function to add values of children to respective parent nodes ; Root node ; Function to return sum of values of each node in path from V to the root ; Path from node V to root node ; Driver Code ; Insert edges into the graph ; Values assigned to each vertex ; Constructing the tree using adjacency list ; Parent array ; store values in the parent array ; Add values of children to the parent ; Find sum of nodes lying in the path ; Add root node since its value is not included yet
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < vector < int > > constructTree ( int n , vector < vector < int > > edges ) { vector < vector < int > > adjl ( n ) ; for ( auto e : edges ) { int u = e [ 0 ] ; int v = e [ 1 ] ; adjl [ u ] . push_back ( v ) ; adjl [ v ] . push_back ( u ) ; } return adjl ; } void DFS ( vector < vector < int > > adjl , vector < int > & parent , int u , int p ) { parent [ u ] = p ; for ( int v : adjl [ u ] ) { if ( v != p ) { DFS ( adjl , parent , v , u ) ; } } } vector < int > valuesFromChildren ( vector < int > parent , vector < int > values ) { vector < int > valuesChildren ( parent . size ( ) ) ; for ( int i = 0 ; i < parent . size ( ) ; i ++ ) { if ( parent [ i ] == -1 ) continue ; else { int p = parent [ i ] ; valuesChildren [ p ] += values [ i ] ; } } return valuesChildren ; } int findSumOfValues ( int v , vector < int > parent , vector < int > valuesChildren ) { int cur_node = v ; int sum = 0 ; while ( cur_node != -1 ) { sum += valuesChildren [ cur_node ] ; cur_node = parent [ cur_node ] ; } return sum ; } int main ( ) { int n = 8 ; vector < vector < int > > edges = { { 0 , 1 } , { 0 , 2 } , { 0 , 3 } , { 1 , 4 } , { 1 , 5 } , { 4 , 7 } , { 3 , 6 } } ; int v = 7 ; vector < int > values = { 1 , 2 , 3 , 0 , 0 , 4 , 3 , 6 } ; vector < vector < int > > adjl = constructTree ( n , edges ) ; vector < int > parent ( n ) ; DFS ( adjl , parent , 0 , -1 ) ; vector < int > valuesChildren = valuesFromChildren ( parent , values ) ; int sum = findSumOfValues ( v , parent , valuesChildren ) ; sum += values [ 0 ] ; cout << sum << endl ; }
Find a pair in Array with second largest product | C ++ program for the above approach ; Function to find second largest product pair in arr [ 0. . n - 1 ] ; No pair exits ; Initialize max product pair ; Traverse through every possible pair and keep track of largest product ; If pair is largest ; Second largest ; If pair dose not largest but larger then second largest ; Print the pairs ; Driver Code ; Given array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxProduct ( int arr [ ] , int N ) { if ( N < 3 ) { return ; } int a = arr [ 0 ] , b = arr [ 1 ] ; int c = 0 , d = 0 ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = i + 1 ; j < N ; j ++ ) { if ( arr [ i ] * arr [ j ] > a * b ) { c = a , d = b ; a = arr [ i ] , b = arr [ j ] ; } if ( arr [ i ] * arr [ j ] < a * b && arr [ i ] * arr [ j ] > c * d ) c = arr [ i ] , d = arr [ j ] ; } cout << c << " ▁ " << d ; } int main ( ) { int arr [ ] = { 5 , 2 , 67 , 45 , 160 , 78 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maxProduct ( arr , N ) ; return 0 ; }
Count of substrings consisting of even number of vowels | C ++ program to implement the above approach ; Utility function to check if a character is a vowel ; Function to calculate and return the count of substrings with even number of vowels ; Stores the count of substrings ; If the current character is a vowel ; Increase count ; If substring contains even number of vowels ; Increase the answer ; Print the final answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isVowel ( char c ) { if ( c == ' a ' c == ' e ' c == ' i ' c == ' o ' c == ' u ' ) return true ; return false ; } void countSubstrings ( string s , int n ) { int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int count = 0 ; for ( int j = i ; j < n ; j ++ ) { if ( isVowel ( s [ j ] ) ) { count ++ ; } if ( count % 2 == 0 ) result ++ ; } } cout << result ; } int main ( ) { int n = 5 ; string s = " abcde " ; countSubstrings ( s , n ) ; return 0 ; }
Count of substrings consisting of even number of vowels | C ++ program to implement the above approach ; Utility function to check if a character is a vowel ; Function to calculate and return the count of substrings with even number of vowels ; Stores the count of substrings with even and odd number of vowels respectively ; Update count of vowels modulo 2 in sum to obtain even or odd ; Increment even / odd count ; Count substrings with even number of vowels using Handshaking Lemma ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isVowel ( char c ) { if ( c == ' a ' c == ' e ' c == ' i ' c == ' o ' c == ' u ' ) return true ; return false ; } void countSubstrings ( string s , int n ) { int temp [ ] = { 1 , 0 } ; int result = 0 , sum = 0 ; for ( int i = 0 ; i <= n - 1 ; i ++ ) { sum += ( isVowel ( s [ i ] ) ? 1 : 0 ) ; sum %= 2 ; temp [ sum ] ++ ; } result += ( ( temp [ 0 ] * ( temp [ 0 ] - 1 ) ) / 2 ) ; result += ( ( temp [ 1 ] * ( temp [ 1 ] - 1 ) ) / 2 ) ; cout << result ; } int main ( ) { int n = 5 ; string s = " abcde " ; countSubstrings ( s , n ) ; }
Find the Level of a Binary Tree with Width K | C ++ Program to implement the above approach ; Structure of a Tree node ; Utility function to create and initialize a new node ; Function returns required level of width k , if found else - 1 ; To store the node and the label and perform traversal ; Taking the last label of each level of the tree ; Check width of current level ; If the width is equal to k then return that level ; Taking the first label of each level of the tree ; If any level does not has width equal to k , return - 1 ; 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 ) ; } int findLevel ( Node * root , int k , int level ) { queue < pair < Node * , int > > qt ; qt . push ( make_pair ( root , 0 ) ) ; int count = 1 , b , a = 0 ; while ( ! qt . empty ( ) ) { pair < Node * , int > temp = qt . front ( ) ; qt . pop ( ) ; if ( count == 1 ) { b = temp . second ; } if ( ( temp . first ) -> left ) { qt . push ( make_pair ( temp . first -> left , 2 * temp . second ) ) ; } if ( temp . first -> right ) { qt . push ( make_pair ( temp . first -> right , 2 * temp . second + 1 ) ) ; } count -- ; if ( count == 0 ) { if ( b - a + 1 == k ) return level ; pair < Node * , int > secondLabel = qt . front ( ) ; a = secondLabel . second ; level += 1 ; count = qt . size ( ) ; } } return -1 ; } int main ( ) { Node * root = newNode ( 5 ) ; root -> left = newNode ( 6 ) ; root -> right = newNode ( 2 ) ; root -> right -> right = newNode ( 8 ) ; root -> left -> left = newNode ( 7 ) ; root -> left -> left -> left = newNode ( 5 ) ; root -> left -> right = newNode ( 3 ) ; root -> left -> right -> right = newNode ( 4 ) ; int k = 4 ; cout << findLevel ( root , k , 1 ) << endl ; return 0 ; }
Maximize median after doing K addition operation on the Array | C ++ program for the above approach ; Function to check operation can be perform or not ; Number of operation to perform s . t . mid is median ; If mid is median of the array ; Function to find max median of the array ; Lowest possible median ; Highest possible median ; Checking for mid is possible for the median of array after doing at most k operation ; Return the max possible ans ; Driver Code ; Given array ; Given number of operation ; Size of array ; Sort the array ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool possible ( int arr [ ] , int N , int mid , int K ) { int add = 0 ; for ( int i = N / 2 - ( N + 1 ) % 2 ; i < N ; ++ i ) { if ( mid - arr [ i ] > 0 ) { add += ( mid - arr [ i ] ) ; if ( add > K ) return false ; } } if ( add <= K ) return true ; else return false ; } int findMaxMedian ( int arr [ ] , int N , int K ) { int low = 1 ; int mx = 0 ; for ( int i = 0 ; i < N ; ++ i ) { mx = max ( mx , arr [ i ] ) ; } long long int high = K + mx ; while ( low <= high ) { int mid = ( high + low ) / 2 ; if ( possible ( arr , N , mid , K ) ) { low = mid + 1 ; } else { high = mid - 1 ; } } if ( N % 2 == 0 ) { if ( low - 1 < arr [ N / 2 ] ) { return ( arr [ N / 2 ] + low - 1 ) / 2 ; } } return low - 1 ; } int main ( ) { int arr [ ] = { 1 , 3 , 6 } ; int K = 10 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sort ( arr , arr + N ) ; cout << findMaxMedian ( arr , N , K ) ; return 0 ; }
Kth Smallest Element of a Matrix of given dimensions filled with product of indices | C ++ program for the above approach ; Function that returns true if the count of elements is less than mid ; To store count of elements less than mid ; Loop through each row ; Count elements less than mid in the ith row ; Function that returns the Kth smallest element in the NxM Matrix after sorting in an array ; Initialize low and high ; Perform binary search ; Find the mid ; Check if the count of elements is less than mid ; Return Kth smallest element of the matrix ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define LL long long NEW_LINE bool countLessThanMid ( LL mid , LL N , LL M , LL K ) { LL count = 0 ; for ( int i = 1 ; i <= min ( ( LL ) N , mid ) ; ++ i ) { count = count + min ( mid / i , M ) ; } if ( count >= K ) return false ; else return true ; } LL findKthElement ( LL N , LL M , LL K ) { LL low = 1 , high = N * M ; while ( low <= high ) { LL mid = low + ( high - low ) / 2 ; if ( countLessThanMid ( mid , N , M , K ) ) low = mid + 1 ; else high = mid - 1 ; } return high + 1 ; } int main ( ) { LL N = 2 , M = 3 ; LL int K = 5 ; cout << findKthElement ( N , M , K ) << endl ; return 0 ; }
Count of substrings containing only the given character | C ++ program to implement the above approach ; Function that finds the count of substrings containing only character C in the string S ; To store total count of substrings ; To store count of consecutive C 's ; Loop through the string ; Increase the consecutive count of C 's ; Add count of sub - strings from consecutive strings ; Reset the consecutive count of C 's ; Add count of sub - strings from consecutive strings ; Print the count of sub - strings containing only C ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countSubString ( string S , char C ) { int count = 0 ; int conCount = 0 ; for ( char ch : S ) { if ( ch == C ) conCount ++ ; else { count += ( conCount * ( conCount + 1 ) ) / 2 ; conCount = 0 ; } } count += ( conCount * ( conCount + 1 ) ) / 2 ; cout << count ; } int main ( ) { string S = " geeksforgeeks " ; char C = ' e ' ; countSubString ( S , C ) ; return 0 ; }
Check if both halves of a string are Palindrome or not | C ++ Program to check whether both halves of a string is Palindrome or not ; Function to check if both halves of a string are palindrome or not ; Length of string ; Initialize both part as true ; If first half is not palindrome ; If second half is not palindrome ; If both halves are Palindrome ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void checkPalindrome ( string S ) { int N = S . size ( ) ; bool first_half = true ; bool second_half = true ; int cnt = ( N / 2 ) - 1 ; for ( int i = 0 ; i < ( ( N / 2 ) / 2 ) ; i ++ ) { if ( S [ i ] != S [ cnt ] ) { first_half = false ; break ; } if ( S [ N / 2 + i ] != S [ N / 2 + cnt ] ) { second_half - false ; break ; } cnt -- ; } if ( first_half && second_half ) { cout << " Yes " << endl ; } else { cout << " No " << endl ; } } int main ( ) { string S = " momdad " ; checkPalindrome ( S ) ; return 0 ; }
Count of pairs of strings whose concatenation forms a palindromic string | C ++ Program to find palindromic string ; Stores frequency array and its count ; Total number of pairs ; Initializing array of size 26 to store count of character ; Counting occurrence of each character of current string ; Convert each count to parity ( 0 or 1 ) on the basis of its frequency ; Adding to answer ; Frequency of single character can be possibly changed , so change its parity ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getCount ( int N , vector < string > & s ) { map < vector < int > , int > mp ; int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { vector < int > a ( 26 , 0 ) ; for ( int j = 0 ; j < s [ i ] . size ( ) ; j ++ ) { a [ s [ i ] [ j ] - ' a ' ] ++ ; } for ( int j = 0 ; j < 26 ; j ++ ) { a [ j ] = a [ j ] % 2 ; } ans += mp [ a ] ; for ( int j = 0 ; j < 26 ; j ++ ) { vector < int > changedCount = a ; if ( a [ j ] == 0 ) changedCount [ j ] = 1 ; else changedCount [ j ] = 0 ; ans += mp [ changedCount ] ; } mp [ a ] ++ ; } return ans ; } int main ( ) { int N = 6 ; vector < string > A = { " aab " , " abcac " , " dffe " , " ed " , " aa " , " aade " } ; cout << getCount ( N , A ) ; return 0 ; }
Kth Smallest element in a Perfect Binary Search Tree | C ++ program to find K - th smallest element in a perfect BST ; A BST node ; A utility function to create a new BST node ; A utility function to insert a new node with given key in BST ; If the tree is empty ; Recur down the left subtree for smaller values ; Recur down the right subtree for smaller values ; Return the ( unchanged ) node pointer ; FUnction to find Kth Smallest element in a perfect BST ; Find the median ( division operation is floored ) ; If the element is at the median ; calculate the number of nodes in the right and left sub - trees ( division operation is floored ) ; If median is located higher ; If median is located lower ; Driver Code ; Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 / \ / \ / \ / \ 14 25 35 45 55 65 75 85 ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; Node * left , * right ; } ; Node * newNode ( int item ) { Node * temp = new Node ; temp -> key = item ; temp -> left = temp -> right = NULL ; return temp ; } Node * insert ( Node * node , int key ) { if ( node == NULL ) return newNode ( key ) ; if ( key < node -> key ) node -> left = insert ( node -> left , key ) ; else if ( key > node -> key ) node -> right = insert ( node -> right , key ) ; return node ; } bool KSmallestPerfectBST ( Node * root , int k , int treeSize , int & kth_smallest ) { if ( root == NULL ) return false ; int median_loc = ( treeSize / 2 ) + 1 ; if ( k == median_loc ) { kth_smallest = root -> key ; return true ; } int newTreeSize = treeSize / 2 ; if ( k < median_loc ) { return KSmallestPerfectBST ( root -> left , k , newTreeSize , kth_smallest ) ; } int newK = k - median_loc ; return KSmallestPerfectBST ( root -> right , newK , newTreeSize , kth_smallest ) ; } int main ( ) { Node * root = NULL ; root = insert ( root , 50 ) ; insert ( root , 30 ) ; insert ( root , 20 ) ; insert ( root , 40 ) ; insert ( root , 70 ) ; insert ( root , 60 ) ; insert ( root , 80 ) ; insert ( root , 14 ) ; insert ( root , 25 ) ; insert ( root , 35 ) ; insert ( root , 45 ) ; insert ( root , 55 ) ; insert ( root , 65 ) ; insert ( root , 75 ) ; insert ( root , 85 ) ; int n = 15 , k = 5 ; int ans = -1 ; if ( KSmallestPerfectBST ( root , k , n , ans ) ) { cout << ans << " ▁ " ; } return 0 ; }
Check if given Binary string follows then given condition or not | C ++ program for the above approach ; Function to check if the string follows rules or not ; Check for the first condition ; Check for the third condition ; Check for the second condition ; Driver Code ; Given String str ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkrules ( string s ) { if ( s . length ( ) == 0 ) return true ; if ( s [ 0 ] != '1' ) return false ; if ( s . length ( ) > 2 ) { if ( s [ 1 ] == '0' && s [ 2 ] == '0' ) return checkrules ( s . substr ( 3 ) ) ; } return checkrules ( s . substr ( 1 ) ) ; } int main ( ) { string str = "1111" ; if ( checkrules ( str ) ) { cout << " Valid ▁ String " ; } else { cout << " Invalid ▁ String " ; } return 0 ; }
Length of longest subsequence in an Array having all elements as Nude Numbers | C ++ program for the above approach ; Function to check if the number is a Nude number ; Variable initialization ; Integer ' copy ' is converted to a string ; Total digits in the number ; Loop through all digits and check if every digit divides n or not ; flag is used to keep check ; Return true or false as per the condition ; Function to find the longest subsequence which contain all Nude numbers ; Find the length of longest Nude number subsequence ; Driver Code ; Given array arr [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isNudeNum ( int n ) { int copy , length , flag = 0 ; copy = n ; string temp ; temp = to_string ( copy ) ; length = temp . length ( ) ; for ( int i = 0 ; i < length ; i ++ ) { int num = temp [ i ] - '0' ; if ( num == 0 or n % num != 0 ) { flag = 1 ; } } if ( flag == 1 ) return false ; else return true ; } int longestNudeSubseq ( int arr [ ] , int n ) { int answer = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( isNudeNum ( arr [ i ] ) ) answer ++ ; } return answer ; } int main ( ) { int arr [ ] = { 34 , 34 , 2 , 2 , 3 , 333 , 221 , 32 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << longestNudeSubseq ( arr , n ) << endl ; return 0 ; }
Longest subarray with difference exactly K between any two distinct values | C ++ implementation to find the longest subarray consisting of only two values with difference K ; Function to return the length of the longest sub - array ; Initialize set ; Store 1 st element of sub - array into set ; Check absolute difference between two elements ; If the new element is not present in the set ; If the set contains two elements ; Otherwise ; Update the maximum length ; Remove the set elements ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longestSubarray ( int arr [ ] , int n , int k ) { int i , j , Max = 1 ; set < int > s ; for ( i = 0 ; i < n - 1 ; i ++ ) { s . insert ( arr [ i ] ) ; for ( j = i + 1 ; j < n ; j ++ ) { if ( abs ( arr [ i ] - arr [ j ] ) == 0 || abs ( arr [ i ] - arr [ j ] ) == k ) { if ( ! s . count ( arr [ j ] ) ) { if ( s . size ( ) == 2 ) break ; else s . insert ( arr [ j ] ) ; } } else break ; } if ( s . size ( ) == 2 ) { Max = max ( Max , j - i ) ; s . clear ( ) ; } else s . clear ( ) ; } return Max ; } int main ( ) { int arr [ ] = { 1 , 0 , 2 , 2 , 5 , 5 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 1 ; int length = longestSubarray ( arr , N , K ) ; if ( length == 1 ) cout << -1 ; else cout << length ; return 0 ; }
Longest subarray of non | C ++ program for the above approach ; Function to find the maximum length of a subarray of 1 s after removing at most one 0 ; Stores the count of consecutive 1 's from left ; Stores the count of consecutive 1 's from right ; Traverse left to right ; If cell is non - empty ; Increase count ; If cell is empty ; Store the count of consecutive 1 's till (i - 1)-th index ; Traverse from right to left ; Store the count of consecutive 1 s till ( i + 1 ) - th index ; Stores the length of longest subarray ; Store the maximum ; If array a contains only 1 s return n else return ans ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longestSubarray ( int a [ ] , int n ) { int l [ n ] ; int r [ n ] ; for ( int i = 0 , count = 0 ; i < n ; i ++ ) { if ( a [ i ] == 1 ) count ++ ; else { l [ i ] = count ; count = 0 ; } } for ( int i = n - 1 , count = 0 ; i >= 0 ; i -- ) { if ( a [ i ] == 1 ) count ++ ; else { r [ i ] = count ; count = 0 ; } } int ans = -1 ; for ( int i = 0 ; i < n ; ++ i ) { if ( a [ i ] == 0 ) ans = max ( ans , l [ i ] + r [ i ] ) ; } return ans < 0 ? n : ans ; } int main ( ) { int arr [ ] = { 0 , 1 , 1 , 1 , 0 , 1 , 0 , 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << longestSubarray ( arr , n ) ; return 0 ; }
Find largest factor of N such that N / F is less than K | C ++ program for the above approach ; Function to find the value of X ; Loop to check all the numbers divisible by N that yield minimum N / i value ; Print the value of packages ; Driver Code ; Given N and K ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMaxValue ( int N , int K ) { int packages ; int maxi = 1 ; for ( int i = 1 ; i <= K ; i ++ ) { if ( N % i == 0 ) maxi = max ( maxi , i ) ; } packages = N / maxi ; cout << packages << endl ; } int main ( ) { int N = 8 , K = 7 ; findMaxValue ( N , K ) ; return 0 ; }
Largest square which can be formed using given rectangular blocks | C ++ program for the above approach ; Function to find maximum side length of square ; Sort array in asc order ; Traverse array in desc order ; Driver Code ; Given array arr [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxSide ( int a [ ] , int n ) { int sideLength = 0 ; sort ( a , a + n ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( a [ i ] > sideLength ) { sideLength ++ ; } else { break ; } } cout << sideLength << endl ; } int main ( ) { int N = 6 ; int arr [ ] = { 3 , 2 , 1 , 5 , 2 , 4 } ; maxSide ( arr , N ) ; return 0 ; }
Count of subtrees from an N | C ++ program for the above approach ; Function to implement DFS traversal ; Mark node v as visited ; Traverse Adj_List of node v ; If current node is not visited ; DFS call for current node ; Count the total red and blue nodes of children of its subtree ; Count the no . of red and blue nodes in the subtree ; If subtree contains all red node & no blue node ; If subtree contains all blue node & no red node ; Function to count the number of nodes with red color ; Function to count the number of nodes with blue color ; Function to create a Tree with given vertices ; Traverse the edge [ ] array ; Create adjacency list ; Function to count the number of subtree with the given condition ; For creating adjacency list ; To store the count of subtree with only blue and red color ; visited array for DFS Traversal ; Count the number of red node in the tree ; Count the number of blue node in the tree ; Function Call to build tree ; DFS Traversal ; Print the final count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void Solution_dfs ( int v , int color [ ] , int red , int blue , int * sub_red , int * sub_blue , int * vis , map < int , vector < int > > & adj , int * ans ) { vis [ v ] = 1 ; for ( int i = 0 ; i < adj [ v ] . size ( ) ; i ++ ) { if ( vis [ adj [ v ] [ i ] ] == 0 ) { Solution_dfs ( adj [ v ] [ i ] , color , red , blue , sub_red , sub_blue , vis , adj , ans ) ; sub_red [ v ] += sub_red [ adj [ v ] [ i ] ] ; sub_blue [ v ] += sub_blue [ adj [ v ] [ i ] ] ; } } if ( color [ v ] == 1 ) { sub_red [ v ] ++ ; } if ( color [ v ] == 2 ) { sub_blue [ v ] ++ ; } if ( sub_red [ v ] == red && sub_blue [ v ] == 0 ) { ( * ans ) ++ ; } if ( sub_red [ v ] == 0 && sub_blue [ v ] == blue ) { ( * ans ) ++ ; } } int countRed ( int color [ ] , int n ) { int red = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( color [ i ] == 1 ) red ++ ; } return red ; } int countBlue ( int color [ ] , int n ) { int blue = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( color [ i ] == 2 ) blue ++ ; } return blue ; } void buildTree ( int edge [ ] [ 2 ] , map < int , vector < int > > & m , int n ) { int u , v , i ; for ( i = 0 ; i < n - 1 ; i ++ ) { u = edge [ i ] [ 0 ] - 1 ; v = edge [ i ] [ 1 ] - 1 ; m [ u ] . push_back ( v ) ; m [ v ] . push_back ( u ) ; } } void countSubtree ( int color [ ] , int n , int edge [ ] [ 2 ] ) { map < int , vector < int > > adj ; int ans = 0 ; int sub_red [ n + 3 ] = { 0 } ; int sub_blue [ n + 3 ] = { 0 } ; int vis [ n + 3 ] = { 0 } ; int red = countRed ( color , n ) ; int blue = countBlue ( color , n ) ; buildTree ( edge , adj , n ) ; Solution_dfs ( 0 , color , red , blue , sub_red , sub_blue , vis , adj , & ans ) ; cout << ans ; } int main ( ) { int N = 5 ; int color [ ] = { 1 , 0 , 0 , 0 , 2 } ; int edge [ ] [ 2 ] = { { 1 , 2 } , { 2 , 3 } , { 3 , 4 } , { 4 , 5 } } ; countSubtree ( color , N , edge ) ; return 0 ; }
Minimize difference after changing all odd elements to even | C ++ program for the above approach ; Function to minimize the difference between two elements of array ; Find all the element which are possible by multiplying 2 to odd numbers ; Sort the array ; Find the minimum difference Iterate and find which adjacent elements have the minimum difference ; Print the minimum difference ; Driver Code ; Given array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long NEW_LINE void minDiff ( vector < ll > a , int n ) { for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] % 2 == 1 ) a . push_back ( a [ i ] * 2 ) ; } sort ( a . begin ( ) , a . end ( ) ) ; ll mindifference = a [ 1 ] - a [ 0 ] ; for ( int i = 1 ; i < a . size ( ) ; i ++ ) { mindifference = min ( mindifference , a [ i ] - a [ i - 1 ] ) ; } cout << mindifference << endl ; } int main ( ) { vector < ll > arr = { 3 , 8 , 13 , 30 , 50 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minDiff ( arr , n ) ; return 0 ; }
Longest subarray having sum K | Set 2 | C ++ program for the above approach ; To store the prefix sum array ; Function for searching the lower bound of the subarray ; Iterate until low less than equal to high ; For each mid finding sum of sub array less than or equal to k ; Return the final answer ; Function to find the length of subarray with sum K ; Initialize sum to 0 ; Push the prefix sum of the array arr [ ] in prefix [ ] ; Search r for each i ; Update ans ; Print the length of subarray found in the array ; Driver Code ; Given array arr [ ] ; Given sum K ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > v ; int bin ( int val , int k , int n ) { int lo = 0 ; int hi = n ; int mid ; int ans = -1 ; while ( lo <= hi ) { mid = lo + ( hi - lo ) / 2 ; if ( v [ mid ] - val <= k ) { lo = mid + 1 ; ans = mid ; } else hi = mid - 1 ; } return ans ; } void findSubarraySumK ( int arr [ ] , int N , int K ) { int sum = 0 ; v . push_back ( 0 ) ; for ( int i = 0 ; i < N ; i ++ ) { sum += arr [ i ] ; v . push_back ( sum ) ; } int l = 0 , ans = 0 , r ; for ( int i = 0 ; i < N ; i ++ ) { r = bin ( v [ i ] , K , N ) ; ans = max ( ans , r - i ) ; } cout << ans ; } int main ( ) { int arr [ ] = { 6 , 8 , 14 , 9 , 4 , 11 , 10 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 13 ; findSubarraySumK ( arr , N , K ) ; return 0 ; }
Minimum number of reversals to reach node 0 from every other node | C ++ program for the above approach ; Function to find minimum reversals ; Add all adjacent nodes to the node in the graph ; Insert edges in the graph ; Insert edges in the reversed graph ; Create array visited to mark all the visited nodes ; Stores the number of edges to be reversed ; BFS Traversal ; Pop the current node from the queue ; mark the current node visited ; Intitialize count of edges need to be reversed to 0 ; Push adjacent nodes in the reversed graph to the queue , if not visited ; Push adjacent nodes in graph to the queue , if not visited count the number of nodes added to the queue ; Update the reverse edge to the final count ; Return the result ; Driver Code ; Given edges to the graph ; Number of nodes ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minRev ( vector < vector < int > > edges , int n ) { unordered_map < int , vector < int > > graph ; unordered_map < int , vector < int > > graph_rev ; for ( int i = 0 ; i < edges . size ( ) ; i ++ ) { int x = edges [ i ] [ 0 ] ; int y = edges [ i ] [ 1 ] ; graph [ x ] . push_back ( y ) ; graph_rev [ y ] . push_back ( x ) ; } queue < int > q ; vector < int > visited ( n , 0 ) ; q . push ( 0 ) ; int ans = 0 ; while ( ! q . empty ( ) ) { int curr = q . front ( ) ; visited [ curr ] = 1 ; int count = 0 ; q . pop ( ) ; for ( int i = 0 ; i < graph_rev [ curr ] . size ( ) ; i ++ ) { if ( ! visited [ graph_rev [ curr ] [ i ] ] ) { q . push ( graph_rev [ curr ] [ i ] ) ; } } for ( int i = 0 ; i < graph [ curr ] . size ( ) ; i ++ ) { if ( ! visited [ graph [ curr ] [ i ] ] ) { q . push ( graph [ curr ] [ i ] ) ; count ++ ; } } ans += count ; } return ans ; } int main ( ) { vector < vector < int > > edges ; edges = { { 0 , 1 } , { 1 , 3 } , { 2 , 3 } , { 4 , 0 } , { 4 , 5 } } ; int n = 6 ; cout << minRev ( edges , n ) ; return 0 ; }
Partition a set into two subsets such that difference between max of one and min of other is minimized | C ++ program for the above approach ; Function to split the array ; Sort the array in increasing order ; Calculating the max difference between consecutive elements ; Return the final minimum difference ; Driver Code ; Given array arr [ ] ; Size of array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int splitArray ( int arr [ ] , int N ) { sort ( arr , arr + N ) ; int result = INT_MAX ; for ( int i = 1 ; i < N ; i ++ ) { result = min ( result , arr [ i ] - arr [ i - 1 ] ) ; } return result ; } int main ( ) { int arr [ ] = { 3 , 1 , 2 , 6 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << splitArray ( arr , N ) ; return 0 ; }
Find the element at R ' th ▁ row ▁ and ▁ C ' th column in given a 2D pattern | C ++ implementation to compute the R ' th ▁ row ▁ and ▁ C ' th column of the given pattern ; Function to compute the R ' th ▁ row ▁ and ▁ C ' th column of the given pattern ; First element of a given row ; Element in the given column ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findValue ( int R , int C ) { int k = ( R * ( R - 1 ) ) / 2 + 1 ; int diff = R + 1 ; for ( int i = 1 ; i < C ; i ++ ) { k = ( k + diff ) ; diff ++ ; } return k ; } int main ( ) { int R = 4 ; int C = 4 ; int k = findValue ( R , C ) ; cout << k ; return 0 ; }
Maximize number of groups formed with size not smaller than its largest element | C ++ implementation of above approach ; Function that prints the number of maximum groups ; Store the number of occurrence of elements ; Make all groups of similar elements and store the left numbers ; Condition for finding first leftover element ; Condition for current leftover element ; Condition if group size is equal to or more than current element ; Printing maximum number of groups ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void makeGroups ( int a [ ] , int n ) { vector < int > v ( n + 1 , 0 ) ; for ( int i = 0 ; i < n ; i ++ ) { v [ a [ i ] ] ++ ; } int no_of_groups = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { no_of_groups += v [ i ] / i ; v [ i ] = v [ i ] % i ; } int i = 1 ; int total = 0 ; for ( i = 1 ; i <= n ; i ++ ) { if ( v [ i ] != 0 ) { total = v [ i ] ; break ; } } i ++ ; while ( i <= n ) { if ( v [ i ] != 0 ) { total += v [ i ] ; if ( total >= i ) { int rem = total - i ; no_of_groups ++ ; total = rem ; } } i ++ ; } cout << no_of_groups << " STRNEWLINE " ; } int main ( ) { int arr [ ] = { 2 , 3 , 1 , 2 , 2 } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; makeGroups ( arr , size ) ; return 0 ; }
Leftmost Column with atleast one 1 in a row | C ++ program to calculate leftmost column having at least a 1 ; Function return leftmost column having at least a 1 ; If current element is 1 decrement column by 1 ; If current element is 0 increment row by 1 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 3 NEW_LINE #define M 4 NEW_LINE int FindColumn ( int mat [ N ] [ M ] ) { int row = 0 , col = M - 1 ; int flag = 0 ; while ( row < N && col >= 0 ) { if ( mat [ row ] [ col ] == 1 ) { col -- ; flag = 1 ; } else { row ++ ; } } col ++ ; if ( flag ) return col + 1 ; else return -1 ; } int main ( ) { int mat [ N ] [ M ] = { { 0 , 0 , 0 , 1 } , { 0 , 1 , 1 , 1 } , { 0 , 0 , 1 , 1 } } ; cout << FindColumn ( mat ) ; return 0 ; }
Find two numbers made up of a given digit such that their difference is divisible by N | C ++ implementation of the above approach ; Function to implement the above approach ; Hashmap to store remainder - length of the number as key - value pairs ; Iterate till N + 1 length ; Search remainder in the map ; If remainder is not already present insert the length for the corresponding remainder ; Keep increasing M ; To keep M in range of integer ; Length of one number is the current Length ; Length of the other number is the length paired with current remainder in map ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findNumbers ( int N , int M ) { int m = M ; map < int , int > remLen ; int len , remainder ; for ( len = 1 ; len <= N + 1 ; ++ len ) { remainder = M % N ; if ( remLen . find ( remainder ) == remLen . end ( ) ) remLen [ remainder ] = len ; else break ; M = M * 10 + m ; M = M % N ; } int LenA = len ; int LenB = remLen [ remainder ] ; for ( int i = 0 ; i < LenB ; ++ i ) cout << m ; cout << " ▁ " ; for ( int i = 0 ; i < LenA ; ++ i ) cout << m ; return ; } int main ( ) { int N = 8 , M = 2 ; findNumbers ( N , M ) ; return 0 ; }
Number of ways to select equal sized subarrays from two arrays having atleast K equal pairs of elements | C ++ implementation to count the number of ways to select equal sized subarrays such that they have atleast K common elements ; 2D prefix sum for submatrix sum query for matrix ; Function to find the prefix sum of the matrix from i and j ; Function to count the number of ways to select equal sized subarrays such that they have atleast K common elements ; Combining the two arrays ; Calculating the 2D prefix sum ; iterating through all the elements of matrix and considering them to be the bottom right ; applying binary search over side length ; if sum of this submatrix >= k then new search space will be [ low , mid ] ; else new search space will be [ mid + 1 , high ] ; Adding the total submatrices ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int prefix_2D [ 2005 ] [ 2005 ] ; int subMatrixSum ( int i , int j , int len ) { return prefix_2D [ i ] [ j ] - prefix_2D [ i ] [ j - len ] - prefix_2D [ i - len ] [ j ] + prefix_2D [ i - len ] [ j - len ] ; } int numberOfWays ( int a [ ] , int b [ ] , int n , int m , int k ) { for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { if ( a [ i - 1 ] == b [ j - 1 ] ) prefix_2D [ i ] [ j ] = 1 ; else prefix_2D [ i ] [ j ] = 0 ; } } for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { prefix_2D [ i ] [ j ] += prefix_2D [ i ] [ j - 1 ] ; } } for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { prefix_2D [ i ] [ j ] += prefix_2D [ i - 1 ] [ j ] ; } } int answer = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { int low = 1 ; int high = min ( i , j ) ; while ( low < high ) { int mid = ( low + high ) >> 1 ; if ( subMatrixSum ( i , j , mid ) >= k ) { high = mid ; } else { low = mid + 1 ; } } if ( subMatrixSum ( i , j , low ) >= k ) { answer += ( min ( i , j ) - low + 1 ) ; } } } return answer ; } int main ( ) { int N = 2 , M = 3 ; int A [ N ] = { 1 , 2 } ; int B [ M ] = { 1 , 2 , 3 } ; int K = 1 ; cout << numberOfWays ( A , B , N , M , K ) ; return 0 ; }
Find lexicographically smallest string in at most one swaps | C ++ implementation of the above approach ; Function to return the lexicographically smallest string that can be formed by swapping at most one character . The characters might not necessarily be adjacent . ; Store last occurrence of every character ; Set - 1 as default for every character . ; Character index to fill in the last occurrence array ; If this is true then this character is being visited for the first time from the last Thus last occurrence of this character is stored in this index ; Character to replace ; Find the last occurrence of this character . ; Swap this with the last occurrence ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string findSmallest ( string s ) { int len = s . size ( ) ; int loccur [ 26 ] ; memset ( loccur , -1 , sizeof ( loccur ) ) ; for ( int i = len - 1 ; i >= 0 ; -- i ) { int chI = s [ i ] - ' a ' ; if ( loccur [ chI ] == -1 ) { loccur [ chI ] = i ; } } string sorted_s = s ; sort ( sorted_s . begin ( ) , sorted_s . end ( ) ) ; for ( int i = 0 ; i < len ; ++ i ) { if ( s [ i ] != sorted_s [ i ] ) { int chI = sorted_s [ i ] - ' a ' ; int last_occ = loccur [ chI ] ; swap ( s [ i ] , s [ last_occ ] ) ; break ; } } return s ; } int main ( ) { string s = " geeks " ; cout << findSmallest ( s ) ; return 0 ; }
Maximum size of square such that all submatrices of that size have sum less than K | C ++ implementation to find the maximum size square submatrix such that their sum is less than K ; Size of matrix ; Function to preprocess the matrix for computing the sum of every possible matrix of the given size ; Loop to copy the first row of the matrix into the aux matrix ; Computing the sum column - wise ; Computing row wise sum ; Function to find the sum of a submatrix with the given indices ; Overall sum from the top to right corner of matrix ; Removing the sum from the top corer of the matrix ; Remove the overlapping sum ; Add the sum of top corner which is subtracted twice ; Function to check whether square sub matrices of size mid satisfy the condition or not ; Iterating throught all possible submatrices of given size ; Function to find the maximum square size possible with the such that every submatrix have sum less than the given sum ; Search space ; Binary search for size ; Check if the mid satisfies the given condition ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 4 NEW_LINE #define M 5 NEW_LINE void preProcess ( int mat [ N ] [ M ] , int aux [ N ] [ M ] ) { for ( int i = 0 ; i < M ; i ++ ) aux [ 0 ] [ i ] = mat [ 0 ] [ i ] ; for ( int i = 1 ; i < N ; i ++ ) for ( int j = 0 ; j < M ; j ++ ) aux [ i ] [ j ] = mat [ i ] [ j ] + aux [ i - 1 ] [ j ] ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 1 ; j < M ; j ++ ) aux [ i ] [ j ] += aux [ i ] [ j - 1 ] ; } int sumQuery ( int aux [ N ] [ M ] , int tli , int tlj , int rbi , int rbj ) { int res = aux [ rbi ] [ rbj ] ; if ( tli > 0 ) res = res - aux [ tli - 1 ] [ rbj ] ; if ( tlj > 0 ) res = res - aux [ rbi ] [ tlj - 1 ] ; if ( tli > 0 && tlj > 0 ) res = res + aux [ tli - 1 ] [ tlj - 1 ] ; return res ; } bool check ( int mid , int aux [ N ] [ M ] , int K ) { bool satisfies = true ; for ( int x = 0 ; x < N ; x ++ ) { for ( int y = 0 ; y < M ; y ++ ) { if ( x + mid - 1 <= N - 1 && y + mid - 1 <= M - 1 ) { if ( sumQuery ( aux , x , y , x + mid - 1 , y + mid - 1 ) > K ) satisfies = false ; } } } return ( satisfies == true ) ; } int maximumSquareSize ( int mat [ N ] [ M ] , int K ) { int aux [ N ] [ M ] ; preProcess ( mat , aux ) ; int low = 1 , high = min ( N , M ) ; int mid ; while ( high - low > 1 ) { mid = ( low + high ) / 2 ; if ( check ( mid , aux , K ) ) { low = mid ; } else high = mid ; } if ( check ( high , aux , K ) ) return high ; return low ; } int main ( ) { int K = 30 ; int mat [ N ] [ M ] = { { 1 , 2 , 3 , 4 , 6 } , { 5 , 3 , 8 , 1 , 2 } , { 4 , 6 , 7 , 5 , 5 } , { 2 , 4 , 8 , 9 , 4 } } ; cout << maximumSquareSize ( mat , K ) ; return 0 ; }
Length of Longest Subarray with same elements in atmost K increments | C ++ program to find the length of Longest Subarray with same elements in atmost K increments ; Initialize array for segment tree ; Function that builds the segment tree to return the max element in a range ; update the value in segment tree from given array ; find the middle index ; If there are more than one elements , then recur for left and right subtrees and store the max of values in this node ; Function to return the max element in the given range ; If the range is out of bounds , return - 1 ; Function that returns length of longest subarray with same elements in atmost K increments . ; Initialize the result variable Even though the K is 0 , the required longest subarray , in that case , will also be of length 1 ; Initialize the prefix sum array ; Build the prefix sum array ; Build the segment tree for range max query ; Loop through the array with a starting point as i for the required subarray till the longest subarray is found ; Performing the binary search to find the endpoint for the selected range ; Find the mid for binary search ; Find the max element in the range [ i , mid ] using Segment Tree ; Total sum of subarray after increments ; Actual sum of elements before increments ; Check if such increment is possible If true , then current i is the actual starting point of the required longest subarray ; Now for finding the endpoint for this range Perform the Binary search again with the updated start ; Store max end point for the range to give longest subarray ; If false , it means that the selected range is invalid ; Perform the Binary Search again with the updated end ; Store the length of longest subarray ; Return result ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int segment_tree [ 4 * 1000000 ] ; int build ( int * A , int start , int end , int node ) { if ( start == end ) segment_tree [ node ] = A [ start ] ; else { int mid = ( start + end ) / 2 ; segment_tree [ node ] = max ( build ( A , start , mid , 2 * node + 1 ) , build ( A , mid + 1 , end , 2 * node + 2 ) ) ; } return segment_tree [ node ] ; } int query ( int start , int end , int l , int r , int node ) { if ( start > r end < l ) return -1 ; if ( start >= l && end <= r ) return segment_tree [ node ] ; int mid = ( start + end ) / 2 ; return max ( query ( start , mid , l , r , 2 * node + 1 ) , query ( mid + 1 , end , l , r , 2 * node + 2 ) ) ; } int longestSubArray ( int * A , int N , int K ) { int res = 1 ; int preSum [ N + 1 ] ; preSum [ 0 ] = A [ 0 ] ; for ( int i = 0 ; i < N ; i ++ ) preSum [ i + 1 ] = preSum [ i ] + A [ i ] ; build ( A , 0 , N - 1 , 0 ) ; for ( int i = 0 ; i < N ; i ++ ) { int start = i , end = N - 1 , mid , max_index = i ; while ( start <= end ) { mid = ( start + end ) / 2 ; int max_element = query ( 0 , N - 1 , i , mid , 0 ) ; int expected_sum = ( mid - i + 1 ) * max_element ; int actual_sum = preSum [ mid + 1 ] - preSum [ i ] ; if ( expected_sum - actual_sum <= K ) { start = mid + 1 ; max_index = max ( max_index , mid ) ; } else { end = mid - 1 ; } } res = max ( res , max_index - i + 1 ) ; } return res ; } int main ( ) { int arr [ ] = { 2 , 0 , 4 , 6 , 7 } , K = 6 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << longestSubArray ( arr , N , K ) ; return 0 ; }
Count of numbers from range [ L , R ] that end with any of the given digits | C ++ implementation of the approach ; Function to return the count of the required numbers ; Last digit of the current number ; If the last digit is equal to any of the given digits ; Driver code
#include <iostream> NEW_LINE using namespace std ; int countNums ( int l , int r ) { int cnt = 0 ; for ( int i = l ; i <= r ; i ++ ) { int lastDigit = ( i % 10 ) ; if ( ( lastDigit % 10 ) == 2 || ( lastDigit % 10 ) == 3 || ( lastDigit % 10 ) == 9 ) { cnt ++ ; } } return cnt ; } int main ( ) { int l = 11 , r = 33 ; cout << countNums ( l , r ) ; }
Minimum K such that sum of array elements after division by K does not exceed S | C ++ implementation of the approach ; Function to return the minimum value of k that satisfies the given condition ; Find the maximum element ; Lowest answer can be 1 and the highest answer can be ( maximum + 1 ) ; Binary search ; Get the mid element ; Calculate the sum after dividing the array by new K which is mid ; Search in the second half ; First half ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinimumK ( int a [ ] , int n , int s ) { int maximum = a [ 0 ] ; for ( int i = 0 ; i < n ; i ++ ) { maximum = max ( maximum , a [ i ] ) ; } int low = 1 , high = maximum + 1 ; int ans = high ; while ( low <= high ) { int mid = ( low + high ) / 2 ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += ( int ) ( a [ i ] / mid ) ; } if ( sum > s ) low = mid + 1 ; else { ans = min ( ans , mid ) ; high = mid - 1 ; } } return ans ; } int main ( ) { int a [ ] = { 10 , 7 , 8 , 10 , 12 , 19 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int s = 27 ; cout << findMinimumK ( a , n , s ) ; return 0 ; }
Calculate the Sum of GCD over all subarrays | C ++ program to find Sum of GCD over all subarrays ; int a [ 100001 ] ; ; Build Sparse Table ; Building the Sparse Table for GCD [ L , R ] Queries ; Utility Function to calculate GCD in range [ L , R ] ; Calculating where the answer is stored in our Sparse Table ; Utility Function to find next - farther position where gcd is same ; BinarySearch for Next Position for EndPointer ; Utility function to calculate sum of gcd ; Initializing all the values ; Finding the next position for endPointer ; Adding the suitable sum to our answer ; Changing prevEndPointer ; Recalculating tempGCD ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int SparseTable [ 100001 ] [ 51 ] ; void buildSparseTable ( int a [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { SparseTable [ i ] [ 0 ] = a [ i ] ; } for ( int j = 1 ; j <= 19 ; j ++ ) { for ( int i = 0 ; i <= n - ( 1 << j ) ; i ++ ) { SparseTable [ i ] [ j ] = __gcd ( SparseTable [ i ] [ j - 1 ] , SparseTable [ i + ( 1 << ( j - 1 ) ) ] [ j - 1 ] ) ; } } } int queryForGCD ( int L , int R ) { int returnValue ; int j = int ( log2 ( R - L + 1 ) ) ; returnValue = __gcd ( SparseTable [ L ] [ j ] , SparseTable [ R - ( 1 << j ) + 1 ] [ j ] ) ; return returnValue ; } int nextPosition ( int tempGCD , int startPointer , int prevEndPointer , int n ) { int high = n - 1 ; int low = prevEndPointer ; int mid = prevEndPointer ; int nextPos = prevEndPointer ; while ( high >= low ) { mid = ( ( high + low ) >> 1 ) ; if ( queryForGCD ( startPointer , mid ) == tempGCD ) { nextPos = mid ; low = mid + 1 ; } else { high = mid - 1 ; } } return nextPos + 1 ; } int calculateSum ( int a [ ] , int n ) { buildSparseTable ( a , n ) ; int endPointer , startPointer , prevEndPointer , tempGCD ; int tempAns = 0 ; for ( int i = 0 ; i < n ; i ++ ) { endPointer = i ; startPointer = i ; prevEndPointer = i ; tempGCD = a [ i ] ; while ( endPointer < n ) { endPointer = nextPosition ( tempGCD , startPointer , prevEndPointer , n ) ; tempAns += ( ( endPointer - prevEndPointer ) * tempGCD ) ; prevEndPointer = endPointer ; if ( endPointer < n ) { tempGCD = __gcd ( tempGCD , a [ endPointer ] ) ; } } } return tempAns ; } int main ( ) { int n = 6 ; int a [ ] = { 2 , 2 , 2 , 3 , 5 , 5 } ; cout << calculateSum ( a , n ) << " STRNEWLINE " ; return 0 ; }
QuickSelect ( A Simple Iterative Implementation ) | CPP program for iterative implementation of QuickSelect ; Standard Lomuto partition function ; Implementation of QuickSelect ; Partition a [ left . . right ] around a pivot and find the position of the pivot ; If pivot itself is the k - th smallest element ; If there are more than k - 1 elements on left of pivot , then k - th smallest must be on left side . ; Else k - th smallest is on right side . ; Driver program to test above methods
#include <bits/stdc++.h> NEW_LINE using namespace std ; int partition ( int arr [ ] , int low , int high ) { int pivot = arr [ high ] ; int i = ( low - 1 ) ; for ( int j = low ; j <= high - 1 ; j ++ ) { if ( arr [ j ] <= pivot ) { i ++ ; swap ( arr [ i ] , arr [ j ] ) ; } } swap ( arr [ i + 1 ] , arr [ high ] ) ; return ( i + 1 ) ; } int kthSmallest ( int a [ ] , int left , int right , int k ) { while ( left <= right ) { int pivotIndex = partition ( a , left , right ) ; if ( pivotIndex == k - 1 ) return a [ pivotIndex ] ; else if ( pivotIndex > k - 1 ) right = pivotIndex - 1 ; else left = pivotIndex + 1 ; } return -1 ; } int main ( ) { int arr [ ] = { 10 , 4 , 5 , 8 , 11 , 6 , 26 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 5 ; cout << " K - th ▁ smallest ▁ element ▁ is ▁ " << kthSmallest ( arr , 0 , n - 1 , k ) ; return 0 ; }
Pair with largest sum which is less than K in the array | CPP program to find pair with largest sum which is less than K in the array ; Function to find pair with largest sum which is less than K in the array ; To store the break point ; Sort the given array ; Find the break point ; No need to look beyond i 'th index ; Find the required pair ; Print the required answer ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void Max_Sum ( int arr [ ] , int n , int k ) { int p = n ; sort ( arr , arr + n ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] >= k ) { p = i ; break ; } } int maxsum = 0 , a , b ; for ( int i = 0 ; i < p ; i ++ ) { for ( int j = i + 1 ; j < p ; j ++ ) { if ( arr [ i ] + arr [ j ] < k and arr [ i ] + arr [ j ] > maxsum ) { maxsum = arr [ i ] + arr [ j ] ; a = arr [ i ] ; b = arr [ j ] ; } } } cout << a << " ▁ " << b ; } int main ( ) { int arr [ ] = { 5 , 20 , 110 , 100 , 10 } , k = 85 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; Max_Sum ( arr , n , k ) ; return 0 ; }
Maximum length palindromic substring such that it starts and ends with given char | C ++ implementation of the approach ; Function that returns true if str [ i ... j ] is a palindrome ; Function to return the length of the longest palindromic sub - string such that it starts and ends with the character ch ; If current character is a valid starting index ; Instead of finding the ending index from the beginning , find the index from the end This is because if the current sub - string is a palindrome then there is no need to check the sub - strings of smaller length and we can skip to the next iteration of the outer loop ; If current character is a valid ending index ; If str [ i ... j ] is a palindrome then update the length of the maximum palindrome so far ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( string str , int i , int j ) { while ( i < j ) { if ( str [ i ] != str [ j ] ) return false ; i ++ ; j -- ; } return true ; } int maxLenPalindrome ( string str , int n , char ch ) { int maxLen = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == ch ) { for ( int j = n - 1 ; j >= i ; j -- ) { if ( str [ j ] == ch ) { if ( isPalindrome ( str , i , j ) ) { maxLen = max ( maxLen , j - i + 1 ) ; break ; } } } } } return maxLen ; } int main ( ) { string str = " lapqooqpqpl " ; int n = str . length ( ) ; char ch = ' p ' ; cout << maxLenPalindrome ( str , n , ch ) ; return 0 ; }
Longest sub | C ++ implementation of the approach ; Function to find the starting and the ending index of the sub - array with equal number of alphabets and numeric digits ; If its an alphabet ; Else its a number ; Pick a starting point as i ; Consider all sub - arrays starting from i ; If this is a 0 sum sub - array then compare it with maximum size sub - array calculated so far ; If no valid sub - array found ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findSubArray ( int arr [ ] , int n ) { int sum = 0 ; int maxsize = -1 , startindex ; for ( int i = 0 ; i < n ; i ++ ) { if ( isalpha ( arr [ i ] ) ) { arr [ i ] = 0 ; } else { arr [ i ] = 1 ; } } for ( int i = 0 ; i < n - 1 ; i ++ ) { sum = ( arr [ i ] == 0 ) ? -1 : 1 ; for ( int j = i + 1 ; j < n ; j ++ ) { ( arr [ j ] == 0 ) ? ( sum += -1 ) : ( sum += 1 ) ; if ( sum == 0 && maxsize < j - i + 1 ) { maxsize = j - i + 1 ; startindex = i ; } } } if ( maxsize == -1 ) cout << maxsize ; else cout << startindex << " ▁ " << ( startindex + maxsize - 1 ) ; } int main ( ) { int arr [ ] = { ' A ' , ' B ' , ' X ' , 4 , 6 , ' X ' , ' a ' } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findSubArray ( arr , size ) ; return 0 ; }
Check if given string can be formed by two other strings or their permutations | C ++ implementation of the approach ; Function to sort the given string using counting sort ; Array to store the count of each character ; Insert characters in the string in increasing order ; Function that returns true if str can be generated from any permutation of the two strings selected from the given vector ; Sort the given string ; Select two strings at a time from given vector ; Get the concatenated string ; Sort the resultant string ; If the resultant string is equal to the given string str ; No valid pair found ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 26 NEW_LINE void countingsort ( string & s ) { int count [ MAX ] = { 0 } ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { count [ s [ i ] - ' a ' ] ++ ; } int index = 0 ; for ( int i = 0 ; i < MAX ; i ++ ) { int j = 0 ; while ( j < count [ i ] ) { s [ index ++ ] = i + ' a ' ; j ++ ; } } } bool isPossible ( vector < string > v , string str ) { countingsort ( str ) ; for ( int i = 0 ; i < v . size ( ) - 1 ; i ++ ) { for ( int j = i + 1 ; j < v . size ( ) ; j ++ ) { string temp = v [ i ] + v [ j ] ; countingsort ( temp ) ; if ( temp . compare ( str ) == 0 ) { return true ; } } } return false ; } int main ( ) { string str = " amazon " ; vector < string > v { " fds " , " oxq " , " zoa " , " epw " , " amn " } ; if ( isPossible ( v , str ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Queries to find the first non | C ++ implementation of the approach ; Maximum distinct characters possible ; To store the frequency of the characters ; Function to pre - calculate the frequency array ; Only the first character has frequency 1 till index 0 ; Starting from the second character of the string ; For every possible character ; Current character under consideration ; If it is equal to the character at the current index ; Function to return the frequency of the given character in the sub - string str [ l ... r ] ; Function to return the first non - repeating character in range [ l . . r ] ; Starting from the first character ; Current character ; If frequency of the current character is 1 then return the character ; All the characters of the sub - string are repeating ; Driver code ; Pre - calculate the frequency array
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 256 NEW_LINE int freq [ MAX ] [ MAX ] ; void preCalculate ( string str , int n ) { freq [ ( int ) str [ 0 ] ] [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { char ch = str [ i ] ; for ( int j = 0 ; j < MAX ; j ++ ) { char charToUpdate = j ; if ( charToUpdate == ch ) freq [ j ] [ i ] = freq [ j ] [ i - 1 ] + 1 ; else freq [ j ] [ i ] = freq [ j ] [ i - 1 ] ; } } } int getFrequency ( char ch , int l , int r ) { if ( l == 0 ) return freq [ ( int ) ch ] [ r ] ; else return ( freq [ ( int ) ch ] [ r ] - freq [ ( int ) ch ] [ l - 1 ] ) ; } string firstNonRepeating ( string str , int n , int l , int r ) { char t [ 2 ] = " " ; for ( int i = l ; i < r ; i ++ ) { char ch = str [ i ] ; if ( getFrequency ( ch , l , r ) == 1 ) { t [ 0 ] = ch ; return t ; } } return " - 1" ; } int main ( ) { string str = " GeeksForGeeks " ; int n = str . length ( ) ; int queries [ ] [ 2 ] = { { 0 , 3 } , { 2 , 3 } , { 5 , 12 } } ; int q = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; freq [ MAX ] [ n ] = { 0 } ; preCalculate ( str , n ) ; for ( int i = 0 ; i < q ; i ++ ) cout << firstNonRepeating ( str , n , queries [ i ] [ 0 ] , queries [ i ] [ 1 ] ) << endl ; return 0 ; }
Length of the largest substring which have character with frequency greater than or equal to half of the substring | C ++ implementation of the above approach ; Function to return the length of the longest sub string having frequency of a character greater than half of the length of the sub string ; for each of the character ' a ' to ' z ' ; finding frequency prefix array of the character ; Finding the r [ ] and l [ ] arrays . ; for each j from 0 to n ; Finding the lower bound of i . ; storing the maximum value of i - j + 1 ; clearing all the vector so that it clearing be use for other character . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxLength ( string s , int n ) { int ans = INT_MIN ; vector < int > A , L , R ; int freq [ n + 5 ] ; for ( int i = 0 ; i < 26 ; i ++ ) { int count = 0 ; memset ( freq , 0 , sizeof freq ) ; for ( int j = 0 ; j < n ; j ++ ) { if ( s [ j ] - ' a ' == i ) count ++ ; freq [ j ] = count ; } for ( int j = 0 ; j < n ; j ++ ) { L . push_back ( ( 2 * freq [ j - 1 ] ) - j ) ; R . push_back ( ( 2 * freq [ j ] ) - j ) ; } int max_len = INT_MIN ; int min_val = INT_MAX ; for ( int j = 0 ; j < n ; j ++ ) { min_val = min ( min_val , L [ j ] ) ; A . push_back ( min_val ) ; int l = 0 , r = j ; while ( l <= r ) { int mid = ( l + r ) >> 1 ; if ( A [ mid ] <= R [ j ] ) { max_len = max ( max_len , j - mid + 1 ) ; r = mid - 1 ; } else { l = mid + 1 ; } } } ans = max ( ans , max_len ) ; A . clear ( ) ; R . clear ( ) ; L . clear ( ) ; } return ans ; } int main ( ) { string s = " ababbbacbcbcca " ; int n = s . length ( ) ; cout << maxLength ( s , n ) << ' ' ; return 0 ; }
Repeated Character Whose First Appearance is Leftmost | CPP program to find first repeating character ; The function returns index of the first repeating character in a string . If all characters are repeating then returns - 1 ; Mark all characters as not visited ; Traverse from right and update res as soon as we see a visited character . ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define NO_OF_CHARS 256 NEW_LINE int firstRepeating ( string & str ) { bool visited [ NO_OF_CHARS ] ; for ( int i = 0 ; i < NO_OF_CHARS ; i ++ ) visited [ i ] = false ; int res = -1 ; for ( int i = str . length ( ) - 1 ; i >= 0 ; i -- ) { if ( visited [ str [ i ] ] == false ) visited [ str [ i ] ] = true ; else res = i ; } return res ; } int main ( ) { string str = " geeksforgeeks " ; int index = firstRepeating ( str ) ; if ( index == -1 ) printf ( " Either ▁ all ▁ characters ▁ are ▁ " " distinct ▁ or ▁ string ▁ is ▁ empty " ) ; else printf ( " First ▁ Repeating ▁ character " " ▁ is ▁ % c " , str [ index ] ) ; return 0 ; }
Find maximum sum taking every Kth element in the array | C ++ implementation of the approach ; Function to return the maximum sum for every possible sequence such that a [ i ] + a [ i + k ] + a [ i + 2 k ] + ... + a [ i + qk ] is maximized ; Initialize the maximum with the smallest value ; Initialize the sum array with zero ; Iterate from the right ; Update the sum starting at the current element ; Update the maximum so far ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSum ( int arr [ ] , int n , int K ) { int maximum = INT_MIN ; int sum [ n ] = { 0 } ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( i + K < n ) sum [ i ] = sum [ i + K ] + arr [ i ] ; else sum [ i ] = arr [ i ] ; maximum = max ( maximum , sum [ i ] ) ; } return maximum ; } int main ( ) { int arr [ ] = { 3 , 6 , 4 , 7 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 2 ; cout << maxSum ( arr , n , K ) ; return ( 0 ) ; }
Count common characters in two strings | C ++ implementation of the approach ; Function to return the count of valid indices pairs ; To store the frequencies of characters of string s1 and s2 ; To store the count of valid pairs ; Update the frequencies of the characters of string s1 ; Update the frequencies of the characters of string s2 ; Find the count of valid pairs ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( string s1 , int n1 , string s2 , int n2 ) { int freq1 [ 26 ] = { 0 } ; int freq2 [ 26 ] = { 0 } ; int i , count = 0 ; for ( i = 0 ; i < n1 ; i ++ ) freq1 [ s1 [ i ] - ' a ' ] ++ ; for ( i = 0 ; i < n2 ; i ++ ) freq2 [ s2 [ i ] - ' a ' ] ++ ; for ( i = 0 ; i < 26 ; i ++ ) count += ( min ( freq1 [ i ] , freq2 [ i ] ) ) ; return count ; } int main ( ) { string s1 = " geeksforgeeks " , s2 = " platformforgeeks " ; int n1 = s1 . length ( ) , n2 = s2 . length ( ) ; cout << countPairs ( s1 , n1 , s2 , n2 ) ; return 0 ; }
Find a distinct pair ( x , y ) in given range such that x divides y | C ++ implementation of the approach ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findpair ( int l , int r ) { int c = 0 ; for ( int i = l ; i <= r ; i ++ ) { for ( int j = i + 1 ; j <= r ; j ++ ) { if ( j % i == 0 && j != i ) { cout << i << " , ▁ " << j ; c = 1 ; break ; } } if ( c == 1 ) break ; } } int main ( ) { int l = 1 , r = 10 ; findpair ( l , r ) ; }
Check if the given array can be reduced to zeros with the given operation performed given number of times | C ++ implementation of the approach ; Function that returns true if the array can be reduced to 0 s with the given operation performed given number of times ; Set to store unique elements ; Add every element of the array to the set ; Count of all the unique elements in the array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int arr [ ] , int N , int K ) { set < int > unique ; for ( int i = 0 ; i < N ; i ++ ) unique . insert ( arr [ i ] ) ; if ( unique . size ( ) == K ) return true ; return false ; } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; if ( check ( arr , N , K ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Print all the sum pairs which occur maximum number of times | C ++ implementation of the approach ; Function to find the sum pairs that occur the most ; Hash - table ; Keep a count of sum pairs ; Variables to store maximum occurrence ; Iterate in the hash table ; Print all sum pair which occur maximum number of times ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findSumPairs ( int a [ ] , int n ) { unordered_map < int , int > mpp ; for ( int i = 0 ; i < n - 1 ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { mpp [ a [ i ] + a [ j ] ] ++ ; } } int occur = 0 ; for ( auto it : mpp ) { if ( it . second > occur ) { occur = it . second ; } } for ( auto it : mpp ) { if ( it . second == occur ) cout << it . first << endl ; } } int main ( ) { int a [ ] = { 1 , 8 , 3 , 11 , 4 , 9 , 2 , 7 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; findSumPairs ( a , n ) ; return 0 ; }
Minimum index i such that all the elements from index i to given index are equal | C ++ implementation of the approach ; Function to return the minimum required index ; Start from arr [ pos - 1 ] ; All elements are equal from arr [ i + 1 ] to arr [ pos ] ; Driver code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minIndex ( int arr [ ] , int n , int pos ) { int num = arr [ pos ] ; int i = pos - 1 ; while ( i >= 0 ) { if ( arr [ i ] != num ) break ; i -- ; } return i + 1 ; } int main ( ) { int arr [ ] = { 2 , 1 , 1 , 1 , 5 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int pos = 4 ; cout << minIndex ( arr , n , pos ) ; return 0 ; }
Minimum index i such that all the elements from index i to given index are equal | C ++ implementation of the approach ; Function to return the minimum required index ; Short - circuit more comparisions as found the border point ; For cases were high = low + 1 and arr [ high ] will match with arr [ pos ] but not arr [ low ] or arr [ mid ] . In such iteration the if condition will satisfy and loop will break post that low will be updated . Hence i will not point to the correct index . ; Driver code ; cout << minIndex ( arr , 2 ) << endl ; Should be 1 cout << minIndex ( arr , 3 ) << endl ; Should be 1 cout << minIndex ( arr , 4 ) << endl ; Should be 4
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minIndex ( int arr [ ] , int pos ) { int low = 0 ; int high = pos ; int i = pos ; while ( low < high ) { int mid = ( low + high ) / 2 ; if ( arr [ mid ] != arr [ pos ] ) { low = mid + 1 ; } else { high = mid - 1 ; i = mid ; if ( mid > 0 && arr [ mid - 1 ] != arr [ pos ] ) { break ; } } } return arr [ low ] == arr [ pos ] ? low : i ; } int main ( ) { int arr [ ] = { 2 , 1 , 1 , 1 , 5 , 2 } ; return 0 ; }
Count of strings that become equal to one of the two strings after one removal | C ++ implementation of the approach ; Function to return the count of the required strings ; Searching index after longest common prefix ends ; Searching index before longest common suffix ends ; If str1 = str2 ; If only 1 character is different in both the strings ; Checking remaining part of string for equality ; Searching in right of string h ( g to h ) ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findAnswer ( string str1 , string str2 , int n ) { int l , r ; int ans = 2 ; for ( int i = 0 ; i < n ; ++ i ) { if ( str1 [ i ] != str2 [ i ] ) { l = i ; break ; } } for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( str1 [ i ] != str2 [ i ] ) { r = i ; break ; } } if ( r < l ) return 26 * ( n + 1 ) ; else if ( l == r ) return ans ; else { for ( int i = l + 1 ; i <= r ; i ++ ) { if ( str1 [ i ] != str2 [ i - 1 ] ) { ans -- ; break ; } } for ( int i = l + 1 ; i <= r ; i ++ ) { if ( str1 [ i - 1 ] != str2 [ i ] ) { ans -- ; break ; } } return ans ; } } int main ( ) { string str1 = " toy " , str2 = " try " ; int n = str1 . length ( ) ; cout << findAnswer ( str1 , str2 , n ) ; return 0 ; }