text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Remove all occurrences of a word from a given string using Z | C ++ program for the above approach ; Function to fill the Z - array for str ; L Stores start index of window which matches with prefix of str ; R Stores end index of window which matches with prefix of str ; Iterate over the characters of str ; If i is greater thn R ; Update L and R ; If substring match with prefix ; Update R ; Update Z [ i ] ; Update R ; Update k ; if Z [ k ] is less than remaining interval ; Update Z [ i ] ; Start from R and check manually ; Update R ; Update Z [ i ] ; Update R ; Function to remove all the occurrences of word from str ; Create concatenated string " P $ T " ; Store Z array of concat ; Stores string , str by removing all the occurrences of word from str ; Stores length of word ; Traverse the array , Z [ ] ; if Z [ i + pSize + 1 ] equal to length of word ; Update i ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void getZarr ( string str , int Z [ ] ) { int n = str . length ( ) ; int k ; int L = 0 ; int R = 0 ; for ( int i = 1 ; i < n ; ++ i ) { if ( i > R ) { L = R = i ; while ( R < n && str [ R - L ] == str [ R ] ) { R ++ ; } Z [ i ] = R - L ; R -- ; } else { k = i - L ; if ( Z [ k ] < R - i + 1 ) { Z [ i ] = Z [ k ] ; } else { L = i ; while ( R < n && str [ R - L ] == str [ R ] ) { R ++ ; } Z [ i ] = R - L ; R -- ; } } } } string goodStr ( string str , string word ) { string concat = word + " $ " + str ; int l = concat . length ( ) ; int Z [ l ] ; getZarr ( concat , Z ) ; string res ; int pSize = word . size ( ) ; for ( int i = 0 ; i < l ; ++ i ) { if ( i + pSize < l - 1 && Z [ i + pSize + 1 ] == pSize ) { i += pSize - 1 ; } else if ( i < str . length ( ) ) { res += str [ i ] ; } } return res ; } int main ( ) { string str = " Z - kmalgorithmkmiskmkmkmhelpfulkminkmsearching " ; string word = " km " ; cout << goodStr ( str , word ) ; return 0 ; } |
Count of substrings of a string containing another given string as a substring | Set 2 | C ++ program for the above approach ; Function to count the substrings of string containing another given string as a substring ; Store length of string S ; Store length of string T ; Store the required count of substrings ; Store the starting index of last occurence of T in S ; Iterate in range [ 0 , n1 - n2 ] ; Check if substring from i to i + n2 is equal to T ; Check if substring from i to i + n2 is equal to T ; Mark chk as false and break the loop ; If chk is true ; Add ( i + 1 - last ) * ( n1 - ( i + n2 - 1 ) ) to answer ; Update the last to i + 1 ; Print the answer ; Driver code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findOccurrences ( string S , string T ) { int n1 = S . size ( ) ; int n2 = T . size ( ) ; int ans = 0 ; int last = 0 ; for ( int i = 0 ; i <= n1 - n2 ; i ++ ) { bool chk = true ; for ( int j = 0 ; j < n2 ; j ++ ) { if ( T [ j ] != S [ i + j ] ) { chk = false ; break ; } } if ( chk ) { ans += ( i + 1 - last ) * ( n1 - ( i + n2 - 1 ) ) ; last = i + 1 ; } } cout << ans ; } int main ( ) { string S = " dabc " , T = " ab " ; findOccurrences ( S , T ) ; } |
Lexicographically largest N | C ++ program for the above approach ; Function to find the lexicographically largest bitonic sequence of size N elements lies in the range [ low , high ] ; Store index of highest element ; If high_index > ( N - 1 ) / 2 , then remaining N / 2 elements cannot be placed in bitonic order ; If high_index <= 0 , then set high_index as 1 ; Stores the resultant sequence ; Store the high value ; Maintain strictly decreasing sequence from index high_index to 0 starting with temp ; Store the value and decrement the temp variable by 1 ; Maintain the strictly decreasing sequence from index high_index + 1 to N - 1 starting with high - 1 ; Store the value and decrement high by 1 ; Print the resultant sequence ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void LargestArray ( int N , int low , int high ) { int high_index = N - ( high - low + 1 ) ; if ( high_index > ( N - 1 ) / 2 ) { cout << " Not β Possible " ; return ; } if ( high_index <= 0 ) high_index = 1 ; int A [ N ] ; int temp = high ; for ( int i = high_index ; i >= 0 ; i -- ) { A [ i ] = temp -- ; } high -= 1 ; for ( int i = high_index + 1 ; i < N ; i ++ ) A [ i ] = high -- ; for ( int i = 0 ; i < N ; i ++ ) { cout << A [ i ] << ' β ' ; } } int main ( ) { int N = 5 , low = 2 , high = 6 ; LargestArray ( N , low , high ) ; return 0 ; } |
Print matrix elements from top | C ++ program for the above approach ; Function to traverse the matrix diagonally upwards ; Stores the maximum size of vector from all row of matrix nums [ ] [ ] ; Store elements in desired order ; Store every element on the basis of sum of index ( i + j ) ; Print the stored result ; Reverse all sublist ; Driver code ; Given vector of vectors arr ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printDiagonalTraversal ( vector < vector < int > > & nums ) { int max_size = nums . size ( ) ; for ( int i = 0 ; i < nums . size ( ) ; i ++ ) { if ( max_size < nums [ i ] . size ( ) ) { max_size = nums [ i ] . size ( ) ; } } vector < vector < int > > v ( 2 * max_size - 1 ) ; for ( int i = 0 ; i < nums . size ( ) ; i ++ ) { for ( int j = 0 ; j < nums [ i ] . size ( ) ; j ++ ) { v [ i + j ] . push_back ( nums [ i ] [ j ] ) ; } } for ( int i = 0 ; i < v . size ( ) ; i ++ ) { reverse ( v [ i ] . begin ( ) , v [ i ] . end ( ) ) ; for ( int j = 0 ; j < v [ i ] . size ( ) ; j ++ ) cout << v [ i ] [ j ] << " β " ; } } int main ( ) { vector < vector < int > > arr = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; printDiagonalTraversal ( arr ) ; return 0 ; } |
Check if given string satisfies the following conditions | C ++ program for the above approach ; Function to check if given string satisfies the given conditions ; Dimensions ; Left diagonal ; Right diagonal ; Conditions not satisfied ; Print Yes ; Driver Code ; Given String ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void isValid ( string s ) { int n = sqrt ( s . length ( ) ) ; char check = s [ 0 ] ; for ( int i = 0 ; i < n ; i ++ ) { int x = i , y = i ; while ( x >= 0 && y < n ) { if ( s [ ( n * x ) + y ] != check || s [ ( n * y ) + x ] != check ) { cout << " No " << endl ; return ; } x -- ; y ++ ; } } cout << " Yes " << endl ; } int main ( ) { string str = " abacdaeaafaghaia " ; isValid ( str ) ; return 0 ; } |
Sum of all possible strings obtained by removal of non | C ++ program for the above approach ; Function to convert a character to its equivalent digit ; Function to precompute powers of 10 ; Function to precompute prefix sum of numerical strings ; Function to return the i - th term of Triangular Number ; Function to return the sum of all resulting strings ; Precompute powers of 10 ; Precompute prefix sum ; Initialize result ; Apply the above general formula for every i ; Return the answer ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 10 ; int pref [ N ] , power [ N ] ; int toDigit ( char ch ) { return ( ch - '0' ) ; } void powerOf10 ( ) { power [ 0 ] = 1 ; for ( int i = 1 ; i < N ; i ++ ) power [ i ] = power [ i - 1 ] * 10 ; } void precomputePrefix ( string str , int n ) { pref [ 0 ] = str [ 0 ] - '0' ; for ( int i = 1 ; i < n ; i ++ ) pref [ i ] = pref [ i - 1 ] + toDigit ( str [ i ] ) ; } int triangularNumber ( int i ) { int res = i * ( i + 1 ) / 2 ; return res ; } int sumOfSubstrings ( string str ) { int n = str . size ( ) ; powerOf10 ( ) ; precomputePrefix ( str , n ) ; int ans = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { ans += ( pref [ n - i - 2 ] * ( i + 1 ) + toDigit ( str [ n - i - 1 ] ) * triangularNumber ( n - i - 1 ) ) * power [ i ] ; } return ans ; } int main ( ) { string str = "1234" ; cout << sumOfSubstrings ( str ) ; return 0 ; } |
Sum of products of all possible Subarrays | C ++ program for the above approach ; Function that finds the sum of products of all subarray of arr [ ] ; Stores sum of all subarrays ; Iterate array from behind ; Update the ans ; Update the res ; Print the final sum ; Driver Code ; Given array arr [ ] ; Size of array ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sumOfSubarrayProd ( int arr [ ] , int n ) { int ans = 0 ; int res = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { int incr = arr [ i ] * ( 1 + res ) ; ans += incr ; res = incr ; } cout << ( ans ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sumOfSubarrayProd ( arr , N ) ; } |
Sum of all odd length subarrays | C ++ program for the above approach ; Function to calculate the sum of all odd length subarrays ; Stores the sum ; Size of array ; Traverse the array ; Generate all subarray of odd length ; Add the element to sum ; Return the final sum ; Driver Code ; Given array arr [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int OddLengthSum ( vector < int > & arr ) { int sum = 0 ; int l = arr . size ( ) ; for ( int i = 0 ; i < l ; i ++ ) { for ( int j = i ; j < l ; j += 2 ) { for ( int k = i ; k <= j ; k ++ ) { sum += arr [ k ] ; } } } return sum ; } int main ( ) { vector < int > arr = { 1 , 5 , 3 , 1 , 2 } ; cout << OddLengthSum ( arr ) ; return 0 ; } |
Sum of all odd length subarrays | C ++ program for the above approach ; Function that finds the sum of all the element of subarrays of odd length ; Stores the sum ; Size of array ; Traverse the given array arr [ ] ; Add to the sum for each contribution of the arr [ i ] ; Return the final sum ; Driver Code ; Given array arr [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int OddLengthSum ( vector < int > & arr ) { int sum = 0 ; int l = arr . size ( ) ; for ( int i = 0 ; i < l ; i ++ ) { sum += ( ( ( i + 1 ) * ( l - i ) + 1 ) / 2 ) * arr [ i ] ; } return sum ; } int main ( ) { vector < int > arr = { 1 , 5 , 3 , 1 , 2 } ; cout << OddLengthSum ( arr ) ; return 0 ; } |
Check if Euler Totient Function is same for a given number and twice of that number | C ++ program of the above approach ; Function to find the Euler 's Totient Function ; Initialize result as N ; Consider all prime factors of n and subtract their multiples from result ; Return the count ; Function to check if phi ( n ) is equals phi ( 2 * n ) ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int phi ( int n ) { int result = 1 ; for ( int p = 2 ; p < n ; p ++ ) { if ( __gcd ( p , n ) == 1 ) { result ++ ; } } return result ; } bool sameEulerTotient ( int n ) { return phi ( n ) == phi ( 2 * n ) ; } int main ( ) { int N = 13 ; if ( sameEulerTotient ( N ) ) cout << " Yes " ; else cout << " No " ; } |
Check if Euler Totient Function is same for a given number and twice of that number | C ++ program of the above approach ; Function to check if phi ( n ) is equals phi ( 2 * n ) ; Return if N is odd ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool sameEulerTotient ( int N ) { return ( N & 1 ) ; } int main ( ) { int N = 13 ; if ( sameEulerTotient ( N ) ) cout << " Yes " ; else cout << " No " ; } |
Smallest occurring element in each subsequence | C ++ program for the above approach ; Function that count the subsequence such that each element as the minimum element in the subsequence ; Store index in a map ; Sort the array ; To store count of subsequence ; Traverse the array ; Store count of subsequence ; Print the count of subsequence ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( int arr [ ] , int N ) { map < int , int > M ; for ( int i = 0 ; i < N ; i ++ ) { M [ i ] = arr [ i ] ; } sort ( arr , arr + N ) ; unordered_map < int , int > Count ; for ( int i = 0 ; i < N ; i ++ ) { Count [ arr [ i ] ] = pow ( 2 , N - i - 1 ) ; } for ( auto & it : M ) { cout << Count [ M [ it . second ] ] << ' β ' ; } } int main ( ) { int arr [ ] = { 5 , 2 , 1 } ; int N = sizeof arr / sizeof arr [ 0 ] ; solve ( arr , N ) ; } |
Program to insert dashes between two adjacent odd digits in given Number | C ++ program for the above approach ; Function to check if char ch is odd or not ; Function to insert dash - between any 2 consecutive digit in string str ; Traverse the string character by character ; Compare every consecutive character with the odd value ; Print the resultant string ; Driver Code ; Given number in form of string ; Function Call | #include <iostream> NEW_LINE #include <string> NEW_LINE using namespace std ; bool checkOdd ( char ch ) { return ( ( ch - '0' ) & 1 ) ; } string Insert_dash ( string num_str ) { string result_str = num_str ; for ( int x = 0 ; x < num_str . length ( ) - 1 ; x ++ ) { if ( checkOdd ( num_str [ x ] ) && checkOdd ( num_str [ x + 1 ] ) ) { result_str . insert ( x + 1 , " - " ) ; num_str = result_str ; x ++ ; } } return result_str ; } int main ( ) { string str = "1745389" ; cout << Insert_dash ( str ) ; return 0 ; } |
Check if a Matrix is Reverse Bitonic or Not | C ++ Program to check if a matrix is Reverse Bitonic or not ; Function to check if an array is Reverse Bitonic or not ; Check for decreasing sequence ; Check for increasing sequence ; Function to check whether given matrix is bitonic or not ; Check row - wise ; Check column wise ; Generate an array consisting of elements of the current column ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 3 , M = 3 ; bool checkReverseBitonic ( int arr [ ] , int n ) { int i , j , f = 0 ; for ( i = 1 ; i < n ; i ++ ) { if ( arr [ i ] < arr [ i - 1 ] ) continue ; if ( arr [ i ] == arr [ i - 1 ] ) return false ; else { f = 1 ; break ; } } if ( i == n ) return true ; for ( j = i + 1 ; j < n ; j ++ ) { if ( arr [ j ] > arr [ j - 1 ] ) continue ; if ( arr [ i ] == arr [ i - 1 ] ) return false ; else { if ( f == 1 ) return false ; } } return true ; } void check ( int arr [ N ] [ M ] ) { int f = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( ! checkReverseBitonic ( arr [ i ] , M ) ) { cout << " No " << endl ; return ; } } for ( int i = 0 ; i < N ; i ++ ) { int temp [ N ] ; for ( int j = 0 ; j < N ; j ++ ) { temp [ j ] = arr [ j ] [ i ] ; } if ( ! checkReverseBitonic ( temp , N ) ) { cout << " No " << endl ; return ; } } cout << " Yes " ; } int main ( ) { int m [ N ] [ M ] = { { 2 , 3 , 4 } , { 1 , 2 , 3 } , { 4 , 5 , 6 } } ; check ( m ) ; return 0 ; } |
Find the element at the specified index of a Spirally Filled Matrix | C ++ Program to find the element at given position in spirally filled matrix ; Function to return the element at ( x , y ) ; If y is greater ; If y is odd ; If y is even ; If x is even ; If x is odd ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int SpiralElement ( int x , int y ) { int r ; if ( x < y ) { if ( y % 2 == 1 ) { r = y * y ; return ( r - x + 1 ) ; } else { r = ( y - 1 ) * ( y - 1 ) ; return ( r + x ) ; } } else { if ( x % 2 == 0 ) { r = x * x ; return ( r - y + 1 ) ; } else { r = ( x - 1 ) * ( x - 1 ) ; return ( r + y ) ; } } } int main ( ) { int x = 2 , y = 3 ; cout << SpiralElement ( x , y ) ; return 0 ; } |
Make the string in AP by changing a character | C ++ program for the above problem ; Function to modify the given string and find the index where modification is needed ; Array to store the ASCII values of alphabets ; loop to compute the ASCII values of characters a - z ; Set to store all the possible differences between consecutive elements ; Loop to find out the differences between consecutive elements and storing them in the set ; Checks if any character of the string disobeys the pattern ; Constructing the strings with all possible values of consecutive difference and comparing them with staring string S . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void string_modify ( string s ) { char alphabets [ 26 ] ; int flag = 0 , hold_i ; char hold_l ; int i ; for ( i = 0 ; i < 26 ; i ++ ) { alphabets [ i ] = i + ' a ' ; } set < int > difference ; string reconstruct = " " ; for ( int i = 1 ; i < s . size ( ) ; i ++ ) { difference . insert ( s [ i ] - s [ i - 1 ] ) ; } if ( difference . size ( ) == 1 ) { cout << " No β modifications β required " ; return ; } for ( auto it = difference . begin ( ) ; it != difference . end ( ) ; it ++ ) { int index = s [ 0 ] - ' a ' ; reconstruct = " " ; flag = 0 ; for ( int i = 0 ; i < s . size ( ) && flag <= 1 ; i ++ ) { reconstruct += alphabets [ index ] ; index += * it ; if ( index < 0 ) { index += 26 ; } index %= 26 ; if ( reconstruct [ i ] != s [ i ] ) { flag ++ ; hold_i = i ; hold_l = s [ i ] ; } } if ( flag == 1 ) { s [ hold_i ] = reconstruct [ hold_i ] ; break ; } } if ( flag > 1 ) { hold_i = 0 ; hold_l = s [ 0 ] ; int temp = ( s [ 1 ] - ' a ' - ( s [ 2 ] - s [ 1 ] ) ) % 26 ; if ( temp < 0 ) { temp += 26 ; } s [ 0 ] = alphabets [ temp ] ; } cout << hold_i << " β - > β " << hold_l << endl << s << endl ; } int main ( ) { string s = " aeimqux " ; string_modify ( s ) ; } |
Create matrix whose sum of diagonals in each sub matrix is even | C ++ program for the above approach ; Function to print N * N order matrix with all sub - matrix of even order is sum of its diagonal also even ; Even index ; Odd index ; Iterate two nested loop ; For even index the element should be consecutive odd ; for odd index the element should be consecutive even ; Driver Code ; Given order of matrix ; Function call | #include <iostream> NEW_LINE using namespace std ; void evenSubMatrix ( int N ) { int even = 1 ; int odd = 2 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( ( i + j ) % 2 == 0 ) { cout << even << " β " ; even += 2 ; } else { cout << odd << " β " ; odd += 2 ; } } cout << " STRNEWLINE " ; } } int main ( ) { int N = 4 ; evenSubMatrix ( N ) ; return 0 ; } |
Remove leading zeros from a Number given as a string | C ++ Program to implement the above approach ; Function to remove all leading zeros from a a given string ; Regex to remove leading zeros from a string ; Replaces the matched value with given string ; Driver Code | #include <iostream> NEW_LINE #include <regex> NEW_LINE using namespace std ; void removeLeadingZeros ( string str ) { const regex pattern ( " ^ 0 + ( ? ! $ ) " ) ; str = regex_replace ( str , pattern , " " ) ; cout << str ; } int main ( ) { string str = "0001234" ; removeLeadingZeros ( str ) ; return 0 ; } |
Maximum inversions in a sequence of 1 to N after performing given operations at most K times | C ++ program for the above approach ; Function which computes the maximum number of inversions ; ' answer ' will store the required number of inversions ; We do this because we will never require more than floor ( n / 2 ) operations ; left pointer in the array ; right pointer in the array ; Doing k operations ; Incrementing ans by number of inversions increase due to this swapping ; Driver code ; Input 1 ; Input 2 | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximum_inversion ( int n , int k ) { int answer = 0 ; k = min ( k , n / 2 ) ; int left = 1 ; int right = n ; while ( k -- ) { answer += 2 * ( right - left ) - 1 ; left ++ ; right -- ; } cout << answer << endl ; } int main ( ) { int N = 5 ; int K = 3 ; maximum_inversion ( N , K ) ; N = 4 ; K = 1 ; maximum_inversion ( N , K ) ; return 0 ; } |
First number to leave an odd remainder after repetitive division by 2 | C ++ Program to implement the above approach ; Function to return the position least significant set bit ; Function return the first number to be converted to an odd integer ; Stores the positions of the first set bit ; If both are same ; If A has the least significant set bit ; Otherwise ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getFirstSetBitPos ( int n ) { return log2 ( n & - n ) + 1 ; } int oddFirst ( int a , int b ) { int steps_a = getFirstSetBitPos ( a ) ; int steps_b = getFirstSetBitPos ( b ) ; if ( steps_a == steps_b ) { return -1 ; } if ( steps_a > steps_b ) { return b ; } if ( steps_a < steps_b ) { return a ; } } int main ( ) { int a = 10 ; int b = 8 ; cout << oddFirst ( a , b ) ; } |
Check if a string can be split into substrings starting with N followed by N characters | C ++ Program to implement the above approach ; Function to check if the given can be split into desired substrings ; Length of the string ; Traverse the string ; Extract the digit ; Check if the extracted number does not exceed the remaining length ; Check for the remaining string ; If generating desired substrings is not possible ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool helper ( string & s , int pos ) { int len = s . size ( ) ; if ( pos >= len ) return true ; if ( ! isdigit ( s [ pos ] ) ) return false ; int num = 0 ; for ( int i = pos ; i < len ; i ++ ) { num = num * 10 + s [ pos ] - '0' ; if ( i + 1 + num > len ) return false ; if ( helper ( s , i + 1 + num ) ) return true ; } return false ; } int main ( ) { string s = "123abc4db1c " ; if ( helper ( s , 0 ) ) cout << " Yes " ; else cout << " No " ; } |
Represent K as sum of N | C ++ program for the above problem ; array to store the N - Bonacci series ; Function to express K as sum of several N_bonacci numbers ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long N_bonacci [ 100 ] ; void N_bonacci_nums ( int n , int k ) { N_bonacci [ 0 ] = 1 ; for ( int i = 1 ; i <= 50 ; ++ i ) { for ( int j = i - 1 ; j >= i - k and j >= 0 ; -- j ) N_bonacci [ i ] += N_bonacci [ j ] ; } vector < long long > ans ; for ( int i = 50 ; i >= 0 ; -- i ) if ( n - N_bonacci [ i ] >= 0 ) { ans . push_back ( N_bonacci [ i ] ) ; n -= N_bonacci [ i ] ; } if ( ans . size ( ) == 1 ) ans . push_back ( 0 ) ; cout << ans . size ( ) << endl ; for ( int i = 0 ; i < ans . size ( ) ; ++ i ) cout << ans [ i ] << " , β " ; } int main ( ) { int n = 21 , k = 5 ; N_bonacci_nums ( n , k ) ; return 0 ; } |
Divide N into K parts in the form ( X , 2 X , ... , KX ) for some value of X | C ++ program for the above approach ; Function to find the division ; Calculating value of x1 ; Print - 1 if division is not possible ; Get the first number ie x1 then successively multiply it by x1 k times by index number to get the required answer ; Driver Code ; Given N and K ; Function Call | #include <iostream> NEW_LINE using namespace std ; typedef long long int ll ; void solve ( int n , int k ) { int x1 , d ; d = k * ( k + 1 ) ; if ( ( 2 * n ) % d != 0 ) { cout << " - 1" ; return ; } x1 = 2 * n / d ; for ( int i = 1 ; i <= k ; i ++ ) { cout << x1 * i << " β " ; } cout << endl ; } int main ( ) { int n = 10 , k = 4 ; solve ( n , k ) ; } |
Bitonic string | C ++ program for the above approach ; Function to check if the given string is bitonic ; Check for increasing sequence ; If end of string has been reached ; Check for decreasing sequence ; If the end of string hasn 't been reached ; Return true if bitonic ; Driver Code ; Given string ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int checkBitonic ( string s ) { int i , j ; for ( i = 1 ; i < s . size ( ) ; i ++ ) { if ( s [ i ] > s [ i - 1 ] ) continue ; if ( s [ i ] <= s [ i - 1 ] ) break ; } if ( i == s . size ( ) - 1 ) return 1 ; for ( j = i + 1 ; j < s . size ( ) ; j ++ ) { if ( s [ j ] < s [ j - 1 ] ) continue ; if ( s [ j ] >= s [ j - 1 ] ) break ; } i = j ; if ( i != s . size ( ) ) return 0 ; return 1 ; } int main ( ) { string s = " abcdfgcba " ; ( checkBitonic ( s ) == 1 ) ? cout << " YES " : cout << " NO " ; return 0 ; } |
Find pair with maximum GCD for integers in range 2 to N | C ++ Program to find a pair of integers less than or equal to N such that their GCD is maximum ; Function to find the required pair whose GCD is maximum ; If N is even ; If N is odd ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( int N ) { if ( N % 2 == 0 ) { cout << N / 2 << " β " << N << endl ; } else { cout << ( N - 1 ) / 2 << " β " << ( N - 1 ) << endl ; } } int main ( ) { int N = 10 ; solve ( N ) ; return 0 ; } |
Find initial sequence that produces a given Array by cyclic increments upto index P | C ++ program to implement the above approach ; Function to generate and return the required initial arrangement ; Store the minimum element in the array ; Store the number of increments ; Subtract mi - 1 from every index ; Start from the last index which had been incremented ; Stores the index chosen to distribute its element ; Traverse the array cyclically and find the index whose element was distributed ; If any index has its value reduced to 0 ; Index whose element was distributed ; Store the number of increments at the starting index ; Print the original array ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findArray ( int * a , int n , int P ) { int mi = * min_element ( a , a + n ) ; int ctr = 0 ; mi = max ( 0 , mi - 1 ) ; for ( int i = 0 ; i < n ; i ++ ) { a [ i ] -= mi ; ctr += mi ; } int i = P - 1 ; int start = -1 ; while ( 1 ) { if ( a [ i ] == 0 ) { start = i ; break ; } a [ i ] -= 1 ; ctr += 1 ; i = ( i - 1 + n ) % n ; } a [ start ] = ctr ; for ( int i = 0 ; i < n ; i ++ ) { cout << a [ i ] << " , β " ; } } int main ( ) { int N = 5 ; int P = 2 ; int arr [ ] = { 3 , 2 , 0 , 2 , 7 } ; findArray ( arr , N , P ) ; return 0 ; } |
Generate a unique Array of length N with sum of all subarrays divisible by N | C ++ implementation of the above approach ; Function to print the required array ; Print the array ; Driver Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void makeArray ( int a [ ] , int n ) { for ( int i = 1 ; i <= n ; i ++ ) cout << i * n << " β " ; } int main ( ) { int N = 6 ; int arr [ N ] ; makeArray ( arr , N ) ; } |
Find elements in a given range having at least one odd divisor | C ++ program to print all numbers with least one odd factor in the given range ; Function to prints all numbers with at least one odd divisor ; Check if the number is not a power of two ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int printOddFactorNumber ( int n , int m ) { for ( int i = n ; i <= m ; i ++ ) { if ( ( i > 0 ) && ( ( i & ( i - 1 ) ) != 0 ) ) cout << i << " β " ; } } int main ( ) { int N = 2 , M = 10 ; printOddFactorNumber ( N , M ) ; return 0 ; } |
Print the first N terms of the series 6 , 28 , 66 , 120 , 190 , 276 , ... | C ++ program for the above approach ; Function to print the series ; Initialise the value of k with 2 ; Iterate from 1 to n ; Print each number ; Increment the value of K by 2 for next number ; Driver Code ; Given number N ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printSeries ( int n ) { int k = 2 ; for ( int i = 0 ; i < n ; i ++ ) { cout << ( k * ( 2 * k - 1 ) ) << " β " ; k += 2 ; } cout << endl ; } int main ( ) { int N = 12 ; printSeries ( N ) ; return 0 ; } |
Find a string which matches all the patterns in the given array | C ++ implementation to find the string which matches all the patterns ; Function to find a common string which matches all the pattern ; For storing prefix till first most * without conflicts ; For storing suffix till last most * without conflicts ; For storing all middle characters between first and last * ; Loop to iterate over every pattern of the array ; Index of the first " * " ; Index of Last " * " ; Iterate over the first " * " ; Prefix till first most * without conflicts ; Iterate till last most * from last ; Make suffix till last most * without conflicts ; Take all middle characters in between first and last most * ; Driver Code ; Take all the strings ; Method for finding common string | #include <bits/stdc++.h> NEW_LINE using namespace std ; string find ( vector < string > S , int N ) { string pref ; string suff ; string mid ; for ( int i = 0 ; i < N ; i ++ ) { int first = int ( S [ i ] . find_first_of ( ' * ' ) ) ; int last = int ( S [ i ] . find_last_of ( ' * ' ) ) ; for ( int z = 0 ; z < int ( pref . size ( ) ) && z < first ; z ++ ) { if ( pref [ z ] != S [ i ] [ z ] ) { return " * " ; } } for ( int z = int ( pref . size ( ) ) ; z < first ; z ++ ) { pref += S [ i ] [ z ] ; } for ( int z = 0 ; z < int ( suff . size ( ) ) && int ( S [ i ] . size ( ) ) - 1 - z > last ; z ++ ) { if ( suff [ z ] != S [ i ] [ int ( S [ i ] . size ( ) ) - 1 - z ] ) { return " * " ; } } for ( int z = int ( suff . size ( ) ) ; int ( S [ i ] . size ( ) ) - 1 - z > last ; z ++ ) { suff += S [ i ] [ int ( S [ i ] . size ( ) ) - 1 - z ] ; } for ( int z = first ; z <= last ; z ++ ) { if ( S [ i ] [ z ] != ' * ' ) mid += S [ i ] [ z ] ; } } reverse ( suff . begin ( ) , suff . end ( ) ) ; return pref + mid + suff ; } int main ( ) { int N = 3 ; vector < string > s ( N ) ; s [ 0 ] = " pq * du * q " ; s [ 1 ] = " pq * abc * q " ; s [ 2 ] = " p * d * q " ; cout << find ( s , N ) ; return 0 ; } |
Mountain Sequence Pattern | C ++ program for the above approach ; Function to print pattern recursively ; Base Case ; Condition to check row limit ; Condition for assigning gaps ; Conditions to print * ; Else print ' β ' ; Recursive call for columns ; Recursive call for rows ; Driver Code ; Given Number N ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int k1 = 2 ; int k2 = 2 ; int gap = 5 ; int printPattern ( int i , int j , int n ) { if ( j >= n ) { k1 = 2 ; k2 = 2 ; k1 -- ; k2 ++ ; if ( i == 2 ) { k1 = 0 ; k2 = n - 1 ; } return 0 ; } if ( i >= 3 ) { return 1 ; } if ( j > k2 ) { k1 += gap ; k2 += gap ; } if ( j >= k1 && j <= k2 i == 2 ) { cout << " * " ; } else { cout << " β " ; } if ( printPattern ( i , j + 1 , n ) == 1 ) { return 1 ; } cout << endl ; return printPattern ( i + 1 , 0 , n ) ; } int main ( ) { int N = 3 ; printPattern ( 0 , 0 , N * 5 ) ; return 0 ; } |
Build a DFA to accept Binary strings that starts or ends with "01" | C ++ program to check if a string either starts or ends with 01 ; Function for transition state A ; State transition to B if the character is 0 ; State transition to D if the character is 1 ; Function for transition state B ; Check if the string has ended ; State transition to C if the character is 1 ; State transition to D if the character is 0 ; Function for transition state C ; Function for transition state D ; State transition to D if the character is 1 ; State transition to E if the character is 0 ; Function for transition state E ; State transition to E if the character is 0 ; State transition to F if the character is 1 ; Function for transition state F ; State transition to D if the character is 1 ; State transition to E if the character is 0 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void stateA ( string ) ; void stateB ( string ) ; void stateC ( string ) ; void stateD ( string ) ; void stateE ( string ) ; void stateF ( string ) ; void checkstateA ( string n ) { if ( n [ 0 ] == '0' ) stateB ( n . substr ( 1 ) ) ; else stateD ( n . substr ( 1 ) ) ; } void stateB ( string n ) { if ( n . length ( ) == 0 ) cout << " string β not β accepted " ; else { if ( n [ 0 ] == '1' ) stateC ( n . substr ( 1 ) ) ; else stateD ( n . substr ( 1 ) ) ; } } void stateC ( string n ) { cout << " String β accepted " ; } void stateD ( string n ) { if ( n . length ( ) == 0 ) cout << " string β not β accepted " ; else { if ( n [ 0 ] == '1' ) stateD ( n . substr ( 1 ) ) ; else stateE ( n . substr ( 1 ) ) ; } } void stateE ( string n ) { if ( n . length ( ) == 0 ) cout << " string β not β accepted " ; else { if ( n [ 0 ] == '0' ) stateE ( n . substr ( 1 ) ) ; else stateF ( n . substr ( 1 ) ) ; } } void stateF ( string n ) { if ( n . length ( ) == 0 ) cout << " string β accepred " ; else { if ( n [ 0 ] == '1' ) stateD ( n . substr ( 1 ) ) ; else stateE ( n . substr ( 1 ) ) ; } } int main ( ) { string n = "0100101" ; checkstateA ( n ) ; return 0 ; } |
Find the Nth Hogben Numbers | C ++ program to print N - th Hogben Number ; Function returns N - th Hogben Number ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int HogbenNumber ( int a ) { int p = ( pow ( a , 2 ) - a + 1 ) ; return p ; } int main ( ) { int N = 10 ; cout << HogbenNumber ( N ) ; return 0 ; } |
Check if left and right shift of any string results into given string | C ++ program to check if left and right shift of any string results into the given string ; Function to check string exist or not as per above approach ; Check if any character at position i and i + 2 are not equal then string doesnot exist ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void check_string_exist ( string S ) { int size = S . length ( ) ; bool check = true ; for ( int i = 0 ; i < size ; i ++ ) { if ( S [ i ] != S [ ( i + 2 ) % size ] ) { check = false ; break ; } } if ( check ) cout << " Yes " << endl ; else cout << " No " << endl ; } int main ( ) { string S = " papa " ; check_string_exist ( S ) ; return 0 ; } |
Cumulative product of digits of all numbers in the given range | C ++ program to print the product of all numbers in range L and R ; Function to get product of digits ; Function to find the product of digits of all natural numbers in range L to R ; Iterate between L to R ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getProduct ( int n ) { int product = 1 ; while ( n != 0 ) { product = product * ( n % 10 ) ; n = n / 10 ; } return product ; } int productinRange ( int l , int r ) { if ( r - l > 9 ) return 0 ; else { int p = 1 ; for ( int i = l ; i <= r ; i ++ ) p *= getProduct ( i ) ; return p ; } } int main ( ) { int l = 11 , r = 15 ; cout << productinRange ( l , r ) << endl ; l = 1 , r = 15 ; cout << productinRange ( l , r ) ; return 0 ; } |
Check whether the string can be printed using same row of qwerty keypad | C ++ Program to check whether the string can be printed using same row of qwerty keypad ; Function to find the row of the character in the qwerty keypad ; Sets to include the characters from the same row of the qwerty keypad ; Condition to check the row of the current character of the string ; Function to check the characters are from the same row of the qwerty keypad ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int checkQwertyRow ( char x ) { set < char > first_row = { '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , '0' , ' - ' , ' = ' } ; set < char > second_row = { ' Q ' , ' W ' , ' E ' , ' R ' , ' T ' , ' Y ' , ' U ' , ' I ' , ' O ' , ' P ' , ' [ ' , ' ] ' , ' q ' , ' w ' , ' e ' , ' r ' , ' t ' , ' y ' , ' u ' , ' i ' , ' o ' , ' p ' } ; set < char > third_row = { ' A ' , ' S ' , ' D ' , ' F ' , ' G ' , ' H ' , ' J ' , ' K ' , ' L ' , ' ; ' , ' : ' , ' a ' , ' s ' , ' d ' , ' f ' , ' g ' , ' h ' , ' j ' , ' k ' , ' l ' } ; set < char > fourth_row = { ' Z ' , ' X ' , ' C ' , ' V ' , ' B ' , ' N ' , ' M ' , ' , ' , ' . ' , ' / ' , ' z ' , ' x ' , ' c ' , ' v ' , ' b ' , ' n ' , ' m ' } ; if ( first_row . count ( x ) > 0 ) { return 1 ; } else if ( second_row . count ( x ) > 0 ) { return 2 ; } else if ( third_row . count ( x ) > 0 ) { return 3 ; } else if ( fourth_row . count ( x ) > 0 ) { return 4 ; } return 0 ; } bool checkValidity ( string str ) { char x = str [ 0 ] ; int row = checkQwertyRow ( x ) ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { x = str [ i ] ; if ( row != checkQwertyRow ( x ) ) { return false ; } } return true ; } int main ( ) { string str = " GeeksforGeeks " ; if ( checkValidity ( str ) ) cout << " Yes " ; else cout << " No " ; return ( 0 ) ; } |
Last digit of sum of numbers in the given range in the Fibonacci series | C ++ program to calculate last digit of the sum of the fibonacci numbers from M to N ; Calculate the sum of the first N Fibonacci numbers using Pisano period ; The first two Fibonacci numbers ; Base case ; Pisano period for % 10 is 60 ; Checking the remainder ; The loop will range from 2 to two terms after the remainder ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long fib ( long long n ) { long long f0 = 0 ; long long f1 = 1 ; if ( n == 0 ) return 0 ; if ( n == 1 ) return 1 ; else { long long rem = n % 60 ; if ( rem == 0 ) return 0 ; for ( long long i = 2 ; i < rem + 3 ; i ++ ) { long long f = ( f0 + f1 ) % 60 ; f0 = f1 ; f1 = f ; } long long s = f1 - 1 ; return s ; } } int main ( ) { long long m = 10087887 ; long long n = 2983097899 ; long long final = abs ( fib ( n ) - fib ( m - 1 ) ) ; cout << final % 10 << endl ; } |
Find N values of X1 , X2 , ... Xn such that X1 < X2 < ... < XN and sin ( X1 ) < sin ( X2 ) < ... < sin ( XN ) | C ++ program for the above approach ; Function to print all such Xi s . t . all Xi and sin ( Xi ) are strictly increasing ; Till N becomes zero ; Find the value of sin ( ) using inbuilt function ; increment by 710 ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printSinX ( int N ) { int Xi = 0 ; int num = 1 ; while ( N -- ) { cout << " X " << num << " β = β " << Xi ; cout << " β sin ( X " << num << " ) β = β " << fixed ; cout << setprecision ( 6 ) << sin ( Xi ) << endl ; num += 1 ; Xi += 710 ; } } int main ( ) { int N = 5 ; printSinX ( N ) ; return 0 ; } |
Sum of all elements in an array between zeros | C ++ program for the above approach ; Function to find the sum between two zeros in the given array arr [ ] ; To store the sum of element between two zeros ; To store the sum ; Find first index of 0 ; Traverse the given array arr [ ] ; If 0 occurs then add it to A [ ] ; Else add element to the sum ; Print all the sum stored in A ; If there is no such element print - 1 ; Driver Code ; Function call | #include " bits / stdc + + . h " NEW_LINE using namespace std ; void sumBetweenZero ( int arr [ ] , int N ) { int i = 0 ; vector < int > A ; int sum = 0 ; for ( i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == 0 ) { i ++ ; break ; } } for ( ; i < N ; i ++ ) { if ( arr [ i ] == 0 ) { A . push_back ( sum ) ; sum = 0 ; } else { sum += arr [ i ] ; } } for ( int i = 0 ; i < A . size ( ) ; i ++ ) { cout << A [ i ] << ' β ' ; } if ( A . size ( ) == 0 ) cout << " - 1" ; } int main ( ) { int arr [ ] = { 1 , 0 , 3 , 4 , 0 , 4 , 4 , 0 , 2 , 1 , 4 , 0 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sumBetweenZero ( arr , N ) ; return 0 ; } |
Find the Nth term of the series 2 , 15 , 41 , 80 , 132. . . | C ++ program for the above approach ; Recursive function to find Nth term ; Base Case ; Recursive Call according to Nth term of the series ; Driver Code ; Input Nth term ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int nthTerm ( int N ) { if ( N == 1 ) { return 2 ; } return ( ( N - 1 ) * 13 ) + nthTerm ( N - 1 ) ; } int main ( ) { int N = 17 ; cout << nthTerm ( N ) << endl ; return 0 ; } |
Subsequence pair from given Array having all unique and all same elements respectively | C ++ program for the above approach ; Function to find the maximum length of subsequences with given property ; To store the frequency ; Traverse the array to store the frequency ; M . size ( ) given count of distinct element in arr [ ] ; Traverse map to find max frequency ; Find the maximum length on the basis of two cases in the approach ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumSubsequence ( int arr [ ] , int N ) { unordered_map < int , int > M ; for ( int i = 0 ; i < N ; i ++ ) { M [ arr [ i ] ] ++ ; } int distinct_size = M . size ( ) ; int maxFreq = 1 ; for ( auto & it : M ) { maxFreq = max ( maxFreq , it . second ) ; } cout << max ( min ( distinct_size , maxFreq - 1 ) , min ( distinct_size - 1 , maxFreq ) ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 4 , 4 , 4 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maximumSubsequence ( arr , N ) ; return 0 ; } |
Total length of string from given Array of strings composed using given characters | C ++ implementation to find total length of string composed of given characters formed from given Array of strings ; Function to count the total length ; Unordered_map for keeping frequency of characters ; Calculate the frequency ; Iterate in the N strings ; Iterates in the string ; Checks if given character of string string appears in it or not ; Adds the length of string if all characters are present ; Return the final result ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countCharacters ( vector < string > & strings , string chars ) { int res = 0 ; unordered_map < char , int > freq ; for ( int i = 0 ; i < chars . length ( ) ; i ++ ) freq [ chars [ i ] ] += 1 ; for ( auto st : strings ) { bool flag = true ; for ( auto c : st ) { if ( ! freq ) { flag = false ; break ; } } if ( flag ) res += st . length ( ) ; } return res ; } int main ( ) { vector < string > strings = { " hi " , " data " , " geeksforgeeks " } ; string chars = " tiadhae " ; cout << countCharacters ( strings , chars ) ; return 0 ; } |
Construct an Array of size N in which sum of odd elements is equal to sum of even elements | C ++ program to Create an array of size N consisting of distinct elements where sum of odd elements is equal to sum of even elements ; Function to construct the required array ; To construct first half , distinct even numbers ; To construct second half , distinct odd numbers ; Calculate the last number of second half so as to make both the halves equal ; Function to construct the required array ; check if size is multiple of 4 then array exist ; function call to construct array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void arrayConstruct ( int N ) { for ( int i = 2 ; i <= N ; i = i + 2 ) cout << i << " β " ; for ( int i = 1 ; i < N - 1 ; i = i + 2 ) cout << i << " β " ; cout << N - 1 + ( N / 2 ) << endl ; } void createArray ( int N ) { if ( N % 4 == 0 ) arrayConstruct ( N ) ; else cout << -1 << endl ; } int main ( ) { int N = 8 ; createArray ( N ) ; return 0 ; } |
Count of all sub | C ++ implementation to Count all sub - strings with sum of weights at most K ; Function to count all substrings ; Hashmap to store substrings ; iterate over all substrings ; variable to maintain sum of all characters encountered ; variable to maintain substring till current position ; get position of character in string W ; add weight to current sum ; add current character to substring ; check if sum of characters is <= K insert in Hashmap ; Driver code ; initialise string ; initialise weight | #include <bits/stdc++.h> NEW_LINE using namespace std ; int distinctSubstring ( string & P , string & Q , int K , int N ) { unordered_set < string > S ; for ( int i = 0 ; i < N ; ++ i ) { int sum = 0 ; string s ; for ( int j = i ; j < N ; ++ j ) { int pos = P [ j ] - ' a ' ; sum += Q [ pos ] - '0' ; s += P [ j ] ; if ( sum <= K ) { S . insert ( s ) ; } else { break ; } } } return S . size ( ) ; } int main ( ) { string S = " abcde " ; string W = "12345678912345678912345678" ; int K = 5 ; int N = S . length ( ) ; cout << distinctSubstring ( S , W , K , N ) ; return 0 ; } |
Count all sub | C ++ program to find the count of all the sub - strings with weight of characters atmost K ; Function to find the count of all the substrings with weight of characters atmost K ; Hashmap to store all substrings ; Iterate over all substrings ; Maintain the sum of all characters encountered so far ; Maintain the substring till the current position ; Get the position of the character in string Q ; Add weight to current sum ; Add current character to substring ; If sum of characters is <= K then insert in into the set ; Finding the size of the set ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int distinctSubstring ( string & P , string & Q , int K , int N ) { unordered_set < string > S ; for ( int i = 0 ; i < N ; ++ i ) { int sum = 0 ; string s ; for ( int j = i ; j < N ; ++ j ) { int pos = P [ j ] - ' a ' ; sum += Q [ pos ] - '0' ; s += P [ j ] ; if ( sum <= K ) { S . insert ( s ) ; } else { break ; } } } return S . size ( ) ; } int main ( ) { string P = " abcde " ; string Q = "12345678912345678912345678" ; int K = 5 ; int N = P . length ( ) ; cout << distinctSubstring ( P , Q , K , N ) ; return 0 ; } |
Program to print a Hollow Triangle inside a Triangle | C ++ implementation of the above approach ; Function to print the pattern ; Loop for rows ; Loop for column ; For printing equal sides of outer triangle ; For printing equal sides of inner triangle ; For printing base of both triangle ; For spacing between the triangle ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printPattern ( int n ) { int i , j ; for ( i = 1 ; i <= n ; i ++ ) { for ( j = 1 ; j < 2 * n ; j ++ ) { if ( j == ( n - i + 1 ) || j == ( n + i - 1 ) ) { cout << " * β " ; } else if ( ( i >= 4 && i <= n - 4 ) && ( j == n - i + 4 j == n + i - 4 ) ) { cout << " * β " ; } else if ( i == n || ( i == n - 4 && j >= n - ( n - 2 * 4 ) && j <= n + n - 2 * 4 ) ) { cout << " * β " ; } else { cout << " β " << " β " ; } } cout << " STRNEWLINE " ; } } int main ( ) { int N = 9 ; printPattern ( N ) ; } |
Check if a string is made up of K alternating characters | C ++ implementation of the approach ; Function to check if a string is made up of k alternating characters ; Check if all the characters at indices 0 to K - 1 are different ; If that bit is already set in checker , return false ; Otherwise update and continue by setting that bit in the checker ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isKAlternating ( string s , int k ) { if ( s . length ( ) < k ) return false ; int checker = 0 ; for ( int i = 0 ; i < k ; i ++ ) { int bitAtIndex = s [ i ] - ' a ' ; if ( ( checker & ( 1 << bitAtIndex ) ) > 0 ) { return false ; } checker = checker | ( 1 << bitAtIndex ) ; } for ( int i = k ; i < s . length ( ) ; i ++ ) if ( s [ i - k ] != s [ i ] ) return false ; return true ; } int main ( ) { string str = " acdeac " ; int K = 4 ; if ( isKAlternating ( str , K ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; } |
Find all Factors of Large Perfect Square Natural Number in O ( sqrt ( sqrt ( N ) ) | C ++ program to find the factors of large perfect square number in O ( sqrt ( sqrt ( N ) ) ) time ; Function that find all the prime factors of N ; Store the sqrt ( N ) in temp ; Initialise factor array with 1 as a factor in it ; Check divisibility by 2 ; Store the factors twice ; Check for other prime factors other than 2 ; If j is a prime factor ; Store the prime factor twice ; If j is prime number left other than 2 ; Store j twice ; Initialise Matrix M to to store all the factors ; tpc for rows tpr for column ; Initialise M [ 0 ] [ 0 ] = 1 as it also factor of N ; Traversing factor array ; If current and previous factors are not same then move to next row and insert the current factor ; If current and previous factors are same then , Insert the factor with previous factor inserted in matrix M ; The arr1 [ ] and arr2 [ ] used to store all the factors of N ; Initialise arrays as 1 ; Traversing the matrix M ; Traversing till column element doesn 't become 0 ; Store the product of every element of current row with every element in arr1 [ ] ; Copying every element of arr2 [ ] in arr1 [ ] ; length of arr2 [ ] and arr1 [ ] are equal after copying ; Print all the factors ; Drivers Code | #include " bits / stdc + + . h " NEW_LINE using namespace std ; int MAX = 100000 ; void findFactors ( int N ) { int temp = sqrt ( N ) ; int factor [ MAX ] = { 1 } ; int i , j , k ; int len1 = 1 ; while ( temp % 2 == 0 ) { factor [ len1 ++ ] = 2 ; factor [ len1 ++ ] = 2 ; temp /= 2 ; } for ( j = 3 ; j < sqrt ( temp ) ; j += 2 ) { while ( temp % j == 0 ) { factor [ len1 ++ ] = j ; factor [ len1 ++ ] = j ; temp /= j ; } } if ( temp > 2 ) { factor [ len1 ++ ] = temp ; factor [ len1 ++ ] = temp ; } int M [ len1 ] [ MAX ] = { 0 } ; int tpc = 0 , tpr = 0 ; M [ 0 ] [ 0 ] = 1 ; j = 1 ; while ( j < len1 ) { if ( factor [ j ] != factor [ j - 1 ] ) { tpr ++ ; M [ tpr ] [ 0 ] = factor [ j ] ; j ++ ; tpc = 1 ; } else { M [ tpr ] [ tpc ] = M [ tpr ] [ tpc - 1 ] * factor [ j ] ; j ++ ; tpc ++ ; } } int arr1 [ MAX ] , arr2 [ MAX ] ; int l1 , l2 ; l1 = l2 = 1 ; arr1 [ 0 ] = arr2 [ 0 ] = 1 ; for ( i = 1 ; i < tpr + 1 ; i ++ ) { for ( j = 0 ; M [ i ] [ j ] != 0 ; j ++ ) { for ( k = 0 ; k < l1 ; k ++ ) { arr2 [ l2 ++ ] = arr1 [ k ] * M [ i ] [ j ] ; } } for ( j = l1 ; j < l2 ; j ++ ) { arr1 [ j ] = arr2 [ j ] ; } l1 = l2 ; } for ( i = 0 ; i < l2 ; i ++ ) { cout << arr2 [ i ] << ' β ' ; } } int main ( ) { int N = 900 ; findFactors ( N ) ; return 0 ; } |
Construct a matrix such that union of ith row and ith column contains every element from 1 to 2 N | C ++ implementation of the above approach ; Function to find the square matrix ; For Matrix of order 1 , it will contain only 1 ; For Matrix of odd order , it is not possible ; For Matrix of even order ; All diagonal elements of the matrix can be N itself . ; Assign values at desired place in the matrix ; Loop to add N in the lower half of the matrix such that it contains elements from 1 to 2 * N - 1 ; Loop to print the matrix ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int matrix [ 100 ] [ 100 ] ; void printRequiredMatrix ( int n ) { if ( n == 1 ) { cout << "1" << " STRNEWLINE " ; } else if ( n % 2 != 0 ) { cout << " - 1" << " STRNEWLINE " ; } else { for ( int i = 0 ; i < n ; i ++ ) { matrix [ i ] [ i ] = n ; } int u = n - 1 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { matrix [ i ] [ u ] = i + 1 ; for ( int j = 1 ; j < n / 2 ; j ++ ) { int a = ( i + j ) % ( n - 1 ) ; int b = ( i - j + n - 1 ) % ( n - 1 ) ; if ( a < b ) swap ( a , b ) ; matrix [ b ] [ a ] = i + 1 ; } } for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < i ; j ++ ) matrix [ i ] [ j ] = matrix [ j ] [ i ] + n ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) cout << matrix [ i ] [ j ] << " β " ; cout << " STRNEWLINE " ; } } cout << " STRNEWLINE " ; } int main ( ) { int n = 1 ; printRequiredMatrix ( n ) ; n = 3 ; printRequiredMatrix ( n ) ; n = 6 ; printRequiredMatrix ( n ) ; return 0 ; } |
Count of sub | C ++ implementation of the above approach ; Function to find the count of substrings with equal no . of consecutive 0 ' s β and β 1' s ; To store the total count of substrings ; Traversing the string ; Count of consecutive 0 ' s β & β 1' s ; Counting subarrays of type "01" ; Count the consecutive 0 's ; If consecutive 0 ' s β β ends β then β check β for β β consecutive β 1' s ; Counting consecutive 1 's ; Counting subarrays of type "10" ; Count consecutive 1 's ; If consecutive 1 ' s β β ends β then β check β for β β consecutive β 0' s ; Count consecutive 0 's ; Update the total count of substrings with minimum of ( cnt0 , cnt1 ) ; Return answer ; Driver code ; Function to print the count of substrings | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubstring ( string & S , int & n ) { int ans = 0 ; int i = 0 ; while ( i < n ) { int cnt0 = 0 , cnt1 = 0 ; if ( S [ i ] == '0' ) { while ( i < n && S [ i ] == '0' ) { cnt0 ++ ; i ++ ; } int j = i ; while ( j < n && S [ j ] == '1' ) { cnt1 ++ ; j ++ ; } } else { while ( i < n && S [ i ] == '1' ) { cnt1 ++ ; i ++ ; } int j = i ; while ( j < n && S [ j ] == '0' ) { cnt0 ++ ; j ++ ; } } ans += min ( cnt0 , cnt1 ) ; } return ans ; } int main ( ) { string S = "0001110010" ; int n = S . length ( ) ; cout << countSubstring ( S , n ) ; return 0 ; } |
Print N numbers such that their sum is a Perfect Cube | C ++ implementation to find the N numbers such that their sum is a perfect cube ; Function to find the N numbers such that their sum is a perfect cube ; Loop to find the Ith term of the Centered Hexagonal number ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findNumbers ( int n ) { int i = 1 ; while ( i <= n ) { cout << ( 3 * i * ( i - 1 ) + 1 ) << " β " ; i ++ ; } } int main ( ) { int n = 4 ; findNumbers ( n ) ; } |
Largest N digit Octal number which is a Perfect square | C ++ implementation to find the maximum N - digit octal number which is perfect square ; Function to convert decimal number to a octal number ; Array to store octal number ; Counter for octal number array ; Store remainder in octal array ; Print octal number array in reverse order ; Largest n - digit perfect square ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void decToOctal ( int n ) { int octalNum [ 100 ] ; int i = 0 ; while ( n != 0 ) { octalNum [ i ] = n % 8 ; n = n / 8 ; i ++ ; } for ( int j = i - 1 ; j >= 0 ; j -- ) cout << octalNum [ j ] ; cout << " STRNEWLINE " ; } void nDigitPerfectSquares ( int n ) { int decimal = pow ( ceil ( sqrt ( pow ( 8 , n ) ) ) - 1 , 2 ) ; decToOctal ( decimal ) ; } int main ( ) { int n = 2 ; nDigitPerfectSquares ( n ) ; return 0 ; } |
Reverse the substrings of the given String according to the given Array of indices | C ++ implementation to reverse the substrings of the given String according to the given Array of indices ; Function to reverse a string ; Swap character starting from two corners ; Function to reverse the string with the given array of indices ; Reverse the string from 0 to A [ 0 ] ; Reverse the string for A [ i ] to A [ i + 1 ] ; Reverse String for A [ n - 1 ] to length ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void reverseStr ( string & str , int l , int h ) { int n = h - l ; for ( int i = 0 ; i < n / 2 ; i ++ ) { swap ( str [ i + l ] , str [ n - i - 1 + l ] ) ; } } void reverseString ( string & s , int A [ ] , int n ) { reverseStr ( s , 0 , A [ 0 ] ) ; for ( int i = 1 ; i < n ; i ++ ) reverseStr ( s , A [ i - 1 ] , A [ i ] ) ; reverseStr ( s , A [ n - 1 ] , s . length ( ) ) ; } int main ( ) { string s = " abcdefgh " ; int A [ ] = { 2 , 4 , 6 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; reverseString ( s , A , n ) ; cout << s ; return 0 ; } |
Check if the Depth of Parentheses is correct in the given String | Function to check if the Depth of Parentheses is correct in the given String ; Appending if the Character is not integer ; Iterating till the entire Digit is read ; Check if character is ' ( ' ; Increment depth by 1 ; Increment open by 1 ; Check if character is ' ) ' ; Decrement depth by 1 ; Increment close by 1 ; Check if open parentheses NOT equals close parentheses ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool Formatted ( string s ) { vector < char > k ; int i = 0 ; while ( i < s . size ( ) ) { if ( s [ i ] == ' ) ' or s [ i ] == ' ( ' ) { k . push_back ( s [ i ] ) ; i += 1 ; } else { char st ; while ( s [ i ] != ' ) ' and s [ i ] != ' ) ' ) { st = s [ i ] ; i = i + 1 ; } k . push_back ( st ) ; } } int depth = 0 , flag = 1 ; int open = 0 , close = 0 ; for ( char i : k ) { if ( i == ' ( ' ) { depth += 1 ; open += 1 ; } else if ( i == ' ) ' ) { depth -= 1 ; close += 1 ; } else { if ( i - '0' != depth ) { flag = 0 ; break ; } } } if ( open != close ) flag = 0 ; return ( flag == 1 ) ? true : false ; } int main ( ) { string s = " ( (2 ) ( (3 ) ) ) " ; bool k = Formatted ( s ) ; if ( k == true ) printf ( " Yes " ) ; else printf ( " No " ) ; return 0 ; } |
Maximize the sum of differences of consecutive elements after removing exactly K elements | C ++ implementation of the approach ; Function to return the maximized sum ; Remove any k internal elements ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findSum ( int * arr , int n , int k ) { if ( k <= n - 2 ) return ( arr [ n - 1 ] - arr [ 0 ] ) ; return 0 ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int k = 1 ; cout << findSum ( arr , n , k ) ; return 0 ; } |
Split the binary string into substrings with equal number of 0 s and 1 s | C ++ implementation of the approach ; Function to return the count of maximum substrings str can be divided into ; To store the count of 0 s and 1 s ; To store the count of maximum substrings str can be divided into ; It is not possible to split the string ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSubStr ( string str , int n ) { int count0 = 0 , count1 = 0 ; int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == '0' ) { count0 ++ ; } else { count1 ++ ; } if ( count0 == count1 ) { cnt ++ ; } } if ( cnt == 0 ) { return -1 ; } return cnt ; } int main ( ) { string str = "0100110101" ; int n = str . length ( ) ; cout << maxSubStr ( str , n ) ; return 0 ; } |
Sum of the digits of square of the given number which has only 1 's as its digits | C ++ implementation of the approach ; Function to return the sum of the digits of num ^ 2 ; To store the number of 1 's ; Find the sum of the digits of num ^ 2 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define lli long long int NEW_LINE lli squareDigitSum ( string s ) { lli lengthN = s . length ( ) ; lli result = ( lengthN / 9 ) * 81 + pow ( ( lengthN % 9 ) , 2 ) ; return result ; } int main ( ) { string s = "1111" ; cout << squareDigitSum ( s ) ; return 0 ; } |
Check whether two strings contain same characters in same order | C ++ implementation of the approach ; string class has a constructor that allows us to specify size of string as first parameter and character to be filled in given size as second parameter . ; Function that returns true if the given strings contain same characters in same order ; Get the first character of both strings ; Now if there are adjacent similar character remove that character from s1 ; Now if there are adjacent similar character remove that character from s2 ; If both the strings are equal then return true ; Driver code | #include <iostream> NEW_LINE using namespace std ; string getString ( char x ) { string s ( 1 , x ) ; return s ; } bool solve ( string s1 , string s2 ) { string a = getString ( s1 [ 0 ] ) , b = getString ( s2 [ 0 ] ) ; for ( int i = 1 ; i < s1 . length ( ) ; i ++ ) if ( s1 [ i ] != s1 [ i - 1 ] ) { a += getString ( s1 [ i ] ) ; } for ( int i = 1 ; i < s2 . length ( ) ; i ++ ) if ( s2 [ i ] != s2 [ i - 1 ] ) { b += getString ( s2 [ i ] ) ; } if ( a == b ) return true ; return false ; } int main ( ) { string s1 = " Geeks " , s2 = " Geks " ; if ( solve ( s1 , s2 ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Count number of distinct substrings of a given length | C ++ implementation of above approach ; Function to find the required count ; Variable to the hash ; Finding hash of substring ( 0 , l - 1 ) using random number x ; Computing x ^ ( l - 1 ) ; Unordered set to add hash values ; Generating all possible hash values ; Print the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE #define x 26 NEW_LINE #define mod 3001 NEW_LINE using namespace std ; int CntSubstr ( string s , int l ) { int hash = 0 ; for ( int i = 0 ; i < l ; i ++ ) { hash = ( hash * x + ( s [ i ] - 97 ) ) % mod ; } int pow_l = 1 ; for ( int i = 0 ; i < l - 1 ; i ++ ) pow_l = ( pow_l * x ) % mod ; unordered_set < int > result ; result . insert ( hash ) ; for ( int i = l ; i < s . size ( ) ; i ++ ) { hash = ( ( hash - pow_l * ( s [ i - l ] - 97 ) + 2 * mod ) * x + ( s [ i ] - 97 ) ) % mod ; result . insert ( hash ) ; } cout << result . size ( ) << endl ; } int main ( ) { string s = " abcba " ; int l = 2 ; CntSubstr ( s , l ) ; return 0 ; } |
Check if a binary string has two consecutive occurrences of one everywhere | C ++ implementation of the approach ; Function that returns 1 if str is valid ; Index of first appearance of ' b ' ; If str starts with ' b ' ; While ' b ' occurs in str ; If ' b ' doesn ' t β appear β after β an β ' a ' ; If ' b ' is not succeeded by another ' b ' ; If sub - string is of the type " abbb " ; If str ends with a single b ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isValidString ( string str , int n ) { int index = find ( str . begin ( ) , str . end ( ) , ' b ' ) - str . begin ( ) ; if ( index == 0 ) return false ; while ( index <= n - 1 ) { if ( str [ index - 1 ] != ' a ' ) return false ; if ( index + 1 < n && str [ index + 1 ] != ' b ' ) return false ; if ( index + 2 < n && str [ index + 2 ] == ' b ' ) return false ; if ( index == n - 1 ) return false ; index = find ( str . begin ( ) + index + 2 , str . end ( ) , ' b ' ) - str . begin ( ) ; } return true ; } int main ( ) { string str = " abbaaabbabba " ; int n = str . length ( ) ; isValidString ( str , n ) ? cout << " true " : cout << " false " ; return 0 ; } |
Count strings that end with the given pattern | C ++ implementation of the approach ; Function that return true if str ends with pat ; Pattern is larger in length than the string ; We match starting from the end while patLen is greater than or equal to 0. ; If at any index str doesn 't match with pattern ; If str ends with the given pattern ; Function to return the count of required strings ; If current string ends with the given pattern ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool endsWith ( string str , string pat ) { int patLen = pat . length ( ) ; int strLen = str . length ( ) ; if ( patLen > strLen ) return false ; patLen -- ; strLen -- ; while ( patLen >= 0 ) { if ( pat [ patLen ] != str [ strLen ] ) return false ; patLen -- ; strLen -- ; } return true ; } int countOfStrings ( string pat , int n , string sArr [ ] ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( endsWith ( sArr [ i ] , pat ) ) count ++ ; return count ; } int main ( ) { string pat = " ks " ; int n = 4 ; string sArr [ ] = { " geeks " , " geeksforgeeks " , " games " , " unit " } ; cout << countOfStrings ( pat , n , sArr ) ; return 0 ; } |
Length of the longest substring with consecutive characters | C ++ implementation of the approach ; Function to return the ending index for the largest valid sub - string starting from index i ; If the current character appears after the previous character according to the given circular alphabetical order ; Function to return the length of the longest sub - string of consecutive characters from str ; Valid sub - string exists from index i to end ; Update the length ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getEndingIndex ( string str , int n , int i ) { i ++ ; while ( i < n ) { char curr = str [ i ] ; char prev = str [ i - 1 ] ; if ( ( curr == ' a ' && prev == ' z ' ) || ( curr - prev == 1 ) ) i ++ ; else break ; } return i - 1 ; } int largestSubStr ( string str , int n ) { int len = 0 ; int i = 0 ; while ( i < n ) { int end = getEndingIndex ( str , n , i ) ; len = max ( end - i + 1 , len ) ; i = end + 1 ; } return len ; } int main ( ) { string str = " abcabcdefabc " ; int n = str . length ( ) ; cout << ( largestSubStr ( str , n ) ) ; } |
Sum of integers upto N with given unit digit ( Set 2 ) | C ++ implementation of the approach ; Function to return the required sum ; Decrement N ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE ll getSum ( ll n , int d ) { if ( n < d ) return 0 ; while ( n % 10 != d ) n -- ; ll k = n / 10 ; return ( k + 1 ) * d + ( k * 10 + 10 * k * k ) / 2 ; } int main ( ) { ll n = 30 ; int d = 3 ; cout << getSum ( n , d ) ; return 0 ; } |
Maximum possible time that can be formed from four digits | C ++ implementation of the approach ; Function to return the updated frequency map for the array passed as argument ; Function that returns true if the passed digit is present in the map after decrementing it 's frequency by 1 ; If map contains the digit ; Decrement the frequency of the digit by 1 ; True here indicates that the digit was found in the map ; Digit not found ; Function to return the maximum possible time_value in 24 - Hours format ; First digit of hours can be from the range [ 0 , 2 ] ; If no valid digit found ; If first digit of hours was chosen as 2 then the second digit of hours can be from the range [ 0 , 3 ] ; Else it can be from the range [ 0 , 9 ] ; Hours and minutes separator ; First digit of minutes can be from the range [ 0 , 5 ] ; Second digit of minutes can be from the range [ 0 , 9 ] ; Return the maximum possible time_value ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; map < int , int > getFrequencyMap ( int arr [ ] , int n ) { map < int , int > hashMap ; for ( int i = 0 ; i < n ; i ++ ) { hashMap [ arr [ i ] ] ++ ; } return hashMap ; } bool hasDigit ( map < int , int > * hashMap , int digit ) { if ( ( * hashMap ) [ digit ] ) { ( * hashMap ) [ digit ] -- ; return true ; } return false ; } string getMaxtime_value ( int arr [ ] , int n ) { map < int , int > hashMap = getFrequencyMap ( arr , n ) ; int i ; bool flag ; string time_value = " " ; flag = false ; for ( i = 2 ; i >= 0 ; i -- ) { if ( hasDigit ( & hashMap , i ) ) { flag = true ; time_value += ( char ) i + 48 ; break ; } } if ( ! flag ) return " - 1" ; flag = false ; if ( time_value [ 0 ] == '2' ) { for ( i = 3 ; i >= 0 ; i -- ) { if ( hasDigit ( & hashMap , i ) ) { flag = true ; time_value += ( char ) i + 48 ; break ; } } } else { for ( i = 9 ; i >= 0 ; i -- ) { if ( hasDigit ( & hashMap , i ) ) { flag = true ; time_value += ( char ) i + 48 ; break ; } } } if ( ! flag ) return " - 1" ; time_value += " : " ; flag = false ; for ( i = 5 ; i >= 0 ; i -- ) { if ( hasDigit ( & hashMap , i ) ) { flag = true ; time_value += ( char ) i + 48 ; break ; } } if ( ! flag ) return " - 1" ; flag = false ; for ( i = 9 ; i >= 0 ; i -- ) { if ( hasDigit ( & hashMap , i ) ) { flag = true ; time_value += ( char ) i + 48 ; break ; } } if ( ! flag ) return " - 1" ; return time_value ; } int main ( ) { int arr [ ] = { 0 , 0 , 0 , 9 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << ( getMaxtime_value ( arr , n ) ) ; return 0 ; } |
Most frequent word in first String which is not present in second String | CPP implementation of above approach ; Function to return frequent word from S1 that isn 't present in S2 ; create map of banned words ; find smallest and most frequent word ; check if word is not banned ; return answer ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; string smallestFreq ( string S1 , string S2 ) { map < string , int > banned ; for ( int i = 0 ; i < S2 . length ( ) ; ++ i ) { string s = " " ; while ( i < S2 . length ( ) && S2 [ i ] != ' β ' ) s += S2 [ i ++ ] ; banned [ s ] ++ ; } map < string , int > result ; string ans ; int freq = 0 ; for ( int i = 0 ; i < S1 . length ( ) ; ++ i ) { string s = " " ; while ( i < S1 . length ( ) && S1 [ i ] != ' β ' ) s += S1 [ i ++ ] ; if ( banned [ s ] == 0 ) { result [ s ] ++ ; if ( result [ s ] > freq || ( result [ s ] == freq && s < ans ) ) { ans = s ; freq = result [ s ] ; } } } return ans ; } int main ( ) { string S1 = " geeks β for β geeks β is β best β place β to β learn " ; string S2 = " bad β place " ; cout << smallestFreq ( S1 , S2 ) ; return 0 ; } |
Minimum characters to be replaced to remove the given substring | C ++ implementation of above approach ; function to calculate minimum characters to replace ; mismatch occurs ; if all characters matched , i . e , there is a substring of ' a ' which is same as string ' b ' ; increment i to index m - 1 such that minimum characters are replaced in ' a ' ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int replace ( string A , string B ) { int n = A . length ( ) , m = B . length ( ) ; int count = 0 , i , j ; for ( i = 0 ; i < n ; i ++ ) { for ( j = 0 ; j < m ; j ++ ) { if ( A [ i + j ] != B [ j ] ) break ; } if ( j == m ) { count ++ ; i += m - 1 ; } } return count ; } int main ( ) { string str1 = " aaaaaaaa " ; string str2 = " aaa " ; cout << replace ( str1 , str2 ) ; return 0 ; } |
Largest connected component on a grid | CPP program to print the largest connected component in a grid ; stores information about which cell are already visited in a particular BFS ; result stores the final result grid ; stores the count of cells in the largest connected component ; Function checks if a cell is valid i . e it is inside the grid and equal to the key ; BFS to find all cells in connection with key = input [ i ] [ j ] ; terminating case for BFS ; x_move and y_move arrays are the possible movements in x or y direction ; checks all four points connected with input [ i ] [ j ] ; called every time before a BFS so that visited array is reset to zero ; If a larger connected component is found this function is called to store information about that component . ; function to print the result ; prints the largest component ; function to calculate the largest connected component ; checking cell to the right ; updating result ; checking cell downwards ; updating result ; Drivers Code ; function to compute the largest connected component in the grid | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int n = 6 ; const int m = 8 ; int visited [ n ] [ m ] ; int result [ n ] [ m ] ; int COUNT ; bool is_valid ( int x , int y , int key , int input [ n ] [ m ] ) { if ( x < n && y < m && x >= 0 && y >= 0 ) { if ( visited [ x ] [ y ] == false && input [ x ] [ y ] == key ) return true ; else return false ; } else return false ; } void BFS ( int x , int y , int i , int j , int input [ n ] [ m ] ) { if ( x != y ) return ; visited [ i ] [ j ] = 1 ; COUNT ++ ; int x_move [ ] = { 0 , 0 , 1 , -1 } ; int y_move [ ] = { 1 , -1 , 0 , 0 } ; for ( int u = 0 ; u < 4 ; u ++ ) if ( is_valid ( i + y_move [ u ] , j + x_move [ u ] , x , input ) ) BFS ( x , y , i + y_move [ u ] , j + x_move [ u ] , input ) ; } void reset_visited ( ) { for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < m ; j ++ ) visited [ i ] [ j ] = 0 ; } void reset_result ( int key , int input [ n ] [ m ] ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( visited [ i ] [ j ] && input [ i ] [ j ] == key ) result [ i ] [ j ] = visited [ i ] [ j ] ; else result [ i ] [ j ] = 0 ; } } } void print_result ( int res ) { cout << " The β largest β connected β " << " component β of β the β grid β is β : " << res << " STRNEWLINE " ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( result [ i ] [ j ] ) cout << result [ i ] [ j ] << " β " ; else cout << " . β " ; } cout << " STRNEWLINE " ; } } void computeLargestConnectedGrid ( int input [ n ] [ m ] ) { int current_max = INT_MIN ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { reset_visited ( ) ; COUNT = 0 ; if ( j + 1 < m ) BFS ( input [ i ] [ j ] , input [ i ] [ j + 1 ] , i , j , input ) ; if ( COUNT >= current_max ) { current_max = COUNT ; reset_result ( input [ i ] [ j ] , input ) ; } reset_visited ( ) ; COUNT = 0 ; if ( i + 1 < n ) BFS ( input [ i ] [ j ] , input [ i + 1 ] [ j ] , i , j , input ) ; if ( COUNT >= current_max ) { current_max = COUNT ; reset_result ( input [ i ] [ j ] , input ) ; } } } print_result ( current_max ) ; } int main ( ) { int input [ n ] [ m ] = { { 1 , 4 , 4 , 4 , 4 , 3 , 3 , 1 } , { 2 , 1 , 1 , 4 , 3 , 3 , 1 , 1 } , { 3 , 2 , 1 , 1 , 2 , 3 , 2 , 1 } , { 3 , 3 , 2 , 1 , 2 , 2 , 2 , 2 } , { 3 , 1 , 3 , 1 , 1 , 4 , 4 , 4 } , { 1 , 1 , 3 , 1 , 1 , 4 , 4 , 4 } } ; computeLargestConnectedGrid ( input ) ; return 0 ; } |
Check if a string is substring of another | C ++ program to check if a string is substring of other . ; Returns true if s1 is substring of s2 ; A loop to slide pat [ ] one by one ; For current index i , check for pattern match ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int isSubstring ( string s1 , string s2 ) { int M = s1 . length ( ) ; int N = s2 . length ( ) ; for ( int i = 0 ; i <= N - M ; i ++ ) { int j ; for ( j = 0 ; j < M ; j ++ ) if ( s2 [ i + j ] != s1 [ j ] ) break ; if ( j == M ) return i ; } return -1 ; } int main ( ) { string s1 = " for " ; string s2 = " geeksforgeeks " ; int res = isSubstring ( s1 , s2 ) ; if ( res == -1 ) cout << " Not β present " ; else cout << " Present β at β index β " << res ; return 0 ; } |
Splitting a Numeric String | C ++ program to split a numeric string in an Increasing sequence if possible ; Function accepts a string and checks if string can be split . ; if there is only 1 number in the string then it is not possible to split it ; storing the substring from 0 to i + 1 to form initial number of the increasing sequence ; convert string to integer and add 1 and again convert back to string s2 ; if s2 is not a substring of number than not possible ; if s2 is the next substring of the numeric string ; Incearse num2 by 1 i . e the next number to be looked for ; check if string is fully traversed then break ; If next string doesnot occurs in a given numeric string then it is not possible ; if the string was fully traversed and conditions were satisfied ; if conditions failed to hold ; Driver code ; Call the split function for splitting the string | #include <bits/stdc++.h> NEW_LINE using namespace std ; void split ( string str ) { int len = str . length ( ) ; if ( len == 1 ) { cout << ( " Not β Possible " ) ; return ; } string s1 = " " , s2 = " " ; long num1 , num2 ; for ( int i = 0 ; i <= len / 2 ; i ++ ) { int flag = 0 ; s1 = str . substr ( 0 , i + 1 ) ; num1 = stoi ( ( s1 ) ) ; num2 = num1 + 1 ; s2 = to_string ( num2 ) ; int k = i + 1 ; while ( flag == 0 ) { int l = s2 . length ( ) ; if ( k + l > len ) { flag = 1 ; break ; } if ( ( str . substr ( k , k + l ) == s2 ) ) { flag = 0 ; num2 ++ ; k = k + l ; if ( k == len ) break ; s2 = to_string ( num2 ) ; l = s2 . length ( ) ; if ( k + 1 > len ) { flag = 1 ; break ; } } else flag = 1 ; } if ( flag == 0 ) { cout << " Possible β " << s1 << endl ; break ; } else if ( flag == 1 && i > len / 2 - 1 ) { cout << " Not β Possible " << endl ; break ; } } } int main ( ) { string str = "99100" ; split ( str ) ; return 0 ; } |
Count of number of given string in 2D character array | C ++ code for finding count of string in a given 2D character array . ; utility function to search complete string from any given index of 2d char array ; through Backtrack searching in every directions ; Function to search the string in 2d array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ARRAY_SIZE ( a ) (sizeof(a) / sizeof(*a)) NEW_LINE int internalSearch ( string needle , int row , int col , string hay [ ] , int row_max , int col_max , int xx ) { int found = 0 ; if ( row >= 0 && row <= row_max && col >= 0 && col <= col_max && needle [ xx ] == hay [ row ] [ col ] ) { char match = needle [ xx ] ; xx += 1 ; hay [ row ] [ col ] = 0 ; if ( needle [ xx ] == 0 ) { found = 1 ; } else { found += internalSearch ( needle , row , col + 1 , hay , row_max , col_max , xx ) ; found += internalSearch ( needle , row , col - 1 , hay , row_max , col_max , xx ) ; found += internalSearch ( needle , row + 1 , col , hay , row_max , col_max , xx ) ; found += internalSearch ( needle , row - 1 , col , hay , row_max , col_max , xx ) ; } hay [ row ] [ col ] = match ; } return found ; } int searchString ( string needle , int row , int col , string str [ ] , int row_count , int col_count ) { int found = 0 ; int r , c ; for ( r = 0 ; r < row_count ; ++ r ) { for ( c = 0 ; c < col_count ; ++ c ) { found += internalSearch ( needle , r , c , str , row_count - 1 , col_count - 1 , 0 ) ; } } return found ; } int main ( ) { string needle = " MAGIC " ; string input [ ] = { " BBABBM " , " CBMBBA " , " IBABBG " , " GOZBBI " , " ABBBBC " , " MCIGAM " } ; string str [ ARRAY_SIZE ( input ) ] ; int i ; for ( i = 0 ; i < ARRAY_SIZE ( input ) ; ++ i ) { str [ i ] = input [ i ] ; } cout << " count : β " << searchString ( needle , 0 , 0 , str , ARRAY_SIZE ( str ) , str [ 0 ] . size ( ) ) << endl ; return 0 ; } |
Find minimum shift for longest common prefix | CPP program to find longest common prefix after rotation of second string . ; function for KMP search ; preprocessing of longest proper prefix ; find out the longest prefix and position ; for new position with longer prefix in str2 update pos and len ; print result ; driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void KMP ( int m , int n , string str2 , string str1 ) { int pos = 0 , len = 0 ; int p [ m + 1 ] ; int k = 0 ; p [ 1 ] = 0 ; for ( int i = 2 ; i <= n ; i ++ ) { while ( k > 0 && str1 [ k ] != str1 [ i - 1 ] ) k = p [ k ] ; if ( str1 [ k ] == str1 [ i - 1 ] ) ++ k ; p [ i ] = k ; } for ( int j = 0 , i = 0 ; i < m ; i ++ ) { while ( j > 0 && str1 [ j ] != str2 [ i ] ) j = p [ j ] ; if ( str1 [ j ] == str2 [ i ] ) j ++ ; if ( j > len ) { len = j ; pos = i - j + 1 ; } } cout << " Shift β = β " << pos << endl ; cout << " Prefix β = β " << str1 . substr ( 0 , len ) ; } int main ( ) { string str1 = " geeksforgeeks " ; string str2 = " forgeeksgeeks " ; int n = str1 . size ( ) ; str2 = str2 + str2 ; KMP ( 2 * n , n , str2 , str1 ) ; return 0 ; } |
Find all the patterns of "1(0 + ) 1" in a given string | SET 1 ( General Approach ) | Code to count 1 ( 0 + ) 1 patterns in a string ; Function to count patterns ; Variable to store the last character ; We found 0 and last character was '1' , state change ; After the stream of 0 ' s , β we β got β a β ' 1 ', counter incremented ; Last character stored ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int patternCount ( string str ) { char last = str [ 0 ] ; int i = 1 , counter = 0 ; while ( i < str . size ( ) ) { if ( str [ i ] == '0' && last == '1' ) { while ( str [ i ] == '0' ) i ++ ; if ( str [ i ] == '1' ) counter ++ ; } last = str [ i ] ; i ++ ; } return counter ; } int main ( ) { string str = "1001ab010abc01001" ; cout << patternCount ( str ) << endl ; return 0 ; } |
Boyer Moore Algorithm | Good Suffix heuristic | C program for Boyer Moore Algorithm with Good Suffix heuristic to find pattern in given text string ; preprocessing for strong good suffix rule ; m is the length of pattern ; if character at position i - 1 is not equivalent to character at j - 1 , then continue searching to right of the pattern for border ; the character preceding the occurrence of t in pattern P is different than the mismatching character in P , we stop skipping the occurrences and shift the pattern from i to j ; Update the position of next border ; p [ i - 1 ] matched with p [ j - 1 ] , border is found . store the beginning position of border ; Preprocessing for case 2 ; set the border position of the first character of the pattern to all indices in array shift having shift [ i ] = 0 ; suffix becomes shorter than bpos [ 0 ] , use the position of next widest border as value of j ; Search for a pattern in given text using Boyer Moore algorithm with Good suffix rule ; s is shift of the pattern with respect to text ; initialize all occurrence of shift to 0 ; do preprocessing ; Keep reducing index j of pattern while characters of pattern and text are matching at this shift s ; If the pattern is present at the current shift , then index j will become - 1 after the above loop ; pat [ i ] != pat [ s + j ] so shift the pattern shift [ j + 1 ] times ; Driver | #include <stdio.h> NEW_LINE #include <string.h> NEW_LINE void preprocess_strong_suffix ( int * shift , int * bpos , char * pat , int m ) { int i = m , j = m + 1 ; bpos [ i ] = j ; while ( i > 0 ) { while ( j <= m && pat [ i - 1 ] != pat [ j - 1 ] ) { if ( shift [ j ] == 0 ) shift [ j ] = j - i ; j = bpos [ j ] ; } i -- ; j -- ; bpos [ i ] = j ; } } void preprocess_case2 ( int * shift , int * bpos , char * pat , int m ) { int i , j ; j = bpos [ 0 ] ; for ( i = 0 ; i <= m ; i ++ ) { if ( shift [ i ] == 0 ) shift [ i ] = j ; if ( i == j ) j = bpos [ j ] ; } } void search ( char * text , char * pat ) { int s = 0 , j ; int m = strlen ( pat ) ; int n = strlen ( text ) ; int bpos [ m + 1 ] , shift [ m + 1 ] ; for ( int i = 0 ; i < m + 1 ; i ++ ) shift [ i ] = 0 ; preprocess_strong_suffix ( shift , bpos , pat , m ) ; preprocess_case2 ( shift , bpos , pat , m ) ; while ( s <= n - m ) { j = m - 1 ; while ( j >= 0 && pat [ j ] == text [ s + j ] ) j -- ; if ( j < 0 ) { printf ( " pattern β occurs β at β shift β = β % d STRNEWLINE " , s ) ; s += shift [ 0 ] ; } else s += shift [ j + 1 ] ; } } int main ( ) { char text [ ] = " ABAAAABAACD " ; char pat [ ] = " ABA " ; search ( text , pat ) ; return 0 ; } |
Maximum length prefix of one string that occurs as subsequence in another | C ++ program to find maximum length prefix of one string occur as subsequence in another string . ; Return the maximum length prefix which is subsequence . ; Iterating string T . ; If end of string S . ; If character match , increment counter . ; Driven Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxPrefix ( char s [ ] , char t [ ] ) { int count = 0 ; for ( int i = 0 ; i < strlen ( t ) ; i ++ ) { if ( count == strlen ( s ) ) break ; if ( t [ i ] == s [ count ] ) count ++ ; } return count ; } int main ( ) { char S [ ] = " digger " ; char T [ ] = " biggerdiagram " ; cout << maxPrefix ( S , T ) << endl ; return 0 ; } |
Replace all occurrences of string AB with C without using extra space | C ++ program to replace all occurrences of " AB " with " C " ; Start traversing from second character ; If previous character is ' A ' and current character is 'B" ; Replace previous character with ' C ' and move all subsequent characters one position back ; Driver code | #include <bits/stdc++.h> NEW_LINE void translate ( char * str ) { if ( str [ 0 ] == ' ' ) return ; for ( int i = 1 ; str [ i ] != ' ' ; i ++ ) { if ( str [ i - 1 ] == ' A ' && str [ i ] == ' B ' ) { str [ i - 1 ] = ' C ' ; for ( int j = i ; str [ j ] != ' ' ; j ++ ) str [ j ] = str [ j + 1 ] ; } } return ; } int main ( ) { char str [ ] = " helloABworldABGfG " ; translate ( str ) ; printf ( " The β modified β string β is β : STRNEWLINE " ) ; printf ( " % s " , str ) ; } |
Find all occurrences of a given word in a matrix | Program to find all occurrences of the word in a matrix ; check whether given cell ( row , col ) is a valid cell or not . ; return true if row number and column number is in range ; These arrays are used to get row and column numbers of 8 neighboursof a given cell ; A utility function to do DFS for a 2D boolean matrix . It only considers the 8 neighbours as adjacent vertices ; return if current character doesn 't match with the next character in the word ; append current character position to path ; current character matches with the last character in the word ; Recur for all connected neighbours ; The main function to find all occurrences of the word in a matrix ; traverse through the all cells of given matrix ; occurrence of first character in matrix ; check and print if path exists ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ROW 3 NEW_LINE #define COL 5 NEW_LINE bool isvalid ( int row , int col , int prevRow , int prevCol ) { return ( row >= 0 ) && ( row < ROW ) && ( col >= 0 ) && ( col < COL ) && ! ( row == prevRow && col == prevCol ) ; } int rowNum [ ] = { -1 , -1 , -1 , 0 , 0 , 1 , 1 , 1 } ; int colNum [ ] = { -1 , 0 , 1 , -1 , 1 , -1 , 0 , 1 } ; void DFS ( char mat [ ] [ COL ] , int row , int col , int prevRow , int prevCol , char * word , string path , int index , int n ) { if ( index > n mat [ row ] [ col ] != word [ index ] ) return ; path += string ( 1 , word [ index ] ) + " ( " + to_string ( row ) + " , β " + to_string ( col ) + " ) β " ; if ( index == n ) { cout << path << endl ; return ; } for ( int k = 0 ; k < 8 ; ++ k ) if ( isvalid ( row + rowNum [ k ] , col + colNum [ k ] , prevRow , prevCol ) ) DFS ( mat , row + rowNum [ k ] , col + colNum [ k ] , row , col , word , path , index + 1 , n ) ; } void findWords ( char mat [ ] [ COL ] , char * word , int n ) { for ( int i = 0 ; i < ROW ; ++ i ) for ( int j = 0 ; j < COL ; ++ j ) if ( mat [ i ] [ j ] == word [ 0 ] ) DFS ( mat , i , j , -1 , -1 , word , " " , 0 , n ) ; } int main ( ) { char mat [ ROW ] [ COL ] = { { ' B ' , ' N ' , ' E ' , ' Y ' , ' S ' } , { ' H ' , ' E ' , ' D ' , ' E ' , ' S ' } , { ' S ' , ' G ' , ' N ' , ' D ' , ' E ' } } ; char word [ ] = " DES " ; findWords ( mat , word , strlen ( word ) - 1 ) ; return 0 ; } |
Generate N Random Hexadecimal Numbers | C ++ program for the above approach ; Maximum length of the random integer ; Function to generate N Hexadecimal integers ; Stores all the possible charcters in the Hexadecimal notation ; Loop to print N integers ; Randomly select length of the int in the range [ 1 , maxSize ] ; Print len charcters ; Print a randomly selected character ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int maxSize = 10 ; void randomHexInt ( int N ) { srand ( time ( 0 ) ) ; char hexChar [ ] = { '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , ' A ' , ' B ' , ' C ' , ' D ' , ' E ' , ' F ' } ; for ( int i = 0 ; i < N ; i ++ ) { int len = rand ( ) % maxSize + 1 ; for ( int j = 0 ; j < len ; j ++ ) { cout << hexChar [ rand ( ) % 16 ] ; } cout << ' ' ; } } int main ( ) { int N = 3 ; randomHexInt ( N ) ; return 0 ; } |
Check if two array of string are equal by performing swapping operations | C ++ program for above approach ; Function to check whether brr [ ] can be made equal to arr [ ] by doing swapping operations ; siz variable to store siz of string ; iterate till N to sort strings ; sort each string in arr [ ] ; sort each string in brr [ ] ; Sort both the vectors so that all the comparable strings will be arranged ; iterate till N to compare string in arr [ ] and brr [ ] ; Compare each string ; Return false becaues if atleast one string is not equal then brr [ ] cannot be converted to arr [ ] ; All the strings are compared so at last return true . ; Driver code ; Store the answer in variable | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkEqualArrays ( vector < string > arr , vector < string > brr , int N ) { int siz = arr [ 0 ] . size ( ) ; for ( int i = 0 ; i < N ; i ++ ) { sort ( arr [ i ] . begin ( ) , arr [ i ] . end ( ) ) ; sort ( brr [ i ] . begin ( ) , brr [ i ] . end ( ) ) ; } sort ( arr . begin ( ) , arr . end ( ) ) ; sort ( brr . begin ( ) , brr . end ( ) ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] != brr [ i ] ) { return false ; } } return true ; } int main ( ) { int N = 2 ; vector < string > arr = { " bcd " , " aac " } ; vector < string > brr = { " aca " , " dbc " } ; bool ans = checkEqualArrays ( arr , brr , N ) ; if ( ans ) cout << " true " ; else cout << " false " ; return 0 ; } |
Maximum length of string formed by concatenation having even frequency of each character | C ++ implementation of the above approach ; Function to check the string ; Count the frequency of the string ; Check the frequency of the string ; Store the length of the new String ; Function to find the longest concatenated string having every character of even frequency ; Checking the string ; Dont Include the string ; Include the string ; Driver code ; Call the function ; Print the answer | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxi = 0 ; string ans1 = " " ; void calculate ( string ans ) { int dp [ 26 ] = { 0 } ; for ( int i = 0 ; i < ans . length ( ) ; ++ i ) { dp [ ans [ i ] - ' A ' ] ++ ; } for ( int i = 0 ; i < 26 ; ++ i ) { if ( dp [ i ] % 2 == 1 ) { return ; } } if ( maxi < ans . length ( ) ) { maxi = ans . length ( ) ; ans1 = ans ; } } void longestString ( vector < string > arr , int index , string str ) { if ( index == arr . size ( ) ) { return ; } longestString ( arr , index + 1 , str ) ; str += arr [ index ] ; calculate ( str ) ; longestString ( arr , index + 1 , str ) ; } int main ( ) { vector < string > A = { " ABAB " , " ABF " , " CDA " , " AD " , " CCC " } ; longestString ( A , 0 , " " ) ; cout << ans1 << " β " << ans1 . length ( ) ; return 0 ; } |
Find the next number by adding natural numbers in order on alternating indices from last | C ++ program for the above approach ; Function to generate the resultant number using the given criteria ; Storing end result ; Find the length of numeric string ; Traverse the string ; Storing digit at ith position ; Checking that the number would be added or not ; Logic for summing the digits if the digit is greater than 10 ; Storing the result ; Returning the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string generateNumber ( string number ) { int temp = 0 , adding_number = 0 ; string result = " " ; int len = number . size ( ) ; for ( int i = len - 1 ; i >= 0 ; i -- ) { int digit = number [ i ] - '0' ; if ( temp % 2 == 0 ) { adding_number += 1 ; digit += adding_number ; if ( digit >= 10 ) { digit %= 9 ; if ( digit == 0 ) digit = 9 ; } } result = to_string ( digit ) + result ; temp += 1 ; } return result ; } int main ( ) { string S = "1345" ; cout << generateNumber ( S ) ; return 0 ; } |
Find the single digit sum of alphabetical values of a string | C ++ program for the above approach ; Traverse the given string ; If character is an alphabet ; Stores the sum of order of values ; Find the score ; Find the single digit sum ; Return the resultant sum ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findTheSum ( string str ) { string alpha ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( ( str [ i ] >= ' A ' && str [ i ] <= ' Z ' ) || ( str [ i ] >= ' a ' && str [ i ] <= ' z ' ) ) alpha . push_back ( str [ i ] ) ; } int score = 0 , n = 0 ; for ( int i = 0 ; i < alpha . length ( ) ; i ++ ) { if ( alpha [ i ] >= ' A ' && alpha [ i ] <= ' Z ' ) score += alpha [ i ] - ' A ' + 1 ; else score += alpha [ i ] - ' a ' + 1 ; } while ( score > 0 n > 9 ) { if ( score == 0 ) { score = n ; n = 0 ; } n += score % 10 ; score /= 10 ; } return n ; } int main ( ) { string S = " GeeksforGeeks " ; cout << findTheSum ( S ) ; return 0 ; } |
Minimum value of K such that each substring of size K has the given character | C ++ program for the above approach ; Function to find the minimum value of K such that char c occurs in all K sized substrings of string S ; Store the string length ; Store difference of lengths of segments of every two consecutive occurrences of c ; Stores the maximum difference ; Store the previous occurence of char c ; Check if the current character is c or not ; Stores the difference of consecutive occurrences of c ; Update previous occurrence of c with current occurence ; Comparing diff with max ; If string doesn 't contain c ; Return max ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findK ( string s , char c ) { int n = s . length ( ) ; int diff ; int max = 0 ; int prev = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == c ) { diff = i - prev ; prev = i ; if ( diff > max ) { max = diff ; } } } if ( max == 0 ) return -1 ; return max ; } int main ( ) { string S = " abdegb " ; char ch = ' b ' ; cout << findK ( S , ch ) ; return 0 ; } |
Count subsequences 01 in string generated by concatenation of given numeric string K times | C ++ program for the above approach ; Function to calculate the number of subsequences of "01" ; Store count of 0 ' s β and β 1' s ; Count of subsequences without concatenation ; Case 1 ; Case 2 ; Return the total count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubsequence ( string S , int N , int K ) { int C = 0 , C1 = 0 , C0 = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] == '1' ) C1 ++ ; else if ( S [ i ] == '0' ) C0 ++ ; } int B1 = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] == '1' ) B1 ++ ; else if ( S [ i ] == '0' ) C = C + ( C1 - B1 ) ; } int ans = C * K ; ans += ( C1 * C0 * ( ( ( K ) * ( K - 1 ) ) / 2 ) ) ; return ans ; } int main ( ) { string S = "230013110087" ; int K = 2 ; int N = S . length ( ) ; cout << countSubsequence ( S , N , K ) ; return 0 ; } |
Make Palindrome binary string with exactly a 0 s and b 1 s by replacing wild card ? | C ++ program for the above approach ; Function to convert the given string to a palindrome with a 0 ' s β and β b β 1' s ; Stores the size of the string ; Loop to iterate over the string ; If one of S [ i ] or S [ N - i - 1 ] is equal to ' ? ' , replace it with corresponding character ; Subtract the count of 0 from the required number of zeroes ; Subtract the count of 1 from required number of ones ; Traverse the string ; If both S [ i ] and S [ N - i - 1 ] are ' ? ' ; If a is greater than b ; Update S [ i ] and S [ N - i - 1 ] to '0' ; Update the value of a ; Update S [ i ] and S [ N - i - 1 ] to '1' ; Update the value of b ; Case with middle character ' ? ' in case of odd length string ; If a is greater than b ; Update middle character with '0' ; Update middle character by '1' ; Return Answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string convertString ( string S , int a , int b ) { int N = S . size ( ) ; for ( int i = 0 ; i < N / 2 ; ++ i ) { if ( S [ i ] == ' ? ' && S [ N - i - 1 ] != ' ? ' ) { S [ i ] = S [ N - i - 1 ] ; } else if ( S [ i ] != ' ? ' && S [ N - i - 1 ] == ' ? ' ) { S [ N - i - 1 ] = S [ i ] ; } } a = a - count ( S . begin ( ) , S . end ( ) , '0' ) ; b = b - count ( S . begin ( ) , S . end ( ) , '1' ) ; for ( int i = 0 ; i < N / 2 ; ++ i ) { if ( S [ i ] == ' ? ' && S [ N - i - 1 ] == ' ? ' ) { if ( a > b ) { S [ i ] = S [ N - i - 1 ] = '0' ; a -= 2 ; } else { S [ i ] = S [ N - i - 1 ] = '1' ; b -= 2 ; } } } if ( S [ N / 2 ] == ' ? ' ) { if ( a > b ) { S [ N / 2 ] = '0' ; a -- ; } else { S [ N / 2 ] = '1' ; b -- ; } } if ( a == 0 && b == 0 ) { return S ; } else { return " - 1" ; } } int main ( ) { string S = "10 ? ? ? ? ?1" ; int a = 4 , b = 4 ; cout << convertString ( S , a , b ) ; return 0 ; } |
Count of distinct groups of strings formed after performing equivalent operation | C ++ program for the above approach ; Function to perform the find operation to find the parent of a disjoint set ; Function to perform union operation of disjoint set union ; Find the parent of node a and b ; Update the rank ; Function to find the number of distinct strings after performing the given operations ; Stores the parent elements of the sets ; Stores the rank of the sets ; Update parent [ i ] to i ; Stores the total characters traversed through the strings ; Stores the current characters traversed through a string ; Update current [ i ] to false ; Update current [ ch - ' a ' ] to true ; Check if current [ j ] is true ; Update total [ j ] to true ; Add arr [ i ] [ 0 ] - ' a ' and j elements to same set ; Stores the count of distinct strings ; Check total [ i ] is true and parent of i is i only ; Increment the value of distCount by 1 ; Print the value of distCount ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Find ( vector < int > & parent , int a ) { return parent [ a ] = ( parent [ a ] == a ? a : Find ( parent , parent [ a ] ) ) ; } void Union ( vector < int > & parent , vector < int > & rank , int a , int b ) { a = Find ( parent , a ) ; b = Find ( parent , b ) ; if ( rank [ a ] == rank [ b ] ) rank [ a ] ++ ; if ( rank [ a ] > rank [ b ] ) parent [ b ] = a ; else parent [ a ] = b ; } void numOfDistinctStrings ( string arr [ ] , int N ) { vector < int > parent ( 27 ) ; vector < int > rank ( 27 , 0 ) ; for ( int j = 0 ; j < 27 ; j ++ ) { parent [ j ] = j ; } vector < bool > total ( 26 , false ) ; vector < bool > current ( 26 , false ) ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < 26 ; j ++ ) { current [ j ] = false ; } for ( char ch : arr [ i ] ) { current [ ch - ' a ' ] = true ; } for ( int j = 0 ; j < 26 ; j ++ ) { if ( current [ j ] ) { total [ j ] = true ; Union ( parent , rank , arr [ i ] [ 0 ] - ' a ' , j ) ; } } } int distCount = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( total [ i ] && Find ( parent , i ) == i ) { distCount ++ ; } } cout << distCount << endl ; } int main ( ) { string arr [ ] = { " a " , " ab " , " b " , " d " } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; numOfDistinctStrings ( arr , N ) ; return 0 ; } |
Minimum adjacent swaps required to make a binary string alternating | C ++ program for the above approach ; Function to find the minimum number of adjacent swaps to make the string alternating ; Count the no of zeros and ones ; Base Case ; Store no of min swaps when string starts with "1" ; Keep track of the odd positions ; Checking for when the string starts with "1" ; Adding the no of swaps to fix "1" at odd positions ; Store no of min swaps when string starts with "0" ; Keep track of the odd positions ; Checking for when the string starts with "0" ; Adding the no of swaps to fix "1" at odd positions ; Returning the answer based on the conditions when string length is even ; When string length is odd ; When no of ones is greater than no of zeros ; When no of ones is greater than no of zeros ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minSwaps ( string s ) { int ones = 0 , zeros = 0 ; int N = s . length ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( s [ i ] == '1' ) ones ++ ; else zeros ++ ; } if ( ( N % 2 == 0 && ones != zeros ) || ( N % 2 == 1 && abs ( ones - zeros ) != 1 ) ) { return -1 ; } int ans_1 = 0 ; int j = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( s [ i ] == '1' ) { ans_1 += abs ( j - i ) ; j += 2 ; } } int ans_0 = 0 ; int k = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( s [ i ] == '0' ) { ans_0 += abs ( k - i ) ; k += 2 ; } } if ( N % 2 == 0 ) return min ( ans_1 , ans_0 ) ; else { if ( ones > zeros ) return ans_1 ; else return ans_0 ; } } int main ( ) { string S = "110100" ; cout << minSwaps ( S ) ; return 0 ; } |
Print all ways to reach the Nth stair with the jump of 1 or 2 units at a time | C ++ program for the above approach ; Function to find all the ways to reach Nth stair using one or two jumps ; Base Cases ; Recur for jump1 and jump2 ; Stores the total possible jumps ; Add "1" with every element present in jump1 ; Add "2" with every element present in jump2 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < string > TotalPossibleJumps ( int N ) { if ( ( N - 1 ) == 0 ) { vector < string > newvec ; newvec . push_back ( " " ) ; return newvec ; } else { if ( N < 0 ) { vector < string > newvec ; return newvec ; } } vector < string > jump1 = TotalPossibleJumps ( N - 1 ) ; vector < string > jump2 = TotalPossibleJumps ( N - 2 ) ; vector < string > totaljumps ; for ( string s : jump1 ) { totaljumps . push_back ( "1" + s ) ; } for ( string s : jump2 ) { totaljumps . push_back ( "2" + s ) ; } return totaljumps ; } int main ( ) { int N = 3 ; vector < string > Ans = TotalPossibleJumps ( N ) ; for ( auto & it : Ans ) cout << it << ' ' ; return 0 ; } |
Find any permutation of Binary String of given size not present in Array | C ++ Program for the above approach ; Function to find a binary string of N bits that does not occur in the given array arr [ ] ; Stores the resultant string ; Loop to iterate over all the given strings in a diagonal order ; Append the complement of element at current index into ans ; Return Answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string findString ( vector < string > & arr , int N ) { string ans = " " ; for ( int i = 0 ; i < N ; i ++ ) { ans += arr [ i ] [ i ] == '0' ? '1' : '0' ; } return ans ; } int main ( ) { vector < string > arr { "111" , "011" , "001" } ; int N = arr . size ( ) ; cout << findString ( arr , N ) ; return 0 ; } |
Check if the string has a reversible equal substring at the ends | C ++ program for the above approach ; Function to print longest substring that appears at beginning of string and also at end in reverse order ; Stores the resultant string ; If the characters are same ; Otherwise , break ; If the string can 't be formed ; Otherwise print resultant string ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void commonSubstring ( string s ) { int n = s . size ( ) ; int i = 0 ; int j = n - 1 ; string ans = " " ; while ( j >= 0 ) { if ( s [ i ] == s [ j ] ) { ans += s [ i ] ; i ++ ; j -- ; } else { break ; } } if ( ans . size ( ) == 0 ) cout << " False " ; else { cout << " True β STRNEWLINE " << ans ; } } int main ( ) { string S = " abca " ; commonSubstring ( S ) ; return 0 ; } |
Length of Smallest Non Prime Subsequence in given numeric String | C ++ program for the above approach ; Function to find the smallest length of resultant subsequence ; Check for a subsequence of size 1 ; Check for a subsequence of size 2 ; If none of the above check is successful then subsequence must be of size 3 ; Never executed ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findMinimumSubsequence ( string S ) { bool flag = false ; string dummy ; for ( int j = 0 ; j < S . length ( ) ; j ++ ) { if ( S [ j ] != '2' && S [ j ] != '3' && S [ j ] != '5' && S [ j ] != '7' ) { cout << 1 ; flag = true ; break ; } } if ( ! flag ) { for ( int j = 0 ; j < S . length ( ) - 1 ; j ++ ) { for ( int j1 = j + 1 ; j1 < S . length ( ) ; j1 ++ ) { dummy = S [ j ] + S [ j1 ] ; if ( dummy != "23" && dummy != "37" && dummy != "53" && dummy != "73" ) { cout << 2 ; } if ( flag = true ) break ; } if ( flag = true ) break ; } } if ( ! flag ) { if ( S . length ( ) >= 3 ) { cout << 3 ; } else { cout << -1 ; } } } int main ( ) { string S = "237" ; findMinimumSubsequence ( S ) ; return 0 ; } |
Minimize changes to make all characters equal by changing vowel to consonant and vice versa | C ++ program for the above approach ; Function to find the minimum number of steps to make all characters equal ; Initializing the variables ; Store the frequency ; Iterate over the string ; Calculate the total number of vowels ; Storing frequency of each vowel ; Count the consonants ; Storing the frequency of each consonant ; Iterate over the 2 maps ; Maximum frequency of consonant ; Maximum frequency of vowel ; Find the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int operations ( string s ) { int ans = 0 ; int vowels = 0 , consonants = 0 ; int max_vowels = INT_MIN ; int max_consonants = INT_MIN ; unordered_map < char , int > freq_consonants ; unordered_map < char , int > freq_vowels ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { if ( s [ i ] == ' a ' or s [ i ] == ' e ' or s [ i ] == ' i ' or s [ i ] == ' o ' or s [ i ] == ' u ' ) { vowels += 1 ; freq_vowels [ s [ i ] ] += 1 ; } else { consonants += 1 ; freq_consonants [ s [ i ] ] += 1 ; } } for ( auto it = freq_consonants . begin ( ) ; it != freq_consonants . end ( ) ; it ++ ) { max_consonants = max ( max_consonants , it -> second ) ; } for ( auto it = freq_vowels . begin ( ) ; it != freq_vowels . end ( ) ; it ++ ) { max_vowels = max ( max_vowels , it -> second ) ; } ans = min ( ( 2 * ( vowels - max_vowels ) + consonants ) , ( 2 * ( consonants - max_vowels ) + consonants ) ) ; return ans ; } int main ( ) { string S = " geeksforgeeks " ; cout << operations ( S ) ; return 0 ; } |
Count of ways to empty given String by recursively removing all adjacent duplicates | C ++ implementation for the above approach ; Define the dp table globally ; Recursive function to calculate the dp values for range [ L , R ] ; The range is odd length ; The state is already calculated ; If the length is 2 ; Total answer for this state ; Variable to store the current answer . ; Remove characters s [ l ] and s [ i ] . ; Initialize all the states of dp to - 1 ; Calculate all Combinations ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 505 ] [ 505 ] , choose [ 502 ] [ 502 ] ; int calc ( int l , int r , string & s ) { if ( abs ( r - l ) % 2 == 0 ) { return 0 ; } if ( l > r ) { return dp [ l ] [ r ] = 1 ; } if ( dp [ l ] [ r ] != -1 ) { return dp [ l ] [ r ] ; } if ( ( r - l ) == 1 ) { if ( s [ l ] == s [ r ] ) { dp [ l ] [ r ] = 1 ; } else { dp [ l ] [ r ] = 0 ; } return dp [ l ] [ r ] ; } int ans = 0 ; for ( int k = l + 1 ; k <= r ; k += 2 ) { int temp = 1 ; if ( s [ l ] == s [ k ] ) { temp = calc ( l + 1 , k - 1 , s ) * calc ( k + 1 , r , s ) * choose [ ( r - l + 1 ) / 2 ] [ ( r - k ) / 2 ] ; ans += temp ; } } return dp [ l ] [ r ] = ans ; } int waysToClearString ( string S ) { memset ( dp , -1 , sizeof ( dp ) ) ; int n = S . length ( ) ; choose [ 0 ] [ 0 ] = 1 ; for ( int i = 1 ; i <= n / 2 ; ++ i ) { choose [ i ] [ 0 ] = 1 ; for ( int j = 1 ; j <= i ; ++ j ) { choose [ i ] [ j ] = ( choose [ i - 1 ] [ j ] + choose [ i - 1 ] [ j - 1 ] ) ; } } return calc ( 0 , n - 1 , S ) ; } int main ( ) { string S = " aabccb " ; cout << waysToClearString ( S ) ; return 0 ; } |
Divide given numeric string into at most two increasing subsequences which form an increasing string upon concatenation | C ++ program for the above approach ; Function to check for valid subsequences ; Stores which element belongs to which subsequence ; Check for each pos if a possible subsequence exist or not ; Last member of 1 subsequence ; Last Member of 2 nd subsequence ; Check if current element can go to 2 nd subsequence ; Check if the current elements belongs to first subsequence ; If the current element does not belong to any subsequence ; Check if last digit of first subsequence is greater than pos ; If a subsequence is found , find the subsequences ; Stores the resulting subsequences ; Print the subsequence ; If no subsequence found , print - 1 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findSubsequence ( string str ) { int n = str . size ( ) ; char res [ n ] ; for ( int i = 0 ; i < n ; i ++ ) res [ i ] = 0 ; for ( int pos = 0 ; pos <= 9 ; pos ++ ) { char lst1 = '0' ; bool flag = 1 ; char lst2 = pos + '0' ; for ( int i = 0 ; i < n ; i ++ ) { if ( lst2 <= str [ i ] ) { res [ i ] = '2' ; lst2 = str [ i ] ; } else if ( lst1 <= str [ i ] ) { res [ i ] = '1' ; lst1 = str [ i ] ; } else flag = 0 ; } if ( lst1 > pos + '0' ) flag = 0 ; if ( flag ) { string S1 = " " ; string S2 = " " ; for ( int i = 0 ; i < n ; i ++ ) { if ( res [ i ] == '1' ) { S1 += str [ i ] ; } else { S2 += str [ i ] ; } } cout << S1 << ' β ' << S2 << endl ; return ; } } cout << " - 1" ; } int main ( ) { string S = "040425524644" ; findSubsequence ( S ) ; S = "123456789" ; findSubsequence ( S ) ; return 0 ; } |
Find Kth lexicographical ordered numeric string of length N with distinct products of each substring | C ++ program for the above approach ; Function to find the required string ; If the current length is equal to n exit from here only ; Iterate for all the characters ; Check if the product is present before ; If the current string is good then recurse for the next character ; Decrease all the products back to their original state ; Erase the last character ; Function to calculate kth ordered valid string ; Check for the base cases ; There are atmost 10 valid strings for n = 1 ; Vector to keep a check on number of occurences of products ; Recursively construct the strings ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void getString ( int curlen , string & ans , string & s , int N , int & K , vector < int > & prod ) { if ( curlen == N ) { K -- ; if ( K == 0 ) ans = s ; return ; } char ch ; int ok , t , i ; for ( ch = '2' ; ch <= '9' ; ch ++ ) { s += ch ; ok = 1 ; t = 1 ; for ( i = curlen ; i >= 0 ; i -- ) { t *= s [ i ] - 48 ; if ( prod [ t ] ) ok = 0 ; prod [ t ] ++ ; } if ( ok ) getString ( curlen + 1 , ans , s , N , K , prod ) ; t = 1 ; for ( i = curlen ; i >= 0 ; i -- ) { t *= s [ i ] - 48 ; prod [ t ] -- ; } s . erase ( s . length ( ) - 1 ) ; } } string kthValidString ( int N , int K ) { if ( N > 10 ) { return " - 1" ; } if ( N == 1 ) { if ( K > 10 ) { return " - 1" ; } string s = " " ; K -- ; s += ( K + '0' ) ; return s ; } string ans = " - 1" ; string s = " " ; vector < int > prod ( 10005 , 0 ) ; getString ( 0 , ans , s , N , K , prod ) ; return ans ; } int main ( ) { int N = 3 , K = 4 ; cout << kthValidString ( N , K ) ; } |
Minimum swaps to balance the given brackets at any index | C ++ implementation for the above approach ; Function to balance the given bracket by swap ; To count the number of uunbalanced pairs ; if there is an opening bracket and we encounter closing bracket then it will decrement the count of unbalanced bracket . ; else it will increment unbalanced pair count ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int BalancedStringBySwapping ( string s ) { int unbalancedPair = 0 ; for ( int i = 0 ; i < s . length ( ) ; ++ i ) { if ( unbalancedPair > 0 && s [ i ] == ' ] ' ) { -- unbalancedPair ; } else if ( s [ i ] == ' [ ' ) { ++ unbalancedPair ; } } return ( unbalancedPair + 1 ) / 2 ; } int main ( ) { string s = " ] ] ] [ [ [ " ; cout << ( BalancedStringBySwapping ( s ) ) ; return 0 ; } |
Count of palindromic strings of size upto N consisting of first K alphabets occurring at most twice | C ++ program for the above approach ; Function of return the number of palindromic strings of length N with first K alphabets possible ; If N is odd , half + 1 position can be filled to cope with the extra middle element ; K is reduced by one , because count of choices for the next position is reduced by 1 as a element can only once ; Return the possible count ; Function to find the count of palindromic string of first K characters according to the given criteria ; If N = 1 , then only K palindromic strings possible . ; If N = 2 , the 2 * K palindromic strings possible , K for N = 1 and K for N = 2 ; Initialize ans with the count of strings possible till N = 2 ; Return the possible count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int lengthNPalindrome ( int N , int K ) { int half = N / 2 ; if ( N & 1 ) { half += 1 ; } int ans = 1 ; for ( int i = 1 ; i <= half ; i ++ ) { ans *= K ; K -- ; } return ans ; } int palindromicStrings ( int N , int K ) { if ( N == 1 ) { return K ; } if ( N == 2 ) { return 2 * K ; } int ans = 0 ; ans += ( 2 * K ) ; for ( int i = 3 ; i <= N ; i ++ ) { ans += lengthNPalindrome ( i , K ) ; } return ans ; } int main ( ) { int N = 4 , K = 3 ; cout << palindromicStrings ( N , K ) ; return 0 ; } |
Minimum number of characters required to be added to a String such that all lowercase alphabets occurs as a subsequence in increasing order | C ++ program for the above approach ; Function to find the LCS of strings S and string T ; Base Case ; Already Calculated State ; If the characters are the same ; Otherwise ; Function to find the minimum number of characters that needs to be appended in the string to get all lowercase alphabets as a subsequences ; String containing all the characters ; Stores the result of overlapping subproblems ; Return the minimum characters required ; Driver Code | #include " bits / stdc + + . h " NEW_LINE using namespace std ; int LCS ( string & S , int N , string & T , int M , vector < vector < int > > & dp ) { if ( N == 0 or M == 0 ) return 0 ; if ( dp [ N ] [ M ] != -1 ) return dp [ N ] [ M ] ; if ( S [ N - 1 ] == T [ M - 1 ] ) { return dp [ N ] [ M ] = 1 + LCS ( S , N - 1 , T , M - 1 , dp ) ; } return dp [ N ] [ M ] = max ( LCS ( S , N - 1 , T , M , dp ) , LCS ( S , N , T , M - 1 , dp ) ) ; } int minimumCharacter ( string & S ) { string T = " abcdefghijklmnopqrstuvwxyz " ; int N = S . length ( ) , M = T . length ( ) ; vector < vector < int > > dp ( N + 1 , vector < int > ( M + 1 , -1 ) ) ; return ( 26 - LCS ( S , N , T , M , dp ) ) ; } int main ( ) { string S = " abcdadc " ; cout << minimumCharacter ( S ) ; return 0 ; } |
Count ways to make the number formed by K concatenations of a numeric string divisible by 5 | C ++ program for the above approach ; Function to find the value of a ^ b modulo 1000000007 ; Stores the resultant value a ^ b ; Find the value of a ^ b ; Function to count the number of ways such that the formed number is divisible by 5 by removing digits ; Stores the count of ways ; Find the count for string S ; If the digit is 5 or 0 ; Find the count of string for K concatenation of string S ; Find the total count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; typedef long long LL ; const int MOD = 1000000007 ; int exp_mod ( LL a , LL b ) { LL ret = 1 ; for ( ; b ; b >>= 1 , a = a * a % MOD ) { if ( b & 1 ) ret = ret * a % MOD ; } return ret ; } int countOfWays ( string s , int k ) { int N = s . size ( ) ; LL ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( s [ i ] == '5' s [ i ] == '0' ) { ans = ( ans + exp_mod ( 2 , i ) ) % MOD ; } } LL q = exp_mod ( 2 , N ) ; LL qk = exp_mod ( q , k ) ; LL inv = exp_mod ( q - 1 , MOD - 2 ) ; ans = ans * ( qk - 1 ) % MOD ; ans = ans * inv % MOD ; return ans ; } int main ( ) { string S = "1256" ; int K = 1 ; cout << countOfWays ( S , K ) ; return 0 ; } |
Find the string present at the middle of a lexicographically increasing sequence of strings from S to T | C ++ Program for the above approach ; Function to print the string at the middle of lexicographically increasing sequence of strings from S to T ; Stores the base 26 digits after addition ; Iterete from right to left and add carry to next position ; Reduce the number to find the middle string by dividing each position by 2 ; If current value is odd , carry 26 to the next index value ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int printMiddleString ( string S , string T , int N ) { vector < int > a1 ( N + 1 ) ; for ( int i = 0 ; i < N ; i ++ ) { a1 [ i + 1 ] = S [ i ] - ' a ' + T [ i ] - ' a ' ; } for ( int i = N ; i >= 1 ; i -- ) { a1 [ i - 1 ] += a1 [ i ] / 26 ; a1 [ i ] %= 26 ; } for ( int i = 0 ; i <= N ; i ++ ) { if ( a1 [ i ] & 1 ) { if ( i + 1 <= N ) { a1 [ i + 1 ] += 26 ; } } a1 [ i ] /= 2 ; } for ( int i = 1 ; i <= N ; i ++ ) { cout << char ( a1 [ i ] + ' a ' ) ; } return 0 ; } int main ( ) { int N = 5 ; string S = " afogk " ; string T = " asdji " ; printMiddleString ( S , T , N ) ; } |
Find character at Kth index by appending S1 ( M ) times and S2 ( M + 1 ) times | C ++ program to solve the above approach ; initializing first and second variable as to store how many string ' s ' and string ' t ' will be appended ; storing tmp length ; if length of string tmp is greater than k , then we have reached our destination string now we can return character at index k ; appending s to tmp , f times ; appending t to tmp , s times ; extracting output character ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; char KthCharacter ( string s , string t , long k ) { long f = 1 ; long ss = 2 ; string tmp = " " ; int len = tmp . length ( ) ; while ( len < k ) { long tf = f ; long ts = ss ; while ( tf -- != 0 ) { tmp += s ; } while ( ts -- != 0 ) { tmp += t ; } f += 2 ; ss += 2 ; len = tmp . length ( ) ; } char output = tmp [ k - 1 ] ; return output ; } int main ( ) { string S1 = " a " , S2 = " bc " ; int k = 4 ; char ans = KthCharacter ( S1 , S2 , k ) ; cout << ans ; } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.