text stringlengths 17 4.49k | code stringlengths 49 5.46k |
|---|---|
Find the String having each substring with exactly K distinct characters | C ++ Program to Find the String having each substring with exactly K distinct characters ; Function to find the required output string ; Each element at index i is modulus of K ; Driver code ; initialise integers N and K | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findString ( int N , int K ) { for ( int i = 0 ; i < N ; i ++ ) { cout << char ( ' A ' + i % K ) ; } } int main ( ) { int N = 10 ; int K = 3 ; findString ( N , K ) ; return 0 ; } |
Find total no of collisions taking place between the balls in which initial direction of each ball is given | C ++ implementation to Find total no of collisions taking place between the balls in which initial direction of each ball is given ; Function to count no of collision ; length of the string ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int count ( string s ) { int N , i , cnt = 0 , ans = 0 ; N = s . length ( ) ; for ( i = 0 ; i < N ; i ++ ) { if ( s [ i ] == ' R ' ) cnt ++ ; if ( s [ i ] == ' L ' ) ans += cnt ; } return ans ; } int main ( ) { string s = " RRLL " ; cout << count ( s ) << endl ; r... |
Maximum number on 7 | C ++ implementation to find the maximum number that can be using the N segments in N segments display ; Function to find the maximum number that can be displayed using the N segments ; Condition to check base case ; Condition to check if the number is even ; Condition to check if the number is odd... | #include <iostream> NEW_LINE using namespace std ; void segments ( int n ) { if ( n == 1 n == 0 ) { return ; } if ( n % 2 == 0 ) { cout << "1" ; segments ( n - 2 ) ; } else if ( n % 2 == 1 ) { cout << "7" ; segments ( n - 3 ) ; } } int main ( ) { int n ; n = 11 ; segments ( n ) ; return 0 ; } |
Minimum number of subsequences required to convert one string to another using Greedy Algorithm | C ++ implementation for minimum number of subsequences required to convert one string to another ; Function to find the minimum number of subsequences required to convert one string to another S2 == A and S1 == B ; At leas... | #include <iostream> NEW_LINE using namespace std ; int findMinimumSubsequences ( string A , string B ) { int numberOfSubsequences = 1 ; int sizeOfB = B . size ( ) ; int sizeOfA = A . size ( ) ; int inf = 1000000 ; int next [ 26 ] [ sizeOfB ] ; for ( int i = 0 ; i < 26 ; i ++ ) { for ( int j = 0 ; j < sizeOfB ; j ++ ) {... |
Vertical and Horizontal retrieval ( MRT ) on Tapes | C ++ program to print Horizontal filling ; It is used for checking whether tape is full or not ; It is used for calculating total retrieval time ; It is used for calculating mean retrieval time ; vector is used because n number of records can insert in one tape with ... | #include <bits/stdc++.h> NEW_LINE using namespace std ; void horizontalFill ( int records [ ] , int tape [ ] , int nt ) { int sum = 0 ; int Retrieval_Time = 0 ; double Mrt ; int current = 0 ; vector < int > v ; for ( int i = 0 ; i < nt ; i ++ ) { v . clear ( ) ; Retrieval_Time = 0 ; sum = 0 ; cout << " tape β " << i + ... |
Circular Convolution using Matrix Method | C ++ program to compute circular convolution of two arrays ; Function to find circular convolution ; Finding the maximum size between the two input sequence sizes ; Copying elements of x to row_vec and padding zeros if size of x < maxSize ; Copying elements of h to col_vec and... | #include <iostream> NEW_LINE using namespace std ; #define MAX_SIZE 10 NEW_LINE void convolution ( int * x , int * h , int n , int m ) { int row_vec [ MAX_SIZE ] , col_vec [ MAX_SIZE ] ; int out [ MAX_SIZE ] = { 0 } ; int circular_shift_mat [ MAX_SIZE ] [ MAX_SIZE ] ; int maxSize = n > m ? n : m ; for ( int i = 0 ; i ... |
Maximize the number of palindromic Strings | C ++ program for the above approach ; To check if there is any string of odd length ; If there is at least 1 string of odd length . ; If all the strings are of even length . ; Count of 0 's in all the strings ; Count of 1 's in all the strings ; If z is even and o is even ... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int max_palindrome ( string s [ ] , int n ) { int flag = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] . size ( ) % 2 != 0 ) { flag = 1 ; } } if ( flag == 1 ) { return n ; } int z = 0 , o = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < s [ i ]... |
Minimum possible travel cost among N cities | C ++ implementation of the approach ; Function to return the minimum cost to travel from the first city to the last ; To store the total cost ; Start from the first city ; If found any city with cost less than that of the previous boarded bus then change the bus ; Calculate... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minCost ( vector < int > & cost , int n ) { int totalCost = 0 ; int boardingBus = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( cost [ boardingBus ] > cost [ i ] ) { totalCost += ( ( i - boardingBus ) * cost [ boardingBus ] ) ; boardingBus = i ; } } totalCost +=... |
Minimum cells to be flipped to get a 2 * 2 submatrix with equal elements | C ++ implementation of the approach ; Function to return the minimum flips required such that the submatrix from mat [ i ] [ j ] to mat [ i + 1 ] [ j + 1 ] contains all equal elements ; Function to return the minimum number of slips required suc... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minFlipsSub ( string mat [ ] , int i , int j ) { int cnt0 = 0 , cnt1 = 0 ; if ( mat [ i ] [ j ] == '1' ) cnt1 ++ ; else cnt0 ++ ; if ( mat [ i ] [ j + 1 ] == '1' ) cnt1 ++ ; else cnt0 ++ ; if ( mat [ i + 1 ] [ j ] == '1' ) cnt1 ++ ; else cnt0 ++ ; if ( mat [ i... |
Count set bits in the Kth number after segregating even and odd from N natural numbers | C ++ implementation of the approach ; Function to return the kth element of the Odd - Even sequence of length n ; Finding the index from where the even numbers will be stored ; Return the kth element ; Function to return the count ... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findK ( int n , int k ) { int pos ; if ( n % 2 == 0 ) { pos = n / 2 ; } else { pos = ( n / 2 ) + 1 ; } if ( k <= pos ) { return ( k * 2 - 1 ) ; } else return ( ( k - pos ) * 2 ) ; } int countSetBits ( int n , int k ) { int kth = findK ( n , k ) ; return __buil... |
Minimum cost to convert str1 to str2 with the given operations | C ++ implementation of the approach ; Function to return the minimum cost to convert str1 to sr2 ; For every character of str1 ; If current character is not equal in both the strings ; If the next character is also different in both the strings then these... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minCost ( string str1 , string str2 , int n ) { int cost = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str1 [ i ] != str2 [ i ] ) { if ( i < n - 1 && str1 [ i + 1 ] != str2 [ i + 1 ] ) { swap ( str1 [ i ] , str1 [ i + 1 ] ) ; cost ++ ; } else { cost ++ ; } } }... |
Partition first N natural number into two sets such that their sum is not coprime | C ++ implementation of the approach ; Function to find the required sets ; Impossible case ; Sum of first n - 1 natural numbers ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void find_set ( int n ) { if ( n <= 2 ) { cout << " - 1" ; return ; } int sum1 = ( n * ( n - 1 ) ) / 2 ; int sum2 = n ; cout << sum1 << " β " << sum2 ; } int main ( ) { int n = 8 ; find_set ( n ) ; return 0 ; } |
Count common elements in two arrays containing multiples of N and M | C ++ implementation of the above approach ; Recursive function to find gcd using euclidean algorithm ; Function to find lcm of two numbers using gcd ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } int lcm ( int n , int m ) { return ( n * m ) / gcd ( n , m ) ; } int main ( ) { int n = 2 , m = 3 , k = 5 ; cout << k / lcm ( n , m ) << endl ; return 0 ; } |
Check whether a subsequence exists with sum equal to k if arr [ i ] > 2 * arr [ i | C ++ implementation of above approach ; Function to check whether sum of any set of the array element is equal to k or not ; Traverse the array from end to start ; if k is greater than arr [ i ] then subtract it from k ; If there is any... | #include <iostream> NEW_LINE using namespace std ; bool CheckForSequence ( int arr [ ] , int n , int k ) { for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( k >= arr [ i ] ) k -= arr [ i ] ; } if ( k != 0 ) return false ; else return true ; } int main ( ) { int A [ ] = { 1 , 3 , 7 , 15 , 31 } ; int n = sizeof ( A ) / sizeof... |
Maximum possible sub | C ++ implementation of the approach ; Function to return the maximum sub - array sum after at most x swaps ; To store the required answer ; For all possible intervals ; Keep current ans as zero ; To store the integers which are not part of the sub - array currently under consideration ; To store ... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int SubarraySum ( int a [ ] , int n , int x ) { int ans = -10000 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { int curans = 0 ; priority_queue < int , vector < int > > pq ; priority_queue < int , vector < int > , greater < int > > pq2 ; f... |
Generate an array of size K which satisfies the given conditions | C ++ implementation of the approach ; Function to generate and print the required array ; Initializing the array ; Finding r ( from above approach ) ; If r < 0 ; Finding ceiling and floor values ; Fill the array with ceiling values ; Fill the array with... | #include <bits/stdc++.h> NEW_LINE using namespace std ; void generateArray ( int n , int k ) { vector < int > array ( k , 0 ) ; int remaining = n - int ( k * ( k + 1 ) / 2 ) ; if ( remaining < 0 ) cout << ( " NO " ) ; int right_most = remaining % k ; int high = ceil ( remaining / ( k * 1.0 ) ) ; int low = floor ( remai... |
Maximize the given number by replacing a segment of digits with the alternate digits given | C ++ implementation of the approach ; Function to return the maximized number ; Iterate till the end of the string ; Check if it is greater or not ; Replace with the alternate till smaller ; Return original s in case no change ... | #include <bits/stdc++.h> NEW_LINE using namespace std ; string get_maximum ( string s , int a [ ] ) { int n = s . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] - '0' < a [ s [ i ] - '0' ] ) { int j = i ; while ( j < n && ( s [ j ] - '0' <= a [ s [ j ] - '0' ] ) ) { s [ j ] = '0' + a [ s [ j ] - '0' ] ; j +... |
Number of times the largest perfect square number can be subtracted from N | C ++ implementation of the approach ; Function to return the count of steps ; Variable to store the count of steps ; Iterate while N > 0 ; Get the largest perfect square and subtract it from N ; Increment steps ; Return the required count ; Dr... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSteps ( int n ) { int steps = 0 ; while ( n ) { int largest = sqrt ( n ) ; n -= ( largest * largest ) ; steps ++ ; } return steps ; } int main ( ) { int n = 85 ; cout << countSteps ( n ) ; return 0 ; } |
Maximum array sum that can be obtained after exactly k changes | C ++ implementation of the approach ; Utility function to return the sum of the array elements ; Function to return the maximized sum of the array after performing the given operation exactly k times ; Sort the array elements ; Change signs of the negativ... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sumArr ( int arr [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; return sum ; } int maxSum ( int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; int i = 0 ; while ( i < n && k > 0 && arr [ i ] < 0 ) { arr [ i ] *= -1 ; k ... |
Given count of digits 1 , 2 , 3 , 4 , find the maximum sum possible | CPP program to maximum possible sum ; Function to find the maximum possible sum ; To store required sum ; Number of 234 's can be formed ; Sum obtained with 234 s ; Remaining 2 's ; Sum obtained with 12 s ; Return the required sum ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Maxsum ( int c1 , int c2 , int c3 , int c4 ) { int sum = 0 ; int two34 = min ( c2 , min ( c3 , c4 ) ) ; sum = two34 * 234 ; c2 -= two34 ; sum += min ( c2 , c1 ) * 12 ; return sum ; } int main ( ) { int c1 = 5 , c2 = 2 , c3 = 3 , c4 = 4 ; cout << Maxsum ( c1 , ... |
Replace all elements by difference of sums of positive and negative numbers after that element | C ++ program to implement above approach ; Function to print the array elements ; Function to replace all elements with absolute difference of absolute sums of positive and negative elements ; calculate difference of both s... | #include <iostream> NEW_LINE using namespace std ; void printArray ( int N , int arr [ ] ) { for ( int i = 0 ; i < N ; i ++ ) cout << arr [ i ] << " β " ; cout << endl ; } void replacedArray ( int N , int arr [ ] ) { int pos_sum , neg_sum , i , j , diff ; pos_sum = 0 ; neg_sum = 0 ; for ( i = N - 1 ; i >= 0 ; i -- ) { ... |
Count of pairs from 1 to a and 1 to b whose sum is divisible by N | C ++ implementation of above approach ; Function to find the distinct pairs from 1 - a & 1 - b such that their sum is divisible by n . ; pairs from 1 to n * ( a / n ) and 1 to n * ( b / n ) ; pairs from 1 to n * ( a / n ) and n * ( b / n ) to b ; pairs... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findCountOfPairs ( int a , int b , int n ) { int ans = 0 ; ans += n * ( a / n ) * ( b / n ) ; ans += ( a / n ) * ( b % n ) ; ans += ( a % n ) * ( b / n ) ; ans += ( ( a % n ) + ( b % n ) ) / n ; return ans ; } int main ( ) { int a = 5 , b = 13 , n = 3 ; cout <... |
Generate array with minimum sum which can be deleted in P steps | C ++ implementation of above approach ; Function to find the required array ; calculating minimum possible sum ; Array ; place first P natural elements ; Fill rest of the elements with 1 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findArray ( int N , int P ) { int ans = ( P * ( P + 1 ) ) / 2 + ( N - P ) ; int arr [ N + 1 ] ; for ( int i = 1 ; i <= P ; i ++ ) arr [ i ] = i ; for ( int i = P + 1 ; i <= N ; i ++ ) arr [ i ] = 1 ; cout << " The β Minimum β Possible β Sum β is : β " << ans ... |
Find Intersection of all Intervals | C ++ implementation of the approach ; Function to print the intersection ; First interval ; Check rest of the intervals and find the intersection ; If no intersection exists ; Else update the intersection ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findIntersection ( int intervals [ ] [ 2 ] , int N ) { int l = intervals [ 0 ] [ 0 ] ; int r = intervals [ 0 ] [ 1 ] ; for ( int i = 1 ; i < N ; i ++ ) { if ( intervals [ i ] [ 0 ] > r intervals [ i ] [ 1 ] < l ) { cout << -1 ; return ; } else { l = max ( l ,... |
Maximum size of sub | C ++ implementation of the approach ; Function that compares a and b ; Function to return length of longest subarray that satisfies one of the given conditions ; Driver Code ; Print the required answer | #include <bits/stdc++.h> NEW_LINE using namespace std ; int cmp ( int a , int b ) { return ( a > b ) - ( a < b ) ; } int maxSubarraySize ( int arr [ ] , int n ) { int ans = 1 ; int anchor = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int c = cmp ( arr [ i - 1 ] , arr [ i ] ) ; if ( c == 0 ) anchor = i ; else if ( i == n - 1... |
Maximum count of sub | C ++ implementation of the approach ; Function to return the count of the required sub - strings ; Iterate over all characters ; Count with current character ; If the substring has a length k then increment count with current character ; Update max count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSubStrings ( string s , int k ) { int maxSubStr = 0 , n = s . size ( ) ; for ( int c = 0 ; c < 26 ; c ++ ) { char ch = ' a ' + c ; int curr = 0 ; for ( int i = 0 ; i <= n - k ; i ++ ) { if ( s [ i ] != ch ) continue ; int cnt = 0 ; while ( i < n && s [ i ] ... |
Count valid pairs in the array satisfying given conditions | C ++ implementation of the approach ; Function to return total valid pairs ; Initialize count of all the elements ; frequency count of all the elements ; Add total valid pairs ; Exclude pairs made with a single element i . e . ( x , x ) ; Driver Code ; Functi... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int ValidPairs ( int arr [ ] , int n ) { int count [ 121 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) count [ arr [ i ] ] += 1 ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ i ] < arr [ j ] ) continue ; if ( abs ( ar... |
Distribution of candies according to ages of students | C ++ implementation of the approach ; Function to check The validity of distribution ; Stroring the max age of all students + 1 ; Stroring the max candy + 1 ; Creating the frequency array of the age of students ; Creating the frequency array of the packets of cand... | #include <bits/stdc++.h> NEW_LINE using namespace std ; void check_distribution ( int n , int k , int age [ ] , int candy [ ] ) { int mxage = * ( std :: max_element ( age , age + n ) ) + 1 ; int mxcandy = * ( std :: max_element ( candy , candy + k ) ) + 1 ; int fr1 [ mxage ] = { 0 } ; int fr2 [ mxcandy ] = { 0 } ; for ... |
Find a palindromic string B such that given String A is a subsequense of B | C ++ program to find a palindromic string B such that given String A is a subsequense of B ; Function to check if a string is palindrome ; Reversing a string ; check if reversed string is equal to given string ; Function to find a palindromic ... | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkPalindrome ( string s ) { string x = s ; reverse ( s . begin ( ) , s . end ( ) ) ; return s == x ; } string findStringB ( string A ) { string B = A ; reverse ( A . begin ( ) , A . end ( ) ) ; A = A + B ; if ( checkPalindrome ( B ) ) return B ; return A ;... |
Minimum number of 1 's to be replaced in a binary array | C ++ program to find minimum number of 1 ' s β to β be β replaced β to β 0' s ; Function to find minimum number of 1 ' s β to β be β replaced β to β 0' s ; return final answer ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minChanges ( int A [ ] , int n ) { int cnt = 0 ; for ( int i = 0 ; i < n - 2 ; ++ i ) { if ( ( i - 1 >= 0 ) && A [ i - 1 ] == 1 && A [ i + 1 ] == 1 && A [ i ] == 0 ) { A [ i + 1 ] = 0 ; cnt ++ ; } } return cnt ; } int main ( ) { int A [ ] = { 1 , 1 , 0 , 1 , 1... |
Number of closing brackets needed to complete a regular bracket sequence | C ++ program to find number of closing brackets needed and complete a regular bracket sequence ; Function to find number of closing brackets and complete a regular bracket sequence ; Finding the length of sequence ; Counting opening brackets ; C... | #include <iostream> NEW_LINE using namespace std ; void completeSuquence ( string s ) { int n = s . length ( ) ; int open = 0 , close = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ' ( ' ) open ++ ; else close ++ ; if ( close > open ) { cout << " Impossible " << endl ; return ; } } cout << s ; for ( int i = 0... |
Lexicographically smallest permutation with no digits at Original Index | C ++ program to find the smallest permutation ; Function to print the smallest permutation ; when n is even ; when n is odd ; handling last 3 digit ; add EOL and print result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string smallestPermute ( int n ) { char res [ n + 1 ] ; if ( n % 2 == 0 ) { for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) res [ i ] = 48 + i + 2 ; else res [ i ] = 48 + i ; } } else { for ( int i = 0 ; i < n - 2 ; i ++ ) { if ( i % 2 == 0 ) res [ i ] = 48 +... |
Minimum array insertions required to make consecutive difference <= K | CPP implementation of above approach ; Function to return minimum number of insertions required ; Initialize insertions to 0 ; return total insertions ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minInsertions ( int H [ ] , int n , int K ) { int inser = 0 ; for ( int i = 1 ; i < n ; ++ i ) { float diff = abs ( H [ i ] - H [ i - 1 ] ) ; if ( diff <= K ) continue ; else inser += ceil ( diff / K ) - 1 ; } return inser ; } int main ( ) { int H [ ] = { 2 , ... |
Minimum number of operations required to reduce N to 1 | C ++ implementation of above approach ; Function that returns the minimum number of operations to be performed to reduce the number to 1 ; To stores the total number of operations to be performed ; if n is divisible by 3 then reduce it to n / 3 ; if n modulo 3 is... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int count_minimum_operations ( long long n ) { int count = 0 ; while ( n > 1 ) { if ( n % 3 == 0 ) n /= 3 ; else if ( n % 3 == 1 ) n -- ; else { if ( n == 2 ) n -- ; else n ++ ; } count ++ ; } return count ; } int main ( ) { long long n = 4 ; long long ans = count... |
Minimum number of operations required to reduce N to 1 | C ++ implementation of above approach ; Function that returns the minimum number of operations to be performed to reduce the number to 1 ; Base cases ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int count_minimum_operations ( long long n ) { if ( n == 2 ) { return 1 ; } else if ( n == 1 ) { return 0 ; } if ( n % 3 == 0 ) { return 1 + count_minimum_operations ( n / 3 ) ; } else if ( n % 3 == 1 ) { return 1 + count_minimum_operations ( n - 1 ) ; } else { re... |
Maximize the sum of array by multiplying prefix of array with | C ++ implementation of the approach ; To store sum ; To store ending indices of the chosen prefix array vect ; Adding the absolute value of a [ i ] ; If i == 0 then there is no index to be flipped in ( i - 1 ) position ; print the maximized sum ; print the... | #include <bits/stdc++.h> NEW_LINE using namespace std ; void maxSum ( int * a , int n ) { vector < int > l ; int s = 0 ; for ( int i = 0 ; i < n ; i ++ ) { s += abs ( a [ i ] ) ; if ( a [ i ] >= 0 ) continue ; if ( i == 0 ) l . push_back ( i + 1 ) ; else { l . push_back ( i + 1 ) ; l . push_back ( i ) ; } } cout << s <... |
Find the longest common prefix between two strings after performing swaps on second string | C ++ program to find the longest common prefix between two strings after performing swaps on the second string ; int a = x . length ( ) ; length of x int b = y . length ( ) ; length of y ; creating frequency array of characters... | #include <bits/stdc++.h> NEW_LINE using namespace std ; void LengthLCP ( string x , string y ) { int fr [ 26 ] = { 0 } ; for ( int i = 0 ; i < b ; i ++ ) { fr [ y [ i ] - 97 ] += 1 ; } int c = 0 ; for ( int i = 0 ; i < a ; i ++ ) { if ( fr [ x [ i ] - 97 ] > 0 ) { c += 1 ; fr [ x [ i ] - 97 ] -= 1 ; } else break ; } co... |
All possible co | C ++ implementation of the approach ; Function to count possible pairs ; total count of numbers in range ; printing count of pairs ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void CountPair ( int L , int R ) { int x = ( R - L + 1 ) ; cout << x / 2 << " STRNEWLINE " ; } int main ( ) { int L , R ; L = 1 , R = 8 ; CountPair ( L , R ) ; return 0 ; } |
Problems not solved at the end of Nth day | C ++ program to find problems not solved at the end of Nth day ; Function to find problems not solved at the end of Nth day ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int problemsLeft ( int K , int P , int N ) { if ( K <= P ) return 0 ; else return ( K - P ) * N ; } int main ( ) { int K , P , N ; K = 4 ; P = 1 ; N = 10 ; cout << problemsLeft ( K , P , N ) ; return 0 ; } |
Kruskal 's Algorithm (Simple Implementation for Adjacency Matrix) | Simple C ++ implementation for Kruskal 's algorithm ; Find set of vertex i ; Does union of i and j . It returns false if i and j are already in same set . ; Finds MST using Kruskal 's algorithm ; Initialize sets of disjoint sets . ; Include minimum wei... | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define V 5 NEW_LINE int parent [ V ] ; int find ( int i ) { while ( parent [ i ] != i ) i = parent [ i ] ; return i ; } void union1 ( int i , int j ) { int a = find ( i ) ; int b = find ( j ) ; parent [ a ] = b ; } void kruskalMST ( int cost [ ] [ V ] ) { for ( ... |
Number of chocolates left after k iterations | C ++ program to find remaining chocolates after k iterations ; Function to find the chocolates left ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int results ( int n , int k ) { return round ( pow ( n , ( 1.0 / pow ( 2 , k ) ) ) ) ; } int main ( ) { int k = 3 , n = 100000000 ; cout << " Chocolates β left β after β " << k << " β iterations β are β " << results ( n , k ) ; return 0 ; } |
Subarray whose absolute sum is closest to K | C ++ code to find sub - array whose sum shows the minimum deviation ; Starting index , ending index , Deviation ; Iterate i and j to get all subarrays ; Found sub - array with less sum ; Exactly same sum ; Driver code ; Array to store return values | #include <bits/stdc++.h> NEW_LINE using namespace std ; int * getSubArray ( int arr [ ] , int n , int K ) { int i = -1 ; int j = -1 ; int currSum = 0 ; int * result = new int [ 3 ] { i , j , abs ( K - abs ( currSum ) ) } ; for ( i = 0 ; i < n ; i ++ ) { currSum = 0 ; for ( j = i ; j < n ; j ++ ) { currSum += arr [ j ] ... |
Longest subsequence whose average is less than K | C ++ program to perform Q queries to find longest subsequence whose average is less than K ; Function to print the length for evey query ; sort array of N elements ; Array to store average from left ; Sort array of average ; number of queries ; print answer to every qu... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int longestSubsequence ( int a [ ] , int n , int q [ ] , int m ) { sort ( a , a + n ) ; int sum = 0 ; int b [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { sum += a [ i ] ; double av = ( double ) ( sum ) / ( double ) ( i + 1 ) ; b [ i ] = ( ( int ) ( av + 1 ) ) ; } sor... |
Make array elements equal in Minimum Steps | C ++ program to make the array elements equal in minimum steps ; Returns the minimum steps required to make an array of N elements equal , where the first array element equals M ; Corner Case 1 : When N = 1 ; Corner Case 2 : When N = 2 else if ( N == 2 ) corner case 2 ; Driv... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int steps ( int N , int M ) { if ( N == 1 ) return 0 ; return M ; return 2 * M + ( N - 3 ) ; } int main ( ) { int N = 4 , M = 4 ; cout << steps ( N , M ) ; return 0 ; } |
Minimum increment / decrement to make array non | CPP code to count the change required to convert the array into non - increasing array ; min heap ; Here in the loop we will check that whether the upcoming element of array is less than top of priority queue . If yes then we calculate the difference . After that we wil... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int DecreasingArray ( int a [ ] , int n ) { int sum = 0 , dif = 0 ; priority_queue < int , vector < int > , greater < int > > pq ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! pq . empty ( ) && pq . top ( ) < a [ i ] ) { dif = a [ i ] - pq . top ( ) ; sum += dif ; pq... |
Schedule jobs so that each server gets equal load | CPP program to schedule jobs so that each server gets equal load . ; Function to find new array a ; find sum S of both arrays a and b . ; Single element case . ; This checks whether sum s can be divided equally between all array elements . i . e . whether all elements... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( int a [ ] , int b [ ] , int n ) { int i ; long long int s = 0 ; for ( i = 0 ; i < n ; i ++ ) s += ( a [ i ] + b [ i ] ) ; if ( n == 1 ) return a [ 0 ] + b [ 0 ] ; if ( s % n != 0 ) return -1 ; int x = s / n ; for ( i = 0 ; i < n ; i ++ ) { if ( a [ i ]... |
Check if it is possible to survive on Island | C ++ program to find the minimum days on which you need to buy food from the shop so that you can survive the next S days ; function to find the minimum days ; If we can not buy at least a week supply of food during the first week OR We can not buy a day supply of food on ... | #include <bits/stdc++.h> NEW_LINE using namespace std ; void survival ( int S , int N , int M ) { if ( ( ( N * 6 ) < ( M * 7 ) && S > 6 ) M > N ) cout << " No STRNEWLINE " ; else { int days = ( M * S ) / N ; if ( ( ( M * S ) % N ) != 0 ) days ++ ; cout << " Yes β " << days << endl ; } } int main ( ) { int S = 10 , N = ... |
Lexicographically largest subsequence such that every character occurs at least k times | C ++ program to find lexicographically largest subsequence where every character appears at least k times . ; Find lexicographically largest subsequence of s [ 0. . n - 1 ] such that every character appears at least k times . The ... | #include <bits/stdc++.h> NEW_LINE using namespace std ; void subsequence ( char s [ ] , char t [ ] , int n , int k ) { int last = 0 , cnt = 0 , new_last = 0 , size = 0 ; for ( char ch = ' z ' ; ch >= ' a ' ; ch -- ) { cnt = 0 ; for ( int i = last ; i < n ; i ++ ) { if ( s [ i ] == ch ) cnt ++ ; } if ( cnt >= k ) { for ... |
Program for Least Recently Used ( LRU ) Page Replacement algorithm | C ++ implementation of above algorithm ; Function to find page faults using indexes ; To represent set of current pages . We use an unordered_set so that we quickly check if a page is present in set or not ; To store least recently used indexes of pag... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int pageFaults ( int pages [ ] , int n , int capacity ) { unordered_set < int > s ; unordered_map < int , int > indexes ; int page_faults = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . size ( ) < capacity ) { if ( s . find ( pages [ i ] ) == s . end ( ) ) { s .... |
Largest permutation after at most k swaps | C ++ Program to find the largest permutation after at most k swaps using unordered_map . ; Function to find the largest permutation after k swaps ; Storing the elements and their index in map ; If number of swaps allowed are equal to number of elements then the resulting perm... | #include <bits/stdc++.h> NEW_LINE #include <unordered_map> NEW_LINE using namespace std ; void bestpermutation ( int arr [ ] , int k , int n ) { unordered_map < int , int > h ; for ( int i = 0 ; i < n ; i ++ ) { h . insert ( make_pair ( arr [ i ] , i ) ) ; } if ( n <= k ) { sort ( arr , arr + n , greater < int > ( ) ) ... |
Program for Best Fit algorithm in Memory Management | C ++ implementation of Best - Fit algorithm ; Function to allocate memory to blocks as per Best fit algorithm ; Stores block id of the block allocated to a process ; Initially no block is assigned to any process ; pick each process and find suitable blocks according... | #include <bits/stdc++.h> NEW_LINE using namespace std ; void bestFit ( int blockSize [ ] , int m , int processSize [ ] , int n ) { int allocation [ n ] ; memset ( allocation , -1 , sizeof ( allocation ) ) ; for ( int i = 0 ; i < n ; i ++ ) { int bestIdx = -1 ; for ( int j = 0 ; j < m ; j ++ ) { if ( blockSize [ j ] >= ... |
Bin Packing Problem ( Minimize number of used Bins ) | C ++ program to find number of bins required using Best fit algorithm . ; Returns number of bins required using best fit online algorithm ; Initialize result ( Count of bins ) ; Create an array to store remaining space in bins there can be at most n bins ; Place it... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int bestFit ( int weight [ ] , int n , int c ) { int res = 0 ; int bin_rem [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { int j ; int min = c + 1 , bi = 0 ; for ( j = 0 ; j < res ; j ++ ) { if ( bin_rem [ j ] >= weight [ i ] && bin_rem [ j ] - weight [ i ] < min ) { b... |
Bin Packing Problem ( Minimize number of used Bins ) | C ++ program to find number of bins required using Worst fit algorithm . ; Returns number of bins required using worst fit online algorithm ; Initialize result ( Count of bins ) ; Create an array to store remaining space in bins there can be at most n bins ; Place ... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int worstFit ( int weight [ ] , int n , int c ) { int res = 0 ; int bin_rem [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { int j ; int mx = -1 , wi = 0 ; for ( j = 0 ; j < res ; j ++ ) { if ( bin_rem [ j ] >= weight [ i ] && bin_rem [ j ] - weight [ i ] > mx ) { wi = ... |
Find minimum time to finish all jobs with given constraints | C ++ program to find minimum time to finish all jobs with given number of assignees ; Utility function to get maximum element in job [ 0. . n - 1 ] ; Returns true if it is possible to finish jobs [ ] within given time ' time ' ; cnt is count of current assig... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getMax ( int arr [ ] , int n ) { int result = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] > result ) result = arr [ i ] ; return result ; } bool isPossible ( int time , int K , int job [ ] , int n ) { int cnt = 1 ; for ( int i = 0 ; i < n ; ) {... |
Longest subarray with all even or all odd elements | C ++ implementation for the above approach ; Function to calculate longest substring with odd or even elements ; Initializing dp [ ] ; Initializing dp [ 0 ] with 1 ; ans will store the final answer ; Traversing the array from index 1 to N - 1 ; Checking both current ... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int LongestOddEvenSubarray ( int A [ ] , int N ) { int dp [ N ] ; dp [ 0 ] = 1 ; int ans = 1 ; for ( int i = 1 ; i < N ; i ++ ) { if ( ( A [ i ] % 2 == 0 && A [ i - 1 ] % 2 == 0 ) || ( A [ i ] % 2 != 0 && A [ i - 1 ] % 2 != 0 ) ) { dp [ i ] = dp [ i - 1 ] + 1 ; } ... |
Count of subarrays with maximum value as K | C ++ implementation of the above approach ; Function to count the subarrays with maximum not greater than K ; If arr [ i ] > k then arr [ i ] cannot be a part of any subarray . ; Count the number of elements where arr [ i ] is not greater than k . ; Summation of all possible... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int totalSubarrays ( int arr [ ] , int n , int k ) { int ans = 0 , i = 0 ; while ( i < n ) { if ( arr [ i ] > k ) { i ++ ; continue ; } int count = 0 ; while ( i < n && arr [ i ] <= k ) { i ++ ; count ++ ; } ans += ( ( count * ( count + 1 ) ) / 2 ) ; } return ans ... |
Count N | C ++ program for the above approach ; Stores the dp - states ; Function to calculate the count of N - digit numbers that contains all digits from [ 0 - 9 ] atleast once ; If all digits are traversed ; Check if all digits are included in the mask ; If the state has already been computed ; If the current digit ... | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long dp [ 100 ] [ 1 << 10 ] ; long long countOfNumbers ( int digit , int mask , int N ) { if ( digit == N + 1 ) { if ( mask == ( 1 << 10 ) - 1 ) return 1 ; return 0 ; } long long & val = dp [ digit ] [ mask ] ; if ( val != -1 ) return val ; val = 0 ; if ( dig... |
Maximum subsequence sum such that no three are consecutive in O ( 1 ) space | C ++ implementation for the above approach ; Function to calculate the maximum subsequence sum such that no three elements are consecutive ; when N is 1 , answer would be the only element present ; when N is 2 , answer would be sum of element... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSumWO3Consec ( int A [ ] , int N ) { if ( N == 1 ) return A [ 0 ] ; if ( N == 2 ) return A [ 0 ] + A [ 1 ] ; int third = A [ 0 ] ; int second = third + A [ 1 ] ; int first = max ( second , A [ 1 ] + A [ 2 ] ) ; int sum = max ( max ( third , second ) , first... |
Minimum number of given operations required to reduce a number to 2 | C ++ program for the above approach ; Function to find the minimum number of operations required to reduce n to 2 ; Initialize a dp array ; Handle the base case ; Iterate in the range [ 2 , n ] ; Check if i * 5 <= n ; Check if i + 3 <= n ; Return the... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinOperations ( int n ) { int i , dp [ n + 1 ] ; for ( i = 0 ; i < n + 1 ; i ++ ) { dp [ i ] = 999999 ; } dp [ 2 ] = 0 ; for ( i = 2 ; i < n + 1 ; i ++ ) { if ( i * 5 <= n ) { dp [ i * 5 ] = min ( dp [ i * 5 ] , dp [ i ] + 1 ) ; } if ( i + 3 <= n ) { dp [ ... |
Number of M | C ++ program for the above approach ; Function to find the number of M - length sorted arrays possible using numbers from the range [ 1 , N ] ; Create an array of size M + 1 ; Base cases ; Fill the dp table ; dp [ j ] will be equal to maximum number of sorted array of size j when elements are taken from 1... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSortedArrays ( int n , int m ) { vector < int > dp ( m + 1 , 0 ) ; dp [ 0 ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { dp [ j ] = dp [ j - 1 ] + dp [ j ] ; } } return dp [ m ] ; } int main ( ) { int n = 2 , m = 3 ; cout ... |
Split array into subarrays such that sum of difference between their maximums and minimums is maximum | C ++ program for the above approach ; Function to find maximum sum of difference between maximums and minimums in the splitted subarrays ; Base Case ; Traverse the array ; Stores the maximum and minimum elements upto... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getValue ( int arr [ ] , int N ) { int dp [ N ] ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ 0 ] = 0 ; for ( int i = 1 ; i < N ; i ++ ) { int minn = arr [ i ] ; int maxx = arr [ i ] ; for ( int j = i ; j >= 0 ; j -- ) { minn = min ( arr [ j ] , minn ) ; maxx = m... |
Length of longest subset consisting of A 0 s and B 1 s from an array of strings | C ++ program for the above approach ; Function to count 0 's in a string ; Stores count of 0 s ; Iterate over characters of string ; If current character is '0' ; Recursive function to find the length of longest subset from an array of st... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int count0 ( string s ) { int count = 0 ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { if ( s [ i ] == '0' ) { count ++ ; } } return count ; } int solve ( vector < string > vec , int A , int B , int idx ) { if ( idx == vec . size ( ) A + B == 0 ) { return 0 ; } i... |
Maximum score possible by removing substrings made up of single distinct character | C ++ program for the above approach ; Function to check if the string s consists of a single distinct character or not ; Function to calculate the maximum score possible by removing substrings ; If string is empty ; If length of string... | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isUnique ( string s ) { set < char > Set ; for ( char c : s ) { Set . insert ( c ) ; } return Set . size ( ) == 1 ; } int maxScore ( string s , int a [ ] ) { int n = s . length ( ) ; if ( n == 0 ) return 0 ; if ( n == 1 ) return a [ 0 ] ; int mx = -1 ; for ( ... |
Maximum score possible by removing substrings made up of single distinct character | C ++ program for the above approach ; Initialize a dictionary to store the precomputed results ; Function to calculate the maximum score possible by removing substrings ; If s is present in dp [ ] array ; Base Cases : ; If length of st... | #include <bits/stdc++.h> NEW_LINE using namespace std ; map < string , int > dp ; int maxScore ( string s , vector < int > a ) { if ( dp . find ( s ) != dp . end ( ) ) return dp [ s ] ; int n = s . size ( ) ; if ( n == 0 ) return 0 ; if ( n == 1 ) return a [ 0 ] ; int head = 0 ; int mx = -1 ; while ( head < n ) { int t... |
Count all unique outcomes possible by performing S flips on N coins | C ++ program for the above approach ; Dimensions of the DP table ; Stores the dp states ; Function to recursively count the number of unique outcomes possible by performing S flips on N coins ; Base Case ; If the count for the current state is not ca... | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define size 1001 NEW_LINE int ans [ size ] [ size ] = { 0 } ; int numberOfUniqueOutcomes ( int n , int s ) { if ( s < n ) ans [ n ] [ s ] = 0 ; else if ( n == 1 n == s ) ans [ n ] [ s ] = 1 ; else if ( ! ans [ n ] [ s ] ) { ans [ n ] [ s ] = numberOfUniqueOutcom... |
Minimize removals to remove another string as a subsequence of a given string | C ++ implementation of the above approach ; Function to print the minimum number of character removals required to remove X as a subsequence from the string str ; Length of the string str ; Length of the string X ; Stores the dp states ; Fi... | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printMinimumRemovals ( string str , string X ) { int N = str . size ( ) ; int M = X . size ( ) ; int dp [ N ] [ M ] = { } ; for ( int j = 0 ; j < M ; j ++ ) { if ( str [ 0 ] == X [ j ] ) { dp [ 0 ] [ j ] = 1 ; } } for ( int i = 1 ; i < N ; i ++ ) { for ( int ... |
Railway Station | TCS CodeVita 2020 | C ++ program of the above approach ; Dp table for memoization ; Function to count the number of ways to N - th station ; Base Cases ; If current state is already evaluated ; Count ways in which train 1 can be chosen ; Count ways in which train 2 can be chosen ; Count ways in which ... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 100000 ] ; int findWays ( int x ) { if ( x < 0 ) return 0 ; if ( x == 0 ) return 1 ; if ( x == 1 ) return 2 ; if ( x == 2 ) return 4 ; if ( dp [ x ] != -1 ) return dp [ x ] ; int count = findWays ( x - 1 ) ; count += findWays ( x - 2 ) ; count += findWays... |
Maximum sum not exceeding K possible for any rectangle of a Matrix | C ++ program for the above approach ; Function to find the maximum possible sum of arectangle which is less than K ; Stores the values ( cum_sum - K ) ; Insert 0 into the set sumSet ; Traverse over the rows ; Get cumulative sum from [ 0 to i ] ; Searc... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSubarraySum ( vector < int > & sum , int k , int row ) { int curSum = 0 , curMax = INT_MIN ; set < int > sumSet ; sumSet . insert ( 0 ) ; for ( int r = 0 ; r < row ; ++ r ) { curSum += sum [ r ] ; auto it = sumSet . lower_bound ( curSum - k ) ; if ( it != s... |
Maximum sum submatrix | C ++ program for the above approach ; Function to find maximum continuous maximum sum in the array ; Stores current and maximum sum ; Traverse the array v ; Add the value of the current element ; Update the maximum sum ; Return the maximum sum ; Function to find the maximum submatrix sum ; Store... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int kadane ( vector < int > v ) { int currSum = 0 ; int maxSum = INT_MIN ; for ( int i = 0 ; i < ( int ) v . size ( ) ; i ++ ) { currSum += v [ i ] ; if ( currSum > maxSum ) { maxSum = currSum ; } if ( currSum < 0 ) { currSum = 0 ; } } return maxSum ; } void maxSu... |
Minimize cost of painting N houses such that adjacent houses have different colors | C ++ program for the above approach ; Function to find the minimum cost of coloring the houses such that no two adjacent houses has the same color ; Corner Case ; Auxiliary 2D dp array ; Base Case ; If current house is colored with red... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minCost ( vector < vector < int > > & costs , int N ) { if ( N == 0 ) return 0 ; vector < vector < int > > dp ( N , vector < int > ( 3 , 0 ) ) ; dp [ 0 ] [ 0 ] = costs [ 0 ] [ 0 ] ; dp [ 0 ] [ 1 ] = costs [ 0 ] [ 1 ] ; dp [ 0 ] [ 2 ] = costs [ 0 ] [ 2 ] ; for ... |
Minimize count of flips required to make sum of the given array equal to 0 | C ++ program for the above approach ; Initialize dp [ ] [ ] ; Function to find the minimum number of operations to make sum of A [ ] 0 ; Initialize answer ; Base case ; Otherwise , return 0 ; Pre - computed subproblem ; Recurrence relation for... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 2001 ] [ 2001 ] ; int solve ( vector < int > & A , int i , int sum , int N ) { int res = 2001 ; if ( sum < 0 or ( i == N and sum != 0 ) ) { return 2001 ; } if ( sum == 0 or i >= N ) { return dp [ i ] [ sum ] = 0 ; } if ( dp [ i ] [ sum ] != -1 ) { return ... |
Count subsequences having average of its elements equal to K | C ++ program for the above approach ; Stores the dp states ; Function to find the count of subsequences having average K ; Base condition ; Three loops for three states ; Recurrence relation ; Stores the sum of dp [ n ] [ j ] [ K * j ] all possible values o... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 101 ] [ 101 ] [ 1001 ] ; int countAverage ( int n , int K , int * arr ) { dp [ 0 ] [ 0 ] [ 0 ] = 1 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int k = 0 ; k < n ; k ++ ) { for ( int s = 0 ; s <= 1000 ; s ++ ) { dp [ i + 1 ] [ k + 1 ] [ s + arr [ i ] ] += d... |
Count ways to remove pairs from a matrix such that remaining elements can be grouped in vertical or horizontal pairs | C ++ program for the above approach ; Function to count ways to remove pairs such that the remaining elements can be arranged in pairs vertically or horizontally ; Store the size of matrix ; If N is od... | #include <bits/stdc++.h> NEW_LINE using namespace std ; void numberofpairs ( vector < vector < int > > v , int k ) { int n = v . size ( ) ; if ( n % 2 == 1 ) { cout << 0 ; return ; } int ans = 0 ; int dp [ k ] [ 2 ] ; for ( int i = 0 ; i < k ; i ++ ) { for ( int j = 0 ; j < 2 ; j ++ ) { dp [ i ] [ j ] = 0 ; } } for ( i... |
Maximize sum by selecting X different | C ++ program for the above approach ; Store overlapping subproblems of the recurrence relation ; Function to find maximum sum of at most N with different index array elements such that at most X are from A [ ] , Y are from B [ ] and Z are from C [ ] ; Base Cases ; If the subprobl... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 50 ] [ 50 ] [ 50 ] [ 50 ] ; int FindMaxS ( int X , int Y , int Z , int n , vector < int > & A , vector < int > & B , vector < int > & C ) { if ( X < 0 or Y < 0 or Z < 0 ) return INT_MIN ; if ( n < 0 ) return 0 ; if ( dp [ n ] [ X ] [ Y ] [ Z ] != -1 ) { r... |
Minimize swaps of adjacent characters to sort every possible rearrangement of given Binary String | C ++ program for the above approach ; Precalculate the values of power of 2 ; Function to calculate 2 ^ N % mod ; Function to find sum of inversions ; Initialise a list of 0 s and ? s ; Traverse the string in the reverse... | #include <bits/stdc++.h> NEW_LINE #define MOD 1000000007 NEW_LINE using namespace std ; vector < int > MEM = { 1 , 2 , 4 , 8 , 16 , 32 , 64 , 128 , 256 , 512 , 1024 , 2048 , 4096 } ; int mod_pow2 ( int n ) { while ( n >= MEM . size ( ) ) MEM . push_back ( ( MEM [ -1 ] * 2 ) % MOD ) ; return MEM [ n ] ; } int inversion... |
Minimum removals required to convert given array to a Mountain Array | C ++ program of the above approach ; Utility function to count array elements required to be removed to make array a mountain array ; Stores length of increasing subsequence from [ 0 , i - 1 ] ; Stores length of increasing subsequence from [ i + 1 ,... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minRemovalsUtil ( int arr [ ] , int n ) { int result = 0 ; if ( n < 3 ) { return -1 ; } int leftIncreasing [ n ] = { 0 } ; int rightIncreasing [ n ] = { 0 } ; for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { if ( arr [ j ] < arr [ i ] ) { ... |
Minimum number of jumps to obtain an element of opposite parity | C ++ program for the above approach ; Bfs for odd numbers are source ; Initialize queue ; Stores for each node , the nodes visited and their distances ; If parity is 0 -> odd Otherwise -> even ; Perform multi - source bfs ; Extract the front element of t... | #include <bits/stdc++.h> NEW_LINE using namespace std ; void bfs ( int n , vector < int > & a , vector < int > invGr [ ] , vector < int > & ans , int parity ) { queue < int > q ; vector < int > vis ( n + 1 , 0 ) ; vector < int > dist ( n + 1 , 0 ) ; for ( int i = 1 ; i <= n ; i ++ ) { if ( ( a [ i ] + parity ) & 1 ) { ... |
Longest subsequence having maximum GCD between any pair of distinct elements | C ++ program for the above approach ; Function to find GCD of pair with maximum GCD ; Stores maximum element of arr [ ] ; Find the maximum element ; Maintain a count array ; Store the frequency of arr [ ] ; Stores the multiples of a number ;... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaxGCD ( int arr [ ] , int N ) { int high = 0 ; for ( int i = 0 ; i < N ; i ++ ) { high = max ( high , arr [ i ] ) ; } int count [ high + 1 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { count [ arr [ i ] ] += 1 ; } int counter = 0 ; for ( int i = high ; i... |
Count unique paths is a matrix whose product of elements contains odd number of divisors | C ++ program for the above approach ; Stores the results ; Count of unique product paths ; Function to check whether number is perfect square or not ; If square root is an integer ; Function to calculate and store all the paths p... | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < vector < vector < int > > > dp ( 105 , vector < vector < int > > ( 105 ) ) ; int countPaths = 0 ; bool isPerfectSquare ( int n ) { long double sr = sqrt ( n ) ; return ( ( sr - floor ( sr ) ) == 0 ) ; } void countUniquePaths ( int a [ ] [ 105 ] , int m , ... |
Generate a combination of minimum coins that sums to a given value | C ++ program for the above approach ; dp array to memoize the results ; List to store the result ; Function to find the minimum number of coins to make the sum equals to X ; Base case ; If previously computed subproblem occurred ; Initialize result ; ... | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100000 NEW_LINE int dp [ MAX + 1 ] ; list < int > denomination ; int countMinCoins ( int n , int C [ ] , int m ) { if ( n == 0 ) { dp [ 0 ] = 0 ; return 0 ; } if ( dp [ n ] != -1 ) return dp [ n ] ; int ret = INT_MAX ; for ( int i = 0 ; i < m ; i ++ )... |
Count all possible paths from top left to bottom right of a Matrix without crossing the diagonal | C ++ Program to implement the above approach ; Function to calculate Binomial Coefficient C ( n , r ) ; C ( n , r ) = C ( n , n - r ) ; [ n * ( n - 1 ) * -- - * ( n - r + 1 ) ] / [ r * ( r - 1 ) * -- -- * 1 ] ; Function t... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int binCoff ( int n , int r ) { int val = 1 ; int i ; if ( r > ( n - r ) ) { r = ( n - r ) ; } for ( i = 0 ; i < r ; i ++ ) { val *= ( n - i ) ; val /= ( i + 1 ) ; } return val ; } int findWays ( int n ) { n -- ; int a , b , ans ; a = binCoff ( 2 * n , n ) ; b = a... |
Minimum operations to transform given string to another by moving characters to front or end | C ++ program for the above approach ; Function that finds the minimum number of steps to find the minimum characters must be moved to convert string s to t ; r = maximum value over all dp [ i ] [ j ] computed so far ; dp [ i ... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 1010 ] [ 1010 ] ; int solve ( string s , string t ) { int n = s . size ( ) ; int r = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { dp [ i ] [ j ] = 0 ; if ( i > 0 ) { dp [ i ] [ j ] = max ( dp [ i - 1 ] [ j ] , dp [ i ] [ j ] )... |
Longest substring whose characters can be rearranged to form a Palindrome | C ++ program for the above approach ; Function to get the length of longest substring whose characters can be arranged to form a palindromic string ; To keep track of the last index of each xor ; Initialize answer with 0 ; Now iterate through e... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int longestSubstring ( string s , int n ) { map < int , int > index ; int answer = 0 ; int mask = 0 ; index [ mask ] = -1 ; for ( int i = 0 ; i < n ; i ++ ) { int temp = ( int ) s [ i ] - 97 ; mask ^= ( 1 << temp ) ; if ( index [ mask ] ) { answer = max ( answer ,... |
Count of N | C ++ program for the above approach ; Function to find count of N - digit numbers with single digit XOR ; dp [ i ] [ j ] stores the number of i - digit numbers with XOR equal to j ; For 1 - 9 store the value ; Iterate till N ; Calculate XOR ; Store in DP table ; Initialize count ; Print the answer ; Driver... | #include <bits/stdc++.h> NEW_LINE using namespace std ; void countNums ( int N ) { int dp [ N ] [ 16 ] ; memset ( dp , 0 , sizeof ( dp [ 0 ] [ 0 ] ) * N * 16 ) ; for ( int i = 1 ; i <= 9 ; i ++ ) dp [ 0 ] [ i ] = 1 ; for ( int i = 1 ; i < N ; i ++ ) { for ( int j = 0 ; j < 10 ; j ++ ) { for ( int k = 0 ; k < 16 ; k ++ ... |
Count of numbers upto M divisible by given Prime Numbers | C ++ program for the above approach ; Function to count the numbers that are divisible by the numbers in the array from range 1 to M ; Initialize the count variable ; Iterate over [ 1 , M ] ; Iterate over array elements arr [ ] ; Check if i is divisible by a [ ... | #include <iostream> NEW_LINE using namespace std ; int count ( int a [ ] , int M , int N ) { int cnt = 0 ; for ( int i = 1 ; i <= M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( i % a [ j ] == 0 ) { cnt ++ ; break ; } } } return cnt ; } int main ( ) { int arr [ ] = { 2 , 3 , 5 , 7 } ; int m = 100 ; int n = sizeof ... |
Count of numbers upto N digits formed using digits 0 to K | C ++ implementation to count the numbers upto N digits such that no two zeros are adjacent ; Function to count the numbers upto N digits such that no two zeros are adjacent ; Condition to check if only one element remains ; If last element is non zero , return... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 15 ] [ 10 ] ; int solve ( int n , int last , int k ) { if ( n == 1 ) { if ( last == k ) { return ( k - 1 ) ; } else { return 1 ; } } if ( dp [ n ] [ last ] ) return dp [ n ] [ last ] ; if ( last == k ) { return dp [ n ] [ last ] = ( k - 1 ) * solve ( n - ... |
Count of occurrences of each prefix in a string using modified KMP algorithm | C ++ program for the above approach ; Function to print the count of all prefix in the given string ; Iterate over string s ; Print the prefix and their frequency ; Function to implement the LPS array to store the longest prefix which is als... | #include <bits/stdc++.h> NEW_LINE using namespace std ; void print ( vector < int > & occ , string & s ) { for ( int i = 1 ; i <= int ( s . size ( ) ) ; i ++ ) { cout << s . substr ( 0 , i ) << " β occurs β " << occ [ i ] << " β times . " << endl ; } } vector < int > prefix_function ( string & s ) { vector < int > LPS ... |
Maximum sum by picking elements from two arrays in order | Set 2 | C ++ program to find maximum sum possible by selecting an element from one of two arrays for every index ; Function to calculate maximum sum ; Maximum elements that can be chosen from array A ; Maximum elements that can be chosen from array B ; Stores t... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumSum ( int A [ ] , int B [ ] , int length , int X , int Y ) { int l = length ; int l1 = min ( length , X ) ; int l2 = min ( length , Y ) ; int dp [ l1 + 1 ] [ l2 + 1 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ 0 ] [ 0 ] = 0 ; int max_sum = INT_MIN ; for... |
Min number of operations to reduce N to 0 by subtracting any digits from N | C ++ program for the above approach ; Function to reduce an integer N to Zero in minimum operations by removing digits from N ; Initialise dp [ ] to steps ; Iterate for all elements ; For each digit in number i ; Either select the number or do... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int reduceZero ( int N ) { vector < int > dp ( N + 1 , 1e9 ) ; dp [ 0 ] = 0 ; for ( int i = 0 ; i <= N ; i ++ ) { for ( char c : to_string ( i ) ) { dp [ i ] = min ( dp [ i ] , dp [ i - ( c - '0' ) ] + 1 ) ; } } return dp [ N ] ; } int main ( ) { int N = 25 ; cout... |
Pentanacci Numbers | C ++ 14 implementation to print Nth Pentanacci numbers . ; Function to print Nth Pentanacci number ; Initialize first five numbers to base cases ; Declare a current variable ; Loop to add previous five numbers for each number starting from 5 and then assign first , second , third , fourth to second... | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printpenta ( int n ) { if ( n < 0 ) return ; int first = 0 ; int second = 0 ; int third = 0 ; int fourth = 0 ; int fifth = 1 ; int curr = 0 ; if ( n == 0 n == 1 n == 2 n == 3 ) cout << first << " STRNEWLINE " ; else if ( n == 5 ) cout << fifth << " STRNEWLINE... |
Count of binary strings of length N with even set bit count and at most K consecutive 1 s | C ++ program for the above approach ; Table to store solution of each subproblem ; Function to calculate the possible binary strings ; If number of ones is equal to K ; pos : current position Base Case : When n length is travers... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 100001 ] [ 20 ] [ 2 ] ; int possibleBinaries ( int pos , int ones , int sum , int k ) { if ( ones == k ) return 0 ; if ( pos == 0 ) return ( sum == 0 ) ? 1 : 0 ; if ( dp [ pos ] [ ones ] [ sum ] != -1 ) return dp [ pos ] [ ones ] [ sum ] ; int ret = possi... |
Sum of absolute difference of all pairs raised to power K | C ++ program for the above approach ; Since K can be 100 max ; Constructor ; Initializing with - 1 ; Making vector A as 1 - Indexing ; To Calculate the value nCk ; Since nCj = ( n - 1 ) Cj + ( n - 1 ) C ( j - 1 ) ; ; Function that summation of absolute differe... | #include <bits/stdc++.h> NEW_LINE #define ll long long NEW_LINE using namespace std ; class Solution { public : ll ncr [ 101 ] [ 101 ] ; int n , k ; vector < ll > A ; Solution ( int N , int K , vector < ll > B ) { memset ( ncr , -1 , sizeof ( ncr ) ) ; n = N ; k = K ; A = B ; A . insert ( A . begin ( ) , 0 ) ; } ll f ... |
Count of ways to traverse a Matrix and return to origin in K steps | C ++ program to count total number of ways to return to origin after completing given number of steps . ; Function Initialize dp [ ] [ ] [ ] array with - 1 ; Function returns the total count ; Driver Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MOD 1000000007 NEW_LINE long long dp [ 101 ] [ 101 ] [ 101 ] ; int N , M , K ; void Initialize ( ) { for ( int i = 0 ; i <= 100 ; i ++ ) for ( int j = 0 ; j <= 100 ; j ++ ) for ( int z = 0 ; z <= 100 ; z ++ ) dp [ i ] [ j ] [ z ] = -1 ; } int CountWays ( ... |
Count of subsequences of length atmost K containing distinct prime elements | C ++ Program to find the count of distinct prime subsequences at most of of length K from a given array ; Initialize all indices as true ; A value in prime [ i ] will finally be false if i is not a prime , else true ; If prime [ p ] is true ,... | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool prime [ 100001 ] ; void SieveOfEratosthenes ( ) { memset ( prime , true , sizeof ( prime ) ) ; prime [ 0 ] = prime [ 1 ] = false ; for ( int p = 2 ; p * p <= 100000 ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= 100000 ; i += p ) prime [ i... |
Minimize prize count required such that smaller value gets less prize in an adjacent pair | C ++ implementation to find the minimum prizes required such that adjacent smaller elements gets less number of prizes ; Function to find the minimum number of required such that adjacent smaller elements gets less number of pri... | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinPrizes ( int arr [ ] , int n ) { int totalPrizes = 0 , j , x , y ; for ( int i = 0 ; i < n ; i ++ ) { x = 1 ; j = i ; while ( j > 0 && arr [ j ] > arr [ j - 1 ] ) { x ++ ; j -- ; } j = i ; y = 1 ; while ( j < n - 1 && arr [ j ] > arr [ j + 1 ] ) { y ++ ... |
Number of ways to split N as sum of K numbers from the given range | C ++ implementation to count the number of ways to divide N in K groups such that each group has elements in range [ L , R ] ; DP Table ; Function to count the number of ways to divide the number N in K groups such that each group has number of elemen... | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int mod = 1000000007 ; int dp [ 1000 ] [ 1000 ] ; int calculate ( int pos , int left , int k , int L , int R ) { if ( pos == k ) { if ( left == 0 ) return 1 ; else return 0 ; } if ( left == 0 ) return 0 ; if ( dp [ pos ] [ left ] != -1 ) return dp [ pos ] [ ... |
Minimum number of squares whose sum equals to given number N | set 2 | C ++ program to represent N as the sum of minimum square numbers . ; Function for finding minimum square numbers ; A [ i ] of array arr store minimum count of square number to get i ; sqrNum [ i ] store last square number to get i ; Initialize ; Fin... | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > minSqrNum ( int n ) { int arr [ n + 1 ] , k ; int sqrNum [ n + 1 ] ; vector < int > v ; arr [ 0 ] = 0 ; sqrNum [ 0 ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { arr [ i ] = arr [ i - 1 ] + 1 ; sqrNum [ i ] = 1 ; k = 1 ; while ( k * k <= i ) { if ( arr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.