text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Check if all strings of an array can be made same by interchanging characters | C ++ Program to implement the above approach ; Function to check if all strings are equal after swap operations ; Stores the frequency of characters ; Stores the length of string ; Traverse the array ; Traverse each string ; Check if frequency of character is divisible by N ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkEqual ( string arr [ ] , int N ) { int hash [ 256 ] = { 0 } ; int M = arr [ 0 ] . length ( ) ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { hash [ arr [ i ] [ j ] ] ++ ; } } for ( int i = 0 ; i < 256 ; i ++ ) { if ( hash [ i ] % N != 0 ) { return false ; } } return true ; } int main ( ) { string arr [ ] = { " fdd " , " fhh " } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( checkEqual ( arr , N ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; } |
Maximize sum of remaining elements after every removal of the array half with greater sum | C ++ program to implement the above approach ; Function to find the maximum sum ; Base Case ; Check if ( mapped key is found in the dictionary ; Traverse the array ; Store left prefix sum ; Store right prefix sum ; Compare the left and right values ; Store the value in dp array ; Return the final answer ; Function to print maximum sum ; Stores prefix sum ; Store results of subproblems ; Traversing the array ; Add prefix sum of array ; Print the answer ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 100 ] [ 100 ] ; int maxweight ( int s , int e , map < int , int > pre ) { if ( s == e ) return 0 ; if ( dp [ s ] [ e ] != -1 ) return dp [ s ] [ e ] ; int ans = 0 ; for ( int i = s ; i < e ; i ++ ) { int left = pre [ i ] - pre [ s - 1 ] ; int right = pre [ e ] - pre [ i ] ; if ( left < right ) ans = max ( ans , ( int ) ( left + maxweight ( s , i , pre ) ) ) ; if ( left == right ) ans = max ( ans , max ( left + maxweight ( s , i , pre ) , right + maxweight ( i + 1 , e , pre ) ) ) ; if ( left > right ) ans = max ( ans , right + maxweight ( i + 1 , e , pre ) ) ; dp [ s ] [ e ] = ans ; } return dp [ s ] [ e ] ; } void maxSum ( int arr [ ] , int n ) { map < int , int > pre ; pre [ -1 ] = 0 ; pre [ 0 ] = arr [ 0 ] ; memset ( dp , -1 , sizeof dp ) ; for ( int i = 0 ; i < n ; i ++ ) pre [ i ] = pre [ i - 1 ] + arr [ i ] ; cout << ( maxweight ( 0 , n - 1 , pre ) ) ; } int main ( ) { int arr [ ] = { 6 , 2 , 3 , 4 , 5 , 5 } ; maxSum ( arr , 6 ) ; } |
Find K smallest leaf nodes from a given Binary Tree | C ++ program of the above approach ; Structure of binary tree node ; Function to create new node ; Utility function which calculates smallest three nodes of all leaf nodes ; Check if current root is a leaf node ; Traverse the left and right subtree ; Function to find the K smallest nodes of the Binary Tree ; Sorting the Leaf nodes array ; Loop to print the K smallest Leaf nodes of the array ; Driver Code ; Construct binary tree ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int data ) { Node * temp = new Node ( ) ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } void storeLeaf ( Node * root , vector < int > & arr ) { if ( ! root ) return ; if ( ! root -> left and ! root -> right ) { arr . push_back ( root -> data ) ; return ; } storeLeaf ( root -> left , arr ) ; storeLeaf ( root -> right , arr ) ; } void KSmallest ( Node * root , int k ) { vector < int > arr ; storeLeaf ( root , arr ) ; sort ( arr . begin ( ) , arr . end ( ) ) ; for ( int i = 0 ; i < k ; i ++ ) { if ( i < arr . size ( ) ) { cout << arr [ i ] << " β " ; } else { break ; } } } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> left -> left = newNode ( 21 ) ; root -> left -> right = newNode ( 5 ) ; root -> left -> right -> right = newNode ( 8 ) ; root -> right = newNode ( 3 ) ; root -> right -> left = newNode ( 6 ) ; root -> right -> right = newNode ( 7 ) ; root -> right -> right -> right = newNode ( 19 ) ; KSmallest ( root , 3 ) ; return 0 ; } |
Check if all the pairs of an array are coprime with each other | C ++ implementation of the above approach ; Function to check if all the pairs of the array are coprime with each other or not ; Check if GCD of the pair is not equal to 1 ; All pairs are non - coprime Return false ; ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool allCoprime ( int A [ ] , int n ) { bool all_coprime = true ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( __gcd ( A [ i ] , A [ j ] ) != 1 ) { all_coprime = false ; break ; } } } return all_coprime ; } ' ' Function return gcd of two number ' ' ' int main ( ) { int A [ ] = { 3 , 5 , 11 , 7 , 19 } ; int arr_size = sizeof ( A ) / sizeof ( A [ 0 ] ) ; if ( allCoprime ( A , arr_size ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; } |
Smallest power of 2 consisting of N digits | C ++ Program of the above approach ; Function to return smallest power of 2 consisting of N digits ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int smallestNum ( int n ) { float power = log2 ( 10 ) ; cout << power ; return ceil ( ( n - 1 ) * power ) ; } int main ( ) { int n = 4 ; cout << smallestNum ( n ) ; return 0 ; } |
Find a valid parenthesis sequence of length K from a given valid parenthesis sequence | C ++ program for the above approach ; Function to find the subsequence of length K forming valid sequence ; Stores the resultant string ; Check whether character at index i is visited or not ; Traverse the string ; Push index of open bracket ; Pop and mark visited ; Increment count by 2 ; Append the characters and create the resultant string ; Return the resultant string ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE #define ll long long NEW_LINE using namespace std ; string findString ( string s , int k ) { int n = s . length ( ) ; string ans = " " ; stack < int > st ; vector < bool > vis ( n , false ) ; int count = 0 ; Vector < boolean > vis ( n , false ) ; for ( int i = 0 ; i < n ; ++ i ) { if ( s [ i ] == ' ( ' ) { st . push ( i ) ; } if ( count < k && s [ i ] == ' ) ' ) { vis [ st . top ( ) ] = 1 ; st . pop ( ) ; vis [ i ] = true ; count += 2 ; } } for ( int i = 0 ; i < n ; ++ i ) { if ( vis [ i ] == true ) { ans += s [ i ] ; } } return ans ; } int main ( ) { string s = " ( ) ( ) ( ) " ; int K = 2 ; cout << findString ( s , K ) ; } |
Node having maximum number of nodes less than its value in its subtree | C ++ program for the above approach ; Stores the nodes to be deleted ; Structure of a Tree node ; Function to create a new node ; Function to compare the current node key with keys received from it left & right tree by Post Order traversal ; Base Case ; Find nodes lesser than the current root in the left subtree ; Find nodes lesser than the current root in the right subtree ; Stores all the nodes less than the current node 's ; Add the nodes which are less than current node in left [ ] ; Add the nodes which are less than current node in right [ ] ; Create a combined vector for pass to it 's parent ; Stores key that has maximum nodes ; Return the vector of nodes ; Driver Code ; Given Tree ; Function Call ; Print the node value | #include <bits/stdc++.h> NEW_LINE using namespace std ; unordered_map < int , bool > mp ; struct Node { int key ; struct Node * left , * right ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return ( temp ) ; } vector < int > findNodes ( Node * root , int & max_v , int & rootIndex ) { if ( ! root ) { return vector < int > { } ; } vector < int > left = findNodes ( root -> left , max_v , rootIndex ) ; vector < int > right = findNodes ( root -> right , max_v , rootIndex ) ; vector < int > combined ; int count = 0 ; for ( int i = 0 ; i < left . size ( ) ; i ++ ) { if ( left [ i ] < root -> key ) { count += 1 ; } combined . push_back ( left [ i ] ) ; } for ( int i = 0 ; i < right . size ( ) ; i ++ ) { if ( right [ i ] < root -> key ) { count += 1 ; } combined . push_back ( right [ i ] ) ; } combined . push_back ( root -> key ) ; if ( count > max_v ) { rootIndex = root -> key ; max_v = count ; } return combined ; } int main ( ) { Node * root = newNode ( 3 ) ; root -> left = newNode ( 4 ) ; root -> right = newNode ( 6 ) ; root -> right -> left = newNode ( 4 ) ; root -> right -> right = newNode ( 5 ) ; root -> left -> left = newNode ( 10 ) ; root -> left -> right = newNode ( 2 ) ; int max_v = 0 ; int rootIndex = -1 ; findNodes ( root , max_v , rootIndex ) ; cout << rootIndex ; } |
Maximum sum path in a matrix from top | C ++ program for the above approach ; Function to find the maximum sum path in the grid ; Dimensions of grid [ ] [ ] ; Stores maximum sum at each cell sum [ i ] [ j ] from cell sum [ 0 ] [ 0 ] ; Iterate to compute the maximum sum path in the grid ; Update the maximum path sum ; Return the maximum sum ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int MaximumPath ( vector < vector < int > > & grid ) { int N = grid . size ( ) ; int M = grid [ 0 ] . size ( ) ; vector < vector < int > > sum ; sum . resize ( N + 1 , vector < int > ( M + 1 ) ) ; for ( int i = 1 ; i <= N ; i ++ ) { for ( int j = 1 ; j <= M ; j ++ ) { sum [ i ] [ j ] = max ( sum [ i - 1 ] [ j ] , sum [ i ] [ j - 1 ] ) + grid [ i - 1 ] [ j - 1 ] ; } } return sum [ N ] [ M ] ; } int main ( ) { vector < vector < int > > grid = { { 1 , 2 } , { 3 , 5 } } ; cout << MaximumPath ( grid ) ; return 0 ; } |
Maximize cost of deletions to obtain string having no pair of similar adjacent characters | C ++ program for the above approach ; Function to find maximum cost to remove consecutive characters ; Initialize the count ; Maximum cost ; Traverse from 0 to len ( s ) - 2 ; If characters are identical ; Add cost [ i ] if its maximum ; Add cost [ i + 1 ] if its maximum ; Increment i ; Return the final max count ; Driver Code ; Given string s ; Given cost of removal ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Maxcost ( string s , int cost [ ] ) { int count = 0 ; int maxcost = 0 , i = 0 ; while ( i < s . size ( ) - 1 ) { if ( s [ i ] == s [ i + 1 ] ) { if ( cost [ i ] > cost [ i + 1 ] ) maxcost += cost [ i ] ; else { maxcost += cost [ i + 1 ] ; cost [ i + 1 ] = cost [ i ] ; } } i += 1 ; } return maxcost ; } int main ( ) { string s = " abaac " ; int cost [ ] = { 1 , 2 , 3 , 4 , 5 } ; cout << Maxcost ( s , cost ) ; return 0 ; } |
Maximum count of values of S modulo M lying in a range [ L , R ] after performing given operations on the array | C ++ program for the above approach ; Lookup table ; Function to count the value of S after adding arr [ i ] or arr [ i - 1 ] to the sum S at each time ; Base Case ; Store the mod value ; If the mod value lies in the range then return 1 ; Else return 0 ; Store the current state ; If already computed , return the computed value ; Recursively adding the elements to the sum adding ai value ; Adding arr [ i ] - 1 value ; Return the maximum count to check for root value as well ; Avoid counting idx = 0 as possible solution we are using idx != 0 ; Return the value of current state ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; map < pair < int , int > , int > dp ; int countMagicNumbers ( int idx , int sum , int a [ ] , int n , int m , int l , int r ) { if ( idx == n ) { int temp = sum % m ; if ( temp == l || temp == r || ( temp > l && temp < r ) ) return dp [ { idx , sum } ] = 1 ; else return dp [ { idx , sum } ] = 0 ; } pair < int , int > curr = make_pair ( idx , sum ) ; if ( dp . find ( curr ) != dp . end ( ) ) return dp [ curr ] ; int ls = countMagicNumbers ( idx + 1 , sum + a [ idx ] , a , n , m , l , r ) ; int rs = countMagicNumbers ( idx + 1 , sum + ( a [ idx ] - 1 ) , a , n , m , l , r ) ; int temp1 = max ( ls , rs ) ; int temp = sum % m ; if ( ( temp == l || temp == r || ( temp > l && temp < r ) ) && idx != 0 ) { temp1 += 1 ; } return dp [ { idx , sum } ] = temp1 ; } int main ( ) { int N = 5 , M = 22 , L = 14 , R = 16 ; int arr [ ] = { 17 , 11 , 10 , 8 , 15 } ; cout << countMagicNumbers ( 0 , 0 , arr , N , M , L , R ) ; return 0 ; } |
Check if a path exists for a cell valued 1 to reach the bottom right corner of a Matrix before any cell valued 2 | C ++ program for the above approach ; Function to check if cell with value 1 doesn 't reaches the bottom right cell or not ; Number of rows and columns ; Initialise the deque ; Traverse the matrix ; Push 1 to front of queue ; Push 2 to back of queue ; Store all the possible direction of the current cell ; Run multi - source BFS ; Get the front element ; Pop the front element ; If 1 reached corner first ; Insert new point in queue ; If 1 can 't reach the bottom right then return false ; Driver Code ; Given matrix ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool reachesBottom ( vector < vector < int > > & a ) { int n = a . size ( ) ; int m = a [ 0 ] . size ( ) ; deque < vector < int > > q ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( a [ i ] [ j ] == 1 ) { q . push_front ( { i , j , 1 } ) ; } else if ( a [ i ] [ j ] == 2 ) { q . push_back ( { i , j , 2 } ) ; } a [ i ] [ j ] = 0 ; } } int dx [ ] = { -1 , 0 , 1 , 0 } ; int dy [ ] = { 0 , 1 , 0 , -1 } ; while ( ! q . empty ( ) ) { auto front = q . front ( ) ; q . pop_front ( ) ; int i = front [ 0 ] , j = front [ 1 ] ; int t = front [ 2 ] ; if ( a [ i ] [ j ] ) continue ; a [ i ] [ j ] = 1 ; if ( t == 1 and ( i == n - 1 && j == m - 1 ) ) { return true ; } for ( int d = 0 ; d < 4 ; d ++ ) { int ni = i + dx [ d ] ; int nj = j + dy [ d ] ; if ( ni >= 0 and ni < n and nj > = 0 and nj < m ) { q . push_back ( { ni , nj , t } ) ; } } } return false ; } int main ( ) { vector < vector < int > > matrix { { 0 , 2 , 0 } , { 0 , 1 , 0 } , { 0 , 2 , 0 } } ; if ( reachesBottom ( matrix ) ) { cout << " YES " ; } else { cout << " NO " ; } return 0 ; } |
Smallest element from all square submatrices of size K from a given Matrix | C ++ Program for the above approach ; Function to returns a smallest elements of all KxK submatrices of a given NxM matrix ; Stores the dimensions of the given matrix ; Stores the required smallest elements ; Update the smallest elements row - wise ; Update the minimum column - wise ; Store the final submatrix with required minimum values ; Return the resultant matrix ; Function Call ; Print resultant matrix with the minimum values of KxK sub - matrix ; Driver Code ; Given matrix ; Given K | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < vector < int > > matrixMinimum ( vector < vector < int > > nums , int K ) { int N = nums . size ( ) ; int M = nums [ 0 ] . size ( ) ; vector < vector < int > > res ( N - K + 1 , vector < int > ( M - K + 1 ) ) ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M - K + 1 ; j ++ ) { int mini = INT_MAX ; for ( int k = j ; k < j + K ; k ++ ) { mini = min ( mini , nums [ i ] [ k ] ) ; } nums [ i ] [ j ] = mini ; } } for ( int j = 0 ; j < M ; j ++ ) { for ( int i = 0 ; i < N - K + 1 ; i ++ ) { int mini = INT_MAX ; for ( int k = i ; k < i + K ; k ++ ) { mini = min ( mini , nums [ k ] [ j ] ) ; } nums [ i ] [ j ] = mini ; } } for ( int i = 0 ; i < N - K + 1 ; i ++ ) for ( int j = 0 ; j < M - K + 1 ; j ++ ) res [ i ] [ j ] = nums [ i ] [ j ] ; return res ; } void smallestinKsubmatrices ( vector < vector < int > > arr , int K ) { vector < vector < int > > res = matrixMinimum ( arr , K ) ; for ( int i = 0 ; i < res . size ( ) ; i ++ ) { for ( int j = 0 ; j < res [ 0 ] . size ( ) ; j ++ ) { cout << res [ i ] [ j ] << " β " ; } cout << endl ; } } int main ( ) { vector < vector < int > > arr = { { -1 , 5 , 4 , 1 , -3 } , { 4 , 3 , 1 , 1 , 6 } , { 2 , -2 , 5 , 3 , 1 } , { 8 , 5 , 1 , 9 , -4 } , { 12 , 3 , 5 , 8 , 1 } } ; int K = 3 ; smallestinKsubmatrices ( arr , K ) ; } |
Queries to find Kth greatest character in a range [ L , R ] from a string with updates | C ++ Program to implement the above approach ; Function to find the kth greatest character from the strijng ; Sorting the string in non - increasing Order ; Function to print the K - th character from the substring S [ l ] . . S [ r ] ; 0 - based indexing ; Substring of str from the indices l to r . ; Extract kth Largest character ; Function to replace character at pos of str by the character s ; Index of S to be updated . ; Character to be replaced at index in S ; Driver Code ; Given string ; Count of queries ; Queries | #include " bits / stdc + + . h " NEW_LINE using namespace std ; char find_kth_largest ( string str , int k ) { sort ( str . begin ( ) , str . end ( ) , greater < char > ( ) ) ; return str [ k - 1 ] ; } char printCharacter ( string str , int l , int r , int k ) { l = l - 1 ; r = r - 1 ; string temp = str . substr ( l , r - l + 1 ) ; char ans = find_kth_largest ( temp , k ) ; return ans ; } void updateString ( string str , int pos , char s ) { int index = pos - 1 ; char c = s ; str [ index ] = c ; } int main ( ) { string str = " abcddef " ; int Q = 3 ; cout << printCharacter ( str , 1 , 2 , 2 ) << endl ; updateString ( str , 4 , ' g ' ) ; cout << printCharacter ( str , 1 , 5 , 4 ) << endl ; return 0 ; } |
Split array into two subarrays such that difference of their sum is minimum | C ++ program for above approach ; Function to return minimum difference between sum of two subarrays ; To store total sum of array ; Calculate the total sum of the array ; Stores the prefix sum ; Stores the minimum difference ; Traverse the given array ; To store minimum difference ; Update minDiff ; Return minDiff ; Driver code ; Given array ; Length of the array | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minDiffSubArray ( int arr [ ] , int n ) { int total_sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) total_sum += arr [ i ] ; int prefix_sum = 0 ; int minDiff = INT_MAX ; for ( int i = 0 ; i < n - 1 ; i ++ ) { prefix_sum += arr [ i ] ; int diff = abs ( ( total_sum - prefix_sum ) - prefix_sum ) ; if ( diff < minDiff ) minDiff = diff ; } return minDiff ; } int main ( ) { int arr [ ] = { 7 , 9 , 5 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minDiffSubArray ( arr , n ) << endl ; return 0 ; } |
Maximize count of non | C ++ Program to implement the above approach ; Function to count the maximum number of subarrays with sum K ; Stores all the distinct prefixSums obtained ; Stores the prefix sum of the current subarray ; Stores the count of subarrays with sum K ; If a subarray with sum K is already found ; Increase count ; Reset prefix sum ; Clear the set ; Insert the prefix sum ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int CtSubarr ( int arr [ ] , int N , int K ) { unordered_set < int > st ; int prefixSum = 0 ; st . insert ( prefixSum ) ; int res = 0 ; for ( int i = 0 ; i < N ; i ++ ) { prefixSum += arr [ i ] ; if ( st . count ( prefixSum - K ) ) { res += 1 ; prefixSum = 0 ; st . clear ( ) ; st . insert ( 0 ) ; } st . insert ( prefixSum ) ; } return res ; } int main ( ) { int arr [ ] = { -2 , 6 , 6 , 3 , 5 , 4 , 1 , 2 , 8 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 10 ; cout << CtSubarr ( arr , N , K ) ; } |
Count of subarrays consisting of only prime numbers | C ++ Program to implement the above approach ; Function to check if a number is prime or not . ; If n has any factor other than 1 , then n is non - prime . ; Function to return the count of subarrays made up of prime numbers only ; Stores the answer ; Stores the count of continuous prime numbers in an array ; If the current array element is prime ; Increase the count ; Update count of subarrays ; If the array ended with a continuous prime sequence ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool is_prime ( int n ) { if ( n <= 1 ) return 0 ; for ( int i = 2 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) return 0 ; } return 1 ; } int count_prime_subarrays ( int ar [ ] , int n ) { int ans = 0 ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( is_prime ( ar [ i ] ) ) count ++ ; else { if ( count ) { ans += count * ( count + 1 ) / 2 ; count = 0 ; } } } if ( count ) ans += count * ( count + 1 ) / 2 ; return ans ; } int main ( ) { int N = 10 ; int ar [ ] = { 2 , 3 , 5 , 6 , 7 , 11 , 3 , 5 , 9 , 3 } ; cout << count_prime_subarrays ( ar , N ) ; } |
Minimum Subarray flips required to convert all elements of a Binary Array to K | C ++ 14 Program to implement the above approach ; Function to count the minimum number of subarray flips required ; Iterate the array ; If arr [ i ] and flag are equal ; Return the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minSteps ( int arr [ ] , int n , int k ) { int i , cnt = 0 ; int flag ; if ( k == 1 ) flag = 0 ; else flag = 1 ; for ( i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == flag ) { cnt ++ ; flag = ( flag + 1 ) % 2 ; } } return cnt ; } int main ( ) { int arr [ ] = { 1 , 0 , 1 , 0 , 0 , 1 , 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 1 ; cout << minSteps ( arr , n , k ) ; return 0 ; } |
Minimize Sum of an Array by at most K reductions | C ++ program to implement the above approach ; Function to obtain the minimum possible sum from the array by K reductions ; Implements the MaxHeap ; Insert elements into the MaxHeap ; Remove the maximum ; Insert maximum / 2 ; Stores the sum of remaining elements ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minSum ( int a [ ] , int n , int k ) { priority_queue < int > q ; for ( int i = 0 ; i < n ; i ++ ) { q . push ( a [ i ] ) ; } while ( ! q . empty ( ) && k > 0 ) { int top = q . top ( ) / 2 ; q . pop ( ) ; q . push ( top ) ; k -= 1 ; } int sum = 0 ; while ( ! q . empty ( ) ) { sum += q . top ( ) ; q . pop ( ) ; } return sum ; } int main ( ) { int n = 4 ; int k = 3 ; int a [ ] = { 20 , 7 , 5 , 4 } ; cout << ( minSum ( a , n , k ) ) ; return 0 ; } |
Sum of indices of Characters removed to obtain an Empty String based on given conditions | C ++ Program to implement the above approach ; Function to add index of the deleted character ; If index is beyond the range ; Insert the index of the deleted characeter ; Search over the subtrees to find the desired index ; Function to return count of deleted indices which are to the left of the current index ; Function to generate the sum of indices ; Stores the original index of the characters in sorted order of key ; Traverse the map ; Extract smallest index of smallest character ; Delete the character from the map if it has no remaining occurrence ; Stores the original index ; Count of elements removed to the left of current character ; Current index of the current character ; For 1 - based indexing ; Insert the deleted index in the segment tree ; Final answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void add_seg ( int seg [ ] , int start , int end , int current , int index ) { if ( index > end or index < start ) return ; if ( start == end ) { seg [ current ] = 1 ; return ; } int mid = ( start + end ) / 2 ; add_seg ( seg , start , mid , 2 * current + 1 , index ) ; add_seg ( seg , mid + 1 , end , 2 * current + 2 , index ) ; seg [ current ] = seg [ 2 * current + 1 ] + seg [ 2 * current + 2 ] ; } int deleted ( int seg [ ] , int l , int r , int start , int end , int current ) { if ( end < l or start > r ) return 0 ; if ( start >= l and end <= r ) return seg [ current ] ; int mid = ( start + end ) / 2 ; return deleted ( seg , l , r , start , mid , 2 * current + 1 ) + deleted ( seg , l , r , mid + 1 , end , 2 * current + 2 ) ; } void sumOfIndices ( string s ) { int N = s . size ( ) ; int x = int ( ceil ( log2 ( N ) ) ) ; int seg_size = 2 * ( int ) pow ( 2 , x ) - 1 ; int segment [ seg_size ] = { 0 } ; int count = 0 ; map < int , queue < int > > fre ; for ( int i = 0 ; i < N ; i ++ ) { fre [ s [ i ] ] . push ( i ) ; } while ( fre . empty ( ) == false ) { auto it = fre . begin ( ) ; if ( it -> second . empty ( ) == true ) fre . erase ( it -> first ) ; else { int original_index = it -> second . front ( ) ; int curr_index = deleted ( segment , 0 , original_index - 1 , 0 , N - 1 , 0 ) ; int new_index = original_index - curr_index ; count += new_index + 1 ; add_seg ( segment , 0 , N - 1 , 0 , original_index ) ; it -> second . pop ( ) ; } } cout << count << endl ; } int main ( ) { string s = " geeksforgeeks " ; sumOfIndices ( s ) ; } |
Maximum Length of Sequence of Sums of prime factors generated by the given operations | C ++ Program to implement the above approach ; Smallest prime factor array ; Stores if a number is prime or not ; Function to compute all primes using Sieve of Eratosthenes ; Function for finding smallest prime factors for every integer ; Function to find the sum of prime factors of number ; Add smallest prime factor to the sum ; Reduce N ; Return the answer ; Function to return the length of sequence of for the given number ; If the number is prime ; If a previously computed subproblem occurred ; Calculate the sum of prime factors ; Function to return the maximum length of sequence for the given range ; Pre - calculate primes ; Precalculate smallest prime factors ; Iterate over the range ; Update maximum length ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int spf [ 100005 ] ; bool prime [ 100005 ] ; int dp [ 100005 ] ; void sieve ( ) { prime [ 0 ] = prime [ 1 ] = false ; for ( int i = 2 ; i < 100005 ; i ++ ) prime [ i ] = true ; for ( int i = 2 ; i * i < 100005 ; i ++ ) { if ( prime [ i ] ) { for ( int j = i * i ; j < 100005 ; j += i ) { prime [ j ] = false ; } } } } void smallestPrimeFactors ( ) { for ( int i = 0 ; i < 100005 ; i ++ ) spf [ i ] = -1 ; for ( int i = 2 ; i * i < 100005 ; i ++ ) { for ( int j = i ; j < 100005 ; j += i ) { if ( spf [ j ] == -1 ) { spf [ j ] = i ; } } } } int sumOfPrimeFactors ( int n ) { int ans = 0 ; while ( n > 1 ) { ans += spf [ n ] ; n /= spf [ n ] ; } return ans ; } int findLength ( int n ) { if ( prime [ n ] ) { return 1 ; } if ( dp [ n ] ) { return dp [ n ] ; } int sum = sumOfPrimeFactors ( n ) ; return dp [ n ] = 1 + findLength ( sum ) ; } int maxLength ( int n , int m ) { sieve ( ) ; smallestPrimeFactors ( ) ; int ans = INT_MIN ; for ( int i = n ; i <= m ; i ++ ) { if ( i == 4 ) { continue ; } ans = max ( ans , findLength ( i ) ) ; } return ans ; } int main ( ) { int n = 2 , m = 14 ; cout << maxLength ( n , m ) ; } |
Longest Subarray consisting of unique elements from an Array | C ++ program to implement the above approach ; Function to find largest subarray with no duplicates ; Stores index of array elements ; Update j based on previous occurrence of a [ i ] ; Update ans to store maximum length of subarray ; Store the index of current occurrence of a [ i ] ; Return final ans ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int largest_subarray ( int a [ ] , int n ) { unordered_map < int , int > index ; int ans = 0 ; for ( int i = 0 , j = 0 ; i < n ; i ++ ) { j = max ( index [ a [ i ] ] , j ) ; ans = max ( ans , i - j + 1 ) ; index [ a [ i ] ] = i + 1 ; } return ans ; } int32_t main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 1 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << largest_subarray ( arr , n ) ; } |
Count of Ways to obtain given Sum from the given Array elements | C ++ program to implement the above approach ; Function to count the number of ways ; Base Case : Reached the end of the array ; Sum is equal to the required sum ; Recursively check if required sum can be obtained by adding current element or by subtracting the current index element ; Function to call dfs ( ) to calculate the number of ways ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dfs ( int nums [ ] , int S , int curr_sum , int index , int n ) { if ( index == n ) { if ( S == curr_sum ) return 1 ; else return 0 ; } return dfs ( nums , S , curr_sum + nums [ index ] , index + 1 , n ) + dfs ( nums , S , curr_sum - nums [ index ] , index + 1 , n ) ; } int findWays ( int nums [ ] , int S , int n ) { return dfs ( nums , S , 0 , 0 , n ) ; } int main ( ) { int S = 3 ; int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int answer = findWays ( arr , S , n ) ; cout << ( answer ) ; return 0 ; } |
Check if all the Nodes in a Binary Tree having common values are at least D distance apart | C ++ program to implement the above approach ; Structure of a Tree node ; Function to create a new node ; Function to count the frequency of node value present in the tree ; Function that returns the max distance between the nodes that have the same key ; If right and left subtree did not have node whose key is value ; Check if the current node is equal to value ; If the left subtree has no node whose key is equal to value ; If the right subtree has no node whose key is equal to value ; Function that finds if the distance between any same nodes is at most K ; Create the map to look for same value of nodes ; Counting the frequency of nodes ; If the returned value of distance is exceeds dist ; Print the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * left , * right ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return ( temp ) ; } void frequencyCounts ( unordered_map < int , int > & map , Node * root ) { if ( root == NULL ) return ; map [ root -> key ] ++ ; frequencyCounts ( map , root -> left ) ; frequencyCounts ( map , root -> right ) ; } int computeDistance ( Node * root , int value ) { if ( root == NULL ) { return -1 ; } int left = computeDistance ( root -> left , value ) ; int right = computeDistance ( root -> right , value ) ; if ( left == -1 && right == -1 ) { if ( root -> key == value ) { return 1 ; } else return -1 ; } if ( left == -1 ) { return right + 1 ; } if ( right == -1 ) { return left + 1 ; } else { return 1 + max ( left , right ) ; } return -1 ; } void solve ( Node * root , int dist ) { unordered_map < int , int > map ; frequencyCounts ( map , root ) ; int flag = 0 ; for ( auto it = map . begin ( ) ; it != map . end ( ) ; it ++ ) { if ( it -> second > 1 ) { int result = computeDistance ( root , it -> first ) ; if ( result > dist result == -1 ) { flag = 1 ; break ; } } } flag == 0 ? cout << " Yes STRNEWLINE " : cout << " No STRNEWLINE " ; } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 3 ) ; root -> right -> right = newNode ( 4 ) ; root -> right -> left = newNode ( 4 ) ; int dist = 7 ; solve ( root , dist ) ; return 0 ; } |
Minimum Sum of a pair at least K distance apart from an Array | C ++ program to implement the above approach ; Function to find the minimum sum of two elements that are atleast K distance apart ; Length of the array ; Iterate over the array ; Initialize the min value ; Iterate from i + k to N ; Find the minimum ; Update the minimum sum ; Print the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findMinSum ( int A [ ] , int K , int n ) { int minimum_sum = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { int mini = INT_MAX ; for ( int j = i + K ; j < n ; j ++ ) mini = min ( mini , A [ j ] ) ; if ( mini == INT_MAX ) continue ; minimum_sum = min ( minimum_sum , A [ i ] + mini ) ; } cout << ( minimum_sum ) ; } int main ( ) { int A [ ] = { 4 , 2 , 5 , 4 , 3 , 2 , 5 } ; int K = 3 ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; findMinSum ( A , K , n ) ; return 0 ; } |
Absolute distinct count in a Linked List | C ++ Program to print the count of distinct absolute values in a linked list ; Node of a singly linked list ; Function to insert a node at the beginning of a singly Linked List ; Allocate node ; Insert the data ; Point to the current head ; Make the current Node the new head ; Function to return number of distinct absolute values present in the linked list ; Driver Code ; Create the head ; Insert Nodes | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * next ; } ; void push ( Node * * head_ref , int new_data ) { Node * new_node = new Node ( ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } int distinctCount ( Node * head_1 ) { Node * ptr = head_1 ; unordered_set < int > s ; while ( ptr != NULL ) { s . insert ( abs ( ptr -> data ) ) ; ptr = ptr -> next ; } return s . size ( ) ; } int main ( ) { Node * head1 = NULL ; push ( & head1 , -1 ) ; push ( & head1 , -2 ) ; push ( & head1 , 0 ) ; push ( & head1 , 4 ) ; push ( & head1 , 5 ) ; push ( & head1 , 8 ) ; int k = distinctCount ( head1 ) ; cout << k ; return 0 ; } |
Count of all possible pairs having sum of LCM and GCD equal to N | C ++ Program to implement the above approach ; Function to calculate and return LCM of two numbers ; Function to count pairs whose sum of GCD and LCM is equal to N ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int lcm ( int a , int b ) { return ( a * b ) / __gcd ( a , b ) ; } int countPair ( int N ) { int count = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { for ( int j = 1 ; j <= N ; j ++ ) { if ( __gcd ( i , j ) + lcm ( i , j ) == N ) { count ++ ; } } } return count ; } int main ( ) { int N = 14 ; cout << countPair ( N ) ; return 0 ; } |
Minimize cost to color all the vertices of an Undirected Graph using given operation | C ++ Program to find the minimum cost to color all vertices of an Undirected Graph ; Function to add edge in the given graph ; Function to perform DFS traversal and find the node with minimum cost ; Update the minimum cost ; Recur for all connected nodes ; Function to calculate and return the minimum cost of coloring all vertices of the Undirected Graph ; Marks if a vertex is visited or not ; Perform DFS traversal ; If vertex is not visited ; Update minimum cost ; Return the final cost ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 10 NEW_LINE vector < int > adj [ MAX ] ; void addEdge ( int u , int v ) { adj [ u ] . push_back ( v ) ; adj [ v ] . push_back ( u ) ; } void dfs ( int v , int cost [ ] , bool vis [ ] , int & min_cost_node ) { vis [ v ] = true ; min_cost_node = min ( min_cost_node , cost [ v - 1 ] ) ; for ( int i = 0 ; i < adj [ v ] . size ( ) ; i ++ ) { if ( vis [ adj [ v ] [ i ] ] == false ) { dfs ( adj [ v ] [ i ] , cost , vis , min_cost_node ) ; } } } int minimumCost ( int V , int cost [ ] ) { bool vis [ V + 1 ] ; memset ( vis , false , sizeof ( vis ) ) ; int min_cost = 0 ; for ( int i = 1 ; i <= V ; i ++ ) { if ( ! vis [ i ] ) { int min_cost_node = INT_MAX ; dfs ( i , cost , vis , min_cost_node ) ; min_cost += min_cost_node ; } } return min_cost ; } int main ( ) { int V = 6 , E = 5 ; int cost [ ] = { 12 , 25 , 8 , 11 , 10 , 7 } ; addEdge ( 1 , 2 ) ; addEdge ( 1 , 3 ) ; addEdge ( 3 , 2 ) ; addEdge ( 2 , 5 ) ; addEdge ( 4 , 6 ) ; int min_cost = minimumCost ( V , cost ) ; cout << min_cost << endl ; return 0 ; } |
Maximize count of set bits in a root to leaf path in a binary tree | C ++ Program to implement the above approach ; Node structure ; Pointers to left and right child ; Initialize constructor ; Function to find the maximum count of setbits in a root to leaf ; Check if root is not null ; Update the maximum count of setbits ; Traverse left of binary tree ; Traverse right of the binary tree ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxm = 0 ; struct Node { int val ; Node * left , * right ; Node ( int x ) { val = x ; left = NULL ; right = NULL ; } } ; void maxm_setbits ( Node * root , int ans ) { if ( ! root ) return ; if ( root -> left == NULL && root -> right == NULL ) { ans += __builtin_popcount ( root -> val ) ; maxm = max ( ans , maxm ) ; return ; } maxm_setbits ( root -> left , ans + __builtin_popcount ( root -> val ) ) ; maxm_setbits ( root -> right , ans + __builtin_popcount ( root -> val ) ) ; } int main ( ) { Node * root = new Node ( 15 ) ; root -> left = new Node ( 3 ) ; root -> right = new Node ( 7 ) ; root -> left -> left = new Node ( 5 ) ; root -> left -> right = new Node ( 1 ) ; root -> right -> left = new Node ( 31 ) ; root -> right -> right = new Node ( 9 ) ; maxm_setbits ( root , 0 ) ; cout << maxm << endl ; return 0 ; } |
Minimize count of divisions by D to obtain at least K equal array elements | C ++ Program to implement the above approach ; Function to return minimum number of moves required ; Stores the number of moves required to obtain respective values from the given array ; Traverse the array ; Insert 0 into V [ a [ i ] ] as it is the initial state ; Insert the moves required to obtain current a [ i ] ; Traverse v [ ] to obtain minimum count of moves ; Check if there are at least K equal elements for v [ i ] ; Add the sum of minimum K moves ; Update answer ; Return the final answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getMinimumMoves ( int n , int k , int d , vector < int > a ) { int MAX = 100000 ; vector < int > v [ MAX ] ; for ( int i = 0 ; i < n ; i ++ ) { int cnt = 0 ; v [ a [ i ] ] . push_back ( 0 ) ; while ( a [ i ] > 0 ) { a [ i ] /= d ; cnt ++ ; v [ a [ i ] ] . push_back ( cnt ) ; } } int ans = INT_MAX ; for ( int i = 0 ; i < MAX ; i ++ ) { if ( v [ i ] . size ( ) >= k ) { int move = 0 ; sort ( v [ i ] . begin ( ) , v [ i ] . end ( ) ) ; for ( int j = 0 ; j < k ; j ++ ) { move += v [ i ] [ j ] ; } ans = min ( ans , move ) ; } } return ans ; } int main ( ) { int N = 5 , K = 3 , D = 2 ; vector < int > A = { 1 , 2 , 3 , 4 , 5 } ; cout << getMinimumMoves ( N , K , D , A ) ; return 0 ; } |
Longest subarray with odd product | C ++ Program to find the longest subarray with odd product ; Function to return length of longest subarray with odd product ; If even element is encountered ; Update maximum ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Maxlen ( int arr [ ] , int n ) { int ans = 0 ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % 2 == 0 ) count = 0 ; else count ++ ; ans = max ( ans , count ) ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 7 , 2 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << Maxlen ( arr , n ) << endl ; return 0 ; } |
Min difference between maximum and minimum element in all Y size subarrays | C ++ program for the above approach ; Function to get the maximum of all the subarrays of size Y ; ith index of maxarr array will be the index upto which Arr [ i ] is maximum ; Stack is used to find the next larger element and keeps track of index of current iteration ; Loop for remaining indexes ; j < i used to keep track whether jth element is inside or outside the window ; Return submax ; Function to get the minimum for all subarrays of size Y ; ith index of minarr array will be the index upto which Arr [ i ] is minimum ; Stack is used to find the next smaller element and keeping track of index of current iteration ; Loop for remaining indexes ; j < i used to keep track whether jth element is inside or outside the window ; Return submin ; Function to get minimum difference ; Create submin and submax arrays ; Store initial difference ; Calculate temporary difference ; Final minimum difference ; Driver Code ; Given array arr [ ] ; Given subarray size ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > get_submaxarr ( int * arr , int n , int y ) { int j = 0 ; stack < int > stk ; vector < int > maxarr ( n ) ; stk . push ( 0 ) ; for ( int i = 1 ; i < n ; i ++ ) { while ( stk . empty ( ) == false and arr [ i ] > arr [ stk . top ( ) ] ) { maxarr [ stk . top ( ) ] = i - 1 ; stk . pop ( ) ; } stk . push ( i ) ; } while ( ! stk . empty ( ) ) { maxarr [ stk . top ( ) ] = n - 1 ; stk . pop ( ) ; } vector < int > submax ; for ( int i = 0 ; i <= n - y ; i ++ ) { while ( maxarr [ j ] < i + y - 1 or j < i ) { j ++ ; } submax . push_back ( arr [ j ] ) ; } return submax ; } vector < int > get_subminarr ( int * arr , int n , int y ) { int j = 0 ; stack < int > stk ; vector < int > minarr ( n ) ; stk . push ( 0 ) ; for ( int i = 1 ; i < n ; i ++ ) { while ( stk . empty ( ) == false and arr [ i ] < arr [ stk . top ( ) ] ) { minarr [ stk . top ( ) ] = i ; stk . pop ( ) ; } stk . push ( i ) ; } while ( ! stk . empty ( ) ) { minarr [ stk . top ( ) ] = n ; stk . pop ( ) ; } vector < int > submin ; for ( int i = 0 ; i <= n - y ; i ++ ) { while ( minarr [ j ] <= i + y - 1 or j < i ) { j ++ ; } submin . push_back ( arr [ j ] ) ; } return submin ; } void getMinDifference ( int Arr [ ] , int N , int Y ) { vector < int > submin = get_subminarr ( Arr , N , Y ) ; vector < int > submax = get_submaxarr ( Arr , N , Y ) ; int minn = submax [ 0 ] - submin [ 0 ] ; int b = submax . size ( ) ; for ( int i = 1 ; i < b ; i ++ ) { int dif = submax [ i ] - submin [ i ] ; minn = min ( minn , dif ) ; } cout << minn << " STRNEWLINE " ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 3 , 2 , 2 } ; int N = sizeof arr / sizeof arr [ 0 ] ; int Y = 4 ; getMinDifference ( arr , N , Y ) ; return 0 ; } |
Least root of given quadratic equation for value greater than equal to K | C ++ program for the above approach ; Function to calculate value of quadratic equation for some x ; Function to calculate the minimum value of x such that F ( x ) >= K using binary search ; Start and end value for binary search ; Binary Search ; Computing F ( mid ) and F ( mid - 1 ) ; If F ( mid ) >= K and F ( mid - 1 ) < K return mid ; If F ( mid ) < K go to mid + 1 to end ; If F ( mid ) > K go to start to mid - 1 ; If no such value exist ; Driver Code ; Given coefficients of Equations ; Find minimum value of x | #include <bits/stdc++.h> NEW_LINE using namespace std ; int func ( int A , int B , int C , int x ) { return ( A * x * x + B * x + C ) ; } int findMinx ( int A , int B , int C , int K ) { int start = 1 ; int end = ceil ( sqrt ( K ) ) ; while ( start <= end ) { int mid = start + ( end - start ) / 2 ; int x = func ( A , B , C , mid ) ; int Y = func ( A , B , C , mid - 1 ) ; if ( x >= K && Y < K ) { return mid ; } else if ( x < K ) { start = mid + 1 ; } else { end = mid - 1 ; } } return -1 ; } int main ( ) { int A = 3 , B = 4 , C = 5 , K = 6 ; cout << findMinx ( A , B , C , K ) ; return 0 ; } |
Find the node at the center of an N | C ++ implementation of the above approach ; To create tree ; Function to store the path from given vertex to the target vertex in a vector path ; If the target node is found , push it into path vector ; To prevent visiting a node already visited ; Recursive call to the neighbours of current node inorder to get the path ; Function to obtain and return the farthest node from a given vertex ; If the current height is maximum so far , then save the current node ; Iterate over all the neighbours of current node ; This is to prevent visiting a already visited node ; Next call will be at 1 height higher than our current height ; Function to add edges ; Reset to - 1 ; Reset to - 1 ; Stores one end of the diameter ; Reset the maxHeight ; Stores the second end of the diameter ; Store the diameter into the vector path ; Diameter is equal to the path between the two farthest nodes leaf1 and leaf2 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; map < int , vector < int > > tree ; bool getDiameterPath ( int vertex , int targetVertex , int parent , vector < int > & path ) { if ( vertex == targetVertex ) { path . push_back ( vertex ) ; return true ; } for ( auto i : tree [ vertex ] ) { if ( i == parent ) continue ; if ( getDiameterPath ( i , targetVertex , vertex , path ) ) { path . push_back ( vertex ) ; return true ; } } return false ; } void farthestNode ( int vertex , int parent , int height , int & maxHeight , int & maxHeightNode ) { if ( height > maxHeight ) { maxHeight = height ; maxHeightNode = vertex ; } for ( auto i : tree [ vertex ] ) { if ( i == parent ) continue ; farthestNode ( i , vertex , height + 1 , maxHeight , maxHeightNode ) ; } } void addedge ( int a , int b ) { tree [ a ] . push_back ( b ) ; tree [ b ] . push_back ( a ) ; } void FindCenter ( int n ) { int maxHeight = -1 ; int maxHeightNode = -1 ; farthestNode ( 0 , -1 , 0 , maxHeight , maxHeightNode ) ; int leaf1 = maxHeightNode ; maxHeight = -1 ; farthestNode ( maxHeightNode , -1 , 0 , maxHeight , maxHeightNode ) ; int leaf2 = maxHeightNode ; vector < int > path ; getDiameterPath ( leaf1 , leaf2 , -1 , path ) ; int pathSize = path . size ( ) ; if ( pathSize % 2 ) { cout << path [ pathSize / 2 ] << endl ; } else { cout << path [ pathSize / 2 ] << " , β " << path [ ( pathSize - 1 ) / 2 ] << endl ; } } int main ( ) { int N = 4 ; addedge ( 1 , 0 ) ; addedge ( 1 , 2 ) ; addedge ( 1 , 3 ) ; FindCenter ( N ) ; return 0 ; } |
K | C ++ program to find k - th term of N merged Arithmetic Progressions ; Function to count and return the number of values less than equal to N present in the set ; Check whether j - th bit is set bit or not ; Function to implement Binary Search to find K - th element ; Find middle index of the array ; Search in the left half ; Search in the right half ; If exactly K elements are present ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define maxm 1000000000 NEW_LINE int count ( vector < int > v , int n ) { int i , odd = 0 , even = 0 ; int j , d , count ; int t = ( int ) 1 << v . size ( ) ; int size = v . size ( ) ; for ( i = 1 ; i < t ; i ++ ) { d = 1 , count = 0 ; for ( j = 0 ; j < size ; j ++ ) { if ( i & ( 1 << j ) ) { d *= v [ j ] ; count ++ ; } } if ( count & 1 ) odd += n / d ; else even += n / d ; } return ( odd - even ) ; } int BinarySearch ( int l , int r , vector < int > v , int key ) { int mid ; while ( r - l > 1 ) { mid = ( l + r ) / 2 ; if ( key <= count ( v , mid ) ) { r = mid ; } else { l = mid ; } } if ( key == count ( v , l ) ) return l ; else return r ; } int main ( ) { int N = 2 , K = 10 ; vector < int > v = { 2 , 3 } ; cout << BinarySearch ( 1 , maxm , v , K ) << endl ; return 0 ; } |
Find integral points with minimum distance from given set of integers using BFS | C ++ implementation of above approach ; Function to find points at minimum distance ; Hash to store points that are encountered ; Queue to store initial set of points ; Vector to store integral points ; Using bfs to visit nearest points from already visited points ; Get first element from queue ; Check if ( x - 1 ) is not encountered so far ; Update hash with this new element ; Insert ( x - 1 ) into queue ; Push ( x - 1 ) as new element ; Decrement counter by 1 ; Check if ( x + 1 ) is not encountered so far ; Update hash with this new element ; Insert ( x + 1 ) into queue ; Push ( x + 1 ) as new element ; Decrement counter by 1 ; Print result array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minDistancePoints ( int A [ ] , int K , int n ) { map < int , int > m ; queue < int > q ; for ( int i = 0 ; i < n ; ++ i ) { m [ A [ i ] ] = 1 ; q . push ( A [ i ] ) ; } vector < int > ans ; while ( K > 0 ) { int x = q . front ( ) ; q . pop ( ) ; if ( ! m [ x - 1 ] && K > 0 ) { m [ x - 1 ] = 1 ; q . push ( x - 1 ) ; ans . push_back ( x - 1 ) ; K -- ; } if ( ! m [ x + 1 ] && K > 0 ) { m [ x + 1 ] = 1 ; q . push ( x + 1 ) ; ans . push_back ( x + 1 ) ; K -- ; } } for ( auto i : ans ) cout << i << " β " ; } int main ( ) { int A [ ] = { -1 , 4 , 6 } ; int K = 3 ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; minDistancePoints ( A , K , n ) ; return 0 ; } |
Leftmost Column with atleast one 1 in a row | C ++ implementation to find the Leftmost Column with atleast a 1 in a sorted binary matrix ; Function to search for the leftmost column of the matrix with atleast a 1 in sorted binary matrix ; Loop to iterate over all the rows of the matrix ; Binary Search to find the leftmost occurence of the 1 ; Condition if the column contains the 1 at this position of matrix ; If there is a better solution then update the answer ; Condition if the solution doesn 't exist in the matrix ; Driver Code | #include <bits/stdc++.h> NEW_LINE #define N 3 NEW_LINE using namespace std ; int search ( int mat [ ] [ 3 ] , int n , int m ) { int i , a = INT_MAX ; for ( i = 0 ; i < n ; i ++ ) { int low = 0 ; int high = m - 1 ; int mid ; int ans = INT_MAX ; while ( low <= high ) { mid = ( low + high ) / 2 ; if ( mat [ i ] [ mid ] == 1 ) { if ( mid == 0 ) { ans = 0 ; break ; } else if ( mat [ i ] [ mid - 1 ] == 0 ) { ans = mid ; break ; } } if ( mat [ i ] [ mid ] == 1 ) high = mid - 1 ; else low = mid + 1 ; } if ( ans < a ) a = ans ; } if ( a == INT_MAX ) return -1 ; return a + 1 ; } int main ( ) { int mat [ 3 ] [ 3 ] = { 0 , 0 , 0 , 0 , 0 , 1 , 0 , 1 , 1 } ; cout << search ( mat , 3 , 3 ) ; return 0 ; } |
Largest index for each distinct character in given string with frequency K | C ++ implementation of the approach ; Function to find largest index for each distinct character occuring exactly K times . ; finding all characters present in S ; Finding all distinct characters in S ; vector to store result for each character ; loop through each lower case English character ; if current character is absent in s ; getting current character ; finding count of character ch in S ; to store max Index encountred so far ; printing required result ; If no such character exists , print - 1 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void maxSubstring ( string & S , int K , int N ) { int freq [ 26 ] ; memset ( freq , 0 , sizeof freq ) ; for ( int i = 0 ; i < N ; ++ i ) { freq [ S [ i ] - ' a ' ] = 1 ; } vector < pair < char , int > > answer ; for ( int i = 0 ; i < 26 ; ++ i ) { if ( freq [ i ] == 0 ) continue ; char ch = i + 97 ; int count = 0 ; int index = -1 ; for ( int j = 0 ; j < N ; ++ j ) { if ( S [ j ] == ch ) count ++ ; if ( count == K ) index = j ; } answer . push_back ( { ch , index } ) ; } int flag = 0 ; for ( int i = 0 ; i < ( int ) answer . size ( ) ; ++ i ) { if ( answer [ i ] . second > -1 ) { flag = 1 ; cout << answer [ i ] . first << " β " << answer [ i ] . second << endl ; } } if ( flag == 0 ) cout << " - 1" << endl ; } int main ( ) { string S = " cbaabaacbcd " ; int K = 2 ; int N = S . length ( ) ; maxSubstring ( S , K , N ) ; return 0 ; } |
Smallest number greater than n that can be represented as a sum of distinct power of k | C ++ implementation of the above approach ; Function to find the smallest number greater than or equal to n represented as the sum of distinct powers of k ; Vector P to store the base k representation of the number ; If the representation is >= 2 , then this power of k has to be added once again and then increase the next power of k and make the current power 0 ; Reduce all the lower power of k to 0 ; Check if the most significant bit also satisfy the above conditions ; Converting back from the k - nary representation to decimal form . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; typedef long long ll ; #define pb push_back NEW_LINE void greaterK ( ll n , ll k ) { vector < ll > p ; ll x = n ; while ( x ) { p . pb ( x % k ) ; x /= k ; } int idx = 0 ; for ( ll i = 0 ; i < ( ll ) p . size ( ) - 1 ; ++ i ) { if ( p [ i ] >= 2 ) { p [ i ] = 0 ; p [ i + 1 ] ++ ; for ( int j = idx ; j < i ; ++ j ) { p [ j ] = 0 ; } idx = i + 1 ; } if ( p [ i ] == k ) { p [ i ] = 0 ; p [ i + 1 ] ++ ; } } ll j = ( ll ) p . size ( ) - 1 ; if ( p [ j ] >= 2 ) { for ( auto & i : p ) i = 0 ; p . pb ( 1 ) ; } ll ans = 0 ; for ( ll i = p . size ( ) - 1 ; i >= 0 ; -- i ) { ans = ans * k + p [ i ] ; } cout << ans << endl ; } int main ( ) { ll n = 29 , k = 7 ; greaterK ( n , k ) ; return 0 ; } |
Check if the bracket sequence can be balanced with at most one change in the position of a bracket | Set 2 | C ++ implementation of the approach ; Function that returns true if the string can be balanced ; Count to check the difference between the frequencies of ' ( ' and ' ) ' and count_1 is to find the minimum value of freq ( ' ( ' ) - freq ( ' ) ' ) ; Traverse the given string ; Increase the count ; Decrease the count ; Find the minimum value of freq ( ' ( ' ) - freq ( ' ) ' ) ; If the minimum difference is greater than or equal to - 1 and the overall difference is zero ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool canBeBalanced ( string s , int n ) { int count = 0 , count_1 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ' ( ' ) count ++ ; else count -- ; count_1 = min ( count_1 , count ) ; } if ( count_1 >= -1 && count == 0 ) return true ; return false ; } int main ( ) { string s = " ( ) ) ( ) ( " ; int n = s . length ( ) ; if ( canBeBalanced ( s , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Absolute difference between the XOR of Non | C ++ implementation of the approach ; Function to find the absolute difference between the XOR of non - primes and the XOR of primes in the given array ; Find maximum value in the array ; USE SIEVE TO FIND ALL PRIME NUMBERS LESS THAN OR EQUAL TO max_val Create a boolean array " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; Remaining part of SIEVE ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Store the XOR of primes in X1 and the XOR of non primes in X2 ; The number is prime ; The number is non - prime ; Return the absolute difference ; Driver code ; Find the absolute difference | #include <bits/stdc++.h> NEW_LINE using namespace std ; int calculateDifference ( int arr [ ] , int n ) { int max_val = * max_element ( arr , arr + n ) ; vector < bool > prime ( max_val + 1 , true ) ; prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= max_val ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= max_val ; i += p ) prime [ i ] = false ; } } int X1 = 1 , X2 = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ arr [ i ] ] ) { X1 ^= arr [ i ] ; } else if ( arr [ i ] != 1 ) { X2 ^= arr [ i ] ; } } return abs ( X1 - X2 ) ; } int main ( ) { int arr [ ] = { 1 , 3 , 5 , 10 , 15 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << calculateDifference ( arr , n ) ; return 0 ; } |
Search in a trie Recursively | CPP program to search in a trie ; Trie node ; endOfWord is true if the node represents end of a word ; Function will return the new node ( initialized to NULLs ) ; initially assign null to the all child ; function will insert the string in a trie recursively ; Insert a new node ; Recursive call for insertion of a string ; Make the endOfWord true which represents the end of string ; Function call to insert a string ; Function call with necessary arguments ; Function to search the string in a trie recursively ; When a string or any character of a string is not found ; Condition of finding string successfully ; Return true when endOfWord of last node containes true ; Recursive call and return value of function call stack ; Function call to search the string ; If string found ; Driver code ; Function call to insert the string ; Function call to search the string | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define CHILDREN 26 NEW_LINE #define MAX 100 NEW_LINE struct trie { trie * child [ CHILDREN ] ; bool endOfWord ; } ; trie * createNode ( ) { trie * temp = new trie ( ) ; temp -> endOfWord = false ; for ( int i = 0 ; i < CHILDREN ; i ++ ) { temp -> child [ i ] = NULL ; } return temp ; } void insertRecursively ( trie * itr , string str , int i ) { if ( i < str . length ( ) ) { int index = str [ i ] - ' a ' ; if ( itr -> child [ index ] == NULL ) { itr -> child [ index ] = createNode ( ) ; } insertRecursively ( itr -> child [ index ] , str , i + 1 ) ; } else { itr -> endOfWord = true ; } } void insert ( trie * itr , string str ) { insertRecursively ( itr , str , 0 ) ; } bool searchRecursively ( trie * itr , char str [ ] , int i , int len ) { if ( itr == NULL ) return false ; if ( itr -> endOfWord == true && i == len - 1 ) { return true ; } int index = str [ i ] - ' a ' ; return searchRecursively ( itr -> child [ index ] , str , i + 1 , len ) ; } void search ( trie * root , string str ) { char arr [ str . length ( ) + 1 ] ; strcpy ( arr , str . c_str ( ) ) ; if ( searchRecursively ( root , arr , 0 , str . length ( ) + 1 ) ) cout << " found " << endl ; else { cout << " not β found " << endl ; } } int main ( ) { trie * root = createNode ( ) ; insert ( root , " thier " ) ; insert ( root , " there " ) ; insert ( root , " answer " ) ; insert ( root , " any " ) ; search ( root , " anywhere " ) ; search ( root , " answer " ) ; return 0 ; } |
Count duplicates in a given linked list | C ++ implementation of the approach ; Representation of node ; Function to insert a node at the beginning ; Function to count the number of duplicate nodes in the linked list ; Starting from the next node ; If some duplicate node is found ; Return the count of duplicate nodes ; Driver code | #include <iostream> NEW_LINE #include <unordered_set> NEW_LINE using namespace std ; struct Node { int data ; Node * next ; } ; void insert ( Node * * head , int item ) { Node * temp = new Node ( ) ; temp -> data = item ; temp -> next = * head ; * head = temp ; } int countNode ( Node * head ) { int count = 0 ; while ( head -> next != NULL ) { Node * ptr = head -> next ; while ( ptr != NULL ) { if ( head -> data == ptr -> data ) { count ++ ; break ; } ptr = ptr -> next ; } head = head -> next ; } return count ; } int main ( ) { Node * head = NULL ; insert ( & head , 5 ) ; insert ( & head , 7 ) ; insert ( & head , 5 ) ; insert ( & head , 1 ) ; insert ( & head , 7 ) ; cout << countNode ( head ) ; return 0 ; } |
Check if it is possible to form string B from A under the given constraints | C ++ implementation of the approach ; Function that returns true if it is possible to form B from A satisfying the given conditions ; Vector to store the frequency of characters in A ; Vector to store the count of characters used from a particular group of characters ; Store the frequency of the characters ; If a character in B is not present in A ; If count of characters used from a particular group of characters exceeds m ; Update low to the starting index of the next group ; If count of characters used from a particular group of characters has not exceeded m ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPossible ( string A , string B , int b , int m ) { vector < int > S [ 26 ] ; vector < int > box ( A . length ( ) , 0 ) ; for ( int i = 0 ; i < A . length ( ) ; i ++ ) { S [ A [ i ] - ' a ' ] . push_back ( i ) ; } int low = 0 ; for ( int i = 0 ; i < B . length ( ) ; i ++ ) { auto it = lower_bound ( S [ B [ i ] - ' a ' ] . begin ( ) , S [ B [ i ] - ' a ' ] . end ( ) , low ) ; if ( it == S [ B [ i ] - ' a ' ] . end ( ) ) return false ; int count = ( * it ) / b ; box [ count ] = box [ count ] + 1 ; if ( box [ count ] >= m ) { count ++ ; low = ( count ) * b ; } else low = ( * it ) + 1 ; } return true ; } int main ( ) { string A = " abcbbcdefxyz " ; string B = " acdxyz " ; int b = 5 ; int m = 2 ; if ( isPossible ( A , B , b , m ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Remove all occurrences of any element for maximum array sum | Find total sum and frequencies of elements ; Find minimum value to be subtracted . ; Find maximum sum after removal ; Drivers code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSumArray ( int arr [ ] , int n ) { int sum = 0 ; unordered_map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; mp [ arr [ i ] ] ++ ; } int minimum = INT_MAX ; for ( auto x : mp ) minimum = min ( minimum , x . second * x . first ) ; return ( sum - minimum ) ; } int main ( ) { int arr [ ] = { 1 , 1 , 3 , 3 , 2 , 2 , 1 , 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << maxSumArray ( arr , n ) ; return 0 ; } |
Given an array and two integers l and r , find the kth largest element in the range [ l , r ] | C ++ implementation of the approach ; Function to calculate the prefix ; Creating one based indexing ; Initializing and creating prefix array ; Creating a prefix array for every possible value in a given range ; Function to return the kth largest element in the index range [ l , r ] ; Binary searching through the 2d array and only checking the range in which the sub array is a part ; Driver code ; Creating the prefix array for the given array ; Queries ; Perform queries | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1001 NEW_LINE static int prefix [ MAX ] [ MAX ] ; int ar [ MAX ] ; void cal_prefix ( int n , int arr [ ] ) { int i , j ; for ( i = 0 ; i < n ; i ++ ) ar [ i + 1 ] = arr [ i ] ; for ( i = 1 ; i <= 1000 ; i ++ ) { for ( j = 0 ; j <= n ; j ++ ) prefix [ i ] [ j ] = 0 ; for ( j = 1 ; j <= n ; j ++ ) { prefix [ i ] [ j ] = prefix [ i ] [ j - 1 ] + ( int ) ( ar [ j ] <= i ? 1 : 0 ) ; } } } int ksub ( int l , int r , int n , int k ) { int lo , hi , mid ; lo = 1 ; hi = 1000 ; while ( lo + 1 < hi ) { mid = ( lo + hi ) / 2 ; if ( prefix [ mid ] [ r ] - prefix [ mid ] [ l - 1 ] >= k ) hi = mid ; else lo = mid + 1 ; } if ( prefix [ lo ] [ r ] - prefix [ lo ] [ l - 1 ] >= k ) hi = lo ; return hi ; } int main ( ) { int arr [ ] = { 1 , 4 , 2 , 3 , 5 , 7 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 4 ; cal_prefix ( n , arr ) ; int queries [ ] [ 3 ] = { { 1 , n , 1 } , { 2 , n - 2 , 2 } , { 3 , n - 1 , 3 } } ; int q = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; for ( int i = 0 ; i < q ; i ++ ) cout << ksub ( queries [ i ] [ 0 ] , queries [ i ] [ 1 ] , n , queries [ i ] [ 2 ] ) << endl ; return 0 ; } |
Find the number of Islands | Set 2 ( Using Disjoint Set ) | C ++ program to find number of islands using Disjoint Set data structure . ; Class to represent Disjoint Set Data structure ; Initially , all elements are in their own set . ; Finds the representative of the set that x is an element of ; if x is not the parent of itself , then x is not the representative of its set . so we recursively call Find on its parent and move i 's node directly under the representative of this set ; Unites the set that includes x and the set that includes y ; Find the representatives ( or the root nodes ) for x an y ; Elements are in the same set , no need to unite anything . ; If x ' s β rank β is β less β than β y ' s rank Then move x under y so that depth of tree remains less ; Else if y ' s β rank β is β less β than β x ' s rank Then move y under x so that depth of tree remains less ; Else if their ranks are the same ; Then move y under x ( doesn 't matter which one goes where) ; And increment the result tree 's rank by 1 ; Returns number of islands in a [ ] [ ] ; The following loop checks for its neighbours and unites the indexes if both are 1. ; If cell is 0 , nothing to do ; Check all 8 neighbours and do a Union with neighbour 's set if neighbour is also 1 ; Array to note down frequency of each set ; If frequency of set is 0 , increment numberOfIslands ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; class DisjointUnionSets { vector < int > rank , parent ; int n ; public : DisjointUnionSets ( int n ) { rank . resize ( n ) ; parent . resize ( n ) ; this -> n = n ; makeSet ( ) ; } void makeSet ( ) { for ( int i = 0 ; i < n ; i ++ ) parent [ i ] = i ; } int find ( int x ) { if ( parent [ x ] != x ) { return find ( parent [ x ] ) ; } return x ; } void Union ( int x , int y ) { int xRoot = find ( x ) ; int yRoot = find ( y ) ; if ( xRoot == yRoot ) return ; if ( rank [ xRoot ] < rank [ yRoot ] ) parent [ xRoot ] = yRoot ; else if ( rank [ yRoot ] < rank [ xRoot ] ) parent [ yRoot ] = xRoot ; else { parent [ yRoot ] = xRoot ; rank [ xRoot ] = rank [ xRoot ] + 1 ; } } } ; int countIslands ( vector < vector < int > > a ) { int n = a . size ( ) ; int m = a [ 0 ] . size ( ) ; DisjointUnionSets * dus = new DisjointUnionSets ( n * m ) ; for ( int j = 0 ; j < n ; j ++ ) { for ( int k = 0 ; k < m ; k ++ ) { if ( a [ j ] [ k ] == 0 ) continue ; if ( j + 1 < n && a [ j + 1 ] [ k ] == 1 ) dus -> Union ( j * ( m ) + k , ( j + 1 ) * ( m ) + k ) ; if ( j - 1 >= 0 && a [ j - 1 ] [ k ] == 1 ) dus -> Union ( j * ( m ) + k , ( j - 1 ) * ( m ) + k ) ; if ( k + 1 < m && a [ j ] [ k + 1 ] == 1 ) dus -> Union ( j * ( m ) + k , ( j ) * ( m ) + k + 1 ) ; if ( k - 1 >= 0 && a [ j ] [ k - 1 ] == 1 ) dus -> Union ( j * ( m ) + k , ( j ) * ( m ) + k - 1 ) ; if ( j + 1 < n && k + 1 < m && a [ j + 1 ] [ k + 1 ] == 1 ) dus -> Union ( j * ( m ) + k , ( j + 1 ) * ( m ) + k + 1 ) ; if ( j + 1 < n && k - 1 >= 0 && a [ j + 1 ] [ k - 1 ] == 1 ) dus -> Union ( j * m + k , ( j + 1 ) * ( m ) + k - 1 ) ; if ( j - 1 >= 0 && k + 1 < m && a [ j - 1 ] [ k + 1 ] == 1 ) dus -> Union ( j * m + k , ( j - 1 ) * m + k + 1 ) ; if ( j - 1 >= 0 && k - 1 >= 0 && a [ j - 1 ] [ k - 1 ] == 1 ) dus -> Union ( j * m + k , ( j - 1 ) * m + k - 1 ) ; } } int * c = new int [ n * m ] ; int numberOfIslands = 0 ; for ( int j = 0 ; j < n ; j ++ ) { for ( int k = 0 ; k < m ; k ++ ) { if ( a [ j ] [ k ] == 1 ) { int x = dus -> find ( j * m + k ) ; if ( c [ x ] == 0 ) { numberOfIslands ++ ; c [ x ] ++ ; } else c [ x ] ++ ; } } } return numberOfIslands ; } int main ( void ) { vector < vector < int > > a = { { 1 , 1 , 0 , 0 , 0 } , { 0 , 1 , 0 , 0 , 1 } , { 1 , 0 , 0 , 1 , 1 } , { 0 , 0 , 0 , 0 , 0 } , { 1 , 0 , 1 , 0 , 1 } } ; cout << " Number β of β Islands β is : β " << countIslands ( a ) << endl ; } |
Find maximum N such that the sum of square of first N natural numbers is not more than X | C ++ implementation of the approach ; Function to return the sum of the squares of first N natural numbers ; Function to return the maximum N such that the sum of the squares of first N natural numbers is not more than X ; Iterate till maxvalue of N ; If the condition fails then return the i - 1 i . e sum of squares till i - 1 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int squareSum ( int N ) { int sum = ( int ) ( N * ( N + 1 ) * ( 2 * N + 1 ) ) / 6 ; return sum ; } int findMaxN ( int X ) { int N = sqrt ( X ) ; for ( int i = 1 ; i <= N ; i ++ ) { if ( squareSum ( i ) > X ) return i - 1 ; } return -1L ; } int main ( ) { int X = 25 ; cout << findMaxN ( X ) ; return 0 ; } |
Remove exactly one element from the array such that max | C ++ implementation of the above approach ; function to calculate max - min ; There should be at - least two elements ; To store first and second minimums ; To store first and second maximums ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int max_min ( int a [ ] , int n ) { if ( n <= 1 ) return INT_MAX ; int f_min = a [ 0 ] , s_min = INT_MAX ; int f_max = a [ 0 ] , s_max = INT_MIN ; for ( int i = 1 ; i < n ; i ++ ) { if ( a [ i ] <= f_min ) { s_min = f_min ; f_min = a [ i ] ; } else if ( a [ i ] < s_min ) { s_min = a [ i ] ; } if ( a [ i ] >= f_max ) { s_max = f_max ; f_max = a [ i ] ; } else if ( a [ i ] > s_max ) { s_max = a [ i ] ; } } return min ( ( f_max - s_min ) , ( s_max - f_min ) ) ; } int main ( ) { int a [ ] = { 1 , 3 , 3 , 7 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << max_min ( a , n ) ; return 0 ; } |
Minimum in an array which is first decreasing then increasing | C ++ program to find the smallest number in an array of decrease and increasing numbers ; Function to find the smallest number 's index ; Do a binary search ; Find the mid element ; Check for break point ; Return the index ; Driver Code ; Print the smallest number | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimal ( int a [ ] , int n ) { int lo = 0 , hi = n - 1 ; while ( lo < hi ) { int mid = ( lo + hi ) >> 1 ; if ( a [ mid ] < a [ mid + 1 ] ) { hi = mid ; } else { lo = mid + 1 ; } } return lo ; } int main ( ) { int a [ ] = { 8 , 5 , 4 , 3 , 4 , 10 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int ind = minimal ( a , n ) ; cout << a [ ind ] ; } |
Leftmost and rightmost indices of the maximum and the minimum element of an array | C ++ implementation of the approach ; If found new minimum ; If arr [ i ] = min then rightmost index for min will change ; If found new maximum ; If arr [ i ] = max then rightmost index for max will change ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findIndices ( int arr [ ] , int n ) { int leftMin = 0 , rightMin = 0 ; int leftMax = 0 , rightMax = 0 ; int min = arr [ 0 ] , max = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] < min ) { leftMin = rightMin = i ; min = arr [ i ] ; } else if ( arr [ i ] == min ) rightMin = i ; if ( arr [ i ] > max ) { leftMax = rightMax = i ; max = arr [ i ] ; } else if ( arr [ i ] == max ) rightMax = i ; } cout << " Minimum β left β : β " << leftMin << " STRNEWLINE " ; cout << " Minimum β right β : β " << rightMin << " STRNEWLINE " ; cout << " Maximum β left β : β " << leftMax << " STRNEWLINE " ; cout << " Maximum β right β : β " << rightMax << " STRNEWLINE " ; } int main ( ) { int arr [ ] = { 2 , 1 , 1 , 2 , 1 , 5 , 6 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findIndices ( arr , n ) ; } |
Find smallest and largest element from square matrix diagonals | CPP program to find smallest and largest elements of both diagonals ; Function to find smallest and largest element from principal and secondary diagonal ; take length of matrix ; declare and initialize variables with appropriate value ; Condition for principal diagonal ; take new smallest value ; take new largest value ; Condition for secondary diagonal ; take new smallest value ; take new largest value ; Driver code ; Declare and initialize 5 X5 matrix | #include <bits/stdc++.h> NEW_LINE using namespace std ; void diagonalsMinMax ( int mat [ 5 ] [ 5 ] ) { int n = sizeof ( * mat ) / 4 ; if ( n == 0 ) return ; int principalMin = mat [ 0 ] [ 0 ] , principalMax = mat [ 0 ] [ 0 ] ; int secondaryMin = mat [ n - 1 ] [ 0 ] , secondaryMax = mat [ n - 1 ] [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 1 ; j < n ; j ++ ) { if ( i == j ) { if ( mat [ i ] [ j ] < principalMin ) { principalMin = mat [ i ] [ j ] ; } if ( mat [ i ] [ j ] > principalMax ) { principalMax = mat [ i ] [ j ] ; } } if ( ( i + j ) == ( n - 1 ) ) { if ( mat [ i ] [ j ] < secondaryMin ) { secondaryMin = mat [ i ] [ j ] ; } if ( mat [ i ] [ j ] > secondaryMax ) { secondaryMax = mat [ i ] [ j ] ; } } } } cout << ( " Principal β Diagonal β Smallest β Element : β " ) << principalMin << endl ; cout << ( " Principal β Diagonal β Greatest β Element β : β " ) << principalMax << endl ; cout << ( " Secondary β Diagonal β Smallest β Element : β " ) << secondaryMin << endl ; cout << ( " Secondary β Diagonal β Greatest β Element : β " ) << secondaryMax << endl ; } int main ( ) { int matrix [ 5 ] [ 5 ] = { { 1 , 2 , 3 , 4 , -10 } , { 5 , 6 , 7 , 8 , 6 } , { 1 , 2 , 11 , 3 , 4 } , { 5 , 6 , 70 , 5 , 8 } , { 4 , 9 , 7 , 1 , -5 } } ; diagonalsMinMax ( matrix ) ; } |
Count elements such that there are exactly X elements with values greater than or equal to X | C ++ implementation of the approach ; Sorting the vector ; Count of numbers which are greater than v [ i ] ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long NEW_LINE ll int getCount ( vector < ll int > v , int n ) { sort ( ( v ) . begin ( ) , ( v ) . end ( ) ) ; ll int cnt = 0 ; for ( ll int i = 0 ; i < n ; i ++ ) { ll int tmp = v . end ( ) - 1 - upper_bound ( ( v ) . begin ( ) , ( v ) . end ( ) , v [ i ] - 1 ) ; if ( tmp == v [ i ] ) cnt ++ ; } return cnt ; } int main ( ) { ll int n ; n = 4 ; vector < ll int > v ; v . push_back ( 1 ) ; v . push_back ( 2 ) ; v . push_back ( 3 ) ; v . push_back ( 4 ) ; cout << getCount ( v , n ) ; return 0 ; } |
Number of segments where all elements are greater than X | C ++ program to count the number of segments in which all elements are greater than X ; Function to count number of segments ; Iterate in the array ; check if array element greater then X or not ; if flag is true ; After iteration complete check for the last segment ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSegments ( int a [ ] , int n , int x ) { bool flag = false ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] > x ) { flag = true ; } else { if ( flag ) count += 1 ; flag = false ; } } if ( flag ) count += 1 ; return count ; } int main ( ) { int a [ ] = { 8 , 25 , 10 , 19 , 19 , 18 , 20 , 11 , 18 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int x = 13 ; cout << countSegments ( a , n , x ) ; return 0 ; } |
Find array elements with frequencies in range [ l , r ] | C ++ program to find the elements whose frequency lies in the range [ l , r ] ; Hash map which will store the frequency of the elements of the array . ; Increment the frequency of the element by 1. ; Print the element whose frequency lies in the range [ l , r ] ; Driver code | #include " iostream " NEW_LINE #include " unordered _ map " NEW_LINE using namespace std ; void findElements ( int arr [ ] , int n , int l , int r ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < n ; ++ i ) { mp [ arr [ i ] ] ++ ; } for ( int i = 0 ; i < n ; ++ i ) { if ( l <= mp [ arr [ i ] ] && mp [ arr [ i ] <= r ] ) { cout << arr [ i ] << " β " ; } } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 3 , 2 , 2 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int l = 2 , r = 3 ; findElements ( arr , n , l , r ) ; return 0 ; } |
Count triplets ( a , b , c ) such that a + b , b + c and a + c are all divisible by K | C ++ implementation of the approach ; Function returns the count of the triplets ; iterate for all triples pairs ( i , j , l ) ; if the condition is satisfied ; Driver code | #include <iostream> NEW_LINE using namespace std ; class gfg { public : long count_triples ( int n , int k ) ; } ; long gfg :: count_triples ( int n , int k ) { int i = 0 , j = 0 , l = 0 ; int count = 0 ; for ( i = 1 ; i <= n ; i ++ ) { for ( j = 1 ; j <= n ; j ++ ) { for ( l = 1 ; l <= n ; l ++ ) { if ( ( i + j ) % k == 0 && ( i + l ) % k == 0 && ( j + l ) % k == 0 ) count ++ ; } } } return count ; } int main ( ) { gfg g ; int n = 3 ; int k = 2 ; long ans = g . count_triples ( n , k ) ; cout << ans ; } |
kth smallest / largest in a small range unsorted array | C ++ program of kth smallest / largest in a small range unsorted array ; Storing counts of elements ; Traverse hash array build above until we reach k - th smallest element . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define maxs 1000001 NEW_LINE int kthSmallestLargest ( int * arr , int n , int k ) { int max_val = * max_element ( arr , arr + n ) ; int hash [ max_val + 1 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) hash [ arr [ i ] ] ++ ; int count = 0 ; for ( int i = 0 ; i <= max_val ; i ++ ) { while ( hash [ i ] > 0 ) { count ++ ; if ( count == k ) return i ; hash [ i ] -- ; } } return -1 ; } int main ( ) { int arr [ ] = { 11 , 6 , 2 , 9 , 4 , 3 , 16 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) , k = 3 ; cout << " kth β smallest β number β is : β " << kthSmallestLargest ( arr , n , k ) << endl ; return 0 ; } |
Sum and Product of minimum and maximum element of an Array | C ++ program for the above approach ; Function to get sum ; Function to get product ; Driver Code ; sorting the array ; min element would be the element at 0 th index of array after sorting ; max element would be the element at ( n - 1 ) th index of array after sorting | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findSum ( int minEle , int maxEle ) { return minEle + maxEle ; } int findProduct ( int minEle , int maxEle ) { return minEle * maxEle ; } int main ( ) { int arr [ ] = { 12 , 1234 , 45 , 67 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sort ( arr , arr + n ) ; int minEle = arr [ 0 ] ; int maxEle = arr [ n - 1 ] ; cout << " Sum β = β " << findSum ( minEle , maxEle ) << endl ; cout << " Product β = β " << findProduct ( minEle , maxEle ) ; return 0 ; } |
Meta Binary Search | One | C ++ implementation of above approach ; Function to show the working of Meta binary search ; Set number of bits to represent largest array index ; while ( ( 1 << lg ) < n - 1 ) lg += 1 ; ; Incrementally construct the index of the target value ; find the element in one direction and update position ; if element found return pos otherwise - 1 ; Driver code | #include <iostream> NEW_LINE #include <cmath> NEW_LINE #include <vector> NEW_LINE using namespace std ; int bsearch ( vector < int > A , int key_to_search ) { int n = ( int ) A . size ( ) ; int lg = log2 ( n - 1 ) + 1 ; int pos = 0 ; for ( int i = lg ; i >= 0 ; i -- ) { if ( A [ pos ] == key_to_search ) return pos ; int new_pos = pos | ( 1 << i ) ; if ( ( new_pos < n ) && ( A [ new_pos ] <= key_to_search ) ) pos = new_pos ; } return ( ( A [ pos ] == key_to_search ) ? pos : -1 ) ; } int main ( void ) { vector < int > A = { -2 , 10 , 100 , 250 , 32315 } ; cout << bsearch ( A , 10 ) << endl ; return 0 ; } |
Queries to check if a number lies in N ranges of L | C ++ program to check if the number lies in given range ; Function that answers every query ; container to store all range ; hash the L and R ; Push the element to container and hash the L and R ; sort the elements in container ; each query ; get the number same or greater than integer ; if it lies ; check if greater is hashed as 2 ; else check if greater is hashed as 1 ; Driver code ; function call to answer queries | #include <bits/stdc++.h> NEW_LINE using namespace std ; void answerQueries ( int a [ ] [ 2 ] , int n , int queries [ ] , int q ) { vector < int > v ; unordered_map < int , int > mpp ; for ( int i = 0 ; i < n ; i ++ ) { v . push_back ( a [ i ] [ 0 ] ) ; mpp [ a [ i ] [ 0 ] ] = 1 ; v . push_back ( a [ i ] [ 1 ] ) ; mpp [ a [ i ] [ 1 ] ] = 2 ; } sort ( v . begin ( ) , v . end ( ) ) ; for ( int i = 0 ; i < q ; i ++ ) { int num = queries [ i ] ; int ind = lower_bound ( v . begin ( ) , v . end ( ) , num ) - v . begin ( ) ; if ( v [ ind ] == num ) { cout << " Yes STRNEWLINE " ; } else { if ( mpp [ v [ ind ] ] == 2 ) cout << " Yes STRNEWLINE " ; cout << " No STRNEWLINE " ; } } } int main ( ) { int a [ ] [ 2 ] = { { 5 , 6 } , { 1 , 3 } , { 8 , 10 } } ; int n = 3 ; int queries [ ] = { 2 , 3 , 4 , 7 } ; int q = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; answerQueries ( a , n , queries , q ) ; return 0 ; } |
Median of two sorted arrays of different sizes | Set 1 ( Linear ) | A C ++ program to find median of two sorted arrays of unequal sizes ; This function returns median of a [ ] and b [ ] . Assumptions in this function : Both a [ ] and b [ ] are sorted arrays ; Current index of i / p array a [ ] ; Current index of i / p array b [ ] ; Below is to handle the case where all elements of a [ ] are smaller than smallest ( or first ) element of b [ ] or a [ ] is empty ; Below is to handle case where all elements of b [ ] are smaller than smallest ( or first ) element of a [ ] or b [ ] is empty ; Below is to handle the case where sum of number of elements of the arrays is even ; Below is to handle the case where sum of number of elements of the arrays is odd ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; float findmedian ( int a [ ] , int n1 , int b [ ] , int n2 ) { int i = 0 ; int j = 0 ; int k ; int m1 = -1 , m2 = -1 ; for ( k = 0 ; k <= ( n1 + n2 ) / 2 ; k ++ ) { if ( i < n1 && j < n2 ) { if ( a [ i ] < b [ j ] ) { m2 = m1 ; m1 = a [ i ] ; i ++ ; } else { m2 = m1 ; m1 = b [ j ] ; j ++ ; } } else if ( i == n1 ) { m2 = m1 ; m1 = b [ j ] ; j ++ ; } else if ( j == n2 ) { m2 = m1 ; m1 = a [ i ] ; i ++ ; } } if ( ( n1 + n2 ) % 2 == 0 ) return ( m1 + m2 ) * 1.0 / 2 ; return m1 ; } int main ( ) { int a [ ] = { 1 , 12 , 15 , 26 , 38 } ; int b [ ] = { 2 , 13 , 24 } ; int n1 = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int n2 = sizeof ( b ) / sizeof ( b [ 0 ] ) ; printf ( " % f " , findmedian ( a , n1 , b , n2 ) ) ; return 0 ; } |
Next Smaller Element | Simple C ++ program to print next smaller elements in a given array ; prints element and NSE pair for all elements of arr [ ] of size n ; Driver Code | #include " bits / stdc + + . h " NEW_LINE using namespace std ; void printNSE ( int arr [ ] , int n ) { int next , i , j ; for ( i = 0 ; i < n ; i ++ ) { next = -1 ; for ( j = i + 1 ; j < n ; j ++ ) { if ( arr [ i ] > arr [ j ] ) { next = arr [ j ] ; break ; } } cout << arr [ i ] << " β - - β " << next << endl ; } } int main ( ) { int arr [ ] = { 11 , 13 , 21 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printNSE ( arr , n ) ; return 0 ; } |
Longest subarray such that the difference of max and min is at | C ++ code to find longest subarray with difference between max and min as at - most 1. ; longest constant range length ; first number ; If we see same number ; If we see different number , but same as previous . ; If number is neither same as previous nor as current . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int longestSubarray ( int input [ ] , int length ) { int prev = -1 ; int current , next ; int prevCount = 0 , currentCount = 1 ; int longest = 1 ; current = input [ 0 ] ; for ( int i = 1 ; i < length ; i ++ ) { next = input [ i ] ; if ( next == current ) { currentCount ++ ; } else if ( next == prev ) { prevCount += currentCount ; prev = current ; current = next ; currentCount = 1 ; } else { longest = max ( longest , currentCount + prevCount ) ; prev = current ; prevCount = currentCount ; current = next ; currentCount = 1 ; } } return max ( longest , currentCount + prevCount ) ; } int main ( ) { int input [ ] = { 5 , 5 , 6 , 7 , 6 } ; int n = sizeof ( input ) / sizeof ( int ) ; cout << longestSubarray ( input , n ) ; return 0 ; } |
Reverse tree path | CPP program to Reverse Tree path ; A Binary Tree Node ; ' data ' is input . We need to reverse path from root to data . ' level ' is current level . ' temp ' that stores path nodes . ' nextpos ' used to pick next item for reversing . ; return NULL if root NULL ; Final condition if the node is found then ; store the value in it 's level ; change the root value with the current next element of the map ; increment in k for the next element ; store the data in perticular level ; We go to right only when left does not contain given data . This way we make sure that correct path node is stored in temp [ ] ; If current node is part of the path , then do reversing . ; return NULL if not element found ; Reverse Tree path ; store per level data ; it is for replacing the data ; reverse tree path ; INORDER ; Utility function to create a new tree node ; Driver program to test above functions ; Let us create binary tree shown in above diagram ; 7 / \ 6 5 / \ / \ 4 3 2 1 ; Reverse Tree Path ; Traverse inorder | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; Node * reverseTreePathUtil ( Node * root , int data , map < int , int > & temp , int level , int & nextpos ) { if ( root == NULL ) return NULL ; if ( data == root -> data ) { temp [ level ] = root -> data ; root -> data = temp [ nextpos ] ; nextpos ++ ; return root ; } temp [ level ] = root -> data ; Node * left , * right ; left = reverseTreePathUtil ( root -> left , data , temp , level + 1 , nextpos ) ; if ( left == NULL ) right = reverseTreePathUtil ( root -> right , data , temp , level + 1 , nextpos ) ; if ( left right ) { root -> data = temp [ nextpos ] ; nextpos ++ ; return ( left ? left : right ) ; } return NULL ; } void reverseTreePath ( Node * root , int data ) { map < int , int > temp ; int nextpos = 0 ; reverseTreePathUtil ( root , data , temp , 0 , nextpos ) ; } void inorder ( Node * root ) { if ( root != NULL ) { inorder ( root -> left ) ; cout << root -> data << " β " ; inorder ( root -> right ) ; } } Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } int main ( ) { Node * root = newNode ( 7 ) ; root -> left = newNode ( 6 ) ; root -> right = newNode ( 5 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 3 ) ; root -> right -> left = newNode ( 2 ) ; root -> right -> right = newNode ( 1 ) ; int data = 4 ; reverseTreePath ( root , data ) ; inorder ( root ) ; return 0 ; } |
Longest Subarray with first element greater than or equal to Last element | CPP program to find length of the longest array with first element smaller than or equal to last element . ; Search function for searching the first element of the subarray which is greater or equal to the last element ( num ) ; Returns length of the longest array with first element smaller than the last element . ; Search space for the potential first elements . ; It will store the Indexes of the elements of search space in the original array . ; Initially the search space is empty . ; We will add an ith element in the search space if the search space is empty or if the ith element is greater than the last element of the search space . ; we will search for the index first element in the search space and we will use it find the index of it in the original array . ; Update the answer if the length of the subarray is greater than the previously calculated lengths . ; Driver Code | #include <algorithm> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int binarySearch ( int * searchSpace , int s , int e , int num ) { int ans ; while ( s <= e ) { int mid = ( s + e ) / 2 ; if ( searchSpace [ mid ] >= num ) { ans = mid ; e = mid - 1 ; } else s = mid + 1 ; } return ans ; } int longestSubArr ( int * arr , int n ) { int searchSpace [ n ] ; int index [ n ] ; int j = 0 ; int ans = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( j == 0 or searchSpace [ j - 1 ] < arr [ i ] ) { searchSpace [ j ] = arr [ i ] ; index [ j ] = i ; j ++ ; } int idx = binarySearch ( searchSpace , 0 , j - 1 , arr [ i ] ) ; ans = max ( ans , i - index [ idx ] + 1 ) ; } return ans ; } int main ( int argc , char const * argv [ ] ) { int arr [ ] = { -5 , -1 , 7 , 5 , 1 , -2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << longestSubArr ( arr , n ) << endl ; return 0 ; } |
Print all pairs with given sum | C ++ code to implement the above approach ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void pairedElements ( int arr [ ] , int sum , int n ) { int low = 0 ; int high = n - 1 ; while ( low < high ) { if ( arr [ low ] + arr [ high ] == sum ) { cout << " The β pair β is β : β ( " << arr [ low ] << " , β " << arr [ high ] << " ) " << endl ; } if ( arr [ low ] + arr [ high ] > sum ) { high -- ; } else { low ++ ; } } } int main ( ) { int arr [ ] = { 2 , 3 , 4 , -2 , 6 , 8 , 9 , 11 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sort ( arr , arr + n ) ; pairedElements ( arr , 6 , n ) ; } |
Check if a string is suffix of another | CPP program to find if a string is suffix of another ; Driver code ; Test case - sensitive implementation of endsWith function | #include <iostream> NEW_LINE #include <string> NEW_LINE using namespace std ; bool isSuffix ( string s1 , string s2 ) { int n1 = s1 . length ( ) , n2 = s2 . length ( ) ; if ( n1 > n2 ) return false ; for ( int i = 0 ; i < n1 ; i ++ ) if ( s1 [ n1 - i - 1 ] != s2 [ n2 - i - 1 ] ) return false ; return true ; } int main ( ) { string s1 = " geeks " , s2 = " geeksforgeeks " ; bool result = isSuffix ( s1 , s2 ) ; if ( result ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Check if all occurrences of a character appear together | C ++ program to find if all occurrences of a character appear together in a string . ; To indicate if one or more occurrences of ' c ' are seen or not . ; Traverse given string ; If current character is same as c , we first check if c is already seen . ; If this is very first appearance of c , we traverse all consecutive occurrences . ; To indicate that character is seen once . ; Driver program | #include <iostream> NEW_LINE #include <string> NEW_LINE using namespace std ; bool checkIfAllTogether ( string s , char c ) { bool oneSeen = false ; int i = 0 , n = s . length ( ) ; while ( i < n ) { if ( s [ i ] == c ) { if ( oneSeen == true ) return false ; while ( i < n && s [ i ] == c ) i ++ ; oneSeen = true ; } else i ++ ; } return true ; } int main ( ) { string s = "110029" ; if ( checkIfAllTogether ( s , '1' ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; } |
Front and Back Search in unsorted array | CPP program to implement front and back search ; Start searching from both ends ; Keep searching while two indexes do not cross . ; Driver Code | #include <iostream> NEW_LINE using namespace std ; bool search ( int arr [ ] , int n , int x ) { int front = 0 , back = n - 1 ; while ( front <= back ) { if ( arr [ front ] == x arr [ back ] == x ) return true ; front ++ ; back -- ; } return false ; } int main ( ) { int arr [ ] = { 10 , 20 , 80 , 30 , 60 , 50 , 110 , 100 , 130 , 170 } ; int x = 130 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( search ( arr , n , x ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Even | CPP program to find max ( X , Y ) / min ( X , Y ) after P turns ; Driver code ; 1 st test case ; 2 nd test case | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findValue ( int X , int Y , int P ) { if ( P % 2 == 0 ) return ( max ( X , Y ) / min ( X , Y ) ) ; else return ( max ( 2 * X , Y ) / min ( 2 * X , Y ) ) ; } int main ( ) { int X = 1 , Y = 2 , P = 1 ; cout << findValue ( X , Y , P ) << endl ; X = 3 , Y = 7 , P = 2 ; cout << findValue ( X , Y , P ) << endl ; } |
The painter 's partition problem | A DP based CPP program for painter 's partition problem ; function to calculate sum between two indices in array ; bottom up tabular dp ; initialize table ; base cases k = 1 ; n = 1 ; 2 to k partitions for ( int i = 2 ; i <= k ; i ++ ) { 2 to n boards ; track minimum ; i - 1 th separator before position arr [ p = 1. . j ] ; required ; driver function ; Calculate size of array . | #include <climits> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int sum ( int arr [ ] , int from , int to ) { int total = 0 ; for ( int i = from ; i <= to ; i ++ ) total += arr [ i ] ; return total ; } int findMax ( int arr [ ] , int n , int k ) { int dp [ k + 1 ] [ n + 1 ] = { 0 } ; for ( int i = 1 ; i <= n ; i ++ ) dp [ 1 ] [ i ] = sum ( arr , 0 , i - 1 ) ; for ( int i = 1 ; i <= k ; i ++ ) dp [ i ] [ 1 ] = arr [ 0 ] ; for ( int j = 2 ; j <= n ; j ++ ) { int best = INT_MAX ; for ( int p = 1 ; p <= j ; p ++ ) best = min ( best , max ( dp [ i - 1 ] [ p ] , sum ( arr , p , j - 1 ) ) ) ; dp [ i ] [ j ] = best ; } } return dp [ k ] [ n ] ; } int main ( ) { int arr [ ] = { 10 , 20 , 60 , 50 , 30 , 40 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; cout << findMax ( arr , n , k ) << endl ; return 0 ; } |
Counting cross lines in an array | c ++ program to count cross line in array ; function return count of cross line in an array ; Move elements of arr [ 0. . i - 1 ] , that are greater than key , to one position ahead of their current position ; increment cross line by one ; driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countCrossLine ( int arr [ ] , int n ) { int count_crossline = 0 ; int i , key , j ; for ( i = 1 ; i < n ; i ++ ) { key = arr [ i ] ; j = i - 1 ; while ( j >= 0 && arr [ j ] > key ) { arr [ j + 1 ] = arr [ j ] ; j = j - 1 ; count_crossline ++ ; } arr [ j + 1 ] = key ; } return count_crossline ; } int main ( ) { int arr [ ] = { 4 , 3 , 1 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countCrossLine ( arr , n ) << endl ; return 0 ; } |
Recursive Programs to find Minimum and Maximum elements of array | Recursive C ++ program to find maximum ; function to return maximum element using recursion ; if n = 0 means whole array has been traversed ; driver code to test above function ; Function calling | #include <iostream> NEW_LINE using namespace std ; int findMaxRec ( int A [ ] , int n ) { if ( n == 1 ) return A [ 0 ] ; return max ( A [ n - 1 ] , findMaxRec ( A , n - 1 ) ) ; } int main ( ) { int A [ ] = { 1 , 4 , 45 , 6 , -50 , 10 , 2 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << findMaxRec ( A , n ) ; return 0 ; } |
Program to remove vowels from a String | C ++ program to remove vowels from a String ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string remVowel ( string str ) { regex r ( " [ aeiouAEIOU ] " ) ; return regex_replace ( str , r , " " ) ; } int main ( ) { string str = " GeeeksforGeeks β - β A β Computer β Science β Portal β for β Geeks " ; cout << ( remVowel ( str ) ) ; return 0 ; } |
MSD ( Most Significant Digit ) Radix Sort | C ++ implementation of MSD Radix Sort of MSD Radix Sort using counting sort ( ) ; A utility function to print an array ; A utility function to get the digit at index d in a integer ; The main function to sort array using MSD Radix Sort recursively ; recursion break condition ; temp is created to easily swap strings in arr [ ] ; Store occurrences of most significant character from each integer in count [ ] ; Change count [ ] so that count [ ] now contains actual position of this digits in temp [ ] ; Build the temp ; Copy all integers of temp to arr [ ] , so that arr [ ] now contains partially sorted integers ; Recursively MSD_sort ( ) on each partially sorted integers set to sort them by their next digit ; function find the largest integer ; Main function to call MSD_sort ; Find the maximum number to know number of digits ; get the length of the largest integer ; function call ; Driver Code ; Input array ; Size of the array ; Print the unsorted array ; Function Call ; Print the sorted array | #include <iostream> NEW_LINE #include <math.h> NEW_LINE #include <unordered_map> NEW_LINE using namespace std ; void print ( int * arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) { cout << arr [ i ] << " β " ; } cout << endl ; } int digit_at ( int x , int d ) { return ( int ) ( x / pow ( 10 , d - 1 ) ) % 10 ; } void MSD_sort ( int * arr , int lo , int hi , int d ) { if ( hi <= lo ) { return ; } int count [ 10 + 2 ] = { 0 } ; unordered_map < int , int > temp ; for ( int i = lo ; i <= hi ; i ++ ) { int c = digit_at ( arr [ i ] , d ) ; count ++ ; } for ( int r = 0 ; r < 10 + 1 ; r ++ ) count [ r + 1 ] += count [ r ] ; for ( int i = lo ; i <= hi ; i ++ ) { int c = digit_at ( arr [ i ] , d ) ; temp [ count ++ ] = arr [ i ] ; } for ( int i = lo ; i <= hi ; i ++ ) arr [ i ] = temp [ i - lo ] ; for ( int r = 0 ; r < 10 ; r ++ ) MSD_sort ( arr , lo + count [ r ] , lo + count [ r + 1 ] - 1 , d - 1 ) ; } int getMax ( int arr [ ] , int n ) { int mx = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] > mx ) mx = arr [ i ] ; return mx ; } void radixsort ( int * arr , int n ) { int m = getMax ( arr , n ) ; int d = floor ( log10 ( abs ( m ) ) ) + 1 ; MSD_sort ( arr , 0 , n - 1 , d ) ; } int main ( ) { int arr [ ] = { 9330 , 9950 , 718 , 8977 , 6790 , 95 , 9807 , 741 , 8586 , 5710 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Unsorted β array β : β " ) ; print ( arr , n ) ; radixsort ( arr , n ) ; printf ( " Sorted β array β : β " ) ; print ( arr , n ) ; return 0 ; } |
Maximum money that can be collected by both the players in a game of removal of coins | C ++ program for the above approach ; Function to find the maximum score obtained by the players A and B ; Sort the array in descending order ; Stores the maximum amount of money obtained by A ; Stores the maximum amount of money obtained by B ; If the value of N is 1 ; Update the amountA ; Print the amount of money obtained by both players ; Update the amountA ; Update the amountB ; Traverse the array arr [ ] ; If i is an odd number ; Update the amountB ; Update the amountA ; Print the amount of money obtained by both the players ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findAmountPlayers ( int arr [ ] , int N ) { sort ( arr , arr + N , greater < int > ( ) ) ; int amountA = 0 ; int amountB = 0 ; if ( N == 1 ) { amountA += arr [ 0 ] ; cout << " ( A β : β " << amountA << " ) , β " << " ( B β : β " << amountB << " ) " ; return ; } amountA = arr [ 0 ] ; amountB = arr [ 1 ] ; for ( int i = 2 ; i < N ; i ++ ) { if ( i % 2 == 0 ) { amountB += arr [ i ] ; } else { amountA += arr [ i ] ; } } cout << " ( A β : β " << amountA << " ) STRNEWLINE " << " ( B β : β " << amountB << " ) " ; } int main ( ) { int arr [ ] = { 1 , 1 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findAmountPlayers ( arr , N ) ; return 0 ; } |
Minimum number of swaps required to minimize sum of absolute differences between adjacent array elements | C ++ program for the above approach ; Comparator to sort in the descending order ; Function to find the minimum number of swaps required to sort the array in increasing order ; Stores the array elements with its index ; Sort the array in the increasing order ; Keeps the track of visited elements ; Stores the count of swaps required ; Traverse array elements ; If the element is already swapped or at correct position ; Find out the number of nodes in this cycle ; Update the value of j ; Move to the next element ; Increment cycle_size ; Update the ans by adding current cycle ; Function to find the minimum number of swaps required to sort the array in decreasing order ; Stores the array elements with its index ; Sort the array in the descending order ; Keeps track of visited elements ; Stores the count of resultant swap required ; Traverse array elements ; If the element is already swapped or at correct position ; Find out the number of node in this cycle ; Update the value of j ; Move to the next element ; Increment the cycle_size ; Update the ans by adding current cycle size ; Function to find minimum number of swaps required to minimize the sum of absolute difference of adjacent elements ; Sort in ascending order ; Sort in descending order ; Return the minimum value ; Drive Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool mycmp ( pair < int , int > a , pair < int , int > b ) { return a . first > b . first ; } int minSwapsAsc ( vector < int > arr , int n ) { pair < int , int > arrPos [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { arrPos [ i ] . first = arr [ i ] ; arrPos [ i ] . second = i ; } sort ( arrPos , arrPos + n ) ; vector < bool > vis ( n , false ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( vis [ i ] arrPos [ i ] . second == i ) continue ; int cycle_size = 0 ; int j = i ; while ( ! vis [ j ] ) { vis [ j ] = 1 ; j = arrPos [ j ] . second ; cycle_size ++ ; } if ( cycle_size > 0 ) { ans += ( cycle_size - 1 ) ; } } return ans ; } int minSwapsDes ( vector < int > arr , int n ) { pair < int , int > arrPos [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { arrPos [ i ] . first = arr [ i ] ; arrPos [ i ] . second = i ; } sort ( arrPos , arrPos + n , mycmp ) ; vector < bool > vis ( n , false ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( vis [ i ] arrPos [ i ] . second == i ) continue ; int cycle_size = 0 ; int j = i ; while ( ! vis [ j ] ) { vis [ j ] = 1 ; j = arrPos [ j ] . second ; cycle_size ++ ; } if ( cycle_size > 0 ) { ans += ( cycle_size - 1 ) ; } } return ans ; } int minimumSwaps ( vector < int > arr ) { int S1 = minSwapsAsc ( arr , arr . size ( ) ) ; int S2 = minSwapsDes ( arr , arr . size ( ) ) ; return min ( S1 , S2 ) ; } int main ( ) { vector < int > arr { 3 , 4 , 2 , 5 , 1 } ; cout << minimumSwaps ( arr ) ; return 0 ; } |
Sort an array of 0 s , 1 s , 2 s and 3 s | C ++ program for the above approach ; Function to sort the array having array element only 0 , 1 , 2 , and 3 ; Iterate until mid <= j ; If arr [ mid ] is 0 ; Swap integers at indices i and mid ; Increment i ; Increment mid ; Otherwise if the value of arr [ mid ] is 3 ; Swap arr [ mid ] and arr [ j ] ; Decrement j ; Otherwise if the value of arr [ mid ] is either 1 or 2 ; Increment the value of mid ; Iterate until i <= j ; If arr [ i ] the value of is 2 ; Swap arr [ i ] and arr [ j ] ; Decrement j ; Otherwise , increment i ; Print the sorted array arr [ ] ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sortArray ( int arr [ ] , int N ) { int i = 0 , j = N - 1 , mid = 0 ; while ( mid <= j ) { if ( arr [ mid ] == 0 ) { swap ( arr [ i ] , arr [ mid ] ) ; i ++ ; mid ++ ; } else if ( arr [ mid ] == 3 ) { swap ( arr [ mid ] , arr [ j ] ) ; j -- ; } else if ( arr [ mid ] == 1 arr [ mid ] == 2 ) { mid ++ ; } } while ( i <= j ) { if ( arr [ i ] == 2 ) { swap ( arr [ i ] , arr [ j ] ) ; j -- ; } else { i ++ ; } } for ( int i = 0 ; i < N ; i ++ ) { cout << arr [ i ] << " β " ; } } int main ( ) { int arr [ ] = { 3 , 2 , 1 , 0 , 2 , 3 , 1 , 0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortArray ( arr , N ) ; return 0 ; } |
Check whether an array can be made strictly increasing by removing at most one element | C ++ program for the above approach ; Function to find if is it possible to make the array strictly increasing by removing at most one element ; Stores the count of numbers that are needed to be removed ; Store the index of the element that needs to be removed ; Traverse the range [ 1 , N - 1 ] ; If arr [ i - 1 ] is greater than or equal to arr [ i ] ; Increment the count by 1 ; Update index ; If count is greater than one ; If no element is removed ; If only the last or the first element is removed ; If a [ index ] is removed ; If a [ index - 1 ] is removed ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int arr [ ] , int n ) { int count = 0 ; int index = -1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i - 1 ] >= arr [ i ] ) { count ++ ; index = i ; } } if ( count > 1 ) return false ; if ( count == 0 ) return true ; if ( index == n - 1 index == 1 ) return true ; if ( arr [ index - 1 ] < arr [ index + 1 ] ) return true ; if ( index - 2 >= 0 && arr [ index - 2 ] < arr [ index ] ) return true ; if ( index < 0 ) return true ; return false ; } int main ( ) { int arr [ ] = { 1 , 2 , 5 , 3 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( check ( arr , N ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Modify string by rearranging vowels in alphabetical order at their respective indices | C ++ program for the above approach ; Function to arrange the vowels in sorted order in the string at their respective places ; Store the size of the string ; Stores vowels of string S ; Traverse the string , S and push all the vowels to string vow ; If vow is empty , then print S and return ; Sort vow in alphabetical order ; Traverse the string , S ; Replace S [ i ] with vow [ j ] iif S [ i ] is a vowel , and increment j by 1 ; Print the string ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sortVowels ( string S ) { int n = S . size ( ) ; string vow = " " ; for ( int i = 0 ; i < n ; i ++ ) { if ( S [ i ] == ' a ' S [ i ] == ' e ' S [ i ] == ' i ' S [ i ] == ' o ' S [ i ] == ' u ' ) { vow += S [ i ] ; } } if ( vow . size ( ) == 0 ) { cout << S ; return ; } sort ( vow . begin ( ) , vow . end ( ) ) ; int j = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( S [ i ] == ' a ' S [ i ] == ' e ' S [ i ] == ' i ' S [ i ] == ' o ' S [ i ] == ' u ' ) { S [ i ] = vow [ j ++ ] ; } } cout << S ; } int main ( ) { string S = " geeksforgeeks " ; sortVowels ( S ) ; return 0 ; } |
Maximum number of buckets that can be filled | C ++ program for the above approach ; Function to find the maximum number of buckets that can be filled with the amount of water available ; Find the total available water ; Sort the array in ascending order ; Check if bucket can be filled with available water ; Print count of buckets ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getBuckets ( int arr [ ] , int N ) { int availableWater = N * ( N - 1 ) / 2 ; sort ( arr , arr + N ) ; int i = 0 , sum = 0 ; while ( sum <= availableWater ) { sum += arr [ i ] ; i ++ ; } cout << i - 1 ; } int main ( ) { int arr [ ] = { 1 , 5 , 3 , 4 , 7 , 9 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; getBuckets ( arr , N ) ; return 0 ; } |
Minimize the number of strictly increasing subsequences in an array | Set 2 | C ++ program for the above approach ; Function to find the number of strictly increasing subsequences in an array ; Sort the array ; Stores final count of subsequences ; Traverse the array ; Stores current element ; Stores frequency of the current element ; Count frequency of the current element ; If current element frequency is greater than count ; Print the final count ; Driver Code ; Given array ; Size of the array ; Function call to find the number of strictly increasing subsequences | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumIncreasingSubsequences ( int arr [ ] , int N ) { sort ( arr , arr + N ) ; int count = 0 ; int i = 0 ; while ( i < N ) { int x = arr [ i ] ; int freqX = 0 ; while ( i < N && arr [ i ] == x ) { freqX ++ ; i ++ ; } count = max ( count , freqX ) ; } cout << count ; } int main ( ) { int arr [ ] = { 2 , 1 , 2 , 1 , 4 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minimumIncreasingSubsequences ( arr , N ) ; } |
Count triplets from an array which can form quadratic equations with real roots | C ++ program for the above approach ; Function to count the number of triplets ( a , b , c ) such that the equation ax ^ 2 + bx + c = 0 has real roots ; Sort the array in ascending order ; Stores count of triplets ( a , b , c ) such that ax ^ 2 + bx + c = 0 has real roots ; Base case ; Traverse the given array ; If values of a and c are equal to b ; Increment a ; Decrement c ; Condition for having real roots for a quadratic equation ; If b lies in between a and c ; Update count ; Update count ; Increment a ; Decrement c ; For each pair two values are possible of a and c ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getCount ( int arr [ ] , int N ) { sort ( arr , arr + N ) ; int count = 0 ; if ( N < 3 ) return 0 ; for ( int b = 0 ; b < N ; b ++ ) { int a = 0 , c = N - 1 ; int d = arr [ b ] * arr [ b ] / 4 ; while ( a < c ) { if ( a == b ) { a ++ ; continue ; } if ( c == b ) { c -- ; continue ; } if ( arr [ a ] * arr <= d ) { if ( a < b && b < c ) { count += c - a - 1 ; } else { count += c - a ; } a ++ ; } else { c -- ; } } } return count * 2 ; } int main ( ) { int arr [ ] = { 3 , 6 , 10 , 13 , 21 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << getCount ( arr , N ) ; return 0 ; } |
Maximize difference between the sum of absolute differences of each element with the remaining array | C ++ program for the above approach ; Function to maximize difference of the sum of absolute difference of an element with the rest of the elements in the array ; Sort the array in ascending order ; Stores prefix sum at any instant ; Store the total array sum ; Initialize minimum and maximum absolute difference ; Traverse the array to find the total array sum ; Traverse the array arr [ ] ; Store the number of elements to its left ; Store the number of elements to its right ; Update the sum of elements on its left ; Store the absolute difference sum ; Update the Minimum ; Update the Maximum ; Update sum of elements on its left ; Print the result ; Driven Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findMaxDifference ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int Leftsum = 0 ; int Totalsum = 0 ; int Min = INT_MAX , Max = INT_MIN ; for ( int i = 0 ; i < n ; i ++ ) Totalsum += arr [ i ] ; for ( int i = 0 ; i < n ; i ++ ) { int leftNumbers = i ; int rightNumbers = n - i - 1 ; Totalsum = Totalsum - arr [ i ] ; int sum = ( leftNumbers * arr [ i ] ) - Leftsum + Totalsum - ( rightNumbers * arr [ i ] ) ; Min = min ( Min , sum ) ; Max = max ( Max , sum ) ; Leftsum += arr [ i ] ; } cout << Max - Min ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findMaxDifference ( arr , N ) ; return 0 ; } |
Minimum pairs required to be removed such that the array does not contain any pair with sum K | C ++ 14 program to implement the above approach ; Function to find the maximum count of pairs required to be removed such that no pairs exist whose sum equal to K ; Stores maximum count of pairs required to be removed such that no pairs exist whose sum equal to K ; Base Case ; Sort the array ; Stores index of left pointer ; Stores index of right pointer ; Stores sum of left and right pointer ; If s equal to k ; Update cntPairs ; Update left ; Update right ; If s > k ; Update right ; Update left ; Return the cntPairs ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxcntPairsSumKRemoved ( vector < int > arr , int k ) { int cntPairs = 0 ; if ( arr . size ( ) <= 1 ) return cntPairs ; sort ( arr . begin ( ) , arr . end ( ) ) ; int left = 0 ; int right = arr . size ( ) - 1 ; while ( left < right ) { int s = arr [ left ] + arr [ right ] ; if ( s == k ) { cntPairs += 1 ; left += 1 ; right -= 1 ; } else if ( s > k ) right -= 1 ; else left += 1 ; } return cntPairs ; } int main ( ) { vector < int > arr = { 1 , 2 , 3 , 4 } ; int K = 5 ; cout << ( maxcntPairsSumKRemoved ( arr , K ) ) ; return 0 ; } |
Minimize cost to split an array into K subsets such that the cost of each element is its product with its position in the subset | C ++ program to implement the above approach ; Function to find the minimum cost to split array into K subsets ; Sort the array in descending order ; Stores minimum cost to split the array into K subsets ; Stores position of elements of a subset ; Iterate over the range [ 1 , N ] ; Calculate the cost to select X - th element of every subset ; Update min_cost ; Update X ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getMinCost ( int * arr , int n , int k ) { sort ( arr , arr + n , greater < int > ( ) ) ; int min_cost = 0 ; int X = 0 ; for ( int i = 0 ; i < n ; i += k ) { for ( int j = i ; j < i + k && j < n ; j ++ ) { min_cost += arr [ j ] * ( X + 1 ) ; } X ++ ; } return min_cost ; } int main ( ) { int arr [ ] = { 9 , 20 , 7 , 8 } ; int K = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << getMinCost ( arr , N , K ) << endl ; } |
Minimize difference between the largest and smallest array elements by K replacements | C ++ program for the above approach ; Function to find minimum difference between largest and smallest element after K replacements ; Sort array in ascending order ; Minimum difference ; Check for all K + 1 possibilities ; Return answer ; Driver Code ; Given array ; Length of array ; Prints the minimum possible difference | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minDiff ( int A [ ] , int K , int n ) { sort ( A , A + n ) ; if ( n <= K ) return 0 ; int mindiff = A [ n - 1 ] - A [ 0 ] ; if ( K == 0 ) return mindiff ; for ( int i = 0 , j = n - 1 - K ; j < n ; ) { mindiff = min ( mindiff , A [ j ] - A [ i ] ) ; i ++ ; j ++ ; } return mindiff ; } int main ( ) { int A [ ] = { -1 , 3 , -1 , 8 , 5 , 4 } ; int K = 3 ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << minDiff ( A , K , n ) ; return 0 ; } |
Minimize difference between the largest and smallest array elements by K replacements | C ++ program for above approach ; Function to find minimum difference between the largest and smallest element after K replacements ; Create a MaxHeap ; Create a MinHeap ; Update maxHeap and MinHeap with highest and smallest K elements respectively ; Insert current element into the MaxHeap ; If maxHeap size exceeds K + 1 ; Remove top element ; Insert current element into the MaxHeap ; If maxHeap size exceeds K + 1 ; Remove top element ; Store all max element from maxHeap ; Store all min element from minHeap ; Generating all K + 1 possibilities ; Return answer ; Driver Code ; Given array ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minDiff ( int A [ ] , int K , int N ) { if ( N <= K + 1 ) return 0 ; priority_queue < int , vector < int > , greater < int > > maxHeap ; priority_queue < int > minHeap ; for ( int i = 0 ; i < N ; i ++ ) { maxHeap . push ( A [ i ] ) ; if ( maxHeap . size ( ) > K + 1 ) maxHeap . pop ( ) ; minHeap . push ( A [ i ] ) ; if ( minHeap . size ( ) > K + 1 ) minHeap . pop ( ) ; } vector < int > maxList ; while ( maxHeap . size ( ) > 0 ) { maxList . push_back ( maxHeap . top ( ) ) ; maxHeap . pop ( ) ; } vector < int > minList ; while ( minHeap . size ( ) > 0 ) { minList . push_back ( minHeap . top ( ) ) ; minHeap . pop ( ) ; } int mindiff = INT_MAX ; for ( int i = 0 ; i <= K ; i ++ ) { mindiff = min ( mindiff , maxList [ i ] - minList [ K - i ] ) ; } return mindiff ; } int main ( ) { int A [ ] = { -1 , 3 , -1 , 8 , 5 , 4 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int K = 3 ; cout << minDiff ( A , K , N ) ; return 0 ; } |
Check if all K | C ++ program to implement the above approach ; Function to check all subset - sums of K - length subsets in A [ ] is greater that that in the array B [ ] or not ; Sort the array in ascending order ; Sort the array in descending order ; Stores sum of first K elements of A [ ] ; Stores sum of first K elements of B [ ] ; Traverse both the arrays ; Update sum1 ; Update sum2 ; If sum1 exceeds sum2 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkSubsetSum ( int A [ ] , int B [ ] , int N , int K ) { sort ( A , A + N ) ; sort ( B , B + N , greater < int > ( ) ) ; int sum1 = 0 ; int sum2 = 0 ; for ( int i = 0 ; i < K ; i ++ ) { sum1 += A [ i ] ; sum2 += B [ i ] ; } if ( sum1 > sum2 ) { return true ; } return false ; } int main ( ) { int A [ ] = { 12 , 11 , 10 , 13 } ; int B [ ] = { 7 , 10 , 6 , 2 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int K = 3 ; if ( checkSubsetSum ( A , B , N , K ) ) { cout << " YES " ; } else { cout << " NO " ; } return 0 ; } |
Sort given array to descending | C ++ program to implement the above approach ; Function to sort first K array elements in descending and last N - K in ascending order ; Sort the array in descending order ; Sort last ( N - K ) array elements in ascending order ; Print array elements ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sortArrayInDescAsc ( int arr [ ] , int N , int K ) { sort ( arr , arr + N , greater < int > ( ) ) ; sort ( arr + K , arr + N ) ; for ( int i = 0 ; i < N ; i ++ ) { cout << arr [ i ] << " β " ; } } int main ( ) { int arr [ ] = { 7 , 6 , 8 , 9 , 0 , 1 , 2 , 2 , 1 , 8 , 9 , 6 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 6 ; sortArrayInDescAsc ( arr , N , K ) ; } |
Median of all non | C ++ program to implement the above approach ; Function to calculate the median of all possible subsets by given operations ; Stores sum of elements of arr [ ] ; Traverse the array arr [ ] ; Update sum ; Sort the array ; DP [ i ] [ j ] : Stores total number of ways to form the sum j by either selecting ith element or not selecting ith item . ; Initialize all the DP states ; Base case ; Fill dp [ i ] [ 0 ] ; Base case ; Fill all the DP states based on the mentioned DP relation ; If j is greater than or equal to arr [ i ] ; Update dp [ i ] [ j ] ; Update dp [ i ] [ j ] ; Stores all possible subset sum ; Traverse all possible subset sum ; Stores count of subsets whose sum is j ; Itearate over the range [ 1 , M ] ; Insert j into sumSub ; Stores middle element of sumSub ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMedianOfsubSum ( int arr [ ] , int N ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += arr [ i ] ; } sort ( arr , arr + N ) ; int dp [ N ] [ sum + 1 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; for ( int i = 0 ; i < N ; i ++ ) { dp [ i ] [ 0 ] = 1 ; } dp [ 0 ] [ arr [ 0 ] ] = 1 ; for ( int i = 1 ; i < N ; i ++ ) { for ( int j = 1 ; j <= sum ; j ++ ) { if ( j >= arr [ i ] ) { dp [ i ] [ j ] = dp [ i - 1 ] [ j ] + dp [ i - 1 ] [ j - arr [ i ] ] ; } else { dp [ i ] [ j ] = dp [ i - 1 ] [ j ] ; } } } vector < int > sumSub ; for ( int j = 1 ; j <= sum ; j ++ ) { int M = dp [ N - 1 ] [ j ] ; for ( int i = 1 ; i <= M ; i ++ ) { sumSub . push_back ( j ) ; } } int mid = sumSub [ sumSub . size ( ) / 2 ] ; return mid ; } int main ( ) { int arr [ ] = { 2 , 3 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findMedianOfsubSum ( arr , N ) ; return 0 ; } |
Reduce array to a single element by repeatedly replacing adjacent unequal pairs with their maximum | C ++ program for the above approach ; Function to print the index from where the operation can be started ; Initialize B [ ] ; Initialize save ; Make B [ ] equals to arr [ ] ; Sort the array B [ ] ; Traverse from N - 1 to 1 ; If B [ i ] & B [ i - 1 ] are unequal ; If all elements are same ; If arr [ 1 ] is maximum element ; If arr [ N - 1 ] is maximum element ; Find the maximum element ; Driver Code ; Given array arr [ ] ; Length of array ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printIndex ( int arr [ ] , int N ) { int B [ N ] ; int save = -1 ; for ( int i = 0 ; i < N ; i ++ ) { B [ i ] = arr [ i ] ; } sort ( B , B + N ) ; for ( int i = N - 1 ; i >= 1 ; i -- ) { if ( B [ i ] != B [ i - 1 ] ) { save = B [ i ] ; break ; } } if ( save == -1 ) { cout << -1 << endl ; return ; } if ( save == arr [ 0 ] && save != arr [ 1 ] ) { cout << 1 ; } else if ( save == arr [ N - 1 ] && save != arr [ N - 2 ] ) { cout << N ; } for ( int i = 1 ; i < N - 1 ; i ++ ) { if ( save == arr [ i ] && ( save != arr [ i - 1 ] save != arr [ i + 1 ] ) ) { cout << i + 1 ; break ; } } } int main ( ) { int arr [ ] = { 5 , 3 , 4 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printIndex ( arr , N ) ; return 0 ; } |
Lexicographically smallest subsequence possible by removing a character from given string | C ++ program for the above approach ; Function to find the lexicographically smallest subsequence of length N - 1 ; Generate all subsequence of length N - 1 ; Store main value of string str ; Erasing element at position i ; Sort the vector ; Print first element of vector ; Driver Code ; Given string S ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void firstSubsequence ( string s ) { vector < string > allsubseq ; string k ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { k = s ; k . erase ( i , 1 ) ; allsubseq . push_back ( k ) ; } sort ( allsubseq . begin ( ) , allsubseq . end ( ) ) ; cout << allsubseq [ 0 ] ; } int main ( ) { string S = " geeksforgeeks " ; firstSubsequence ( S ) ; return 0 ; } |
Maximum even sum subsequence of length K | C ++ program to implement the above approach ; Function to find the maximum even sum of any subsequence of length K ; If count of elements is less than K ; Stores maximum even subsequence sum ; Stores Even numbers ; Stores Odd numbers ; Traverse the array ; If current element is an odd number ; Insert odd number ; Insert even numbers ; Sort Odd [ ] array ; Sort Even [ ] array ; Stores current index Of Even [ ] array ; Stores current index Of Odd [ ] array ; If K is odd ; If count of elements in Even [ ] >= 1 ; Update maxSum ; Update i ; If count of elements in Even [ ] array is 0. ; Update K ; If count of elements in Even [ ] and odd [ ] >= 2 ; Update maxSum ; Update j . ; Update maxSum ; Update i ; Update K ; If count of elements in Even [ ] array >= 2. ; Update maxSum ; Update i . ; Update K . ; If count of elements in Odd [ ] array >= 1 ; Update maxSum ; Update i . ; Update K . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int evenSumK ( int arr [ ] , int N , int K ) { if ( K > N ) { return -1 ; } int maxSum = 0 ; vector < int > Even ; vector < int > Odd ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] % 2 ) { Odd . push_back ( arr [ i ] ) ; } else { Even . push_back ( arr [ i ] ) ; } } sort ( Odd . begin ( ) , Odd . end ( ) ) ; sort ( Even . begin ( ) , Even . end ( ) ) ; int i = Even . size ( ) - 1 ; int j = Odd . size ( ) - 1 ; while ( K > 0 ) { if ( K % 2 == 1 ) { if ( i >= 0 ) { maxSum += Even [ i ] ; i -- ; } else { return -1 ; } K -- ; } else if ( i >= 1 && j >= 1 ) { if ( Even [ i ] + Even [ i - 1 ] <= Odd [ j ] + Odd [ j - 1 ] ) { maxSum += Odd [ j ] + Odd [ j - 1 ] ; j -= 2 ; } else { maxSum += Even [ i ] + Even [ i - 1 ] ; i -= 2 ; } K -= 2 ; } else if ( i >= 1 ) { maxSum += Even [ i ] + Even [ i - 1 ] ; i -= 2 ; K -= 2 ; } else if ( j >= 1 ) { maxSum += Odd [ j ] + Odd [ j - 1 ] ; j -= 2 ; K -= 2 ; } } return maxSum ; } int main ( ) { int arr [ ] = { 2 , 4 , 10 , 3 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; cout << evenSumK ( arr , N , K ) ; } |
Program to find weighted median of a given array | C ++ program for the above approach ; Function to calculate weighted median ; Store pr of arr [ i ] and W [ i ] ; Sort the list of pr w . r . t . to their arr [ ] values ; If N is odd ; Traverse the set pr from left to right ; Update sums ; If sum becomes > 0.5 ; If N is even ; For lower median traverse the set pr from left ; Update sums ; When sum >= 0.5 ; For upper median traverse the set pr from right ; Update sums ; When sum >= 0.5 ; Driver Code ; Given array arr [ ] ; Given weights W [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void weightedMedian ( vector < int > arr , vector < float > W ) { vector < pair < int , float > > pr ; for ( int index = 0 ; index < arr . size ( ) ; index ++ ) pr . push_back ( { arr [ index ] , W [ index ] } ) ; sort ( pr . begin ( ) , pr . end ( ) ) ; if ( arr . size ( ) % 2 != 0 ) { float sums = 0 ; for ( auto element : pr ) { sums += element . second ; if ( sums > 0.5 ) cout << " The β Weighted β Median β is β element β " << element . first << endl ; } } else { float sums = 0 ; for ( auto element : pr ) { sums += element . second ; if ( sums >= 0.5 ) { cout << " Lower β Weighted β Median β is β element β " << element . first << endl ; break ; } } sums = 0 ; for ( int index = pr . size ( ) - 1 ; index >= 0 ; index -- ) { int element = pr [ index ] . first ; float weight = pr [ index ] . second ; sums += weight ; if ( sums >= 0.5 ) { cout << " Upper β Weighted β Median β is β element β " << element ; break ; } } } } int main ( ) { vector < int > arr = { 4 , 1 , 3 , 2 } ; vector < float > W = { 0.25 , 0.49 , 0.25 , 0.01 } ; weightedMedian ( arr , W ) ; } |
Kth smallest element from an array of intervals | C ++ Program to implement the above approach ; Function to get the Kth smallest element from an array of intervals ; Store all the intervals so that it returns the minimum element in O ( 1 ) ; Insert all Intervals into the MinHeap ; Stores the count of popped elements ; Iterate over MinHeap ; Stores minimum element from all remaining intervals ; Remove minimum element ; Check if the minimum of the current interval is less than the maximum of the current interval ; Insert new interval ; Driver Code ; Intervals given ; Size of the arr | #include <bits/stdc++.h> NEW_LINE using namespace std ; int KthSmallestNum ( pair < int , int > arr [ ] , int n , int k ) { priority_queue < pair < int , int > , vector < pair < int , int > > , greater < pair < int , int > > > pq ; for ( int i = 0 ; i < n ; i ++ ) { pq . push ( { arr [ i ] . first , arr [ i ] . second } ) ; } int cnt = 1 ; while ( cnt < k ) { pair < int , int > interval = pq . top ( ) ; pq . pop ( ) ; if ( interval . first < interval . second ) { pq . push ( { interval . first + 1 , interval . second } ) ; } cnt ++ ; } return pq . top ( ) . first ; } int main ( ) { pair < int , int > arr [ ] = { { 5 , 11 } , { 10 , 15 } , { 12 , 20 } } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 12 ; cout << KthSmallestNum ( arr , n , k ) ; } |
Maximum Manhattan distance between a distinct pair from N coordinates | C ++ program for the above approach ; Function to calculate the maximum Manhattan distance ; Stores the maximum distance ; Find Manhattan distance using the formula | x1 - x2 | + | y1 - y2 | ; Updating the maximum ; Driver Code ; Given Co - ordinates ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void MaxDist ( vector < pair < int , int > > & A , int N ) { int maximum = INT_MIN ; for ( int i = 0 ; i < N ; i ++ ) { int sum = 0 ; for ( int j = i + 1 ; j < N ; j ++ ) { sum = abs ( A [ i ] . first - A [ j ] . first ) + abs ( A [ i ] . second - A [ j ] . second ) ; maximum = max ( maximum , sum ) ; } } cout << maximum ; } int main ( ) { int N = 3 ; vector < pair < int , int > > A = { { 1 , 2 } , { 2 , 3 } , { 3 , 4 } } ; MaxDist ( A , N ) ; return 0 ; } |
Longest increasing subsequence which forms a subarray in the sorted representation of the array | C ++ program to implement the above approach ; Function to find the length of the longest increasing sorted sequence ; Stores the count of all elements ; Store the original array ; Sort the array ; If adjacent element are not same ; Increment count ; Store frequency of each element ; Initialize a DP array ; Iterate over the array ar [ ] ; Length of the longest increasing sorted sequence ; Iterate over the array ; Current element ; If the element has been encountered the first time ; If all the x - 1 previous elements have already appeared ; Otherwise ; If all x - 1 elements have already been encountered ; Increment the count of the current element ; Update maximum subsequence size ; Return the maximum subsequence size ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int LongestSequence ( int a [ ] , int n ) { map < int , int > m ; int ar [ n + 1 ] , i , j ; for ( i = 1 ; i <= n ; i ++ ) { ar [ i ] = a [ i - 1 ] ; } sort ( a , a + n ) ; int c = 1 ; m [ a [ 0 ] ] = c ; for ( i = 1 ; i <= n ; i ++ ) { if ( a [ i ] != a [ i - 1 ] ) { c ++ ; m [ a [ i ] ] = c ; } } map < int , int > cnt ; int dp [ n + 1 ] [ 3 ] = { 0 } ; cnt [ 0 ] = 0 ; for ( i = 1 ; i <= n ; i ++ ) { ar [ i ] = m [ ar [ i ] ] ; cnt [ ar [ i ] ] ++ ; } int ans = 0 , x ; for ( i = 1 ; i <= n ; i ++ ) { x = ar [ i ] ; if ( dp [ x ] [ 0 ] == 0 ) { if ( dp [ x - 1 ] [ 0 ] == cnt [ x - 1 ] ) { dp [ x ] [ 1 ] = dp [ x - 1 ] [ 1 ] ; dp [ x ] [ 2 ] = dp [ x - 1 ] [ 1 ] ; } else { dp [ x ] [ 1 ] = dp [ x - 1 ] [ 0 ] ; } } dp [ x ] [ 2 ] = max ( dp [ x - 1 ] [ 0 ] , dp [ x ] [ 2 ] ) ; if ( dp [ x - 1 ] [ 0 ] == cnt [ x - 1 ] ) { dp [ x ] [ 2 ] = max ( dp [ x ] [ 2 ] , dp [ x - 1 ] [ 1 ] ) ; } for ( j = 0 ; j < 3 ; j ++ ) { dp [ x ] [ j ] ++ ; ans = max ( ans , dp [ x ] [ j ] ) ; } } return ans ; } int main ( ) { int arr [ ] = { 2 , 6 , 4 , 8 , 2 , 9 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << LongestSequence ( arr , N ) ; return 0 ; } |
Maximize the sum of Kth column of a Matrix | C ++ program to implement the above approach ; Function to maximize the Kth column sum ; Store all the elements of the resultant matrix of size N * N ; Store value of each elements of the matrix ; Fill all the columns < K ; Fill all the columns >= K ; Function to print the matrix ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int * * findMatrix ( int N , int K ) { int * * mat = ( int * * ) malloc ( N * sizeof ( int * ) ) ; for ( int i = 0 ; i < N ; ++ i ) { mat [ i ] = ( int * ) malloc ( N * sizeof ( int ) ) ; } int element = 1 ; for ( int i = 0 ; i < N ; ++ i ) { for ( int j = 0 ; j < K - 1 ; ++ j ) { mat [ i ] [ j ] = element ++ ; } } for ( int i = 0 ; i < N ; ++ i ) { for ( int j = K - 1 ; j < N ; ++ j ) { mat [ i ] [ j ] = element ++ ; } } return mat ; } void printMatrix ( int * * mat , int N ) { for ( int i = 0 ; i < N ; ++ i ) { for ( int j = 0 ; j < N ; ++ j ) { cout << mat [ i ] [ j ] << " β " ; } cout << endl ; } } int main ( ) { int N = 3 , K = 2 ; int * * mat = findMatrix ( N , K ) ; printMatrix ( mat , N ) ; } |
Range sum queries based on given conditions | C ++ program for the above approach ; Function to calculate the sum between the given range as per value of m ; Stores the sum ; Condition for a to print the sum between ranges [ a , b ] ; Return sum ; Function to precalculate the sum of both the vectors ; Make Prefix sum array ; Function to compute the result for each query ; Take a dummy vector and copy the element of arr in brr ; Sort the dummy vector ; Compute prefix sum of both vectors ; Performs operations ; Function Call to find sum ; Function Call to find sum ; Driver Code ; Given arr [ ] ; Number of queries ; Given queries ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int range_sum ( vector < int > & arr , int a , int b ) { int sum = 0 ; if ( a - 2 < 0 ) sum = arr [ b - 1 ] ; else sum = arr [ b - 1 ] - arr [ a - 2 ] ; return sum ; } void precompute_sum ( vector < int > & arr , vector < int > & brr ) { int N = ( int ) arr . size ( ) ; for ( int i = 1 ; i <= N ; i ++ ) { arr [ i ] = arr [ i ] + arr [ i - 1 ] ; brr [ i ] = brr [ i ] + brr [ i - 1 ] ; } } void find_sum ( vector < int > & arr , int q , int Queries [ ] [ 3 ] ) { vector < int > brr ( arr ) ; int N = ( int ) arr . size ( ) ; sort ( brr . begin ( ) , brr . end ( ) ) ; precompute_sum ( arr , brr ) ; for ( int i = 0 ; i < q ; i ++ ) { int m = Queries [ i ] [ 0 ] ; int a = Queries [ i ] [ 1 ] ; int b = Queries [ i ] [ 2 ] ; if ( m == 1 ) { cout << range_sum ( arr , a , b ) << ' β ' ; } else if ( m == 2 ) { cout << range_sum ( brr , a , b ) << ' β ' ; } } } int main ( ) { vector < int > arr = { 0 , 6 , 4 , 2 , 7 , 2 , 7 } ; int Q = 1 ; int Queries [ ] [ 3 ] = { { 2 , 3 , 6 } } ; find_sum ( arr , Q , Queries ) ; return 0 ; } |
XOR of all possible pairwise sum from two given Arrays | C ++ Program to implement the above approach ; Function to calculate the XOR of the sum of every pair ; Stores the maximum bit ; Look for all the k - th bit ; Stores the modulo of elements B [ ] with ( 2 ^ ( k + 1 ) ) ; Calculate modulo of array B [ ] with ( 2 ^ ( k + 1 ) ) ; Sort the array C [ ] ; Stores the total number whose k - th bit is set ; Calculate and store the modulo of array A [ ] with ( 2 ^ ( k + 1 ) ) ; Lower bound to count the number of elements having k - th bit in the range ( 2 ^ k - x , 2 * 2 ^ ( k ) - x ) ; Add total number i . e ( r - l ) whose k - th bit is one ; Lower bound to count the number of elements having k - th bit in range ( 3 * 2 ^ k - x , 4 * 2 ^ ( k ) - x ) ; If count is even , Xor of k - th bit becomes zero , no need to add to the answer . If count is odd , only then , add to the final answer ; Return answer ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int XorSum ( int A [ ] , int B [ ] , int N ) { const int maxBit = 29 ; int ans = 0 ; for ( int k = 0 ; k < maxBit ; k ++ ) { int C [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { C [ i ] = B [ i ] % ( 1 << ( k + 1 ) ) ; } sort ( C , C + N ) ; long long count = 0 ; long long l , r ; for ( int i = 0 ; i < N ; i ++ ) { int x = A [ i ] % ( 1 << ( k + 1 ) ) ; l = lower_bound ( C , C + N , ( 1 << k ) - x ) - C ; r = lower_bound ( C , C + N , ( 1 << k ) * 2 - x ) - C ; count += ( r - l ) ; l = lower_bound ( C , C + N , ( 1 << k ) * 3 - x ) - C ; r = lower_bound ( C , C + N , ( 1 << k ) * 4 - x ) - C ; count += ( r - l ) ; } if ( count & 1 ) ans += ( 1 << k ) ; } return ans ; } int main ( ) { int A [ ] = { 4 , 6 , 0 , 0 , 3 , 3 } ; int B [ ] = { 0 , 5 , 6 , 5 , 0 , 3 } ; int N = sizeof A / sizeof A [ 0 ] ; cout << XorSum ( A , B , N ) << endl ; return 0 ; } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.