text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Minimum number of jumps required to sort the given array in ascending order | C ++ program for the above approach ; Function to count minimum number of jumps required to sort the array ; Stores minimum number of jumps ; Stores distances of jumps ; Stores the array elements with their starting indices ; Push the pairs { arr [ i ] , i + 1 } into the vector of pairs vect ; Update vect ; Populate the array temp [ ] ; Update temp [ arr [ i ] ] ; Sort the vector in the ascending order ; Jump till the previous index <= current index ; Update vect [ i ] ; Increment the number of jumps ; Print the minimum number of jumps required ; Driver Code ; Input ; Size of the array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minJumps ( int arr [ ] , int jump [ ] , int N ) { int jumps = 0 ; int temp [ 1000 ] ; vector < pair < int , int > > vect ; for ( int i = 0 ; i < N ; i ++ ) { vect . push_back ( { arr [ i ] , i + 1 } ) ; } for ( int i = 0 ; i < N ; i ++ ) { temp [ arr [ i ] ] = jump [ i ] ; } sort ( vect . begin ( ) , vect . end ( ) ) ; for ( int i = 1 ; i < N ; i ++ ) { while ( vect [ i ] . second <= vect [ i - 1 ] . second ) { vect [ i ] = make_pair ( vect [ i ] . first , vect [ i ] . second + temp [ vect [ i ] . first ] ) ; jumps ++ ; } } cout << jumps << endl ; } int main ( ) { int arr [ ] = { 3 , 2 , 1 } ; int jump [ ] = { 1 , 1 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minJumps ( arr , jump , N ) ; return 0 ; }
Minimum number of basic logic gates required to realize given Boolean expression | C ++ implementation of the above approach ; Function to count the total number of gates required to realize the boolean expression S ; Length of the string ; Stores the count of total gates ; Traverse the string ; AND , OR and NOT Gate ; Print the count of gates required ; Driver Code ; Input ; Function call to count the total number of gates required
#include <bits/stdc++.h> NEW_LINE using namespace std ; void numberOfGates ( string s ) { int N = s . size ( ) ; int ans = 0 ; for ( int i = 0 ; i < ( int ) s . size ( ) ; i ++ ) { if ( s [ i ] == ' . ' s [ i ] == ' + ' s [ i ] == '1' ) { ans ++ ; } } cout << ans ; } int main ( ) { string S = " ( 1 - A ) . B + C " ; numberOfGates ( S ) ; }
Count pairs ( i , j ) from an array such that | arr [ i ] | and | arr [ j ] | both lies between | arr [ i ] | C ++ program for the above approach ; Function to find pairs ( i , j ) such that | arr [ i ] | and | arr [ j ] | lies in between | arr [ i ] - arr [ j ] | and | arr [ i ] + arr [ j ] | ; Calculate absolute value of all array elements ; Sort the array ; Stores the count of pairs ; Traverse the array ; Increment left ; Add to the current count of pairs ; Print the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findPairs ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) arr [ i ] = abs ( arr [ i ] ) ; sort ( arr , arr + N ) ; int left = 0 ; int ans = 0 ; for ( int right = 0 ; right < N ; right ++ ) { while ( 2 * arr [ left ] < arr [ right ] ) left ++ ; ans += ( right - left ) ; } cout << ans ; } int main ( ) { int arr [ ] = { 1 , 3 , 5 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findPairs ( arr , N ) ; return 0 ; }
Calculate absolute difference between minimum and maximum sum of pairs in an array | C ++ program for the above approach ; Function to find the difference between the maximum and minimum sum of a pair ( arr [ i ] , arr [ j ] ) from the array such that i < j and arr [ i ] < arr [ j ] ; Stores the maximum from the suffix of the array ; Set the last element ; Traverse the remaining array ; Update the maximum from suffix for the remaining indices ; Stores the maximum sum of any pair ; Calculate the maximum sum ; Stores the maximum sum of any pair ; Stores the minimum of suffixes from the given array ; Set the last element ; Traverse the remaining array ; Update the maximum from suffix for the remaining indices ; Calculate the minimum sum ; Return the resultant difference ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int GetDiff ( int A [ ] , int N ) { int SuffMaxArr [ N ] ; SuffMaxArr [ N - 1 ] = A [ N - 1 ] ; for ( int i = N - 2 ; i >= 0 ; -- i ) { SuffMaxArr [ i ] = max ( SuffMaxArr [ i + 1 ] , A [ i + 1 ] ) ; } int MaximumSum = INT_MIN ; for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( A [ i ] < SuffMaxArr [ i ] ) MaximumSum = max ( MaximumSum , A [ i ] + SuffMaxArr [ i ] ) ; } int MinimumSum = INT_MAX ; int SuffMinArr [ N ] ; SuffMinArr [ N - 1 ] = INT_MAX ; for ( int i = N - 2 ; i >= 0 ; -- i ) { SuffMinArr [ i ] = min ( SuffMinArr [ i + 1 ] , A [ i + 1 ] ) ; } for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( A [ i ] < SuffMinArr [ i ] ) { MinimumSum = min ( MinimumSum , A [ i ] + SuffMinArr [ i ] ) ; } } return abs ( MaximumSum - MinimumSum ) ; } int main ( ) { int arr [ ] = { 2 , 4 , 1 , 3 , 7 , 5 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << GetDiff ( arr , N ) ; return 0 ; }
Minimum number of swaps required to make parity of array elements same as their indices | C ++ program for the above approach ; Function to count the minimum number of swaps required to make the parity of array elements same as their indices ; Stores count of even and odd array elements ; Traverse the array ; Check if indices and array elements are not of the same parity ; If index is even ; Update even ; Update odd ; Condition for not possible ; Otherwise ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumSwaps ( int arr [ ] , int N ) { int even = 0 , odd = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] % 2 != i % 2 ) { if ( i % 2 == 0 ) { even ++ ; } else { odd ++ ; } } } if ( even != odd ) { cout << -1 ; } else { cout << even ; } } int main ( ) { int arr [ ] = { 3 , 2 , 7 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minimumSwaps ( arr , N ) ; return 0 ; }
Smallest substring occurring only once in a given string | C ++ program for the above approach ; Function to find the smallest substring occurring only once ; Stores all occurences ; Generate all the substrings ; Avoid multiple occurences ; Append all substrings ; Take into account all the substrings ; Iterate over all unique substrings ; If frequency is 1 ; Append into fresh list ; Initialize a dictionary ; Append the keys ; Traverse the dictionary ; Print the minimum of dictionary ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int smallestSubstring ( string a ) { vector < string > a1 ; for ( int i = 0 ; i < a . size ( ) ; i ++ ) { for ( int j = i + 1 ; j < a . size ( ) ; j ++ ) { if ( i != j ) a1 . push_back ( a . substr ( i , j + 1 ) ) ; } } map < string , int > a2 ; for ( string i : a1 ) a2 [ i ] ++ ; vector < string > freshlist ; for ( auto i : a2 ) { if ( i . second == 1 ) freshlist . push_back ( i . first ) ; } map < string , int > dictionary ; for ( auto i : freshlist ) { dictionary [ i ] = i . size ( ) ; } vector < int > newlist ; for ( auto i : dictionary ) newlist . push_back ( i . second ) ; int ans = INT_MAX ; for ( int i : newlist ) ans = min ( ans , i ) ; return ans ; } int main ( ) { string S = " ababaabba " ; cout << smallestSubstring ( S ) ; return 0 ; }
Minimize insertions required to make ratio of maximum and minimum of all pairs of adjacent array elements at most K | C ++ program to implement the above approach ; Function to count the minimum number of insertions required ; Stores the number of insertions required ; Traverse the array ; Store the minimum array element ; Store the maximum array element ; Checking condition ; Increase current count ; Return the count of insertions ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int mininsert ( int arr [ ] , int K , int N ) { int ans = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { int a = min ( arr [ i ] , arr [ i + 1 ] ) ; int b = max ( arr [ i ] , arr [ i + 1 ] ) ; while ( K * a < b ) { a *= K ; ans ++ ; } } return ans ; } int main ( ) { int arr [ ] = { 2 , 10 , 25 , 21 } ; int K = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << mininsert ( arr , K , N ) ; return 0 ; }
Sum of numbers formed by consecutive digits present in a given string | C ++ Program to implement the above approach ; Function to calculate the sum of numbers formed by consecutive sequences of digits present in the string ; Stores consecutive digits present in the string ; Stores the sum ; Iterate over characters of the input string ; If current character is a digit ; Append current digit to curr ; Add curr to sum ; Reset curr ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfDigits ( string s ) { int curr = 0 ; int ret = 0 ; for ( auto & ch : s ) { if ( isdigit ( ch ) ) { curr = curr * 10 + ch - '0' ; } else { ret += curr ; curr = 0 ; } } ret += curr ; return ret ; } int main ( ) { string S = "11aa32bbb5" ; cout << sumOfDigits ( S ) ; return 0 ; }
Find a triplet ( i , j , k ) from an array such that i < j < k and arr [ i ] < arr [ j ] > arr [ k ] | C ++ program for the above approach ; Function to find a triplet such that i < j < k and arr [ i ] < arr [ j ] and arr [ j ] > arr [ k ] ; Traverse the array ; Condition to satisfy for the resultant triplet ; Otherwise , triplet doesn 't exist ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void print_triplet ( int arr [ ] , int n ) { for ( int i = 1 ; i <= n - 2 ; i ++ ) { if ( arr [ i - 1 ] < arr [ i ] && arr [ i ] > arr [ i + 1 ] ) { cout << i - 1 << " ▁ " << i << " ▁ " << i + 1 ; return ; } } cout << -1 ; } int main ( ) { int arr [ ] = { 4 , 3 , 5 , 2 , 1 , 6 } ; int N = sizeof ( arr ) / sizeof ( int ) ; print_triplet ( arr , N ) ; return 0 ; }
Check if an array element is concatenation of two elements from another array | C ++ program for the above approach ; Function to find elements present in the array b [ ] which are concatenation of any pair of elements in the array a [ ] ; Stores if there doesn 't any such element in the array brr[] ; Stored the size of both the arrays ; Store the presence of an element of array a [ ] ; Traverse the array a [ ] ; Traverse the array b [ ] ; Traverse over all possible concatenations of b [ i ] ; Update right and left parts ; Check if both left and right parts are present in a [ ] ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findConcatenatedNumbers ( vector < int > a , vector < int > b ) { bool ans = true ; int n1 = a . size ( ) ; int n2 = b . size ( ) ; unordered_map < int , int > cnt ; for ( int i = 0 ; i < n1 ; i ++ ) { cnt [ a [ i ] ] = 1 ; } for ( int i = 0 ; i < n2 ; i ++ ) { int left = b [ i ] ; int right = 0 ; int mul = 1 ; while ( left > 9 ) { right += ( left % 10 ) * mul ; left /= 10 ; mul *= 10 ; if ( cnt [ left ] == 1 && cnt [ right ] == 1 ) { ans = false ; cout << b [ i ] << " ▁ " ; } } } if ( ans ) cout << " - 1" ; } int main ( ) { vector < int > a = { 2 , 34 , 4 , 5 } ; vector < int > b = { 26 , 24 , 345 , 4 , 22 } ; findConcatenatedNumbers ( a , b ) ; return 0 ; }
Number of subarrays having even product | CPP implementation of the above approach ; Function to count subarrays with even product ; Stores count of subarrays with even product ; Traverse the array ; Initialize product ; Update product of the subarray ; Print total count of subarrays ; Driver Code ; Input ; Length of an array ; Function call to count subarrays with even product
#include <bits/stdc++.h> NEW_LINE using namespace std ; void evenproduct ( int arr [ ] , int length ) { int count = 0 ; for ( int i = 0 ; i < length + 1 ; i ++ ) { int product = 1 ; for ( int j = i ; j < length + 1 ; j ++ ) { product *= arr [ j ] ; if ( product % 2 == 0 ) ++ count ; } } cout << count ; } int main ( ) { int arr [ ] = { 7 , 5 , 4 , 9 } ; int length = ( sizeof ( arr ) / sizeof ( arr [ 0 ] ) ) - 1 ; evenproduct ( arr , length ) ; }
Count pairs of nodes having minimum distance between them equal to the difference of their distances from root | C ++ program for the above approach ; Stores the count of pairs ; Store the adjacency list of the connecting vertex ; Function for theto perform DFS traversal of the given tree ; Traverse the adjacency list of the current node u ; If the current node is the parent node ; Add number of ancestors , which is same as depth of the node ; Function for DFS traversal of the given tree ; Print the result ; Function to find the count of pairs such that the minimum distance between them is equal to the difference between distance of the nodes from root node ; Add edges to adj [ ] ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long ans = 0 ; vector < int > adj [ int ( 1e5 ) + 1 ] ; void dfsUtil ( int u , int par , int depth ) { for ( auto it : adj [ u ] ) { if ( it != par ) { dfsUtil ( it , u , depth + 1 ) ; } } ans += depth ; } void dfs ( int u , int par , int depth ) { dfsUtil ( u , par , depth ) ; cout << ans << endl ; } void countPairs ( vector < vector < int > > edges ) { for ( int i = 0 ; i < edges . size ( ) ; i ++ ) { int u = edges [ i ] [ 0 ] ; int v = edges [ i ] [ 1 ] ; adj [ u ] . push_back ( v ) ; adj [ v ] . push_back ( u ) ; } dfs ( 1 , 1 , 1 ) ; } int main ( ) { vector < vector < int > > edges = { { 1 , 2 } , { 1 , 3 } , { 2 , 4 } } ; countPairs ( edges ) ; return 0 ; }
Number from a given range that requires Kth smallest number of steps to get reduced to 1 | C ++ program for the above approach ; Function to count the number of steps required to reduce val to 1 by the given operations ; Base Case ; If val is even , divide by 2 ; Otherwise , multiply it by 3 and increment by 1 ; Function to find Kth smallest count of steps required for numbers from the range [ L , R ] ; Stores numbers and their respective count of steps ; Count the number of steps for all numbers from the range [ L , R ] ; Insert in the vector ; Sort the vector in ascending order w . r . t . to power value ; Print the K - th smallest number ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE vector < ll > v ( 1000000 , -1 ) ; ll power_value ( ll val ) { if ( val == 1 ) return 0 ; if ( val % 2 == 0 ) { v [ val ] = power_value ( val / 2 ) + 1 ; return v [ val ] ; } else { ll temp = val * 3 ; temp ++ ; v [ val ] = power_value ( temp ) + 1 ; return v [ val ] ; } } ll getKthNumber ( int l , int r , int k ) { vector < pair < ll , ll > > ans ; for ( ll i = l ; i <= r ; i ++ ) { if ( v [ i ] == -1 ) power_value ( i ) ; } ll j = 0 ; for ( ll i = l ; i <= r ; i ++ ) { ans . push_back ( make_pair ( v [ i ] , i ) ) ; j ++ ; } sort ( ans . begin ( ) , ans . end ( ) ) ; cout << ans [ k - 1 ] . second ; } int main ( ) { int L = 7 , R = 10 , K = 4 ; getKthNumber ( L , R , K ) ; return 0 ; }
Sum of decimal equivalents of binary node values in each level of a Binary Tree | CPP program for the above approach ; Structure of a Tree Node ; Function to convert binary number to its equivalent decimal value ; Function to calculate sum of decimal equivalent of binary numbers of node values present at each level ; Push root node into queue ; Connect nodes at the same level to form a binary number ; Append the value of the current node to eachLvl ; Insert the Left child to queue , if its not NULL ; Insert the Right child to queue , if its not NULL ; Decrement length by one ; Stores the front element of the queue ; Add decimal equivalent of the binary number formed on the current level to ans ; Finally print ans ; Driver Code ; Given Tree ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; class TreeNode { public : int val ; TreeNode * left , * right ; TreeNode ( int key ) { val = key ; left = right = NULL ; } } ; int convertBinaryToDecimal ( vector < int > arr ) { int ans = 0 ; for ( int i : arr ) ans = ( ans << 1 ) | i ; return ans ; } void decimalEquilvalentAtEachLevel ( TreeNode * root ) { int ans = 0 ; queue < TreeNode * > que ; que . push ( root ) ; while ( true ) { int length = que . size ( ) ; if ( length == 0 ) break ; vector < int > eachLvl ; while ( length > 0 ) { TreeNode * temp = que . front ( ) ; que . pop ( ) ; eachLvl . push_back ( temp -> val ) ; if ( temp -> left != NULL ) que . push ( temp -> left ) ; if ( temp -> right != NULL ) que . push ( temp -> right ) ; length -= 1 ; } ans += convertBinaryToDecimal ( eachLvl ) ; } cout << ans << endl ; } int main ( ) { TreeNode * root = new TreeNode ( 0 ) ; root -> left = new TreeNode ( 1 ) ; root -> right = new TreeNode ( 0 ) ; root -> left -> left = new TreeNode ( 0 ) ; root -> left -> right = new TreeNode ( 1 ) ; root -> right -> left = new TreeNode ( 1 ) ; root -> right -> right = new TreeNode ( 1 ) ; decimalEquilvalentAtEachLevel ( root ) ; return 0 ; }
Minimize increments required to make differences between all pairs of array elements even | C ++ program for the above approach ; Function to find the minimum increments required to difference between all pairs of array elements even ; Store the count of odd and even numbers ; Traverse the array ; Increment evenCnt by 1 ; Increment eveCnt by 1 ; Print the minimum of oddCnt and eveCnt ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumOperations ( int arr [ ] , int N ) { int oddCnt = 0 , evenCnt = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] % 2 == 0 ) { evenCnt ++ ; } else { oddCnt ++ ; } } cout << min ( oddCnt , evenCnt ) ; } int main ( ) { int arr [ ] = { 4 , 1 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minimumOperations ( arr , N ) ; return 0 ; }
Minimum increments required to make array elements alternately even and odd | C ++ program for the above approach ; Function to find the minimum number of increments required to make the array even - odd alternately or vice - versa ; Store the minimum number of increments required ; Traverse the array arr [ ] ; Increment forEven if even element is present at an odd index ; Increment forEven if odd element is present at an even index ; Return the minimum number of increments ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int minIncr ( int * arr , int n ) { int forEven = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 ) { if ( ( arr [ i ] % 2 ) == 0 ) forEven += 1 ; } else { if ( arr [ i ] % 2 ) forEven += 1 ; } } return min ( forEven , n - forEven ) ; } int main ( ) { int arr [ ] = { 1 , 4 , 6 , 8 , 9 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minIncr ( arr , n ) ; return 0 ; }
Queries to find the minimum array sum possible by removing elements from either end | C ++ program for the above approach ; Function to find the minimum sum for each query after removing element from either ends till each value Q [ i ] ; Stores the prefix sum from both the ends of the array ; Traverse the array from front ; Insert it into the map m1 ; Traverse the array in reverse ; Insert it into the map m2 ; Traverse the query array ; Print the minimum of the two values as the answer ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minOperations ( int arr [ ] , int N , int Q [ ] , int M ) { map < int , int > m1 , m2 ; int front = 0 , rear = 0 ; for ( int i = 0 ; i < N ; i ++ ) { front += arr [ i ] ; m1 . insert ( { arr [ i ] , front } ) ; } for ( int i = N - 1 ; i >= 0 ; i -- ) { rear += arr [ i ] ; m2 . insert ( { arr [ i ] , rear } ) ; } for ( int i = 0 ; i < M ; i ++ ) { cout << min ( m1 [ Q [ i ] ] , m2 [ Q [ i ] ] ) << " ▁ " ; } } int main ( ) { int arr [ ] = { 2 , 3 , 6 , 7 , 4 , 5 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int Q [ ] = { 7 , 6 } ; int M = sizeof ( Q ) / sizeof ( Q [ 0 ] ) ; minOperations ( arr , N , Q , M ) ; return 0 ; }
Check if a string contains an anagram of another string as its substring | C ++ Program to implement the above approach ; Function to check if string s2 contains anagram of the string s1 as its substring ; Stores frequencies of characters in substrings of s2 ; Stores frequencies of characters in s1 ; If length of s2 exceeds length of s1 ; Store frequencies of characters in first substring of length s1len in string s2 ; Perform Sliding Window technique ; If hashmaps are found to be identical for any substring ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkAnagram ( string s1 , string s2 ) { vector < int > s2hash ( 26 , 0 ) ; vector < int > s1hash ( 26 , 0 ) ; int s1len = s1 . size ( ) ; int s2len = s2 . size ( ) ; if ( s1len > s2len ) return false ; int left = 0 , right = 0 ; while ( right < s1len ) { s1hash [ s1 [ right ] - ' a ' ] += 1 ; s2hash [ s2 [ right ] - ' a ' ] += 1 ; right ++ ; } right -= 1 ; while ( right < s2len ) { if ( s1hash == s2hash ) return true ; right ++ ; if ( right != s2len ) s2hash [ s2 [ right ] - ' a ' ] += 1 ; s2hash [ s2 [ left ] - ' a ' ] -= 1 ; left ++ ; } return false ; } int main ( ) { string s1 = " ab " ; string s2 = " bbpobac " ; if ( checkAnagram ( s1 , s2 ) ) cout << " YES STRNEWLINE " ; else cout << " No STRNEWLINE " ; return 0 ; }
Check if K '0' s can be flipped such that Binary String contains no pair of adjacent '1' s | C ++ program for the above approach ; Function to check if k '0' s can be flipped such that the string does not contain any pair of adjacent '1' s ; Store the count of flips ; Variable to iterate the string ; Iterate over characters of the string ; If the current character is '1' , increment i by 2 ; Otherwise , 3 cases arises ; If the current index is the starting index ; If next character is '0' ; Increment i by 1 ; If the current index is the last index ; If previous character is '0' ; For remaining characters ; If both the adjacent characters are '0' ; If cnt is at least K , print " Yes " ; Otherwise , print " No " ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void canPlace ( string s , int n , int k ) { int cnt = 0 ; int i = 0 ; while ( i < n ) { if ( s [ i ] == '1' ) { i += 2 ; } else { if ( i == 0 ) { if ( s [ i + 1 ] == '0' ) { cnt ++ ; i += 2 ; } else i ++ ; } else if ( i == n - 1 ) { if ( s [ i - 1 ] == '0' ) { cnt ++ ; i += 2 ; } else i ++ ; } else { if ( s [ i + 1 ] == '0' && s [ i - 1 ] == '0' ) { cnt ++ ; i += 2 ; } else i ++ ; } } } if ( cnt >= k ) { cout << " Yes " ; } else { cout << " No " ; } } int main ( ) { string S = "10001" ; int K = 1 ; int N = S . size ( ) ; canPlace ( S , N , K ) ; return 0 ; }
Maximum number of intervals that an interval can intersect | C ++ program for the above approach ; Function to count the maximum number of intervals that an interval can intersect ; Store the required answer ; Traverse all the intervals ; Store the number of intersecting intervals ; Iterate in the range [ 0 , n - 1 ] ; Check if jth interval lies outside the ith interval ; Update the overall maximum ; Print the answer ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMaxIntervals ( vector < pair < int , int > > v , int n ) { int maxi = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int c = n ; for ( int j = 0 ; j < n ; j ++ ) { if ( v [ i ] . second < v [ j ] . first v [ i ] . first > v [ j ] . second ) { c -- ; } } maxi = max ( c , maxi ) ; } cout << maxi ; } int main ( ) { vector < pair < int , int > > arr = { { 1 , 2 } , { 3 , 4 } , { 2 , 5 } } ; int N = arr . size ( ) ; findMaxIntervals ( arr , N ) ; return 0 ; }
Check if all disks can be placed at a single rod based on given conditions | C ++ implementation of above approach ; Function to check if it is possible to move all disks to a single rod ; Stores if it is possible to move all disks to a single rod ; Traverse the array ; If i - th element is smaller than both its adjacent elements ; If flag is true ; Otherwise ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int a [ ] , int n ) { bool flag = 0 ; for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( a [ i + 1 ] > a [ i ] && a [ i ] < a [ i - 1 ] ) flag = 1 ; } if ( flag ) return false ; else return true ; } int main ( ) { int arr [ ] = { 1 , 3 , 5 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( check ( arr , N ) ) cout << " YES " ; else cout << " NO " ; return 0 ; }
Smallest positive integer that does not divide any elements of the given array | C ++ program for the above approach ; Function to find the smallest number which doesn 't divides any integer in the given array arr[] ; Traverse the array arr [ ] ; Maximum array element ; Initialize variable ; Traverse from 2 to max ; Stores if any such integer is found or not ; If any array element is divisible by j ; Smallest integer ; Print the answer ; Driver Code ; Function Call
#include <iostream> NEW_LINE using namespace std ; void smallestNumber ( int arr [ ] , int len ) { int maxi = 0 ; for ( int i = 0 ; i < len ; i ++ ) { maxi = std :: max ( maxi , arr [ i ] ) ; } int ans = -1 ; for ( int i = 2 ; i < maxi + 2 ; i ++ ) { bool flag = true ; for ( int j = 0 ; j < len ; j ++ ) { if ( arr [ j ] % i == 0 ) { flag = false ; break ; } } if ( flag ) { ans = i ; break ; } } cout << ans ; } int main ( ) { int arr [ ] = { 3 , 2 , 6 , 9 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; smallestNumber ( arr , N ) ; return 0 ; }
Find the duplicate characters in a string in O ( 1 ) space | C ++ program to implement the above approach ; Function to find duplicate characters in string without using any additional data structure ; Check if ( i + ' a ' ) is present in str at least once or not . ; Check if ( i + ' a ' ) is present in str at least twice or not . ; Iterate over the characters of the string str ; If str [ i ] has already occurred in str ; Set ( str [ i ] - ' a ' ) - th bit of second ; Set ( str [ i ] - ' a ' ) - th bit of second ; Iterate over the range [ 0 , 25 ] ; If i - th bit of both first and second is Set ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findDuplicate ( string str , int N ) { int first = 0 ; int second = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( first & ( 1 << ( str [ i ] - ' a ' ) ) ) { second = second | ( 1 << ( str [ i ] - ' a ' ) ) ; } else { first = first | ( 1 << ( str [ i ] - ' a ' ) ) ; } } for ( int i = 0 ; i < 26 ; i ++ ) { if ( ( first & ( 1 << i ) ) && ( second & ( 1 << i ) ) ) { cout << char ( i + ' a ' ) << " ▁ " ; } } } int main ( ) { string str = " geeksforgeeks " ; int N = str . length ( ) ; findDuplicate ( str , N ) ; }
Minimize insertions required to make all characters of a given string equal | C ++ program for the above approach ; Function to calculate the minimum number of operations required to make all characters of the string same ; Stores count of operations ; Traverse the string ; Check if adjacent characters are same or not ; Increment count ; Print the count obtained ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperations ( string & S ) { int count = 0 ; for ( int i = 1 ; i < S . length ( ) ; i ++ ) { if ( S [ i ] != S [ i - 1 ] ) { count += 1 ; } } cout << count ; } int main ( ) { string S = "0101010101" ; minOperations ( S ) ; return 0 ; }
Count pairs made up of an element divisible by the other from an array consisting of powers of 2 | C ++ program for the above approach ; Function to count the number of pairs as per the given conditions ; Initialize array set_bits as 0 ; Store the total number of required pairs ; Traverse the array arr [ ] ; Store arr [ i ] in x ; Store the position of the leftmost set bit in arr [ i ] ; Increase bit position ; Divide by 2 to shift bits in right at each step ; Count of pairs for index i till its set bit position ; Increasing count of set bit position of current elelement ; Print the answer ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void numberOfPairs ( int arr [ ] , int N ) { int set_bits [ 31 ] = { 0 } ; int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int x = arr [ i ] ; int bitpos = -1 ; while ( x > 0 ) { bitpos ++ ; x /= 2 ; } for ( int j = 0 ; j <= bitpos ; j ++ ) { count += set_bits [ j ] ; } set_bits [ bitpos ] ++ ; } cout << count ; } int main ( ) { int arr [ ] = { 4 , 16 , 8 , 64 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; numberOfPairs ( arr , N ) ; return 0 ; }
Queries to find minimum sum of array elements from either end of an array | C ++ implementation of the above approach ; Function to calculate the minimum sum from either end of the arrays for the given queries ; Traverse the query [ ] array ; Stores sum from start and end of the array ; Calculate distance from start ; Calculate distance from end ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void calculateQuery ( int arr [ ] , int N , int query [ ] , int M ) { for ( int i = 0 ; i < M ; i ++ ) { int X = query [ i ] ; int sum_start = 0 , sum_end = 0 ; for ( int j = 0 ; j < N ; j ++ ) { sum_start += arr [ j ] ; if ( arr [ j ] == X ) break ; } for ( int j = N - 1 ; j >= 0 ; j -- ) { sum_end += arr [ j ] ; if ( arr [ j ] == X ) break ; } cout << min ( sum_end , sum_start ) << " ▁ " ; } } int main ( ) { int arr [ ] = { 2 , 3 , 6 , 7 , 4 , 5 , 30 } ; int queries [ ] = { 6 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int M = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; calculateQuery ( arr , N , queries , M ) ; return 0 ; }
Queries to find minimum sum of array elements from either end of an array | C ++ implementation of the above approach ; Function to find the minimum sum for the given queries ; Stores prefix and suffix sums ; Stores pairs of prefix and suffix sums ; Traverse the array ; Add element to prefix ; Store prefix for each element ; Traverse the array in reverse ; Add element to suffix ; Storing suffix for each element ; Traverse the array queries [ ] ; Minimum of suffix and prefix sums ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void calculateQuery ( int arr [ ] , int N , int query [ ] , int M ) { int prefix = 0 , suffix = 0 ; unordered_map < int , pair < int , int > > mp ; for ( int i = 0 ; i < N ; i ++ ) { prefix += arr [ i ] ; mp [ arr [ i ] ] . first = prefix ; } for ( int i = N - 1 ; i >= 0 ; i -- ) { suffix += arr [ i ] ; mp [ arr [ i ] ] . second = suffix ; } for ( int i = 0 ; i < M ; i ++ ) { int X = query [ i ] ; cout << min ( mp [ X ] . first , mp [ X ] . second ) << " ▁ " ; } } int main ( ) { int arr [ ] = { 2 , 3 , 6 , 7 , 4 , 5 , 30 } ; int queries [ ] = { 6 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int M = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; calculateQuery ( arr , N , queries , M ) ; return 0 ; }
Queries to find the maximum array element after removing elements from a given range | C ++ program for the above approach ; Function to find the maximum element after removing elements in range [ l , r ] ; Store prefix maximum element ; Store suffix maximum element ; Prefix max till first index is first index itself ; Traverse the array to fill prefix max array ; Store maximum till index i ; Suffix max till last index is last index itself ; Traverse the array to fill suffix max array ; Store maximum till index i ; Traverse all queries ; Store the starting and the ending index of the query ; Edge Cases ; Otherwise ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaximum ( int arr [ ] , int N , int Q , int queries [ ] [ 2 ] ) { int prefix_max [ N + 1 ] = { 0 } ; int suffix_max [ N + 1 ] = { 0 } ; prefix_max [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { prefix_max [ i ] = max ( prefix_max [ i - 1 ] , arr [ i ] ) ; } suffix_max [ N - 1 ] = arr [ N - 1 ] ; for ( int i = N - 2 ; i >= 0 ; i -- ) { suffix_max [ i ] = max ( suffix_max [ i + 1 ] , arr [ i ] ) ; } for ( int i = 0 ; i < Q ; i ++ ) { int l = queries [ i ] [ 0 ] ; int r = queries [ i ] [ 1 ] ; if ( l == 0 && r == ( N - 1 ) ) cout << "0 STRNEWLINE " ; else if ( l == 0 ) cout << suffix_max [ r + 1 ] << " STRNEWLINE " ; else if ( r == ( N - 1 ) ) cout << prefix_max [ l - 1 ] << " STRNEWLINE " ; else cout << max ( prefix_max [ l - 1 ] , suffix_max [ r + 1 ] ) << " STRNEWLINE " ; } } int main ( ) { int arr [ ] = { 5 , 6 , 8 , 10 , 15 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int queries [ ] [ 2 ] = { { 0 , 1 } , { 0 , 2 } , { 1 , 4 } } ; int Q = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; findMaximum ( arr , N , Q , queries ) ; return 0 ; }
Queries to find first occurrence of a character in a given range | C ++ implementation for the above approach ; Function to find the first occurence for a given range ; N = length of string ; M = length of queries ; Stores the indices of a character ; Traverse the string ; Push the index i into the vector [ s [ i ] ] ; Traverse the query ; Stores the value L ; Stores the value R ; Stores the character C ; Find index >= L in the vector v ; If there is no index of C >= L ; Stores the value at idx ; If idx > R ; Otherwise ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int firstOccurence ( string s , vector < pair < pair < int , int > , char > > Q ) { int N = s . size ( ) ; int M = Q . size ( ) ; map < char , vector < int > > v ; for ( int i = 0 ; i < N ; i ++ ) { v [ s [ i ] ] . push_back ( i ) ; } for ( int i = 0 ; i < M ; i ++ ) { int left = Q [ i ] . first . first ; int right = Q [ i ] . first . second ; char c = Q [ i ] . second ; if ( v . size ( ) == 0 ) { cout << " - 1 ▁ " ; continue ; } int idx = lower_bound ( v . begin ( ) , v . end ( ) , left ) - v . begin ( ) ; if ( idx == ( int ) v . size ( ) ) { cout << " - 1 ▁ " ; continue ; } idx = v [ idx ] ; if ( idx > right ) { cout << " - 1 ▁ " ; } else { cout << idx << " ▁ " ; } } } int main ( ) { string S = " abcabcabc " ; vector < pair < pair < int , int > , char > > Q = { { { 0 , 3 } , ' a ' } , { { 0 , 2 } , ' b ' } , { { 2 , 4 } , ' z ' } } ; firstOccurence ( S , Q ) ; return 0 ; }
Find index of the element differing in parity with all other array elements | C ++ program for the above approach ; Function to print the element which differs in parity ; Stores the count of odd and even array elements encountered ; Stores the indices of the last odd and even array elements encountered ; Traverse the array ; If array element is even ; Otherwise ; If only one odd element is present in the array ; If only one even element is present in the array ; Driver Code ; Given array ; Size of the array
#include <bits/stdc++.h> NEW_LINE using namespace std ; int oddOneOut ( int arr [ ] , int N ) { int odd = 0 , even = 0 ; int lastOdd = 0 , lastEven = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] % 2 == 0 ) { even ++ ; lastEven = i ; } else { odd ++ ; lastOdd = i ; } } if ( odd == 1 ) { cout << lastOdd << endl ; } else { cout << lastEven << endl ; } } int main ( ) { int arr [ ] = { 2 , 4 , 7 , 8 , 10 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; oddOneOut ( arr , N ) ; return 0 ; }
Reduce a string to a valid email address of minimum length by replacing specified substrings | C ++ program for the above approach ; Function to find the minimum length by replacing at with @ and dot with ' . ' such that the string is valid email ; Stores string by replacing at with @ and dot with ' . ' # such that the string is valid email ; append first character ; Stores index ; Check if at ( @ ) already included or not ; Iterate over characters of the string ; at can be replaced at most once ; Update ans ; Update i ; Update notAt ; If current substring found dot ; Update ans ; Update i ; Update ans ; Update i ; Driver code ; To display the result
#include <bits/stdc++.h> NEW_LINE using namespace std ; string minEmail ( string email ) { string ans = " " ; int len = email . length ( ) ; ans += email [ 0 ] ; int i = 1 ; bool notAt = true ; while ( i < len ) { if ( i < len - 3 && notAt && email [ i ] == ' a ' && email [ i + 1 ] == ' t ' ) { ans += ' @ ' ; i += 1 ; notAt = false ; } else if ( i < len - 4 && email [ i ] == ' d ' && email [ i + 1 ] == ' o ' && email [ i + 2 ] == ' t ' ) { ans += ' . ' ; i += 2 ; } else { ans += email [ i ] ; } i += 1 ; } return ans ; } int main ( ) { string email = " geeksforgeeksatgmaildotcom " ; cout << ( minEmail ( email ) ) ; }
Find the smallest value of N such that sum of first N natural numbers is Γ’ ‰Β₯ X | C ++ Program to implement the above approach ; Function to check if sum of first N natural numbers is >= X ; Finds minimum value of N such that sum of first N natural number >= X ; Check if sum of first i natural number >= X ; Driver Code ; Input ; Finds minimum value of N such that sum of first N natural number >= X
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isGreaterEqual ( int N , int X ) { return ( N * 1LL * ( N + 1 ) / 2 ) >= X ; } int minimumPossible ( int X ) { for ( int i = 1 ; i <= X ; i ++ ) { if ( isGreaterEqual ( i , X ) ) return i ; } } int main ( ) { int X = 14 ; cout << minimumPossible ( X ) ; return 0 ; }
Queries to count numbers from given range which are divisible by all its digits | C ++ program to implement the above approach ; Function to check if a number is divisible by all of its non - zero digits or not ; Stores the number ; Iterate over the digits of the numbers ; If digit of number is non - zero ; If number is not divisible by its current digit ; Update n ; Function to count of numbers which are divisible by all of its non - zero digits in the range [ 1 , i ] ; Stores count of numbers which are divisible by all of its non - zero digits in the range [ 1 , i ] ; Iterate over the range [ 1 , Max ] ; Update ; Traverse the array , arr [ ] ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define Max 1000005 NEW_LINE bool CheckDivByAllDigits ( int number ) { int n = number ; while ( n > 0 ) { if ( n % 10 ) if ( number % ( n % 10 ) ) { return false ; } n /= 10 ; } return true ; } void cntNumInRang ( int arr [ ] [ 2 ] , int N ) { int prefCntDiv [ Max ] = { 0 } ; for ( int i = 1 ; i <= Max ; i ++ ) { prefCntDiv [ i ] = prefCntDiv [ i - 1 ] + ( CheckDivByAllDigits ( i ) ) ; } for ( int i = 0 ; i < N ; i ++ ) cout << ( prefCntDiv [ arr [ i ] [ 1 ] ] - prefCntDiv [ arr [ i ] [ 0 ] - 1 ] ) << " ▁ " ; } int main ( ) { int arr [ ] [ 2 ] = { { 1 , 5 } , { 12 , 14 } } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cntNumInRang ( arr , N ) ; return 0 ; }
Longest subset of nested elements from a given array | C ++ program to implement the above approach ; Function to find length of longest subset such that subset { arr [ i ] , arr [ arr [ i ] ] , . . } ; Stores length of the longest subset that satisfy the condition ; Traverse in the array , arr [ ] ; If arr [ i ] equals to i ; Update res ; Count of elements in a subset ; Stores index of elements in the current subset ; Calculate length of a subset that satisfy the condition ; Make visited the current index ; Update curr_index ; Update count ; Update res ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int arrayNesting ( vector < int > arr ) { int res = 0 ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { if ( arr [ i ] == i ) { res = max ( res , 1 ) ; } else { int count = 0 ; int curr_index = i ; while ( arr [ curr_index ] != curr_index ) { int next_index = arr [ curr_index ] ; arr [ curr_index ] = curr_index ; curr_index = next_index ; count ++ ; } res = max ( res , count ) ; } } return res ; } int main ( ) { vector < int > arr = { 5 , 4 , 0 , 3 , 1 , 6 , 2 } ; int res = arrayNesting ( arr ) ; cout << res ; }
Count numbers from a given range having exactly 5 distinct factors | C ++ Program to implement the above approach ; Stores all prime numbers up to 2 * 10 ^ 5 ; Function to generate all prime numbers up to 2 * 10 ^ 5 using Sieve of Eratosthenes ; Mark 0 and 1 as non - prime ; If i is prime ; Mark all its factors as non - prime ; If current number is prime ; Store the prime ; Function to count numbers in the range [ L , R ] having exactly 5 factors ; Stores the required count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 2e5 ; vector < long long > prime ; void Sieve ( ) { prime . clear ( ) ; vector < bool > p ( N + 1 , true ) ; p [ 0 ] = p [ 1 ] = false ; for ( int i = 2 ; i * i <= N ; i ++ ) { if ( p [ i ] == true ) { for ( int j = i * i ; j <= N ; j += i ) { p [ j ] = false ; } } } for ( int i = 1 ; i < N ; i ++ ) { if ( p [ i ] ) { prime . push_back ( 1LL * pow ( i , 4 ) ) ; } } } void countNumbers ( long long int L , long long int R ) { int Count = 0 ; for ( int p : prime ) { if ( p >= L && p <= R ) { Count ++ ; } } cout << Count << endl ; } int main ( ) { long long L = 16 , R = 85000 ; Sieve ( ) ; countNumbers ( L , R ) ; return 0 ; }
Minimize remaining array sizes by removing equal pairs of first array elements | C ++ program for the above approach ; Function to count the remaining elements in the arrays ; Stores the count of 1 s in L1 [ ] ; Store the count of 0 s in L2 [ ] ; Traverse the array L1 [ ] ; If condition is true ; Increment one by 1 ; Increment zero by 1 ; Stores the index after which no further removals are possible ; Traverse the array L2 [ ] ; If condition is true ; Decrement one by 1 ; If one < 0 , then break out of the loop ; Decrement zero by 1 ; If zero < 0 , then break out of loop ; Print the answer ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countRemainingElements ( int L1 [ ] , int L2 [ ] , int n ) { int one = 0 ; int zero = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( L1 [ i ] == 1 ) one ++ ; else zero ++ ; } int ans = n ; for ( int i = 0 ; i < n ; i ++ ) { if ( L2 [ i ] == 1 ) { one -- ; if ( one < 0 ) { ans = i ; break ; } } else { zero -- ; if ( zero < 0 ) { ans = i ; break ; } } } cout << n - ans ; } int main ( ) { int L1 [ ] = { 1 , 1 , 0 , 0 } ; int L2 [ ] = { 0 , 0 , 0 , 1 } ; int N = sizeof ( L1 ) / sizeof ( L1 [ 0 ] ) ; countRemainingElements ( L1 , L2 , N ) ; return 0 ; }
Count pairs of similar rectangles possible from a given array | C ++ Program for the above approach ; Function to calculate the count of similar rectangles ; Driver Code ; Input
#include <iostream> NEW_LINE using namespace std ; int getCount ( int rows , int columns , int A [ ] [ 2 ] ) { int res = 0 ; for ( int i = 0 ; i < rows ; i ++ ) { for ( int j = i + 1 ; j < rows ; j ++ ) { if ( A [ i ] [ 0 ] * 1LL * A [ j ] [ 1 ] == A [ i ] [ 1 ] * 1LL * A [ j ] [ 0 ] ) { res ++ ; } } } return res ; } int main ( ) { int A [ ] [ 2 ] = { { 4 , 8 } , { 10 , 20 } , { 15 , 30 } , { 3 , 6 } } ; int columns = 2 ; int rows = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << getCount ( rows , columns , A ) ; return 0 ; }
Find the index with minimum score from a given array | C ++ program for the above approach ; Function to find the index with minimum score ; Stores the score of current index ; Traverse the array in reverse ; Update minimum score ; Print the index with minimum score ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void Min_Score_Index ( int N , vector < int > A ) { vector < int > Score ( N , 0 ) ; for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( A [ i ] + i < N ) Score [ i ] = A [ i ] * Score [ A [ i ] + i ] ; else Score [ i ] = A [ i ] ; } int min_value = INT_MAX ; for ( int i : Score ) min_value = min ( i , min_value ) ; int ind = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( Score [ i ] == min_value ) ind = i ; } cout << ( ind ) ; } int main ( ) { int N = 5 ; vector < int > A = { 1 , 2 , 3 , 4 , 5 } ; Min_Score_Index ( N , A ) ; }
Minimize length of a string by removing occurrences of another string from it as a substring | C ++ program for the above approach ; Function to minimize length of string S after removing all occurrences of string T as substring ; Count of characters required to be removed ; Iterate over the string ; Insert the current character to temp ; Check if the last M characters forms t or not ; Getting the last M characters . If they are equal to t then remove the last M characters from the temp string ; Incrementing subtract by M ; Removing last M characters from the string ; Print the final answer ; Driver Code ; Given string S & T ; Length of string S ; Length of string T ; Prints the count of operations required
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minLength ( string & S , string & T , int N , int M ) { string temp ; int subtract = 0 ; for ( int i = 0 ; i < N ; ++ i ) { temp . push_back ( S [ i ] ) ; if ( temp . size ( ) >= M ) { if ( temp . substr ( temp . size ( ) - M , M ) == T ) { subtract += M ; int cnt = 0 ; while ( cnt != M ) { temp . pop_back ( ) ; ++ cnt ; } } } } cout << ( N - subtract ) << " STRNEWLINE " ; } int main ( ) { string S = " aabcbcbd " , T = " abc " ; int N = S . size ( ) ; int M = T . size ( ) ; minLength ( S , T , N , M ) ; }
Minimize swaps between two arrays such that sum of the first array exceeds sum of the second array | C ++ program for the above approach ; Function to find the minimum count of swaps required between the two arrays to make the sum of arr1 [ ] greater than that of arr2 [ ] ; Stores the sum of the two arrays ; Calculate sum of arr1 [ ] ; Calculate sum of arr2 [ ] ; Sort the arrays arr1 [ ] and arr2 [ ] ; Traverse the array arr [ ] ; If the sum1 is less than or equal to sum2 ; Swapping the elements ; Update the sum1 and sum2 ; Increment the count ; Return the final count ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumCount ( int arr1 [ ] , int arr2 [ ] , int s1 , int s2 ) { int sum1 = 0 , sum2 = 0 ; for ( int i = 0 ; i < s1 ; i ++ ) { sum1 += arr1 [ i ] ; } for ( int j = 0 ; j < s2 ; j ++ ) { sum2 += arr2 [ j ] ; } int len = 0 ; if ( s1 >= s2 ) { len = s2 ; } else { len = s1 ; } sort ( arr1 , arr1 + s1 ) ; sort ( arr2 , arr2 + s2 ) ; int j = 0 , k = s2 - 1 , count = 0 ; for ( int i = 0 ; i < len ; i ++ ) { if ( sum1 <= sum2 ) { if ( arr2 [ k ] >= arr1 [ i ] ) { int dif1 = arr1 [ j ] , dif2 = arr2 [ k ] ; sum1 -= dif1 ; sum1 += dif2 ; sum2 -= dif2 ; sum2 += dif1 ; j ++ ; k -- ; count ++ ; } else { break ; } } else { break ; } } return count ; } int main ( ) { int arr1 [ ] = { 1 , 3 , 2 , 4 } ; int arr2 [ ] = { 6 , 7 , 8 } ; int N = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int M = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; cout << maximumCount ( arr1 , arr2 , N , M ) ; return 0 ; }
Count array elements whose all distinct digits appear in K | C ++ program for the above approach ; Function to check a digit occurs in the digit of K or not ; Iterate over all possible digits of K ; If current digit equal to digit ; Update K ; Function to find the count of array elements whose distinct digits are a subset of digits of K ; Stores count of array elements whose distinct digits are subset of digits of K ; Traverse the array , [ ] arr ; Stores the current element ; Check if all the digits arr [ i ] is a subset of the digits of K or not ; Iterate over all possible digits of arr [ i ] ; Stores current digit ; If current digit does not appear in K ; Update flag ; Update no ; If all the digits arr [ i ] appear in K ; Update count ; Finally print count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; static bool isValidDigit ( int digit , int K ) { while ( K != 0 ) { if ( K % 10 == digit ) { return true ; } K = K / 10 ; } return false ; } int noOfValidNumbers ( int K , int arr [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int no = arr [ i ] ; bool flag = true ; while ( no != 0 ) { int digit = no % 10 ; if ( ! isValidDigit ( digit , K ) ) { flag = false ; break ; } no = no / 10 ; } if ( flag == true ) { count ++ ; } } return count ; } int main ( ) { int K = 12 ; int arr [ ] = { 1 , 12 , 1222 , 13 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << noOfValidNumbers ( K , arr , n ) ; return 0 ; }
Queries to find the minimum index in given array having at least value X | C ++ program to implement the above approach ; Function to find the smallest index of an array element whose value is less than or equal to Q [ i ] ; Stores size of array ; Stores coun of queries ; Store array elements along with the index ; Store smallest index of an array element whose value is greater than or equal to i ; Traverse the array ; Insert { arr [ i ] , i } into storeArrIdx [ ] ; Sort the array ; Sort the storeArrIdx ; Stores index of arr [ N - 1 ] in sorted order ; Traverse the array storeArrIdx [ ] ; Update minIdx [ i ] ; Traverse the array Q [ ] ; Store the index of lower_bound of Q [ i ] ; If no index found whose value greater than or equal to arr [ i ] ; Print smallest index whose value greater than or equal to Q [ i ] ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumIndex ( vector < int > & arr , vector < int > & Q ) { int N = arr . size ( ) ; int M = Q . size ( ) ; vector < pair < int , int > > storeArrIdx ; vector < int > minIdx ( N ) ; for ( int i = 0 ; i < N ; ++ i ) { storeArrIdx . push_back ( { arr [ i ] , i } ) ; } sort ( arr . begin ( ) , arr . end ( ) ) ; sort ( storeArrIdx . begin ( ) , storeArrIdx . end ( ) ) ; minIdx [ N - 1 ] = storeArrIdx [ N - 1 ] . second ; for ( int i = N - 2 ; i >= 0 ; i -- ) { minIdx [ i ] = min ( minIdx [ i + 1 ] , storeArrIdx [ i ] . second ) ; } for ( int i = 0 ; i < M ; i ++ ) { int pos = lower_bound ( arr . begin ( ) , arr . end ( ) , Q [ i ] ) - arr . begin ( ) ; if ( pos == N ) { cout << -1 << " ▁ " ; continue ; } cout << minIdx [ pos ] << " ▁ " ; } } int main ( ) { vector < int > arr = { 1 , 9 } ; vector < int > Q = { 7 , 10 , 0 } ; minimumIndex ( arr , Q ) ; return 0 ; }
Find a K | C ++ program to implement the above approach ; Utility function to check if subarray of size K exits whose XOR of elements equal to XOR ofremaning array elements ; Find XOR of whole array ; Find XOR of first K elements ; Adding XOR of next element ; Removing XOR of previous element ; Check if XOR of current subarray matches with the XOR of remaining elements or not ; Function to check if subarray of size K exits whose XOR of elements equal to XOR ofremaning array elements ; Driver Code ; Given array ; Size of the array ; Given K ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isSubarrayExistUtil ( int arr [ ] , int K , int N ) { int totalXOR = 0 ; int SubarrayXOR = 0 ; for ( int i = 0 ; i < N ; i ++ ) totalXOR ^= arr [ i ] ; for ( int i = 0 ; i < K ; i ++ ) SubarrayXOR ^= arr [ i ] ; if ( SubarrayXOR == ( totalXOR ^ SubarrayXOR ) ) return true ; for ( int i = K ; i < N ; i ++ ) { SubarrayXOR ^= arr [ i ] ; SubarrayXOR ^= arr [ i - 1 ] ; if ( SubarrayXOR == ( totalXOR ^ SubarrayXOR ) ) return true ; } return false ; } void isSubarrayExist ( int arr [ ] , int K , int N ) { if ( isSubarrayExistUtil ( arr , K , N ) ) cout << " YES STRNEWLINE " ; else cout << " NO STRNEWLINE " ; } int32_t main ( ) { int arr [ ] = { 2 , 3 , 3 , 5 , 7 , 7 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 5 ; isSubarrayExist ( arr , K , N ) ; }
Count pairs from a given range having even sum | C ++ program for the above approach ; Function to find the count of ordered pairs having even sum ; Stores count of even numbers in the range [ L , R ] ; If L is even ; Update count_even ; Update count_odd ; Stores count of odd numbers in the range [ L , R ] ; Update count_odd ; Update count_odd ; Stores count of pairs whose sum is even and both elements of the pairs are also even ; Stores count of pairs whose sum is even and both elements of the pairs are odd ; Print total ordered pairs whose sum is even ; Driver Code ; Given L & R ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int L , int R ) { int count_even ; if ( L % 2 == 0 ) { count_even = ( R / 2 ) - ( L / 2 ) + 1 ; } else { count_even = ( R / 2 ) - ( L / 2 ) ; } int count_odd ; if ( L % 2 == 0 ) { count_odd = ( ( R + 1 ) / 2 ) - ( ( L + 1 ) / 2 ) ; } else { count_odd = ( ( R + 1 ) / 2 ) - ( ( L + 1 ) / 2 ) + 1 ; } count_even *= count_even ; count_odd *= count_odd ; cout << count_even + count_odd ; } int main ( ) { int L = 1 , R = 3 ; countPairs ( L , R ) ; return 0 ; }
Count of array elements that can be found using Randomized Binary Search on every array element | C ++ program for the above approach ; Function to find minimum count of array elements found by repeatedly applying Randomized Binary Search ; Stores count of array elements ; smallestRight [ i ] : Stores the smallest array element on the right side of i ; Update smallestRight [ 0 ] ; Traverse the array from right to left ; Update smallestRight [ i ] ; Stores the largest element upto i - th index ; Stores the minimum count of elements found by repeatedly applying Randomized Binary Search ; If largest element on left side is less than smallest element on right side ; Update ans ; Update mn ; Driver Code ; Given array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getDefiniteFinds ( vector < int > & arr ) { int n = arr . size ( ) ; vector < int > smallestRight ( n + 1 ) ; smallestRight [ n ] = INT_MAX ; for ( int i = n - 1 ; i >= 0 ; i -- ) { smallestRight [ i ] = min ( smallestRight [ i + 1 ] , arr [ i ] ) ; } int mn = INT_MIN ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( mn < arr [ i ] and arr [ i ] < smallestRight [ i + 1 ] ) { ans ++ ; } mn = max ( arr [ i ] , mn ) ; } return ans ; } int main ( ) { vector < int > arr = { 5 , 4 , 9 } ; cout << getDefiniteFinds ( arr ) << endl ; }
Count numbers from a given range having same first and last digits in their binary representation | C ++ program for the above approach ; Function to count numbers in range [ L , R ] having same first and last digit in the binary representation ; Drivers code ; Given range [ L , R ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void Count_numbers ( int L , int R ) { int count = ( R - L ) / 2 ; if ( R % 2 != 0 L % 2 != 0 ) count += 1 ; cout << count << endl ; } int main ( ) { int L = 6 , R = 30 ; Count_numbers ( L , R ) ; }
Find the index having sum of elements on its left equal to reverse of the sum of elements on its right | C ++ Program to implement the above approach ; Function to check if a number is equal to the reverse of digits of other number ; Stores reverse of digits of rightSum ; Stores rightSum ; Calculate reverse of digits of temp ; Update rev ; Update temp ; If reverse of digits of rightSum equal to leftSum ; Function to find the index that satisfies the condition ; Stores sum of array elements on right side of each index ; Stores sum of array elements on left side of each index ; Traverse the array ; Update rightSum ; Traverse the array ; Update rightSum ; If leftSum equal to reverse of digits of rightSum ; Update leftSum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkReverse ( int leftSum , int rightSum ) { int rev = 0 ; int temp = rightSum ; while ( temp != 0 ) { rev = ( rev * 10 ) + ( temp % 10 ) ; temp /= 10 ; } if ( rev == leftSum ) { return true ; } return false ; } int findIndex ( int arr [ ] , int N ) { int rightSum = 0 ; int leftSum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { rightSum += arr [ i ] ; } for ( int i = 0 ; i < N ; i ++ ) { rightSum -= arr [ i ] ; if ( checkReverse ( leftSum , rightSum ) ) { return i ; } leftSum += arr [ i ] ; } return -1 ; } int main ( ) { int arr [ ] = { 5 , 7 , 3 , 6 , 4 , 9 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findIndex ( arr , N ) ; return 0 ; }
Print distinct absolute differences of all possible pairs from a given array | C ++ program for the above approach ; Function to find all distinct absolute difference of all possible pairs of the array ; bset [ i ] : Check if i is present in the array or not ; diff [ i ] : Check if there exists a pair whose absolute difference is i ; Traverse the array , arr [ ] ; Add in bitset ; Iterate over the range [ 0 , Max ] ; If i - th bit is set ; Insert the absolute difference of all possible pairs whose first element is arr [ i ] ; Stores count of set bits ; If there is at least one duplicate element in arr [ ] ; Printing the distinct absolute differences of all possible pairs ; If i - th bit is set ; Driver Code ; Given array ; Given size ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define Max 100005 NEW_LINE void printUniqDif ( int n , int a [ ] ) { bitset < Max > bset ; bitset < Max > diff ; for ( int i = 0 ; i < n ; i ++ ) { bset . set ( a [ i ] ) ; } for ( int i = 0 ; i <= Max ; i ++ ) { if ( bset [ i ] ) { diff = diff | ( bset >> i ) ; } } int X = bset . count ( ) ; if ( X != n ) { cout << 0 << " ▁ " ; } for ( int i = 1 ; i <= Max ; i ++ ) { if ( diff [ i ] ) { cout << i << " ▁ " ; } } } int main ( ) { int a [ ] = { 1 , 4 , 6 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; printUniqDif ( n , a ) ; return 0 ; }
Longest Common Subsequence of two arrays out of which one array consists of distinct elements only | C ++ program to to implement the above approach ; Function to find the Longest Common Subsequence between the two arrays ; Maps elements of firstArr [ ] to their respective indices ; Traverse the array firstArr [ ] ; Stores the indices of common elements between firstArr [ ] and secondArr [ ] ; Traverse the array secondArr [ ] ; If current element exists in the Map ; Stores lIS from tempArr [ ] ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int LCS ( vector < int > & firstArr , vector < int > & secondArr ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < firstArr . size ( ) ; i ++ ) { mp [ firstArr [ i ] ] = i + 1 ; } vector < int > tempArr ; for ( int i = 0 ; i < secondArr . size ( ) ; i ++ ) { if ( mp . find ( secondArr [ i ] ) != mp . end ( ) ) { tempArr . push_back ( mp [ secondArr [ i ] ] ) ; } } vector < int > tail ; tail . push_back ( tempArr [ 0 ] ) ; for ( int i = 1 ; i < tempArr . size ( ) ; i ++ ) { if ( tempArr [ i ] > tail . back ( ) ) tail . push_back ( tempArr [ i ] ) ; else if ( tempArr [ i ] < tail [ 0 ] ) tail [ 0 ] = tempArr [ i ] ; else { auto it = lower_bound ( tail . begin ( ) , tail . end ( ) , tempArr [ i ] ) ; * it = tempArr [ i ] ; } } return ( int ) tail . size ( ) ; } int main ( ) { vector < int > firstArr = { 3 , 5 , 1 , 8 } ; vector < int > secondArr = { 3 , 3 , 5 , 3 , 8 } ; cout << LCS ( firstArr , secondArr ) ; return 0 ; }
Count ways to partition a Binary String such that each substring contains exactly two 0 s | C ++ program for the above approach ; Function to find count of ways to partition the string such that each partition contains exactly two 0 s . ; Stores indices of 0 s in the given string . ; Store the count of ways to partition the string such that each partition contains exactly two 0 s . ; Iterate over each characters of the given string ; If current character is '0' ; Insert index ; Stores total count of 0 s in str ; Traverse the array , IdxOf0s [ ] ; Update cntWays ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int totalWays ( int n , string str ) { vector < int > IdxOf0s ; int cntWays = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == '0' ) { IdxOf0s . push_back ( i ) ; } } int M = IdxOf0s . size ( ) ; if ( M == 0 or M % 2 ) { return 0 ; } for ( int i = 2 ; i < M ; i += 2 ) { cntWays = cntWays * ( IdxOf0s [ i ] - IdxOf0s [ i - 1 ] ) ; } return cntWays ; } int main ( ) { string str = "00100" ; int n = str . length ( ) ; cout << totalWays ( n , str ) ; return 0 ; }
Count non | C ++ program to implement the above approach ; Function to find the total count of triplets ( i , j , k ) such that i < j < k and ( j - i ) != ( k - j ) ; Stores indices of 0 s ; Stores indices of 1 s ; Stores indices of 2 s ; Traverse the array ; If current array element is 0 ; If current array element is 1 ; If current array element is 2 ; Total count of triplets ; Traverse the array zero_i [ ] ; Traverse the array one_i [ ] ; Stores index of 0 s ; Stores index of 1 s ; Stores third element of triplets that does not satisfy the condition ; If r present in the map ; Update r ; If r present in the map ; Update r ; If r present in the map and equidistant ; Print the obtained count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countTriplets ( int * arr , int N ) { vector < int > zero_i ; vector < int > one_i ; unordered_map < int , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == 0 ) zero_i . push_back ( i + 1 ) ; else if ( arr [ i ] == 1 ) one_i . push_back ( i + 1 ) ; else mp [ i + 1 ] = 1 ; } int total = zero_i . size ( ) * one_i . size ( ) * mp . size ( ) ; for ( int i = 0 ; i < zero_i . size ( ) ; i ++ ) { for ( int j = 0 ; j < one_i . size ( ) ; j ++ ) { int p = zero_i [ i ] ; int q = one_i [ j ] ; int r = 2 * p - q ; if ( mp [ r ] > 0 ) total -- ; r = 2 * q - p ; if ( mp [ r ] > 0 ) total -- ; r = ( p + q ) / 2 ; if ( mp [ r ] > 0 && abs ( r - p ) == abs ( r - q ) ) total -- ; } } cout << total ; } int main ( ) { int arr [ ] = { 0 , 1 , 2 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countTriplets ( arr , N ) ; return 0 ; }
Print prime factors of a given integer in decreasing order using Stack | C ++ program for the above approach ; Function to print prime factors of N in decreasing order ; Stores prime factors of N in decreasing order ; Insert i into stack ; Update N ; Update i ; Print value of stack st ; Driver Code ; function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void PrimeFactors ( int N ) { stack < int > st ; int i = 2 ; while ( N != 1 ) { if ( N % i == 0 ) { st . push ( i ) ; while ( N % i == 0 ) { N = N / i ; } } i ++ ; } while ( ! st . empty ( ) ) { printf ( " % d ▁ " , st . top ( ) ) ; st . pop ( ) ; } } int main ( ) { int N = 8 ; PrimeFactors ( N ) ; return 0 ; }
Count subarrays consisting of first K natural numbers in descending order | C ++ program for the above approach ; Function to count subarray having the decreasing sequence K to 1 ; Traverse the array ; Check if required sequence is present or not ; Reset temp to k ; Return the count ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int CountSubarray ( int arr [ ] , int n , int k ) { int temp = k , count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == temp ) { if ( temp == 1 ) { count ++ ; temp = k ; } else temp -- ; } else { temp = k ; if ( arr [ i ] == k ) i -- ; } } return count ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 7 , 9 , 3 , 2 , 1 , 8 , 3 , 2 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; cout << CountSubarray ( arr , N , K ) ; return 0 ; }
Smallest number not less than N which is divisible by all digits of N | C ++ program for the above approach ; Function to calculate the LCM ; Function to find the smallest number satisfying given constraints ; LCM value is 1 initially ; Finding the LCM of all non zero digits ; Update the value lcm ; Stores ceil value ; Print the answer ; Driver Code ; Function Call
#include " bits / stdc + + . h " NEW_LINE using namespace std ; int LCM ( int A , int B ) { return ( A * B / __gcd ( A , B ) ) ; } int findSmallestNumber ( int X ) { int lcm = 1 ; int temp = X ; while ( temp ) { int last = temp % 10 ; temp /= 10 ; if ( ! last ) continue ; lcm = LCM ( lcm , last ) ; } int answer = ( ( X + lcm - 1 ) / lcm ) * lcm ; cout << answer ; } int main ( ) { int X = 280 ; findSmallestNumber ( X ) ; return 0 ; }
Minimum sum of two integers whose product is strictly greater than N | C ++ program for the above approach ; Function to find the minimum sum of two integers such that their product is strictly greater than N ; Initialise low as 0 and high as 1e9 ; Iterate to find the first number ; Find the middle value ; If mid ^ 2 is greater than equal to A , then update high to mid ; Otherwise update low ; Store the first number ; Again , set low as 0 and high as 1e9 ; Iterate to find the second number ; Find the middle value ; If first number * mid is greater than N then update high to mid ; Else , update low to mid ; Store the second number ; Print the result ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE void minSum ( int N ) { ll low = 0 , high = 1e9 ; while ( low + 1 < high ) { ll mid = low + ( high - low ) / 2 ; if ( mid * mid >= N ) { high = mid ; } else { low = mid ; } } ll first = high ; low = 0 ; high = 1e9 ; while ( low + 1 < high ) { ll mid = low + ( high - low ) / 2 ; if ( first * mid > N ) { high = mid ; } else { low = mid ; } } ll second = high ; cout << first + second ; } int main ( ) { int N = 10 ; minSum ( N ) ; return 0 ; }
Minimum sum of two integers whose product is strictly greater than N | C ++ program for the above approach ; Function to find the minimum sum of two integers such that their product is strictly greater than N ; Store the answer using the AP - GP inequality ; Print the answer ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minSum ( int N ) { int ans = ceil ( 2 * sqrt ( N + 1 ) ) ; cout << ans ; } int main ( ) { int N = 10 ; minSum ( N ) ; return 0 ; }
Query to find length of the longest subarray consisting only of 1 s | C ++ Program for the above approach ; Arrays to store prefix sums , suffix and MAX 's node respectively ; Function to construct Segment Tree ; MAX array for node MAX ; Array for prefix sum node ; Array for suffix sum node ; Calculate MAX node ; Function to update Segment Tree ; Update at position ; Update sums from bottom to the top of Segment Tree ; Update MAX tree ; Update pref tree ; Update suf tree ; Function to perform given queries ; Stores count of queries ; Traverse each query ; Print longest length of subarray in [ 1 , N ] ; Flip the character ; Driver Code ; Size of array ; Given array ; Given queries ; Number of queries
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define INF 1000000 NEW_LINE int pref [ 500005 ] ; int suf [ 500005 ] ; int MAX [ 500005 ] ; void build ( int a [ ] , int tl , int tr , int v ) { if ( tl == tr ) { MAX [ v ] = a [ tl ] ; pref [ v ] = a [ tl ] ; suf [ v ] = a [ tl ] ; } else { int tm = ( tl + tr ) / 2 ; build ( a , tl , tm , v * 2 ) ; build ( a , tm + 1 , tr , v * 2 + 1 ) ; MAX [ v ] = max ( MAX [ v * 2 ] , max ( MAX [ v * 2 + 1 ] , suf [ v * 2 ] + pref [ v * 2 + 1 ] ) ) ; pref [ v ] = max ( pref [ v * 2 ] , pref [ 2 * v ] + ( pref [ 2 * v ] == tm - tl + 1 ) * pref [ v * 2 + 1 ] ) ; suf [ v ] = max ( suf [ v * 2 + 1 ] , suf [ 2 * v + 1 ] + suf [ v * 2 ] * ( suf [ 2 * v + 1 ] == tr - tm ) ) ; } } void update ( int a [ ] , int pos , int tl , int tr , int v ) { if ( tl > pos tr < pos ) { return ; } if ( tl == tr && tl == pos ) { MAX [ v ] = a [ pos ] ; pref [ v ] = a [ pos ] ; suf [ v ] = a [ pos ] ; } else { int tm = ( tl + tr ) / 2 ; update ( a , pos , tl , tm , v * 2 ) ; update ( a , pos , tm + 1 , tr , v * 2 + 1 ) ; MAX [ v ] = max ( MAX [ v * 2 ] , max ( MAX [ v * 2 + 1 ] , suf [ v * 2 ] + pref [ v * 2 + 1 ] ) ) ; pref [ v ] = max ( pref [ v * 2 ] , pref [ 2 * v ] + ( pref [ 2 * v ] == tm - tl + 1 ) * pref [ v * 2 + 1 ] ) ; suf [ v ] = max ( suf [ v * 2 + 1 ] , suf [ 2 * v + 1 ] + ( suf [ 2 * v + 1 ] == tr - tm ) * suf [ v * 2 ] ) ; } } void solveQueries ( int arr [ ] , int n , vector < vector < int > > Q , int k ) { int cntQuery = Q . size ( ) ; build ( arr , 0 , n - 1 , 1 ) ; for ( int i = 0 ; i < cntQuery ; i ++ ) { if ( Q [ i ] [ 0 ] == 1 ) { cout << MAX [ 1 ] << " ▁ " ; } else { arr [ Q [ i ] [ 1 ] - 1 ] ^= 1 ; update ( arr , Q [ i ] [ 1 ] - 1 , 0 , n - 1 , 1 ) ; } } } int main ( ) { int N = 10 ; int arr [ ] = { 1 , 1 , 0 , 1 , 1 , 1 , 0 , 0 , 1 , 1 } ; vector < vector < int > > Q = { { 1 } , { 2 , 3 } , { 1 } } ; int K = 3 ; solveQueries ( arr , N , Q , K ) ; }
Find the array element having maximum frequency of the digit K | C ++ program for the above approach ; Function to find the count of digits , k in the given number n ; Stores count of occurrence of digit K in N ; Iterate over digits of N ; If current digit is k ; Update count ; Update N ; Utility function to find an array element having maximum frequency of digit k ; Stores frequency of digit K in arr [ i ] ; Stores maximum frequency of digit K in the array ; Stores an array element having maximum frequency of digit k ; Initialize max ; Traverse the array ; Count the frequency of digit k in arr [ i ] ; Update max with maximum frequency found so far ; Update ele ; If there is no array element having digit k in it ; Function to find an array element having maximum frequency of digit k ; Stores an array element having maximum frequency of digit k ; If there is no element found having digit k in it ; Print the element having max frequency of digit k ; Driver Code ; The digit whose max occurrence has to be found ; Given array ; Size of array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countFreq ( int N , int K ) { int count = 0 ; while ( N > 0 ) { if ( N % 10 == K ) { count ++ ; } N = N / 10 ; } return count ; } int findElementUtil ( int arr [ ] , int N , int K ) { int c ; int max ; int ele ; max = 0 ; for ( int i = 0 ; i < N ; i ++ ) { c = countFreq ( arr [ i ] , K ) ; if ( c > max ) { max = c ; ele = arr [ i ] ; } } if ( max == 0 ) return -1 ; else return ele ; } void findElement ( int arr [ ] , int N , int K ) { int ele = findElementUtil ( arr , N , K ) ; if ( ele == -1 ) cout << " - 1" ; else cout << ele ; } int main ( ) { int K = 3 ; int arr [ ] = { 3 , 77 , 343 , 456 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findElement ( arr , K , N ) ; return 0 ; }
Minimum removals required to make any interval equal to the union of the given Set | C ++ implementation of the above approach ; Function to count minimum number of removals required to make an interval equal to the union of the given Set ; Stores the minimum number of removals ; Traverse the Set ; Left Boundary ; Right Boundary ; Stores count of intervals lying within current interval ; Traverse over all remaining intervals ; Check if interval lies within the current interval ; Increase count ; Update minimum removals required ; Driver Code ; Returns the minimum removals
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinDeletions ( vector < pair < int , int > > & v , int n ) { int minDel = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { int L = v [ i ] . first ; int R = v [ i ] . second ; int Count = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( v [ j ] . first >= L && v [ j ] . second <= R ) { Count += 1 ; } } minDel = min ( minDel , n - Count ) ; } return minDel ; } int main ( ) { vector < pair < int , int > > v ; v . push_back ( { 1 , 3 } ) ; v . push_back ( { 4 , 12 } ) ; v . push_back ( { 5 , 8 } ) ; v . push_back ( { 13 , 20 } ) ; int N = v . size ( ) ; cout << findMinDeletions ( v , N ) ; return 0 ; }
Maximum even numbers present in any subarray of size K | C ++ program to implement the above approach ; Function to find the maximum count of even numbers from all the subarrays of size K ; Stores the count of even numbers in a subarray of size K ; Calculate the count of even numbers in the current subarray ; If current element is an even number ; Stores the maximum count of even numbers from all the subarrays of size K ; Traverse remaining subarrays of size K using sliding window technique ; If the first element of the subarray is even ; Update curr ; If i - th element is even increment the count ; Update the answer ; Return answer ; Driver Code ; Size of the input array ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxEvenIntegers ( int arr [ ] , int N , int M ) { int curr = 0 ; for ( int i = 0 ; i < M ; i ++ ) { if ( arr [ i ] % 2 == 0 ) curr ++ ; } int ans = curr ; for ( int i = M ; i < N ; i ++ ) { if ( arr [ i - M ] % 2 == 0 ) { curr -- ; } if ( arr [ i ] % 2 == 0 ) curr ++ ; ans = max ( ans , curr ) ; } return ans ; } int main ( ) { int arr [ ] = { 2 , 3 , 5 , 4 , 7 , 6 } ; int M = 3 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxEvenIntegers ( arr , N , M ) << endl ; return 0 ; }
Count numbers up to N having digit D in its octal representation | C ++ program to implement the above approach ; Function to count the numbers in given range whose octal representation contains atleast digit , d ; Store count of numbers up to n whose octal representation contains digit d ; Iterate over the range [ 1 , n ] ; Calculate digit of i in octal representation ; Check if octal representation of x contains digit d ; Update total ; Update x ; Print the answer ; Driver Code ; Given N and D ; Counts and prints numbers up to N having D as a digit in its octal representation
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countNumbers ( int n , int d ) { int total = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { int x = i ; while ( x > 0 ) { if ( x % 8 == d ) { total ++ ; break ; } x = x / 8 ; } } cout << total ; } int main ( ) { int n = 20 , d = 7 ; countNumbers ( n , d ) ; return 0 ; }
Maximize length of longest subarray consisting of same elements by at most K decrements | C ++ program to implement the above approach ; Function to construct Segment Tree to return the minimum element in a range ; If leaf nodes of the tree are found ; Update the value in segment tree from given array ; Divide left and right subtree ; Stores smallest element in subarray { arr [ start ] , arr [ mid ] } ; Stores smallest element in subarray { arr [ mid + 1 ] , arr [ end ] } ; Stores smallest element in subarray { arr [ start ] , arr [ end ] } ; Function to find the smallest element present in a subarray ; If elements of the subarray are not in the range [ l , r ] ; If all the elements of the subarray are in the range [ l , r ] ; Divide tree into left and right subtree ; Stores smallest element in left subtree ; Stores smallest element in right subtree ; Function that find length of longest subarray with all equal elements in atmost K decrements ; Stores length of longest subarray with all equal elements in atmost K decrements . ; Store the prefix sum array ; Calculate the prefix sum array ; Build the segment tree for range min query ; Traverse the array ; Stores start index of the subarray ; Stores end index of the subarray ; Stores end index of the longest subarray ; Performing the binary search to find the endpoint for the selected range ; Find the mid for binary search ; Find the smallest element in range [ i , mid ] using Segment Tree ; Stores total sum of subarray after K decrements ; Stores sum of elements of subarray before K decrements ; If subarray found with all equal elements ; Update start ; Update max_index ; If false , it means that the selected range is invalid ; Update end ; Store the length of longest subarray ; Return result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int build ( int tree [ ] , int * A , int start , int end , int node ) { if ( start == end ) { tree [ node ] = A [ start ] ; return tree [ node ] ; } int mid = ( start + end ) / 2 ; int X = build ( tree , A , start , mid , 2 * node + 1 ) ; int Y = build ( tree , A , mid + 1 , end , 2 * node + 2 ) ; return tree [ node ] = min ( X , Y ) ; } int query ( int tree [ ] , int start , int end , int l , int r , int node ) { if ( start > r end < l ) return INT_MAX ; if ( start >= l && end <= r ) return tree [ node ] ; int mid = ( start + end ) / 2 ; int X = query ( tree , start , mid , l , r , 2 * node + 1 ) ; int Y = query ( tree , mid + 1 , end , l , r , 2 * node + 2 ) ; return min ( X , Y ) ; } int longestSubArray ( int * A , int N , int K ) { int res = 1 ; int preSum [ N + 1 ] ; preSum [ 0 ] = A [ 0 ] ; for ( int i = 0 ; i < N ; i ++ ) preSum [ i + 1 ] = preSum [ i ] + A [ i ] ; int tree [ 4 * N + 5 ] ; build ( tree , A , 0 , N - 1 , 0 ) ; for ( int i = 0 ; i < N ; i ++ ) { int start = i ; int end = N - 1 ; int mid ; int max_index = i ; while ( start <= end ) { mid = ( start + end ) / 2 ; int min_element = query ( tree , 0 , N - 1 , i , mid , 0 ) ; int expected_sum = ( mid - i + 1 ) * min_element ; int actual_sum = preSum [ mid + 1 ] - preSum [ i ] ; if ( actual_sum - expected_sum <= K ) { start = mid + 1 ; max_index = max ( max_index , mid ) ; } else { end = mid - 1 ; } } res = max ( res , max_index - i + 1 ) ; } return res ; } int main ( ) { int arr [ ] = { 1 , 7 , 3 , 4 , 5 , 6 } ; int k = 6 ; int n = 6 ; cout << longestSubArray ( arr , n , k ) ; return 0 ; }
Count number of triplets ( a , b , c ) from first N natural numbers such that a * b + c = N | C ++ program to implement the above approach ; Function to find the count of triplets ( a , b , c ) with a * b + c = N ; Stores count of triplets of 1 st N natural numbers which are of the form a * b + c = N ; Iterate over the range [ 1 , N ] ; If N is divisible by i ; Update cntTriplet ; Update cntTriplet ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findCntTriplet ( int N ) { int cntTriplet = 0 ; for ( int i = 1 ; i < N ; i ++ ) { if ( N % i != 0 ) { cntTriplet += N / i ; } else { cntTriplet += ( N / i ) - 1 ; } } return cntTriplet ; } int main ( ) { int N = 3 ; cout << findCntTriplet ( N ) ; return 0 ; }
Count divisors which generates same Quotient and Remainder | C ++ program of the above approach ; Function to calculate the count of numbers such that it gives same quotient and remainder ; Stores divisor of number N . ; Iterate through numbers from 2 to sqrt ( N ) and store divisors of N ; As N is also divisor of itself ; Iterate through divisors ; Checking whether x satisfies the required condition ; Print the count ; Driver Code ; Given N ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countDivisors ( long long int n ) { int count = 0 ; vector < long long int > divisor ; for ( int i = 2 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( n / i == i ) divisor . push_back ( i ) ; else { divisor . push_back ( i ) ; divisor . push_back ( n / i ) ; } } } divisor . push_back ( n ) ; for ( auto x : divisor ) { x -= 1 ; if ( ( n / x ) == ( n % x ) ) count ++ ; } cout << count ; } int main ( ) { long long int N = 1000000000000 ; countDivisors ( N ) ; return 0 ; }
Smallest indexed array element required to be flipped to make sum of array equal to 0 | C ++ program to implement the above approach ; Function to find the smallest indexed array element required to be flipped to make sum of the given array equal to 0 ; Stores the required index ; Traverse the given array ; Flip the sign of current element ; Stores the sum of array elements ; Find the sum of the array ; Update sum ; If sum is equal to 0 ; Update pos ; Reset the current element to its original value ; Reset the value of arr [ i ] ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int smallestIndexArrayElementsFlip ( int arr [ ] , int N ) { int pos = -1 ; for ( int i = 0 ; i < N ; i ++ ) { arr [ i ] *= -1 ; int sum = 0 ; for ( int j = 0 ; j < N ; j ++ ) { sum += arr [ j ] ; } if ( sum == 0 ) { pos = i ; break ; } else { arr [ i ] *= -1 ; } } return pos ; } int main ( ) { int arr [ ] = { 1 , 3 , -5 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << smallestIndexArrayElementsFlip ( arr , N ) ; return 0 ; }
Smallest indexed array element required to be flipped to make sum of array equal to 0 | C ++ program to implement the above approach ; Function to find the smallest indexed array element required to be flipped to make sum of the given array equal to 0 ; Stores the required index ; Stores the sum of the array ; Traverse the given array ; Update ArrSum ; Traverse the given array ; If sum of array elements double the value of the current element ; Update pos ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int smallestIndexArrayElementsFlip ( int arr [ ] , int N ) { int pos = -1 ; int ArrSum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { ArrSum += arr [ i ] ; } for ( int i = 0 ; i < N ; i ++ ) { if ( 2 * arr [ i ] == ArrSum ) { pos = i ; break ; } } return pos ; } int main ( ) { int arr [ ] = { 1 , 3 , -5 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << smallestIndexArrayElementsFlip ( arr , N ) ; return 0 ; }
Check if a string can be converted to another given string by removal of a substring | C ++ program to implement the above approach ; Function to check if S can be converted to T by removing at most one substring from S ; Check if S can be converted to T by removing at most one substring from S ; Stores length of string T ; Stores length of string S ; Iterate over the range [ 0 , M - 1 ] ; Stores Length of the substring { S [ 0 ] , ... , S [ i ] } ; Stores Length of the substring { S [ 0 ] , ... , S [ i ] } ; Stores prefix substring ; Stores suffix substring ; Checking if prefix + suffix == T ; Driver Code ; Given String S and T ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string make_string_S_to_T ( string S , string T ) { bool possible = false ; int M = T . length ( ) ; int N = S . length ( ) ; for ( int i = 0 ; i <= M ; i ++ ) { int prefix_length = i ; int suffix_length = M - i ; string prefix = S . substr ( 0 , prefix_length ) ; string suffix = S . substr ( N - suffix_length , suffix_length ) ; if ( prefix + suffix == T ) { possible = true ; break ; } } if ( possible ) return " YES " ; else return " NO " ; } int main ( ) { string S = " ababcdcd " ; string T = " abcd " ; cout << make_string_S_to_T ( S , T ) ; return 0 ; }
Sum of maximum of all subarrays by adding even frequent maximum twice | C ++ program for the above approach ; Function to calculate sum of maximum of all subarrays ; Storeas the sum of maximums ; Traverse the array ; Store the frequency of the maximum element in subarray ; Finding maximum ; Increment frequency by 1 ; If new maximum is obtained ; If frequency of maximum is even , then add 2 * maxNumber . Otherwise , add maxNumber ; Print the sum obtained ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findSum ( vector < int > a ) { int ans = 0 ; for ( int low = 0 ; low < a . size ( ) ; low ++ ) { for ( int high = low ; high < a . size ( ) ; high ++ ) { int count = 0 ; int maxNumber = 0 ; for ( int i = low ; i <= high ; i ++ ) { if ( a [ i ] == maxNumber ) count ++ ; else if ( a [ i ] > maxNumber ) { maxNumber = a [ i ] ; count = 1 ; } } ans += maxNumber * ( ( count % 2 == 0 ) ? 2 : 1 ) ; } } cout << ( ans ) ; } int main ( ) { vector < int > arr = { 2 , 1 , 4 , 4 , 2 } ; findSum ( arr ) ; }
Count pairs of indices having equal prefix and suffix sums | C ++ program for the above approach ; Function to find the count of index pairs having equal prefix and suffix sums ; Maps indices with prefix sums ; Traverse the array ; Update prefix sum ; Update frequency in Map ; Traverse the array in reverse ; Update suffix sum ; Check if any prefix sum of equal value exists or not ; Print the obtained count ; Driver code ; Given array ; Given size ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countPairs ( int * arr , int n ) { unordered_map < int , int > mp1 ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; mp1 [ sum ] += 1 ; } sum = 0 ; int ans = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { sum += arr [ i ] ; if ( mp1 . find ( sum ) != mp1 . end ( ) ) { ans += mp1 [ sum ] ; } } cout << ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countPairs ( arr , n ) ; return 0 ; }
Queries to count Composite Magic Numbers from a given range [ L , R ] | C ++ program to implement the above approach ; Check if a number is magic number or not ; Check number is composite number or not ; Corner cases ; Check if the number is a multiple of 2 or 3 ; Check for multiples of remaining primes ; Function to find Composite Magic Numbers in given ranges ; dp [ i ] : Stores the count of composite Magic numbers up to i ; Traverse in the range [ 1 , 1e5 ) ; Check if number is Composite number as well as a Magic number or not ; Print results for each query ; Driver Code
#include <iostream> NEW_LINE using namespace std ; bool isMagic ( int num ) { return ( num % 9 == 1 ) ; } bool isComposite ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return false ; if ( n % 2 == 0 n % 3 == 0 ) return true ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return true ; return false ; } void find ( int L [ ] , int R [ ] , int q ) { int dp [ 1000005 ] ; dp [ 0 ] = 0 ; dp [ 1 ] = 0 ; for ( int i = 1 ; i < 1000005 ; i ++ ) { if ( isComposite ( i ) && isMagic ( i ) ) { dp [ i ] = dp [ i - 1 ] + 1 ; } else dp [ i ] = dp [ i - 1 ] ; } for ( int i = 0 ; i < q ; i ++ ) cout << dp [ R [ i ] ] - dp [ L [ i ] - 1 ] << endl ; } int main ( ) { int L [ ] = { 10 , 3 } ; int R [ ] = { 100 , 2279 } ; int Q = 2 ; find ( L , R , Q ) ; return 0 ; }
Smallest positive integer that divides all array elements to generate quotients with sum not exceeding K | C ++ program to implement the above approach ; Function to find the smallest positive integer that divides array elements to get the sum <= K ; Stores minimum possible of the smallest positive integer satisfying the condition ; Stores maximum possible of the smallest positive integer satisfying the condition ; Apply binary search over the range [ left , right ] ; Stores middle element of left and right ; Stores sum of array elements ; Traverse the array ; Update sum ; If sum is greater than K ; Update left ; Update right ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findSmallestInteger ( int arr [ ] , int N , int K ) { int left = 1 ; int right = * max_element ( arr , arr + N ) ; while ( left < right ) { int mid = ( left + right ) / 2 ; int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += ( arr [ i ] + mid - 1 ) / mid ; } if ( sum > K ) { left = mid + 1 ; } else { right = mid ; } } return left ; } int main ( ) { int arr [ ] = { 1 , 2 , 5 , 9 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; ; int K = 6 ; cout << findSmallestInteger ( arr , N , K ) ; }
Minimum Deci | C ++ Program to implement the above approach ; Function to find the count of minimum Deci - Binary numbers required to obtain S ; Stores the minimum count ; Iterate over the string s ; Convert the char to its equivalent integer ; If current character is the maximum so far ; Update the maximum digit ; Print the required result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimum_deci_binary_number ( string s ) { int m = INT_MIN ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { int temp = s [ i ] - '0' ; if ( temp > m ) { m = temp ; } } return m ; } int main ( ) { string S = "31" ; cout << minimum_deci_binary_number ( S ) ; return 0 ; }
Make all the elements of array odd by incrementing odd | C ++ program for the above approach ; Function to count minimum subarrays whose odd - indexed elements need to be incremented to make array odd ; Stores the minimum number of operations required ; Iterate over even - indices ; Check if the current element is odd ; If true , continue ; Otherwise , mark the starting of the subarray and iterate until i < n and arr [ i ] is even ; Increment number of operations ; Iterate over odd indexed positions of arr [ ] ; Check if the current element is odd ; If true , continue ; Otherwise , mark the starting of the subarray and iterate until i < n and arr [ i ] is even ; Increment the number of operations ; Print the number of operations ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minOperations ( int arr [ ] , int n ) { int flips = 0 ; for ( int i = 0 ; i < n ; i += 2 ) { if ( arr [ i ] % 2 == 1 ) { continue ; } while ( i < n && arr [ i ] % 2 == 0 ) { i += 2 ; } flips ++ ; } for ( int i = 1 ; i < n ; i += 2 ) { if ( arr [ i ] % 2 == 1 ) { continue ; } while ( i < n && arr [ i ] % 2 == 0 ) { i += 2 ; } flips ++ ; } cout << flips ; } int main ( ) { int arr [ ] = { 2 , 3 , 4 , 3 , 5 , 3 , 2 } ; int N = sizeof ( arr ) / sizeof ( int ) ; minOperations ( arr , N ) ; return 0 ; }
Minimum substring reversals required to make given Binary String alternating | C ++ program for the above approach ; Function to count the minimum number of substrings required to be reversed to make the string S alternating ; Store count of consecutive pairs ; Stores the count of 1 s and 0 s ; Traverse through the string ; Increment 1 s count ; Increment 0 s count ; Increment K if consecutive same elements are found ; Increment 1 s count ; else Increment 0 s count ; Check if it is possible or not ; Otherwise , print the number of required operations ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumReverse ( string s , int n ) { int k = 0 , l = 0 ; int sum1 = 0 , sum0 = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( s [ i ] == '1' ) sum1 ++ ; else sum0 ++ ; if ( s [ i ] == s [ i - 1 ] && s [ i ] == '0' ) k ++ ; else if ( s [ i ] == s [ i - 1 ] && s [ i ] == '1' ) l ++ ; } if ( s [ 0 ] == '1' ) sum1 ++ ; sum0 ++ ; if ( abs ( sum1 - sum0 ) > 1 ) return -1 ; return max ( k , l ) ; } int main ( ) { string S = "10001" ; int N = S . size ( ) ; cout << minimumReverse ( S , N ) ; return 0 ; }
Count pairs with Even Product from two given arrays | C ++ program to implement the above approach ; Function to count pairs ( arr [ i ] , brr [ j ] ) whose product is an even number ; Stores count of odd numbers in arr [ ] ; Stores count of odd numbers in brr [ ] ; Traverse the array , arr [ ] ; If arr [ i ] is an odd number ; Update cntOddArr ; Traverse the array , brr [ ] ; If brr [ i ] is an odd number ; Update cntOddArr ; Return pairs whose product is an even number ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int cntPairsInTwoArray ( int arr [ ] , int brr [ ] , int N , int M ) { int cntOddArr = 0 ; int cntOddBrr = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] & 1 ) { cntOddArr += 1 ; } } for ( int i = 0 ; i < M ; i ++ ) { if ( brr [ i ] & 1 ) { cntOddBrr += 1 ; } } return ( N * M ) - ( cntOddArr * cntOddBrr ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int brr [ ] = { 1 , 2 } ; int M = sizeof ( brr ) / sizeof ( brr [ 0 ] ) ; cout << cntPairsInTwoArray ( arr , brr , N , M ) ; return 0 ; }
Maximize count of persons receiving a chocolate | C ++ program for the above approach ; Function to count the maximum number of persons receiving a chocolate ; Initialize count as 0 ; Sort the given arrays ; Initialize a multiset ; Insert B [ ] array values into the multiset ; Traverse elements in array A [ ] ; Search for the lowest value in B [ ] ; If found , increment count , and delete from set ; Return the number of people ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countMaxPersons ( int * A , int n , int * B , int m , int x ) { int count = 0 ; sort ( A , A + n ) ; sort ( B , B + m ) ; multiset < int > s ; for ( int i = 0 ; i < m ; i ++ ) s . insert ( B [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) { int val = A [ i ] - x ; auto it = s . lower_bound ( val ) ; if ( it != s . end ( ) && * it <= A [ i ] + x ) { count ++ ; s . erase ( it ) ; } } return count ; } int main ( ) { int A [ ] = { 90 , 49 , 20 , 39 , 49 } ; int B [ ] = { 14 , 24 , 82 } ; int X = 15 ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int M = sizeof ( B ) / sizeof ( B [ 0 ] ) ; cout << countMaxPersons ( A , N , B , M , X ) ; }
Maximize frequency of an element by at most one increment or decrement of all array elements | C ++ program to implement the above approach ; Function to maximize the frequency of an array element by incrementing or decrementing array elements at most once ; Stores the largest array element ; Stores the smallest array element ; freq [ i ] : Stores frequency of ( i + Min ) in the array ; Traverse the array ; Update frequency of arr [ i ] ; Stores maximum frequency of an array element by incrementing or decrementing array elements ; Iterate all the numbers over the range [ Min , Max ] ; Stores sum of three consecutive numbers ; Update maxSum ; Print maxSum ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void max_freq ( int arr [ ] , int N ) { int Max = * max_element ( arr , arr + N ) ; int Min = * min_element ( arr , arr + N ) ; int freq [ Max - Min + 1 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { freq [ arr [ i ] - Min ] ++ ; } int maxSum = 0 ; for ( int i = 0 ; i < ( Max - Min - 1 ) ; i ++ ) { int val = freq [ i ] + freq [ i + 1 ] + freq [ i + 2 ] ; maxSum = max ( maxSum , val ) ; } cout << maxSum << " STRNEWLINE " ; } int main ( ) { int arr [ ] = { 3 , 1 , 4 , 1 , 5 , 9 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; max_freq ( arr , N ) ; return 0 ; }
Longest increasing subsequence consisting of elements from indices divisible by previously selected indices | C ++ program for the above approach ; Function to find length of longest subsequence generated that satisfies the specified conditions ; Stores the length of longest subsequences of all lengths ; Iterate through the given array ; Iterate through the multiples i ; Update dp [ j ] as maximum of dp [ j ] and dp [ i ] + 1 ; Return the maximum element in dp [ ] as the length of longest subsequence ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaxLength ( int N , vector < int > arr ) { vector < int > dp ( N + 1 , 1 ) ; for ( int i = 1 ; i <= N ; i ++ ) { for ( int j = 2 * i ; j <= N ; j += i ) { if ( arr [ i - 1 ] < arr [ j - 1 ] ) { dp [ j ] = max ( dp [ j ] , dp [ i ] + 1 ) ; } } } return * max_element ( dp . begin ( ) , dp . end ( ) ) ; } int main ( ) { vector < int > arr { 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 } ; int N = arr . size ( ) ; cout << findMaxLength ( N , arr ) ; return 0 ; }
Queries to check if any pair exists in an array having values at most equal to the given pair | C ++ program for the above approach ; Function that performs binary search to find value less than or equal to first value of the pair ; Perform binary search ; Find the mid ; Update the high ; Else update low ; Return the low index ; Function to modify the second value of each pair ; start from index 1 ; Function to evaluate each query ; Find value less than or equal to the first value of pair ; check if we got the required pair or not ; Function to find a pair whose values is less than the given pairs in query ; Find the size of the vector ; sort the vector based on the first value ; Function Call to modify the second value of each pair ; Traverse each queries ; Evaluate each query ; Print the result ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int binary_search ( vector < pair < int , int > > vec , int n , int a ) { int low , high , mid ; low = 0 ; high = n - 1 ; while ( low < high ) { mid = low + ( high - low + 1 ) / 2 ; if ( vec [ mid ] . first > a ) { high = mid - 1 ; } else if ( vec [ mid ] . first <= a ) { low = mid ; } } return low ; } void modify_vec ( vector < pair < int , int > > & v , int n ) { for ( int i = 1 ; i < n ; i ++ ) { v [ i ] . second = min ( v [ i ] . second , v [ i - 1 ] . second ) ; } } int evaluate_query ( vector < pair < int , int > > v , int n , int m1 , int m2 ) { int temp = binary_search ( v , n , m1 ) ; if ( ( v [ temp ] . first <= m1 ) && ( v [ temp ] . second <= m2 ) ) { return 1 ; } return 0 ; } void checkPairs ( vector < pair < int , int > > & v , vector < pair < int , int > > & queries ) { int n = v . size ( ) ; sort ( v . begin ( ) , v . end ( ) ) ; modify_vec ( v , n ) ; int k = queries . size ( ) ; for ( int i = 0 ; i < k ; i ++ ) { int m1 = queries [ i ] . first ; int m2 = queries [ i ] . second ; int result = evaluate_query ( v , n , m1 , m2 ) ; if ( result > 0 ) cout << " Yes STRNEWLINE " ; else cout << " No STRNEWLINE " ; } } int main ( ) { vector < pair < int , int > > arr = { { 3 , 5 } , { 2 , 7 } , { 2 , 3 } , { 4 , 9 } } ; vector < pair < int , int > > queries = { { 3 , 4 } , { 3 , 2 } , { 4 , 1 } , { 3 , 7 } } ; checkPairs ( arr , queries ) ; return 0 ; }
Sort a stream of integers | C ++ program for the above approach ; Function to sort a stream of integers ; Stores the position of array elements ; Traverse through the array ; If any element is found to be greater than the current element ; If an element > num is not present ; Otherwise , place the number at its right position ; Function to print the sorted stream of integers ; Stores the sorted stream of integers ; Traverse the array ; Function Call ; Print the array after every insertion ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void Sort ( vector < int > & ans , int num ) { int pos = -1 ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) { if ( ans [ i ] >= num ) { pos = i ; break ; } } if ( pos == -1 ) ans . push_back ( num ) ; else ans . insert ( ans . begin ( ) + pos , num ) ; } void sortStream ( int arr [ ] , int N ) { vector < int > ans ; for ( int i = 0 ; i < N ; i ++ ) { Sort ( ans , arr [ i ] ) ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) { cout << ans [ i ] << " ▁ " ; } cout << endl ; } } int main ( ) { int arr [ ] = { 4 , 1 , 7 , 6 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortStream ( arr , N ) ; return 0 ; }
Count ways to split array into two equal sum subarrays by changing sign of any one array element | C ++ program for the above approach ; Function to count ways of splitting the array in two subarrays of equal sum by changing sign of any 1 element ; Stores the count of elements in prefix and suffix of array ; Stores the total sum of array ; Traverse the array ; Increase the frequency of current element in suffix ; Stores prefix sum upto an index ; Stores sum of suffix from an index ; Stores the count of ways to split the array in 2 subarrays having equal sum ; Traverse the array ; Modify prefix sum ; Add arr [ i ] to prefix Map ; Calculate suffix sum by subtracting prefix sum from total sum of elements ; Remove arr [ i ] from suffix Map ; Store the difference between the subarrays ; Check if diff is even or not ; Count number of ways to split array at index i such that subarray sums are same ; Update the count ; Return the count ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubArraySignChange ( int arr [ ] , int N ) { unordered_map < int , int > prefixCount ; unordered_map < int , int > suffixCount ; int total = 0 ; for ( int i = N - 1 ; i >= 0 ; i -- ) { total += arr [ i ] ; suffixCount [ arr [ i ] ] ++ ; } int prefixSum = 0 ; int suffixSum = 0 ; int count = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { prefixSum += arr [ i ] ; prefixCount [ arr [ i ] ] ++ ; suffixSum = total - prefixSum ; suffixCount [ arr [ i ] ] -- ; int diff = prefixSum - suffixSum ; if ( diff % 2 == 0 ) { int x = prefixCount + suffixCount [ - diff / 2 ] ; count = count + x ; } } return count ; } int main ( ) { int arr [ ] = { 2 , 2 , -3 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countSubArraySignChange ( arr , N ) ; return 0 ; }
Partition string into two substrings having maximum number of common non | C ++ program to implement the above approach ; Function to count maximum common non - repeating characters that can be obtained by partitioning the string into two non - empty substrings ; Stores count of non - repeating characters present in both the substrings ; Stores distinct characters in left substring ; Stores distinct characters in right substring ; Traverse left substring ; Insert S [ i ] into ls ; Traverse right substring ; Insert S [ i ] into rs ; Traverse distinct characters of left substring ; If current character is present in right substring ; Update cnt ; Return count ; Function to partition the string into two non - empty substrings in all possible ways ; Stores maximum common distinct characters present in both the substring partitions ; Traverse the string ; Update ans ; Print count of maximum common non - repeating characters ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countCommonChar ( int ind , string & S ) { int cnt = 0 ; set < char > ls ; set < char > rs ; for ( int i = 0 ; i < ind ; ++ i ) { ls . insert ( S [ i ] ) ; } for ( int i = ind ; i < S . length ( ) ; ++ i ) { rs . insert ( S [ i ] ) ; } for ( auto v : ls ) { if ( rs . count ( v ) ) { ++ cnt ; } } return cnt ; } void partitionStringWithMaxCom ( string & S ) { int ans = 0 ; for ( int i = 1 ; i < S . length ( ) ; ++ i ) { ans = max ( ans , countCommonChar ( i , S ) ) ; } cout << ans << " STRNEWLINE " ; } int main ( ) { string str = " aabbca " ; partitionStringWithMaxCom ( str ) ; return 0 ; }
Partition string into two substrings having maximum number of common non | C ++ program to implement the above approach ; Function to count maximum common non - repeating characters that can be obtained by partitioning the string into two non - empty substrings ; Stores distinct characters of S in sorted order ; Stores maximum common distinct characters present in both the partitions ; Stores frequency of each distinct character n the string S ; Traverse the string ; Update frequency of S [ i ] ; Traverse the string ; Decreasing frequency of S [ i ] ; If the frequency of S [ i ] is 0 ; Remove S [ i ] from Q ; Insert S [ i ] into Q ; Stores count of distinct characters in Q ; Update res ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE #include <ext/pb_ds/assoc_container.hpp> NEW_LINE #include <ext/pb_ds/tree_policy.hpp> NEW_LINE using namespace std ; using namespace __gnu_cxx ; using namespace __gnu_pbds ; template < typename T > using ordered_set = tree < T , null_type , less < T > , rb_tree_tag , tree_order_statistics_node_update > ; int countMaxCommonChar ( string & S ) { ordered_set < char > Q ; int res = 0 ; map < char , int > freq ; for ( int i = 0 ; i < S . length ( ) ; i ++ ) { freq [ S [ i ] ] ++ ; } for ( int i = 0 ; i < S . length ( ) ; i ++ ) { freq [ S [ i ] ] -- ; if ( ! freq [ S [ i ] ] ) { Q . erase ( S [ i ] ) ; } else { Q . insert ( S [ i ] ) ; } int curr = Q . size ( ) ; res = max ( res , curr ) ; } cout << res << " STRNEWLINE " ; } int main ( ) { string str = " aabbca " ; countMaxCommonChar ( str ) ; return 0 ; }
Longest Substring of 1 's after removing one character | C ++ Program to implement the above approach ; Function to calculate the length of the longest substring of '1' s that can be obtained by deleting one character ; Add '0' at the end ; Iterator to traverse the string ; Stores maximum length of required substring ; Stores length of substring of '1' preceding the current character ; Stores length of substring of '1' succeeding the current character ; Counts number of '0' s ; Traverse the string S ; If current character is '1' ; Increase curr_one by one ; Otherwise ; Increment numberofZeros by one ; Count length of substring obtained y concatenating preceding and succeeding substrings of '1' ; Store maximum size in res ; Assign curr_one to prev_one ; Reset curr_one ; If string contains only one '0' ; Return the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longestSubarray ( string s ) { s += '0' ; int i ; int res = 0 ; int prev_one = 0 ; int curr_one = 0 ; int numberOfZeros = 0 ; for ( i = 0 ; i < s . length ( ) ; i ++ ) { if ( s [ i ] == '1' ) { curr_one += 1 ; } else { numberOfZeros += 1 ; prev_one += curr_one ; res = max ( res , prev_one ) ; prev_one = curr_one ; curr_one = 0 ; } } if ( numberOfZeros == 1 ) { res -= 1 ; } return res ; } int main ( ) { string S = "1101" ; cout << longestSubarray ( S ) ; return 0 ; }
Longest Substring of 1 's after removing one character | C ++ Program to implement the above approach ; Function to calculate the length of the longest substring of '1' s that can be obtained by deleting one character ; Initializing i and j as left and right boundaries of sliding window ; If current character is '0' ; Decrement k by one ; If k is less than zero and character at ith index is '0' ; Return result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longestSubarray ( string s ) { int i = 0 , j = 0 , k = 1 ; for ( j = 0 ; j < s . size ( ) ; ++ j ) { if ( s [ j ] == '0' ) k -- ; if ( k < 0 && s [ i ++ ] == '0' ) k ++ ; } return j - i - 1 ; } int main ( ) { string S = "011101101" ; cout << longestSubarray ( S ) ; return 0 ; }
Lexicographically smallest string possible by inserting given character | C ++ Program to implement the above approach ; Function to obtain lexicographically smallest string possible by inserting character c in the string s ; Traverse the string ; If the current character is greater than the given character ; Insert the character before the greater character ; Return the string ; Append the character at the end ; Return the string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string SmallestString ( string s , char c ) { for ( int i = 0 ; i < s . size ( ) ; i ++ ) { if ( s [ i ] > c ) { s . insert ( i , 1 , c ) ; return s ; } } s += c ; return s ; } int main ( ) { string S = " acd " ; char C = ' b ' ; cout << SmallestString ( S , C ) << endl ; return 0 ; }
Largest Non | C ++ program to implement the above approach ; Function to find the largest unique element of the array ; Store frequency of each distinct array element ; Traverse the array ; Update frequency of arr [ i ] ; Stores largest non - repeating element present in the array ; Stores index of the largest unique element of the array ; Traverse the array ; If frequency of arr [ i ] is equal to 1 and arr [ i ] exceeds LNRElem ; Update ind ; Update LNRElem ; If no array element is found with frequency equal to 1 ; Print the largest non - repeating element ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void LarUnEl ( int arr [ ] , int N ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { mp [ arr [ i ] ] ++ ; } int LNRElem = INT_MIN ; int ind = -1 ; for ( int i = 0 ; i < N ; i ++ ) { if ( mp [ arr [ i ] ] == 1 && arr [ i ] > LNRElem ) { ind = i ; LNRElem = arr [ i ] ; } } if ( ind == -1 ) { cout << ind ; return ; } cout << arr [ ind ] ; } int main ( ) { int arr [ ] = { 3 , 1 , 8 , 8 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; LarUnEl ( arr , N ) ; }
Minimum shifts of substrings of 1 s required to group all 1 s together in a given Binary string | C ++ program for the above approach ; Function to count indices substrings of 1 s need to be shifted such that all 1 s in the string are grouped together ; Stores first occurrence of '1' ; Stores last occurrence of '1' ; Count of 0 s between firstOne and lastOne ; Traverse the string to find the first and last occurrences of '1' ; Count number of 0 s present between firstOne and lastOne ; Print minimum operations ; Driver Code ; Given string
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countShifts ( string str ) { int firstOne = -1 ; int lastOne = -1 ; int count = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] == '1' ) { if ( firstOne == -1 ) firstOne = i ; lastOne = i ; } } if ( ( firstOne == -1 ) || ( firstOne == lastOne ) ) { cout << 0 ; return ; } for ( int i = firstOne ; i <= lastOne ; i ++ ) { if ( str [ i ] == '0' ) { count ++ ; } } cout << count << endl ; } int main ( ) { string str = "00110111011" ; countShifts ( str ) ; return 0 ; }
Check if a non | C ++ program for the above approach ; Utility Function to check whether a subsequence same as the given subarray exists or not ; Check if first element of the subarray is also present before ; Check if last element of the subarray is also present later ; If above two conditions are not satisfied , then no such subsequence exists ; Function to check and print if a subsequence which is same as the given subarray is present or not ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkSubsequenceUtil ( int arr [ ] , int L , int R , int N ) { for ( int i = 0 ; i < L ; i ++ ) if ( arr [ i ] == arr [ L ] ) return true ; for ( int i = R + 1 ; i < N ; i ++ ) if ( arr [ i ] == arr [ R ] ) return true ; return false ; } void checkSubsequence ( int arr [ ] , int L , int R , int N ) { if ( checkSubsequenceUtil ( arr , L , R , N ) ) { cout << " YES STRNEWLINE " ; } else { cout << " NO STRNEWLINE " ; } } int main ( ) { int arr [ ] = { 1 , 7 , 12 , 1 , 7 , 5 , 10 , 11 , 42 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int L = 3 , R = 6 ; checkSubsequence ( arr , L , R , N ) ; }
Search an element in a Doubly Linked List | C ++ program to implement the above approach ; Structure of a node of the doubly linked list ; Stores data value of a node ; Stores pointer to next node ; Stores pointer to previous node ; Function to insert a node at the beginning of the Doubly Linked List ; Allocate memory for new node ; Insert the data ; Since node is added at the beginning , prev is always NULL ; Link the old list to the new node ; If pointer to head is not NULL ; Change the prev of head node to new node ; Move the head to point to the new node ; Function to find the position of an integer in doubly linked list ; Stores head Node ; Stores position of the integer in the doubly linked list ; Traverse the doubly linked list ; Update pos ; Update temp ; If the integer not present in the doubly linked list ; If the integer present in the doubly linked list ; Driver Code ; Create the doubly linked list 18 < -> 15 < -> 8 < -> 9 < -> 14
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * next ; Node * prev ; } ; void push ( Node * * head_ref , int new_data ) { Node * new_node = ( Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> prev = NULL ; new_node -> next = ( * head_ref ) ; if ( ( * head_ref ) != NULL ) { ( * head_ref ) -> prev = new_node ; } ( * head_ref ) = new_node ; } int search ( Node * * head_ref , int x ) { Node * temp = * head_ref ; int pos = 0 ; while ( temp -> data != x && temp -> next != NULL ) { pos ++ ; temp = temp -> next ; } if ( temp -> data != x ) return -1 ; return ( pos + 1 ) ; } int main ( ) { Node * head = NULL ; int X = 8 ; push ( & head , 14 ) ; push ( & head , 9 ) ; push ( & head , 8 ) ; push ( & head , 15 ) ; push ( & head , 18 ) ; cout << search ( & head , X ) ; return 0 ; }
Longest subarray in which all elements are smaller than K | C ++ program for the above approach ; Function to find the length of the longest subarray with all elements smaller than K ; Stores the length of maximum consecutive sequence ; Stores maximum length of subarray ; Iterate through the array ; Check if array element smaller than K ; Store the maximum of length and count ; Reset the counter ; Print the maximum length ; Driver Code ; Given array arr [ ] ; Size of the array ; Given K ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int largestSubarray ( int arr [ ] , int N , int K ) { int count = 0 ; int len = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] < K ) { count += 1 ; } else { len = max ( len , count ) ; count = 0 ; } } if ( count ) { len = max ( len , count ) ; } cout << len ; } int main ( ) { int arr [ ] = { 1 , 8 , 3 , 5 , 2 , 2 , 1 , 13 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 6 ; largestSubarray ( arr , N , K ) ; return 0 ; }
Smallest pair of indices with product of subarray co | C ++ program for the above approach ; Function to calculate GCD of two integers ; Recursively calculate GCD ; Function to find the lexicographically smallest pair of indices whose product is co - prime with the product of the subarrays on its left and right ; Stores the suffix product of array elements ; Set 0 / 1 if pair satisfies the given condition or not ; Initialize array right_prod [ ] ; Update the suffix product ; Stores product of all elements ; Stores the product of subarray in between the pair of indices ; Iterate through every pair of indices ( i , j ) ; Store product of A [ i , j ] ; Check if product is co - prime to product of either the left or right subarrays ; If no such pair is found , then print - 1 ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } void findPair ( int A [ ] , int N ) { int right_prod [ N ] ; int flag = 0 ; right_prod [ N - 1 ] = A [ N - 1 ] ; for ( int i = N - 2 ; i >= 0 ; i -- ) right_prod [ i ] = right_prod [ i + 1 ] * A [ i ] ; int total_prod = right_prod [ 0 ] ; int product ; for ( int i = 1 ; i < N - 1 ; i ++ ) { product = 1 ; for ( int j = i ; j < N - 1 ; j ++ ) { product *= A [ j ] ; if ( gcd ( product , right_prod [ j + 1 ] ) == 1 || gcd ( product , total_prod / right_prod [ i ] ) == 1 ) { flag = 1 ; cout << " ( " << i - 1 << " , ▁ " << j + 1 << " ) " ; break ; } } if ( flag == 1 ) break ; } if ( flag == 0 ) cout << -1 ; } int main ( ) { int arr [ ] = { 2 , 4 , 1 , 3 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findPair ( arr , N ) ; return 0 ; }
Count binary strings of length same as given string after removal of substrings "01" and "00" that consists of at least one '1' | C ++ program for the above approach ; Function to count the strings consisting of at least 1 set bit ; Initialize count ; Iterate through string ; The answer is 2 ^ N - 1 ; Driver Code ; Given string ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countString ( string S ) { long long count = 0 ; for ( auto it : S ) { if ( it == '0' and count > 0 ) { count -- ; } else { count ++ ; } } cout << ( ( 1 << count ) - 1 ) << " STRNEWLINE " ; } int main ( ) { string S = "1001" ; countString ( S ) ; return 0 ; }
Append digits to the end of duplicate strings to make all strings in an array unique | C ++ program for the above approach ; Function to replace duplicate strings by alphanumeric strings to make all strings in the array unique ; Store the frequency of strings ; Iterate over the array ; For the first occurrence , update the frequency count ; Otherwise ; Append frequency count to end of the string ; Print the modified array ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void replaceDuplicates ( vector < string > & names ) { unordered_map < string , int > hash ; for ( int i = 0 ; i < names . size ( ) ; i ++ ) { if ( hash . count ( names [ i ] ) == 0 ) hash [ names [ i ] ] ++ ; else { int count = hash [ names [ i ] ] ++ ; names [ i ] += to_string ( count ) ; } } for ( int i = 0 ; i < names . size ( ) ; i ++ ) { cout << names [ i ] << " ▁ " ; } } int main ( ) { vector < string > str = { " aa " , " bb " , " cc " , " bb " , " aa " , " aa " , " aa " } ; replaceDuplicates ( str ) ; return 0 ; }
Minimum cost of flipping characters required to convert Binary String to 0 s only | C ++ Program to implement the above approach ; Function to find the minimum cost to convert given string to 0 s only ; Length of string ; Stores the index of leftmost '1' in str ; Update the index of leftmost '1' in str ; Stores the index of rightmost '1' in str ; Update the index of rightmost '1' in str ; If str does not contain any '1' s ; No changes required ; Stores minimum cost ; Iterating through str form left_1 to right_1 ; Stores length of consecutive 0 s ; Calculate length of consecutive 0 s ; If a substring of 0 s exists ; Update minimum cost ; Printing the minimum cost ; Driver Code
#include <iostream> NEW_LINE using namespace std ; void convert_to_allzeroes ( string str , int a , int b ) { int len = str . length ( ) ; int left_1 , i = 0 ; while ( i < len && str [ i ] == '0' ) i ++ ; left_1 = i ; int right_1 ; i = len - 1 ; while ( i >= 0 && str [ i ] == '0' ) i -- ; right_1 = i ; if ( left_1 == len && right_1 == -1 ) { cout << 0 ; return ; } int cost = a , zeroes ; for ( i = left_1 ; i <= right_1 ; i ++ ) { zeroes = 0 ; while ( i < len && str [ i ] == '0' ) { zeroes ++ ; i ++ ; } if ( zeroes ) cost += min ( zeroes * b , a ) ; } cout << cost ; } int main ( ) { string str = "01101110" ; int A = 5 , B = 1 ; convert_to_allzeroes ( str , A , B ) ; return 0 ; }
Minimum distance to visit given K points on X | C ++ program to implement the above approach ; Function to find the minimum distance travelled to visit K point ; Stores minimum distance travelled to visit K point ; Stores distance travelled to visit points ; Traverse the array arr [ ] ; If arr [ i ] and arr [ i + K - 1 ] are positive ; Update dist ; Update dist ; Update res ; Driver Code ; initial the array
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MinDistK ( int arr [ ] , int N , int K ) { int res = INT_MAX ; int dist = 0 ; for ( int i = 0 ; i <= ( N - K ) ; i ++ ) { if ( arr [ i ] >= 0 && arr [ i + K - 1 ] >= 0 ) { dist = max ( arr [ i ] , arr [ i + K - 1 ] ) ; } else { dist = abs ( arr [ i ] ) + abs ( arr [ i + K - 1 ] ) + min ( abs ( arr [ i ] ) , abs ( arr [ i + K - 1 ] ) ) ; } res = min ( res , dist ) ; } return res ; } int main ( ) { int K = 3 ; int arr [ ] = { -30 , -10 , 10 , 20 , 50 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << MinDistK ( arr , N , K ) ; }
Maximize the minimum array element by M subarray increments of size S | C ++ program for the above approach ; Function to return index of minimum element in the array ; Initialize a [ 0 ] as minValue ; Traverse the array ; If a [ i ] < existing minValue ; Return the minimum index ; Function that maximize the minimum element of array after incrementing subarray of size S by 1 , M times ; Iterating through the array for M times ; Find minimum element index ; Increment the minimum value ; Storing the left index and right index ; Incrementing S - 1 minimum elements to the left and right of minValue ; Reached extreme left ; Reached extreme right ; Left value is minimum ; Right value is minimum ; Find the minValue in A [ ] after M operations ; Return the minimum value ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int min ( int a [ ] , int n ) { int minIndex = 0 , minValue = a [ 0 ] , i ; for ( i = 1 ; i < n ; i ++ ) { if ( a [ i ] < minValue ) { minValue = a [ i ] ; minIndex = i ; } } return minIndex ; } int maximizeMin ( int A [ ] , int N , int S , int M ) { int minIndex , left , right , i , j ; for ( i = 0 ; i < M ; i ++ ) { minIndex = min ( A , N ) ; A [ minIndex ] ++ ; left = minIndex - 1 ; right = minIndex + 1 ; for ( j = 0 ; j < S - 1 ; j ++ ) { if ( left == -1 ) A [ right ++ ] ++ ; else if ( right == N ) A [ left -- ] ++ ; else { if ( A [ left ] < A [ right ] ) A [ left -- ] ++ ; else A [ right ++ ] ++ ; } } } minIndex = min ( A , N ) ; return A [ minIndex ] ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int S = 2 , M = 3 ; cout << maximizeMin ( arr , N , S , M ) ; return 0 ; }
Sum of nodes in the path from root to N | C ++ program for the above approach ; Function to find sum of all nodes from root to N ; If N is equal to 1 ; If N is equal to 2 or 3 ; Stores the number of nodes at ( i + 1 ) - th level ; Stores the number of nodes ; Stores if the current level is even or odd ; If level is odd ; If level is even ; If level with node N is reached ; Push into vector ; Compute prefix sums of count of nodes in each level ; Stores the level in which node N s present ; Stores the required sum ; Add temp to the sum ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; typedef long long ll ; ll sumOfPathNodes ( ll N ) { if ( N == 1 ) { return 1 ; } else if ( N == 2 N == 3 ) { return N + 1 ; } vector < ll > arr ; arr . push_back ( 1 ) ; ll k = 1 ; bool flag = true ; while ( k < N ) { if ( flag == true ) { k *= 2 ; flag = false ; } else { k *= 4 ; flag = true ; } if ( k > N ) { break ; } arr . push_back ( k ) ; } ll len = arr . size ( ) ; vector < ll > prefix ( len ) ; prefix [ 0 ] = 1 ; for ( ll i = 1 ; i < len ; ++ i ) { prefix [ i ] = arr [ i ] + prefix [ i - 1 ] ; } vector < ll > :: iterator it = lower_bound ( prefix . begin ( ) , prefix . end ( ) , N ) ; ll ind = it - prefix . begin ( ) ; ll final_ans = 0 ; ll temp = N ; while ( ind > 1 ) { ll val = temp - prefix [ ind - 1 ] ; if ( ind % 2 != 0 ) { temp = prefix [ ind - 2 ] + ( val + 1 ) / 2 ; } else { temp = prefix [ ind - 2 ] + ( val + 3 ) / 4 ; } -- ind ; final_ans += temp ; } final_ans += ( N + 1 ) ; return final_ans ; } int main ( ) { ll N = 13 ; cout << sumOfPathNodes ( N ) << endl ; return 0 ; }
Check if given point lies in range of any of the given towers | C ++ program to implement the above approach ; Function to check if the point ( X , Y ) exists in the towers network - range or not ; Traverse the array arr [ ] ; Stores distance of the point ( X , Y ) from i - th tower ; If dist lies within the range of the i - th tower ; If the point ( X , Y ) does not lie in the range of any of the towers ; Driver Code ; If point ( X , Y ) lies in the range of any of the towers ; Otherwise
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkPointRange ( int arr [ ] [ 3 ] , int X , int Y , int N ) { for ( int i = 0 ; i < N ; i ++ ) { double dist = sqrt ( ( arr [ i ] [ 0 ] - X ) * ( arr [ i ] [ 0 ] - X ) + ( arr [ i ] [ 1 ] - Y ) * ( arr [ i ] [ 1 ] - Y ) ) ; if ( dist <= arr [ i ] [ 2 ] ) { return true ; } } return false ; } int main ( ) { int arr [ ] [ 3 ] = { { 1 , 1 , 3 } , { 10 , 10 , 3 } , { 15 , 15 , 15 } } ; int X = 5 , Y = 5 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( checkPointRange ( arr , X , Y , N ) ) { cout << " True " ; } else { cout << " False " ; } }
Find the winner of the Game of removing odd or replacing even array elements | C ++ program for the above approach ; Function to evaluate the winner of the game ; Stores count of odd array elements ; Stores count of even array elements ; Traverse the array ; If array element is odd ; Otherwise ; If count of even is zero ; If count of odd is even ; If count of odd is odd ; If count of odd is odd and count of even is one ; Otherwise ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findWinner ( int arr [ ] , int N ) { int odd = 0 ; int even = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] % 2 == 1 ) { odd ++ ; } else { even ++ ; } } if ( even == 0 ) { if ( odd % 2 == 0 ) { cout << " Player ▁ 2" << endl ; } else if ( odd % 2 == 1 ) { cout << " Player ▁ 1" << endl ; } } else if ( even == 1 && odd % 2 == 1 ) { cout << " Player ▁ 1" << endl ; } else { cout << -1 << endl ; } } int main ( ) { int arr [ ] = { 3 , 1 , 9 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findWinner ( arr , N ) ; return 0 ; }