text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Minimum count of 0 s to be removed from given Binary string to make all 1 s occurs consecutively | C ++ program for the above approach ; Function to find minimum count of 0 s removed from the string S such that all 1 s occurs consecutively ; Stores the first and the last occurrence of 1 ; Iterate over the characters the string , S ; If current character is '1' ; Update fst_occur ; Iterate over the characters the string , S ; If current character is '1' ; Update lst_occur ; Stores the count of 0 s between fst_occur and lst_occur ; Iterate over the characters of S between fst_occur and lst_occur ; If current character is '0' ; Update count ; Print the resultant minimum count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void makeContiguous ( string S , int N ) { int fst_occur , lst_occur ; for ( int x = 0 ; x < N ; x ++ ) { if ( S [ x ] == '1' ) { fst_occur = x ; break ; } } for ( int x = N - 1 ; x >= 0 ; x -- ) { if ( S [ x ] == '1' ) { lst_occur = x ; break ; } } int count = 0 ; for ( int x = fst_occur ; x <= lst_occur ; x ++ ) { if ( S [ x ] == '0' ) { count ++ ; } } cout << count ; } int main ( ) { string S = "010001011" ; int N = S . size ( ) ; makeContiguous ( S , N ) ; return 0 ; }
Lexicographically smallest string with period K possible by replacing ' ? ' s from a given string | C ++ program for the above approach ; Function to modify the given string such that string S is a period of K ; Iterate over the range [ 0 , K ] ; Stores the frequency of the characters S [ i + j * K ] ; Iterate over the string with increment of K ; Print " - 1" ; Replace all characters of the string with ' ? ' to ' a ' to make it smallest ; Otherwise ; Find the character other than ' ? ' ; Replace all characters of the string with ' ? ' to character ch ; Clear the map M ; Return the modified string ; Driver Code
#include " bits / stdc + + . h " NEW_LINE using namespace std ; string modifyString ( string & S , int K ) { int N = S . length ( ) ; for ( int i = 0 ; i < K ; i ++ ) { map < char , int > M ; for ( int j = i ; j < N ; j += K ) { M [ S [ j ] ] ++ ; } if ( M . size ( ) > 2 ) { return " - 1" ; } else if ( M . size ( ) == 1 ) { if ( M [ ' ? ' ] != 0 ) { for ( int j = i ; j < N ; j += K ) { S [ j ] = ' a ' ; } } } else if ( M . size ( ) == 2 ) { char ch ; for ( auto & it : M ) { if ( it . first != ' ? ' ) { ch = it . first ; } } for ( int j = i ; j < N ; j += K ) { S [ j ] = ch ; } } M . clear ( ) ; } return S ; } int main ( ) { string S = " ab ? ? " ; int K = 2 ; cout << modifyString ( S , K ) ; return 0 ; }
Count of ways to rearrange N digits and M alphabets keeping all alphabets together | C ++ program for the above approach ; Function to find the factorial of the given number ; Function to count ways to rearrange characters of the string such that all alphabets are adjacent . ; Stores factorial of ( N + 1 ) ; Stores factorial of ; Driver Code ; Given a and b ; int M = 2 ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int fact ( int n ) { int ans = 1 ; for ( int i = 2 ; i <= n ; i ++ ) ans = ans * i ; return ans ; } int findComb ( int N , int M ) { int x = fact ( N + 1 ) ; int y = fact ( M ) ; return ( x * y ) ; } int main ( ) { int N = 2 ; cout << findComb ( N , M ) ; }
Count of camel case characters present in a given string | C ++ program for the above approach ; Function to count all the camelcase characters in the string S ; Stores the total count of camelcase characters ; Traverse the string S ; If ASCII value of character lies over the range [ 65 , 91 ] then increment the count ; Print the total count obtained ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countCamelCase ( string & S ) { int count = 0 ; for ( int i = 0 ; S [ i ] ; i ++ ) { if ( S [ i ] >= 65 && S [ i ] <= 91 ) { count ++ ; } } cout << count ; } int main ( ) { string S = " ckjkUUYII " ; countCamelCase ( S ) ; return 0 ; }
Decode a given string by removing duplicate occurrences | C ++ program for the above approach ; Function to count the appearances of each character ; If the character is lower case ; If the character is uppercase ; If the character is a punctuation mark ; Function to decode the given encoded string ; Iterate the given string str ; Find the index of the next character to be printed ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findRepitition ( char a ) { if ( a <= ' z ' && a >= ' a ' ) { return a - ' a ' ; } else if ( a <= ' Z ' && a >= ' A ' ) { return a - ' A ' ; } return 0 ; } void decodeString ( string str ) { string output = " " ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { output . push_back ( str [ i ] ) ; i += findRepitition ( str [ i ] ) ; } cout << " Decrypted ▁ code ▁ is ▁ { " << output << " } " << endl ; } int main ( ) { string str = " abbbb ▁ acccdddd " ; decodeString ( str ) ; return 0 ; }
Program to perform a letter frequency attack on a monoalphabetic substitution cipher | C ++ program for the above approach ; Function to decrypt a monoalphabetic substitution cipher using the letter frequency attack ; Stores final 5 possible deciphered plaintext ; Store the frequency of each letter in cipher text ; Stores the frequency of each letter in cipher text in descending order ; Store which alphabet is used already ; Traverse the string S ; Copy the frequency array ; Stores the string formed from concatanating the english letters in the decreasing frequency in the english language ; Sort the array in descending order ; Itearate over the range [ 0 , 5 ] ; Iterate over the range [ 0 , 26 ] ; Store the numerical equivalent of letter at ith index of array letter_frequency ; Calculate the probable shift used in monoalphabetic cipher ; Temporary string to generate one plaintext at a time ; Generate the probable ith plaintext string using the shift calculated above ; Insert whitespaces as it is ; Shift the kth letter of the cipher by x ; Add the kth calculated / shifted letter to temporary string ; Print the generated 5 possible plaintexts ; Driver Code ; Given string ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printString ( string S , int N ) { string plaintext [ 5 ] ; int freq [ 26 ] = { 0 } ; int freqSorted [ 26 ] ; int Used [ 26 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] != ' ▁ ' ) { freq [ S [ i ] - ' A ' ] ++ ; } } for ( int i = 0 ; i < 26 ; i ++ ) { freqSorted [ i ] = freq [ i ] ; } string T = " ETAOINSHRDLCUMWFGYPBVKJXQZ " ; sort ( freqSorted , freqSorted + 26 , greater < int > ( ) ) ; for ( int i = 0 ; i < 5 ; i ++ ) { int ch = -1 ; for ( int j = 0 ; j < 26 ; j ++ ) { if ( freqSorted [ i ] == freq [ j ] && Used [ j ] == 0 ) { Used [ j ] = 1 ; ch = j ; break ; } } if ( ch == -1 ) break ; int x = T [ i ] - ' A ' ; x = x - ch ; string curr = " " ; for ( int k = 0 ; k < N ; k ++ ) { if ( S [ k ] == ' ▁ ' ) { curr += ' ▁ ' ; continue ; } int y = S [ k ] - ' A ' ; y += x ; if ( y < 0 ) y += 26 ; if ( y > 25 ) y -= 26 ; curr += ' A ' + y ; } plaintext [ i ] = curr ; } for ( int i = 0 ; i < 5 ; i ++ ) { cout << plaintext [ i ] << endl ; } } int main ( ) { string S = " B ▁ TJNQMF ▁ NFTTBHF " ; int N = S . length ( ) ; printString ( S , N ) ; return 0 ; }
Count of substrings in a Binary String that contains more 1 s than 0 s | C ++ program for the above approach ; Function to merge two partitions such that the merged array is sorted ; Counting inversions ; Function to implement merge sort ; Function to calculate number of inversions in a given array ; Calculate the number of inversions ; Return the number of inversions ; Function to count the number of substrings that contains more 1 s than 0 s ; Stores the prefix sum array ; Stores the count of valid substrings ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void merge ( vector < int > & v , int left , int mid , int right , int & inversions ) { vector < int > temp ( right - left + 1 ) ; int i = left ; int j = mid + 1 ; int k = 0 ; int cnt = 0 ; while ( i <= mid && j <= right ) { if ( v [ i ] <= v [ j ] ) { temp [ k ++ ] = v [ i ++ ] ; } else { inversions += ( mid - i + 1 ) ; temp [ k ++ ] = v [ j ++ ] ; } } while ( i <= mid ) temp [ k ++ ] = v [ i ++ ] ; while ( j <= right ) temp [ k ++ ] = v [ j ++ ] ; k = 0 ; for ( int a = left ; a <= right ; a ++ ) { v [ a ] = temp [ k ++ ] ; } } void mergeSort ( vector < int > & v , int left , int right , int & inversions ) { if ( left < right ) { int mid = ( left + right ) / 2 ; mergeSort ( v , left , mid , inversions ) ; mergeSort ( v , mid + 1 , right , inversions ) ; merge ( v , left , mid , right , inversions ) ; } } int CountInversions ( vector < int > & v ) { int n = v . size ( ) ; int inversions = 0 ; mergeSort ( v , 0 , n - 1 , inversions ) ; return inversions ; } int getSubsCount ( string & input ) { int n = input . length ( ) ; vector < int > nums ( n ) ; for ( int i = 0 ; i < n ; i ++ ) { nums [ i ] = input [ i ] - '0' ; if ( nums [ i ] == 0 ) nums [ i ] = -1 ; } vector < int > pref ( n ) ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += nums [ i ] ; pref [ i ] = sum ; } int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( pref [ i ] > 0 ) cnt ++ ; } reverse ( pref . begin ( ) , pref . end ( ) ) ; int inversions = CountInversions ( pref ) ; int ans = cnt + inversions ; return ans ; } int main ( ) { string input = "101" ; int ans = getSubsCount ( input ) ; cout << ans << endl ; return 0 ; }
Check if a string consisting only of a , b , c can be made empty by removing substring " abc " recursively | C ++ program for the above approach ; Function to check if the given string S can be made empty ; Stores the characters of the string S ; Traverse the given string ; If the character is c ; If stack size is greater than 2 ; Pop from the stack ; Top two characters in the stack should be ' b ' and ' a ' respectively ; Otherwise , print No ; If character is ' a ' or ' b ' push to stack ; If stack is empty , then print Yes . Otherwise print No ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string canMadeEmpty ( string s , int n ) { stack < char > St ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ' c ' ) { if ( St . size ( ) >= 2 ) { char b = St . top ( ) ; St . pop ( ) ; char a = St . top ( ) ; St . pop ( ) ; if ( a != ' a ' b != ' b ' ) return " No " ; } else return " No " ; } else St . push ( s [ i ] ) ; } if ( St . size ( ) == 0 ) { return " Yes " ; } else { return " No " ; } } int main ( ) { string S = " aabcbc " ; int N = S . length ( ) ; cout << canMadeEmpty ( S , N ) ; return 0 ; }
Maximum count of β€œ 010. . ” subsequences that can be removed from given Binary String | C ++ program for the above approach ; Function to count the maximum number of operations performed on the string ; Size of the string ; Stores the maximum number of operations performed ; Stores the count of ' X ' occurred so far ; Traverse the string ; Check if current char is ' X ' ; Check if the value of cnt is greater than 0 ; Decrement the value of cnt ; Increment the value of ans ; Print the value of ans ; Driver Code
#include <iostream> NEW_LINE using namespace std ; void countOperations ( string S ) { int n = S . length ( ) ; int ans = 0 ; int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( S [ i ] == '0' ) { cnt ++ ; } else { if ( cnt > 0 ) { cnt -- ; ans ++ ; } } } cout << ans ; } int main ( ) { string S = "110011010" ; countOperations ( S ) ; return 0 ; }
Check if given String can be split only into subsequences ABC | C ++ program for the above approach ; Function to check if the given string can be splitted into subsequences " ABC " ; Stores the length of the string ; Stores the indices of ' A ' ; Stores the indices of ' B ' ; Stores the indices of ' C ' ; Traverse the string S ; If S [ i ] is equal to ' A ' ; Push the index i in A ; Else if S [ i ] is equal to ' B ' ; Push the index i in B ; Else if S [ i ] is equal to ' C ' ; Push the index i in C ; If N is not multiple of 3 or count of characters ' A ' , ' B ' and ' C ' are not equal ; Return " No " ; Iterate over the deque B ; If A is not empty and B [ i ] is greater than A [ 0 ] ; Removes the front element of A ; Else return " No " ; Iterate over the deque B in reverse ; If C is not empty and last element of C is greater thab B [ i ] ; Removes the last element of C ; Else return " No " ; If none of the above cases satisfy return "Yes' ; Driver Code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string check ( string S ) { int N = S . length ( ) ; deque < int > A ; deque < int > B ; deque < int > C ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] == ' A ' ) { A . push_back ( i ) ; } else if ( S [ i ] == ' B ' ) { B . push_back ( i ) ; } else { C . push_back ( i ) ; } } if ( N % 3 || A . size ( ) != B . size ( ) || A . size ( ) != C . size ( ) ) { return " No " ; } for ( int i = 0 ; i < B . size ( ) ; i ++ ) { if ( ! A . empty ( ) && B [ i ] > A [ 0 ] ) { A . pop_front ( ) ; } else { return " No " ; } } for ( int i = B . size ( ) - 1 ; i >= 0 ; i -- ) { if ( ! C . empty ( ) && B [ i ] < C . back ( ) ) { C . pop_back ( ) ; } else { return " No " ; } } return " Yes " ; } int main ( ) { string S = " ABABCC " ; cout << check ( S ) << endl ; return 0 ; }
Check if summation of two words is equal to target word | C ++ program for the above approach ; Function to check weather summation of two words equal to target word ; Store the length of each string ; Reverse the strings A , B and C ; Stores the remainder ; Iterate in the range [ 0 , max ( L , max ( M , N ) ) ] ; Stores the integer at ith position from the right in the sum of A and B ; If i is less than L ; If i is less than M ; Update rem and curr ; If i is less than N and curr is not equal to C [ i ] - ' a ' , return " No " ; If rem is greater than 0 , return " No " ; Otherwise , return " Yes " ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string isSumEqual ( string A , string B , string C ) { int L = A . length ( ) ; int M = B . length ( ) ; int N = A . length ( ) ; reverse ( A . begin ( ) , A . end ( ) ) ; reverse ( B . begin ( ) , B . end ( ) ) ; reverse ( C . begin ( ) , C . end ( ) ) ; int rem = 0 ; for ( int i = 0 ; i < max ( L , max ( M , N ) ) ; i ++ ) { int curr = rem ; if ( i < L ) curr += A [ i ] - ' a ' ; if ( i < M ) curr += B [ i ] - ' a ' ; rem = curr / 10 ; curr %= 10 ; if ( i < N && curr != C [ i ] - ' a ' ) { return " No " ; } } if ( rem ) return " No " ; else return " Yes " ; } int main ( ) { string A = " acb " , B = " cba " , C = " cdb " ; cout << isSumEqual ( A , B , C ) ; return 0 ; }
Minimum K such that every substring of length at least K contains a character c | Set | C ++ program for the above approach ; Function to find minimum value of K such that there exist atleast one K amazing character ; Stores the answer ; Update the string S ; Iterate over the characters in range [ a , z ] ; Stores the last index where c appears ; Stores the maximum possible length ; Update string S ; Iterate over characters of string S ; If S [ i ] is equal to c ; Stores the distance between positions of two same c ; Update max_len ; Update the value of prev ; Update the value of ans ; Return the answer ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MinimumLengthSubstring ( string S , int N ) { int ans = N ; S = "0" + S + "0" ; for ( char c = ' a ' ; c <= ' z ' ; ++ c ) { int prev = 0 ; int max_len = 0 ; S [ 0 ] = c ; S [ N + 1 ] = c ; for ( int i = 1 ; i <= N + 1 ; ++ i ) { if ( S [ i ] == c ) { int len = i - prev ; max_len = max ( max_len , len ) ; prev = i ; } } ans = min ( ans , max_len ) ; } return ans ; } int main ( ) { string S = " abcde " ; int N = S . length ( ) ; cout << MinimumLengthSubstring ( S , N ) ; }
Minimize hamming distance in Binary String by setting only one K size substring bits | C ++ program for the above approach ; Function to find minimum Hamming Distance after atmost one operation ; Store the size of the string ; Store the prefix sum of 1 s ; Create Prefix Sum array ; Initialize cnt as number of ones in string S ; Store the required result ; Traverse the string , S ; Store the number of 1 s in the substring S [ i , i + K - 1 ] ; Update the answer ; Return the result ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumHammingDistance ( string S , int K ) { int n = S . size ( ) ; int pref [ n ] ; pref [ 0 ] = S [ 0 ] - '0' ; for ( int i = 1 ; i < n ; i ++ ) pref [ i ] = pref [ i - 1 ] + ( S [ i ] - '0' ) ; int cnt = pref [ n - 1 ] ; int ans = cnt ; for ( int i = 0 ; i < n - K ; i ++ ) { int value = pref [ i + K - 1 ] - ( i - 1 >= 0 ? pref [ i - 1 ] : 0 ) ; ans = min ( ans , cnt - value + ( K - value ) ) ; } return ans ; } int main ( ) { string s = "101" ; int K = 2 ; cout << minimumHammingDistance ( s , K ) ; return 0 ; }
Check if a permutation of S2 can be obtained by adding or removing characters from S1 | C ++ program for the above approach ; Function to check if the given number is prime or not ; If the number is less than 2 ; If the number is 2 ; If N is a multiple of 2 ; Otherwise , check for the odds values ; Function to check if S1 can be a permutation of S2 by adding or removing characters from S1 ; Initialize a frequency array ; Decrement the frequency for occurrence in s1 ; Increment the frequency for occurence in s2 ; If frequency of current char is same in s1 and s2 ; Check the frequency for the current char is not prime ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int n ) { if ( n <= 1 ) return false ; else if ( n == 2 ) return true ; else if ( n % 2 == 0 ) return false ; for ( int i = 3 ; i <= sqrt ( n ) ; i += 2 ) { if ( n % i == 0 ) return false ; } return true ; } void checkPermutation ( string s1 , string s2 ) { int freq [ 26 ] = { 0 } ; for ( char ch : s1 ) { freq [ ch - ' a ' ] -- ; } for ( char ch : s2 ) { freq [ ch - ' a ' ] ++ ; } bool isAllChangesPrime = true ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( freq [ i ] == 0 ) { continue ; } else if ( ! isPrime ( abs ( freq [ i ] ) ) ) { isAllChangesPrime = false ; break ; } } if ( isAllChangesPrime ) { cout << " Yes " ; } else { cout << " No " ; } } int main ( ) { string S1 = " gekforgk " ; string S2 = " geeksforgeeks " ; checkPermutation ( S1 , S2 ) ; }
Count ways to split a string into two subsets that are reverse of each other | C ++ program for the above approach ; Function to find the total number of ways to partitiaon the string into two subset satisfying the conditions ; Stores the resultant number of ways of splitting ; Iterate over the range [ 0 , 2 ^ N ] ; Traverse the string S ; If ith bit is set , then append the character S [ i ] to X ; Otherwise , append the character S [ i ] to Y ; Reverse the second string ; If X is equal to Y ; Return the total number of ways ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countWays ( string S , int N ) { int ans = 0 ; for ( int mask = 0 ; mask < ( 1 << N ) ; mask ++ ) { string X , Y ; for ( int i = 0 ; i < N ; i ++ ) { if ( mask >> i & 1 ) { X += S [ i ] ; } else { Y += S [ i ] ; } } reverse ( Y . begin ( ) , Y . end ( ) ) ; if ( X == Y ) { ans ++ ; } } return ans ; } int main ( ) { string S = " mippiisssisssiipsspiim " ; int N = S . length ( ) ; cout << countWays ( S , N ) ; return 0 ; }
Check if String formed by first and last X characters of a String is a Palindrome | C ++ implementation for the above approach ; Function to check whether the first x characters of both string str and reversed string str are same or not ; Length of the string str ; Traverse over the string while first and last x characters are not equal ; If the current and n - k - 1 from last character are not equal ; Finally , print true ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void isEqualSubstring ( string str , int x ) { int n = str . length ( ) ; int i = 0 ; while ( i < n && i < x ) { if ( str [ i ] != str [ n - i - 1 ] ) { cout << " false " ; return ; } i ++ ; } cout << " true " ; } int main ( ) { string str = " GeeksforGeeks " ; int x = 3 ; isEqualSubstring ( str , x ) ; }
Flip the String by either swapping given characters or rotating it horizontally for Q queries | C ++ program for the above approach ; Function to find final string after applying all Queries on it ; Traverse the Queries array ; convert A , B to zero indexing ; Query of 1 st type ; swap ath and bth characters ; Query of 2 nd type ; swap first N characters with last N characters ; Print answer ; Driver code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( string S , int N , vector < vector < int > > Queries , int Q ) { for ( int i = 0 ; i < Q ; i ++ ) { int T = Queries [ i ] [ 0 ] , A = Queries [ i ] [ 1 ] , B = Queries [ i ] [ 2 ] ; A -- ; B -- ; if ( T == 1 ) { swap ( S [ A ] , S [ B ] ) ; } else { for ( int j = 0 ; j < N ; j ++ ) { swap ( S [ j ] , S [ j + N ] ) ; } } } cout << S << endl ; } int main ( ) { string S = " ABCD " ; int N = S . length ( ) / 2 ; vector < vector < int > > Queries = { { 2 , 0 , 0 } , { 1 , 1 , 3 } , { 2 , 0 , 0 } } ; int Q = Queries . size ( ) ; solve ( S , N , Queries , Q ) ; return 0 ; }
Minimum number of replacement done of substring "01" with "110" to remove it completely | C ++ program for the above approach ; Function to find the minimum number of replacement of "01" with "110" s . t . S doesn 't contain substring "10" ; Stores the number of operations performed ; Stores the resultant count of substrings ; Traverse the string S from end ; If the current character is 0 ; If the current character is 1 ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumOperations ( string S , int N ) { int ans = 0 ; int cntOne = 0 ; for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( S [ i ] == '0' ) { ans += cntOne ; cntOne *= 2 ; } else cntOne ++ ; } cout << ans ; } int main ( ) { string S = "001" ; int N = S . length ( ) ; minimumOperations ( S , N ) ; return 0 ; }
Count different Bitwise OR values of equal length strings S1 and S2 by swapping exactly one pair of characters from the first string | C ++ program for the above approach ; Function to find the number of ways to obtain different Bitwise OR ; Stores the count of pairs t00 , t10 , t01 , t11 ; Traverse the characters of the string S1 and S2 ; Count the pair ( 0 , 0 ) ; Count the pair ( 1 , 0 ) ; Count the pair ( 1 , 1 ) ; Count the pair ( 0 , 1 ) ; Number of ways to calculate the different bitwise OR ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void differentBitwiseOR ( string s1 , string s2 ) { int n = s1 . size ( ) ; int t00 = 0 , t10 = 0 , t01 = 0 , t11 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s1 [ i ] == '0' && s2 [ i ] == '0' ) { t00 ++ ; } if ( s1 [ i ] == '1' && s2 [ i ] == '0' ) { t10 ++ ; } if ( s1 [ i ] == '1' && s2 [ i ] == '1' ) { t11 ++ ; } if ( s1 [ i ] == '0' && s2 [ i ] == '1' ) { t01 ++ ; } } int ans = t00 * t10 + t01 * t10 + t00 * t11 ; cout << ans ; } int main ( ) { string S1 = "01001" ; string S2 = "11011" ; differentBitwiseOR ( S1 , S2 ) ; return 0 ; }
Flip all 0 s in given Binary Strings K times with different neighbours | C ++ program for the above approach ; Function to modify the given string K number of times by flipping 0 s having different adjacent characters ; Size of the string ; Stores modified string after each iteration ; Iterate over the range [ 0 k ] ; Traverse the string S ; If '0' is present at 0 th index then replace it with 1 st index ; If '0' is present at the last index then replace it with last index - 1 character ; Otherwise , convert 0 s to 1 if the adjacent characters are different ; If during this iteration there is no change in the string then break this loop ; Update the string S ; Print the updated string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void convertString ( string S , int k ) { int n = S . length ( ) ; string temp = S ; for ( int i = 0 ; i < k ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( j == 0 && S [ j ] == '0' ) { temp [ j ] = S [ j + 1 ] ; } else if ( j == n - 1 && S [ j ] == '0' ) { temp [ j ] = S [ j - 1 ] ; } else if ( S [ j - 1 ] != S [ j + 1 ] && S [ j ] == '0' ) { temp [ j ] = '1' ; } } if ( S == temp ) { break ; } S = temp ; } cout << S ; } int main ( ) { string S = "10010001" ; int K = 1 ; convertString ( S , K ) ; return 0 ; }
Minimum number of removals required such that no subsequence of length 2 occurs more than once | C ++ program for the above approach ; Function to remove the minimum count of characters from the string such that no subsequence of length 2 repeats ; Initialize the final string ; Stores if any character occurs in the final string or not ; Store the index of the last character added in the string ; Traverse the string ; Add all the unique characters ; Check if S [ 0 ] appears in the range [ pos + 1 , N - 1 ] ; If the characters are the same ; Print the resultant string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void RemoveCharacters ( string s ) { string ans = " " ; bool c [ 26 ] ; for ( int i = 0 ; i < 26 ; i ++ ) c [ i ] = 0 ; int pos = 0 ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { if ( c [ s [ i ] - ' a ' ] == 0 ) { c [ s [ i ] - ' a ' ] = 1 ; pos = i ; ans += s [ i ] ; } } for ( int i = pos + 1 ; i < ( int ) s . size ( ) ; i ++ ) { if ( s [ i ] == s [ 0 ] ) { ans += s [ i ] ; break ; } } cout << ans ; } int main ( ) { string S = " abcaadbcd " ; RemoveCharacters ( S ) ; return 0 ; }
Check if a numeric string can be split into substrings having difference between consecutive numbers equal to K | C ++ program for the above approach ; Function to check if a numeric string can be split into substrings such that the difference between the consecutive substrings is K ; Stores the size of the string ; Iterate over the range [ 1 , N ] and try each possible starting number ; Convert the number to string ; Build up a sequence starting with the number ; Compare it with the original string s ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void isPossible ( string s , int K ) { bool valid = false ; long firstx = -1 ; int n = s . length ( ) ; for ( int i = 1 ; i <= n / 2 ; ++ i ) { long x = stol ( s . substr ( 0 , i ) ) ; firstx = x ; string test = to_string ( x ) ; while ( test . length ( ) < s . length ( ) ) { x -= K ; test += to_string ( x ) ; } if ( test == s ) { valid = true ; break ; } } cout << ( ( valid == true ) ? " Yes ▁ " : " No " ) ; } int main ( ) { string S = "8642" ; int K = 2 ; isPossible ( S , K ) ; return 0 ; }
Convert given Binary string S to all 1 s by changing all 0 s to 1 s in range [ i + 1 , i + K ] if S [ i ] is 1 | C ++ program for the above approach ; Function to check whether all 0 s in the string can be changed into 1 s ; Store the count of 0 s converted for the last occurrence of 1 ; Declere a stack ; Traverse the string , S ; If stack is empty ; There is no 1 that can change this 0 to 1 ; Push 1 into the stack ; The last 1 has reached its limit ; New 1 has been found which can now change at most K 0 s ; If flag is 1 , print " YES " else print " NO " ; Driver code ; Given Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void changeCharacters ( string S , int N , int K ) { int flag = 1 ; int count = 0 ; stack < char > st ; for ( int i = 0 ; i < N ; i ++ ) { if ( st . empty ( ) ) { if ( S [ i ] == '0' ) { flag = 0 ; break ; } count = 0 ; st . push ( S [ i ] ) ; } else { if ( S [ i ] == '0' ) { count ++ ; if ( count == K ) { st . pop ( ) ; count = 0 ; } } else { count = 0 ; } } } if ( flag ) cout << " YES " << endl ; else cout << " NO " << endl ; } int main ( ) { string S = "100100" ; int N = S . length ( ) ; int K = 2 ; changeCharacters ( S , N , K ) ; return 0 ; }
Check if all prefixes of a number is divisible by remaining count of digits | C ++ program for the above approach ; Function to check if all prefixes of a number is divisible by remaining count of digits or not ; Traverse and check divisibility for each updated number ; Update the original number ; Driver Code ; Given Input ; Function Call
#include <iostream> NEW_LINE using namespace std ; bool prefixDivisble ( int n ) { int i = 1 ; while ( n > 0 ) { if ( n % i != 0 ) return false ; n = n / 10 ; i ++ ; } return true ; } int main ( ) { int n = 52248 ; if ( prefixDivisble ( n ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; }
Length of the longest substring that contains even number of vowels | C ++ program for the above approach ; Function to find the length of the longest substring having even number of vowels ; Create two hashmaps ; Keep the track of frequencies of the vowels ; Stores the maximum length ; Traverse the given string S ; Find character in the map ; If it is a vowel , then update the frequency ; Find the index of occurence of the string evenOdd in map ; Update the maximum length ; Print the maximum length ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longestSubstring ( string s ) { unordered_map < string , int > indexes ; unordered_map < char , int > chars ( { { ' a ' , 0 } , { ' e ' , 1 } , { ' i ' , 2 } , { ' o ' , 3 } , { ' u ' , 4 } } ) ; string evenOdd = "00000" ; indexes [ evenOdd ] = -1 ; int length = 0 ; for ( int i = 0 ; i < s . size ( ) ; ++ i ) { char c = s [ i ] ; auto it = chars . find ( c ) ; if ( it != chars . end ( ) ) { evenOdd [ it -> second ] = evenOdd [ it -> second ] == '0' ? '1' : '0' ; } auto lastIndex = indexes . find ( evenOdd ) ; if ( lastIndex == indexes . end ( ) ) { indexes [ evenOdd ] = i ; } else { length = max ( length , i - lastIndex -> second ) ; } } cout << length ; } int main ( ) { string S = " bcbcbc " ; longestSubstring ( S ) ; return 0 ; }
Minimum number whose binary form is not a subsequence of given binary string | C ++ program for the above approach ; Function to check if string str1 is a subsequence of string str2 ; Store index of str1 ; Traverse str2 and str1 , and compare current character of str2 with first unmatched char of str1 ; If matched , move ahead in str1 ; If all characters of str1 were found in str2 ; Function to find the minimum number which is not a subsequence of the given binary string in its binary form ; Store the decimal number of string , S ; Initialize the required result ; Iterate in the range [ 0 , R ] ; Convert integer i to binary string ; Check if the string is not a subsequence ; Update ans and break ; Print the required result ; Driver Code ; Function Call ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isSubsequence ( string str1 , string str2 , int m , int n ) { int j = 0 ; for ( int i = 0 ; i < n && j < m ; i ++ ) if ( str1 [ j ] == str2 [ i ] ) j ++ ; return ( j == m ) ; } void findMinimumNumber ( string s ) { int r = stoi ( s , 0 , 2 ) ; int ans = r + 1 ; for ( int i = 0 ; i <= r ; i ++ ) { string p = " " ; int j = i ; while ( j > 0 ) { p += to_string ( j % 2 ) ; j = j / 2 ; } int m = p . length ( ) ; int n = s . length ( ) ; reverse ( p . begin ( ) , p . end ( ) ) ; if ( ! isSubsequence ( p , s , m , n ) ) { ans = i ; break ; } } cout << ans ; } int main ( ) { string s = "10101" ; findMinimumNumber ( s ) ; return 0 ; }
Minimize cost to make all characters of a Binary String equal to '1' by reversing or flipping characters of substrings | C ++ program for the above approach ; Function to calculate minimum cost to convert all the characters of S to '1' ; Stores the result ; Stores the number of groups that have 0 as characters ; Traverse the string S ; If current character is '0' ; If count is greater than 0 ; Set the count to 0 ; If the last few consecutive characters are '0' ; If string contains all characters as '1' ; Minimum Cost ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void MinimumCost ( string S , int A , int B ) { int count = 0 ; int group = 0 ; for ( int i = 0 ; i < S . size ( ) ; i ++ ) { if ( S [ i ] == '0' ) { count += 1 ; } else { if ( count > 0 ) { group += 1 ; } count = 0 ; } } if ( count > 0 ) group += 1 ; if ( group == 0 ) { cout << 0 << endl ; } else { cout << min ( A , B ) * ( group - 1 ) + B ; } } int main ( ) { int A = 1 ; int B = 5 ; string S = "01100" ; MinimumCost ( S , A , B ) ; return 0 ; }
Largest Prime Number possible from a subsequence of a Binary String | C ++ Program to implement the above approach ; Function to check if a number is prime or not ; Return not prime ; If prime return true ; Function to find the largest prime number possible from a subsequence ; Stores pairs of subsequences and their respective decimal value ; Stores the answer ; Traverse the string ; Stores the size of the vector ; Traverse the vector ; Extract the current pair ; Get the binary string from the pair ; Stores equivalent decimal values ; If the current character is '1' ; Add the character to the subsequence ; Update the value by left shifting the current value and adding 1 to it ; If s [ i ] = = '0' ; Add the character to the subsequence ; Update the value by left shifting the current value and adding 0 to it ; Store the subsequence in the vector ; Check if the decimal representation of current subsequence is prime or not ; If prime ; Update the answer with the largest one ; If no prime number could be obtained ; Driver Code ; Input String
#include <iostream> NEW_LINE #include <vector> NEW_LINE using namespace std ; bool isPrime ( int x ) { if ( x <= 1 ) return false ; for ( int i = 2 ; i * i <= x ; i ++ ) { if ( x % i == 0 ) return false ; } return true ; } void largestPrime ( string s ) { vector < pair < string , int > > vec { { " " , 0 } } ; int ans = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int n = vec . size ( ) ; for ( int j = 0 ; j < n ; j ++ ) { pair < string , int > temp = vec [ j ] ; string str = temp . first ; int val = temp . second ; if ( s [ i ] == '1' ) { temp . first = str + '1' ; temp . second = ( ( val << 1 ) + 1 ) ; } else { temp . first = str + '0' ; temp . second = ( ( val << 1 ) + 0 ) ; } vec . push_back ( temp ) ; int check = temp . second ; if ( isPrime ( check ) ) { ans = max ( ans , check ) ; } } } if ( ans == 0 ) cout << -1 << endl ; else cout << ans << endl ; } int main ( ) { string s = "110" ; largestPrime ( s ) ; return 0 ; }
Count strings having sum of ASCII values of characters equal to a Prime or Armstrong Number | C ++ program for the above approach ; Function to check if a number is prime number ; Define a flag variable ; Check for factors of num ; If factor is found , set flag to True and break out of loop ; Check if flag is True ; Function to calculate order of the number x ; Function to check whether the given number is Armstrong number or not ; If the condition satisfies ; Function to count Armstrong valued strings ; Stores the count of Armstrong valued strings ; Iterate over the list ; Store the value of the string ; Find value of the string ; Check if it an Armstrong number ; Function to count prime valued strings ; Store the count of prime valued strings ; Iterate over the list ; Store the value of the string ; Find value of the string ; Check if it is a Prime Number ; Driver code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int num ) { bool flag = false ; if ( num > 1 ) { for ( int i = 2 ; i < num ; i ++ ) { if ( ( num % i ) == 0 ) { flag = true ; break ; } } } if ( flag ) return false ; else return true ; } int order ( int x ) { int n = 0 ; while ( x != 0 ) { n = n + 1 ; x = x / 10 ; } return n ; } bool isArmstrong ( int x ) { int n = order ( x ) ; int temp = x ; int sum1 = 0 ; while ( temp != 0 ) { int r = temp % 10 ; sum1 = sum1 + pow ( r , n ) ; temp = temp / 10 ; } return ( sum1 == x ) ; } int count_armstrong ( vector < string > li ) { int c = 0 ; for ( string ele : li ) { int val = 0 ; for ( char che : ele ) val += che ; if ( isArmstrong ( val ) ) c += 1 ; } return c ; } int count_prime ( vector < string > li ) { int c = 0 ; for ( string ele : li ) { int val = 0 ; for ( char che : ele ) val += che ; if ( isPrime ( val ) ) c += 1 ; } return c ; } int main ( ) { vector < string > arr = { " geeksforgeeks " , " a " , " computer " , " science " , " portal " , " for " , " geeks " } ; cout << " Number ▁ of ▁ Armstrong ▁ Strings ▁ are : ▁ " << count_armstrong ( arr ) << endl ; cout << " Number ▁ of ▁ Prime ▁ Strings ▁ are : ▁ " << count_prime ( arr ) << endl ; }
Minimize cost of flipping or swaps to make a Binary String balanced | C ++ program for the above approach ; Function to find the minimum cost to convert the given string into balanced string ; Stores count of 1 ' s ▁ and ▁ 0' s in the string ; Traverse the string ; Increment count1 ; Increment count 0 ; Stores absolute difference of counts of 0 ' s ▁ and ▁ 1' s ; If string consists of only 0 ' s ▁ and ▁ 1' s ; Print minimum cost ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMinimumCost ( string s , int N ) { int count_1 = 0 , count_0 = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( s [ i ] == '1' ) count_1 ++ ; else count_0 ++ ; } int k = abs ( count_0 - count_1 ) ; if ( count_1 == N count_0 == N ) cout << -1 << endl ; else cout << k / 2 << endl ; } int main ( ) { string S = "110110" ; int N = S . length ( ) ; findMinimumCost ( S , N ) ; return 0 ; }
Minimum time required to complete all tasks with alteration of their order allowed | C ++ program for the above approach ; Function to find the minimum time required to complete the tasks if the order of tasks can be changed ; If there is no task , print 0 ; Store the maximum occurring character and its frequency ; Stores the frequency of each character ; Traverse the string S ; Increment the frequency of the current character ; Update maxfreq and maxchar ; Store the number of empty slots ; Traverse the hashmap , um ; Fill the empty slots ; Store the required result ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMinimumTime ( string & S , int N , int K ) { if ( N == 0 ) { cout << 0 ; return ; } int maxfreq = INT_MIN ; char maxchar ; unordered_map < char , int > um ; for ( int i = 0 ; i < N ; i ++ ) { um [ S [ i ] ] ++ ; if ( um [ S [ i ] ] > maxfreq ) { maxfreq = um [ S [ i ] ] ; maxchar = S [ i ] ; } } int emptySlots = ( maxfreq - 1 ) * K ; for ( auto & it : um ) { if ( it . first == maxchar ) continue ; emptySlots -= min ( it . second , maxfreq - 1 ) ; } int ans = N + max ( 0 , emptySlots ) ; cout << ans ; } int main ( ) { string S = " AAABBB " ; int K = 2 ; int N = S . length ( ) ; findMinimumTime ( S , N , K ) ; return 0 ; }
Check if all characters of a string can be made equal by increments or decrements | C ++ program for the above approach ; Function to check if it is possible to make all characters of string S same or not ; Length of string ; Stores the sum of ASCII value ; Traverse the string S ; Update the weightOfString ; If the sum is divisible by N then print " Yes " ; Otherwise print " No " ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void canMakeEqual ( string S ) { int N = S . size ( ) ; int weightOfString = 0 ; for ( int i = 0 ; i < N ; i ++ ) { weightOfString += S [ i ] - ' a ' + 1 ; } if ( weightOfString % N == 0 ) cout << " Yes " ; else cout << " No " ; } int main ( ) { string S = " beb " ; canMakeEqual ( S ) ; return 0 ; }
Modify a string by circularly shifting each character to the right by respective frequencies | C ++ program for the above approach ; Function to replace the characters by its frequency of character in it ; Stores frequencies of characters in the string S ; Traverse the string S ; Increment the frequency of each character by 1 ; Traverse the string S ; Find the frequency of the current character ; Update the character ; Print the resultant string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void addFrequencyToCharacter ( string S ) { int frequency [ 26 ] = { 0 } ; int N = S . length ( ) ; for ( int i = 0 ; i < N ; i ++ ) { frequency [ S [ i ] - ' a ' ] += 1 ; } for ( int i = 0 ; i < N ; i ++ ) { int add = frequency [ S [ i ] - ' a ' ] % 26 ; if ( int ( S [ i ] ) + add <= int ( ' z ' ) ) S [ i ] = char ( int ( S [ i ] ) + add ) ; else { add = ( int ( S [ i ] ) + add ) - ( int ( ' z ' ) ) ; S [ i ] = char ( int ( ' a ' ) + add - 1 ) ; } } cout << S ; } int main ( ) { string S = " geeksforgeeks " ; addFrequencyToCharacter ( S ) ; return 0 ; }
Minimize length of a string by removing pairs of consecutive increasing or decreasing digits | C ++ program for the above approach ; Function to find the minimum length of the string possible after removing pairs of consecutive digits ; Initialize the stack st ; Traverse the string S ; If the stack is empty ; Otherwise ; Get the top character of the stack ; If cha and top are consecutive digits ; Otherwise , push the character ch ; Print the size of the stack ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minLength ( string S ) { stack < char > st ; for ( auto ch : S ) { if ( st . empty ( ) ) st . push ( ch ) ; else { char top = st . top ( ) ; if ( abs ( ch - top ) == 1 ) st . pop ( ) ; else { st . push ( ch ) ; } } } return st . size ( ) ; } int main ( ) { string S = "12213" ; cout << minLength ( S ) ; return 0 ; }
Minimum time required to complete all tasks without altering their order | C ++ implementation of the above approach ; Function to find the minimum time required to complete tasks without changing their order ; Keeps track of the last time instant of each task ; Stores the required result ; Traverse the given string ; Check last time instant of task , if it exists before ; Increment the time if task is within the K units of time ; Update the time of the current task in the map ; Increment the time by 1 ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMinimumTime ( string tasks , int K ) { unordered_map < char , int > map ; int curr_time = 0 ; for ( char c : tasks ) { if ( map . find ( c ) != map . end ( ) ) { if ( curr_time - map <= K ) { curr_time += K - ( curr_time - map ) + 1 ; } } map = curr_time ; curr_time ++ ; } cout << curr_time ; } int main ( ) { string S = " ABACCA " ; int K = 2 ; findMinimumTime ( S , K ) ; return 0 ; }
Check if a string is a subsequence of another string ( using Stacks ) | C ++ Program for the above approach ; Function to check if target is a subsequence of string S ; Declare a stack ; Push the characters of target into the stack ; Traverse the string S in reverse ; If the stack is empty ; if S [ i ] is same as the top of the stack ; Pop the top of stack ; Stack s is empty ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void checkforSubsequence ( string S , string target ) { stack < char > s ; for ( int i = 0 ; i < target . size ( ) ; i ++ ) { s . push ( target [ i ] ) ; } for ( int i = ( int ) S . size ( ) - 1 ; i >= 0 ; i -- ) { if ( s . empty ( ) ) { cout << " Yes " << endl ; return ; } if ( S [ i ] == s . top ( ) ) { s . pop ( ) ; } } if ( s . empty ( ) ) cout << " Yes " << endl ; else cout << " No " << endl ; } int main ( ) { string S = " KOTTAYAM " ; string target = " KOTA " ; checkforSubsequence ( S , target ) ; return 0 ; }
Program to construct a DFA to check if a given integer is unsigned or not | C ++ program for the above approach ; Function to construct DFA as per the given conditions ; If at state 0 and a digit has occurred then set it to state 1 ; Similarly for all other states ; Function to build and connect the DFA states ; Connect all the states to the dead state ; Function call to make DFA as per the given conditions ; Function call to check whether an integer in the form of string is unsigned integer or not ; Build the DFA ; Stores the current state ; Traverse the string ; If at a certain state a digit occurs then change the current state according to the DFA ; Or + / - sign ; Or decimal occurred ; Or any other character ; Or e / E or exponent sign ; State 1 , 4 , 8 will give the final answer ; Driver Code
#include " bits / stdc + + . h " NEW_LINE using namespace std ; string digits = "0123456789" , sign = " + - " ; string dot = " . " , ex = " eE " ; int dfa [ 11 ] [ 5 ] ; void makeDFA ( ) { dfa [ 0 ] [ 0 ] = 1 ; dfa [ 1 ] [ 0 ] = 1 ; dfa [ 1 ] [ 2 ] = 3 ; dfa [ 1 ] [ 3 ] = 2 ; dfa [ 1 ] [ 4 ] = 6 ; dfa [ 3 ] [ 0 ] = 4 ; dfa [ 4 ] [ 0 ] = 4 ; dfa [ 4 ] [ 3 ] = 5 ; dfa [ 4 ] [ 4 ] = 6 ; dfa [ 6 ] [ 0 ] = 8 ; dfa [ 6 ] [ 1 ] = 7 ; dfa [ 7 ] [ 0 ] = 8 ; dfa [ 8 ] [ 0 ] = 8 ; dfa [ 8 ] [ 3 ] = 9 ; } void buildDFA ( ) { for ( int i = 0 ; i < 11 ; i ++ ) for ( int j = 0 ; j < 5 ; j ++ ) dfa [ i ] [ j ] = 10 ; makeDFA ( ) ; } void checkDFA ( string s ) { buildDFA ( ) ; int currentstate = 0 ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { if ( digits . find ( s [ i ] ) != digits . npos ) currentstate = dfa [ currentstate ] [ 0 ] ; else if ( sign . find ( s [ i ] ) != sign . npos ) currentstate = dfa [ currentstate ] [ 1 ] ; else if ( dot . find ( s [ i ] ) != dot . npos ) currentstate = dfa [ currentstate ] [ 2 ] ; else if ( ex . find ( s [ i ] ) != ex . npos ) currentstate = dfa [ currentstate ] [ 4 ] ; else currentstate = dfa [ currentstate ] [ 3 ] ; } if ( currentstate == 1 currentstate == 4 currentstate == 8 ) { cout << " Unsigned ▁ integer " ; } else { cout << " Not ▁ an ▁ unsigned ▁ integer " ; } } int main ( ) { string S = "1729" ; checkDFA ( S ) ; return 0 ; }
Convert a Mobile Numeric Keypad sequence to equivalent sentence | C ++ program for the above approach ; Function to convert mobile numeric keypad sequence into its equivalent string ; Store the mobile keypad mappings ; Traverse the string str ; If the current character is ' . ' , then continue to the next iteration ; Stores the number of continuous clicks ; Iterate a loop to find the count of same characters ; 2 , 3 , 4 , 5 , 6 and 8 keys will have maximum of 3 letters ; 7 and 9 keys will have maximum of 4 keys ; Handle the end condition ; Check if the current pressed key is 7 or 9 ; Else , the key pressed is either 2 , 3 , 4 , 5 , 6 or 8 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printSentence ( string str ) { char nums [ ] [ 5 ] = { " " , " " , " ABC " , " DEF " , " GHI " , " JKL " , " MNO " , " PQRS " , " TUV " , " WXYZ " } ; int i = 0 ; while ( str [ i ] != ' \0' ) { if ( str [ i ] == ' . ' ) { i ++ ; continue ; } int count = 0 ; while ( str [ i + 1 ] && str [ i ] == str [ i + 1 ] ) { if ( count == 2 && ( ( str [ i ] >= '2' && str [ i ] <= '6' ) || ( str [ i ] == '8' ) ) ) break ; else if ( count == 3 && ( str [ i ] == '7' str [ i ] == '9' ) ) break ; count ++ ; i ++ ; if ( str [ i ] == ' \0' ) break ; } if ( str [ i ] == '7' str [ i ] == '9' ) { cout << nums [ str [ i ] - 48 ] [ count % 4 ] ; } else { cout << nums [ str [ i ] - 48 ] [ count % 3 ] ; } i ++ ; } } int main ( ) { string str = "234" ; printSentence ( str ) ; return 0 ; }
Lexicographically largest string with sum of characters equal to N | C ++ program for the above approach ; Function to construct the lexicographically largest string having sum of characters as N ; Stores the resulting string ; Iterate until N is at least 26 ; Append ' z ' to the string ans ; Decrement N by 26 ; Append character at index ( N + ' a ' ) ; Return the resultant string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string getString ( int N ) { string ans = " " ; while ( N >= 26 ) { ans += ' z ' ; N -= 26 ; } ans += char ( N + ' a ' - 1 ) ; return ans ; } int main ( ) { int N = 30 ; cout << getString ( N ) ; return 0 ; }
Length of all prefixes that are also the suffixes of given string | C ++ program for the above approach ; Function to find the length of all prefixes of the given string that are also suffixes of the same string ; Stores the prefix string ; Traverse the string S ; Add the current character to the prefix string ; Store the suffix string ; Check if both the strings are equal or not ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countSamePrefixSuffix ( string s , int n ) { string prefix = " " ; for ( int i = 0 ; i < n - 1 ; i ++ ) { prefix += s [ i ] ; string suffix = s . substr ( n - 1 - i , n - 1 ) ; if ( prefix == suffix ) { cout << prefix . size ( ) << " ▁ " ; } } } int main ( ) { string S = " ababababab " ; int N = S . size ( ) ; countSamePrefixSuffix ( S , N ) ; return 0 ; }
Count new pairs of strings that can be obtained by swapping first characters of pairs of strings from given array | C ++ program for the above approach ; Function to count newly created pairs by swapping the first characters of any pairs of strings ; Stores the count all possible pair of strings ; Push all the strings into the Unordered Map ; Generate all possible pairs of strings from the array arr [ ] ; Store the current pair of strings ; Swap the first character ; Check if both string are not present in map ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countStringPairs ( string a [ ] , int n ) { int ans = 0 ; unordered_map < string , int > s ; for ( int i = 0 ; i < n ; i ++ ) { s [ a [ i ] ] ++ ; } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { string p = a [ i ] ; string q = a [ j ] ; if ( p [ 0 ] != q [ 0 ] ) { swap ( p [ 0 ] , q [ 0 ] ) ; if ( s . find ( p ) == s . end ( ) && s . find ( q ) == s . end ( ) ) { ans ++ ; } } } } cout << ans ; } int main ( ) { string arr [ ] = { " good " , " bad " , " food " } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countStringPairs ( arr , N ) ; return 0 ; }
Check if it is possible to obtain a Balanced Parenthesis by shifting brackets to either end at most K times | C ++ program for the above approach ; Function to check if a valid parenthesis can be obtained by moving characters to either end at most K number of times ; Base Case 1 ; Count of ' ( ' and ' ) ' ; Base Case 2 ; Store the count of moves required to make a valid parenthesis ; Traverse the string ; Increment cnt if opening bracket has occurred ; Otherwise , decrement cnt by 1 ; Decrement cnt by 1 ; If cnt is negative ; Update the cnt ; Increment the ans ; If ans is at most K , then print Yes . Otherwise print No ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumMoves ( string s , int n , int k ) { if ( n & 1 ) { cout << " No " ; return ; } int countOpen = count ( s . begin ( ) , s . end ( ) , ' ( ' ) ; int countClose = count ( s . begin ( ) , s . end ( ) , ' ) ' ) ; if ( countOpen != countClose ) { cout << " No " ; return ; } int ans = 0 ; int cnt = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( s [ i ] == ' ( ' ) ++ cnt ; else { -- cnt ; if ( cnt < 0 ) { cnt = 0 ; ++ ans ; } } } if ( ans <= k ) cout << " Yes " ; else cout << " No " ; } int main ( ) { string S = " ) ( " ; int K = 1 ; minimumMoves ( S , S . length ( ) , K ) ; return 0 ; }
Generate a random Binary String of length N | C ++ program for the above approach ; Function to find a random number between 0 or 1 ; Generate the random number ; Return the generated number ; Function to generate a random binary string of length N ; Stores the empty string ; Iterate over the range [ 0 , N - 1 ] ; Store the random number ; Append it to the string ; Print the resulting string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findRandom ( ) { int num = ( ( int ) rand ( ) % 2 ) ; return num ; } void generateBinaryString ( int N ) { srand ( time ( NULL ) ) ; string S = " " ; for ( int i = 0 ; i < N ; i ++ ) { int x = findRandom ( ) ; S += to_string ( x ) ; } cout << S ; } int main ( ) { int N = 7 ; generateBinaryString ( N ) ; return 0 ; }
Partition a string into palindromic strings of at least length 2 with every character present in a single string | C ++ program for the above approach ; Function to check if a string can be split into palindromic strings of at least length 2 by including every character exactly once ; Stores the frequency of each character ; Store the frequency of characters with frequencies 1 and even respectively ; Traverse the string s ; Iterate over all the characters ; If the frequency is 1 ; If frequency is even ; Print the result ; Stores the number of characters with frequency equal to 1 that are not part of a palindromic string ; Iterate over all the characters ; If o becomes less than 0 , then break out of the loop ; If frequency of the current character is > 2 and is odd ; Update the value of o ; If a single character is still remaining ; Increment o by 1 ; Set a [ i ] to 1 ; Print the result ; Driver Code
#include <iostream> NEW_LINE using namespace std ; void checkPalindrome ( string & s ) { int a [ 26 ] = { 0 } ; int o = 0 , e = 0 ; for ( int i = 0 ; s [ i ] != ' \0' ; i ++ ) a [ ( int ) s [ i ] - 97 ] ++ ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( a [ i ] == 1 ) o ++ ; else if ( a [ i ] % 2 == 0 and a [ i ] != 0 ) e += ( a [ i ] / 2 ) ; } if ( e >= o ) cout << " Yes " ; else { o = o - e ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( o <= 0 ) break ; if ( o > 0 and a [ i ] % 2 == 1 and a [ i ] > 2 ) { int k = o ; o = o - a [ i ] / 2 ; if ( o > 0 or 2 * k + 1 == a [ i ] ) { o ++ ; a [ i ] = 1 ; } } } if ( o <= 0 ) cout << " Yes " ; else cout << " No " ; } } int main ( ) { string S = " abbbaddzcz " ; checkPalindrome ( S ) ; return 0 ; }
Maximize time by replacing ' _ ' in a given 24 Hour format time | C ++ program for the above approach ; Function to find the maximum time possible by replacing each ' _ ' with any digit ; If the first character is ' _ ' ; If s [ 1 ] is ' _ ' or s [ 1 ] is less than 4 ; Update s [ 0 ] as 2 ; Otherwise , update s [ 0 ] = 1 ; If s [ 1 ] is equal to ' _ ' ; If s [ 0 ] is equal to '2' ; Otherwise ; If S [ 3 ] is equal to ' _ ' ; If s [ 4 ] is equal to ' _ ' ; Return the modified string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string maximumTime ( string s ) { if ( s [ 0 ] == ' _ ' ) { if ( ( s [ 1 ] == ' _ ' ) || ( s [ 1 ] >= '0' && s [ 1 ] < '4' ) ) { s [ 0 ] = '2' ; } else { s [ 0 ] = '1' ; } } if ( s [ 1 ] == ' _ ' ) { if ( s [ 0 ] == '2' ) { s [ 1 ] = '3' ; } else { s [ 1 ] = '9' ; } } if ( s [ 3 ] == ' _ ' ) { s [ 3 ] = '5' ; } if ( s [ 4 ] == ' _ ' ) { s [ 4 ] = '9' ; } return s ; } int main ( ) { string S = "0 _ : 4 _ " ; cout << maximumTime ( S ) ; return 0 ; }
Count distinct emails present in a given array | C ++ program for the above approach ; Function to count all the distinct emails after preprocessing according to the given rules ; Traverse the given array of strings arr [ ] ; Stores the position of ' @ ' in the string ; If pos2 < x . size ( ) ; Erases all the occurrences of ' . ' before pos2 ; Stores the position of the first ' + ' ; Update the position pos2 ; If ' + ' exists then erase characters after ' + ' and before ' @ ' ; Insert all the updated strings inside the set ; Return the size of set ans ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int distinctEmails ( vector < string > & emails ) { for ( auto & x : emails ) { auto pos2 = x . find ( ' @ ' ) ; if ( pos2 < x . size ( ) ) x . erase ( remove ( x . begin ( ) , x . begin ( ) + pos2 , ' . ' ) , x . begin ( ) + pos2 ) ; auto pos1 = x . find ( ' + ' ) ; pos2 = x . find ( ' @ ' ) ; if ( pos1 < x . size ( ) and pos2 < x . size ( ) ) { x . erase ( pos1 , pos2 - pos1 ) ; } } unordered_set < string > ans ( emails . begin ( ) , emails . end ( ) ) ; return ans . size ( ) ; } int main ( ) { vector < string > arr = { " raghav . agg @ geeksforgeeks . com " , " raghavagg @ geeksforgeeks . com " } ; cout << distinctEmails ( arr ) ; return 0 ; }
Nearest power of 2 of frequencies of each digit of a given number | C ++ program for the above approach ; Function to find the nearest power of 2 for all frequencies in the Map freq ; Traverse the Map ; Calculate log of the current array element ; Find the nearest power of 2 for the current frequency ; Function to find nearest power of 2 for frequency of each digit of num ; Length of string ; Stores the frequency of each character in the string ; Traverse the string S ; Function call to generate nearest power of 2 for each frequency ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void nearestPowerOfTwoUtil ( unordered_map < char , int > & freq ) { for ( auto & it : freq ) { cout << it . first << " ▁ - > ▁ " ; int lg = log2 ( it . second ) ; int a = pow ( 2 , lg ) ; int b = pow ( 2 , lg + 1 ) ; if ( ( it . second - a ) < ( b - it . second ) ) { cout << a << endl ; } else { cout << b << endl ; } } } void nearestPowerOfTwo ( string & S ) { int N = S . size ( ) ; unordered_map < char , int > freq ; for ( int i = 0 ; i < N ; i ++ ) { freq [ S [ i ] ] ++ ; } nearestPowerOfTwoUtil ( freq ) ; } int main ( ) { string N = "16333331163" ; nearestPowerOfTwo ( N ) ; return 0 ; }
Smallest string divisible by two given strings | C ++ program for the above approach ; Function to calculate GCD of two numbers ; Function to calculate LCM of two numbers ; Function to find the smallest string which is divisible by strings S and T ; Store the length of both strings ; Store LCM of n and m ; Temporary strings to store concatenated strings ; Concatenate s1 ( l / n ) times ; Concatenate t1 ( l / m ) times ; If s1 and t1 are equal ; Otherwise , print - 1 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } int lcm ( int a , int b ) { return ( a / gcd ( a , b ) ) * b ; } void findSmallestString ( string s , string t ) { int n = s . length ( ) , m = t . length ( ) ; int l = lcm ( n , m ) ; string s1 = " " , t1 = " " ; for ( int i = 0 ; i < l / n ; i ++ ) { s1 += s ; } for ( int i = 0 ; i < l / m ; i ++ ) { t1 += t ; } if ( s1 == t1 ) cout << s1 ; else cout << -1 ; } int main ( ) { string S = " baba " , T = " ba " ; findSmallestString ( S , T ) ; return 0 ; }
Minimize removal of substring of 0 s to remove all occurrences of 0 s from a circular Binary String | C ++ program for the above approach ; Function to count minimum number of removal of consecutive 0 s required to make binary string consists only of 1 s ; Stores the count of removals ; Traverse the string S ; If the current character is '0' ; Traverse until consecutive characters are only '0' s ; If the binary string only contains 1 s , then return 1 ; If the first and the last characters are 0 ; Return the resultant count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minRemovals ( string str , int N ) { int ans = 0 ; bool X = false ; for ( int i = 0 ; i < N ; i ++ ) { if ( str [ i ] == '0' ) { ans ++ ; while ( str [ i ] == '0' ) { i ++ ; } } else { X = true ; } } if ( ! X ) return 1 ; if ( str [ 0 ] == '0' and str [ N - 1 ] == '0' ) { ans -- ; } return ans ; } int main ( ) { string S = "11010001" ; int N = S . size ( ) ; cout << minRemovals ( S , N ) ; return 0 ; }
Minimum removals required to place all 0 s before 1 s in a Binary String | C ++ program for the above approach ; Function to count minimum removals required to arrange all 0 s before 1 s ; Count the occurences of 0 in s ; Size of the string ; Stores the minimum number of removals required ; Iterate over each of the characters in the string s ; If the i - th character is found to be '0' ; Store the minimum of res and right_0 + left_1 in res ; Return the final result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumDeletions ( string s ) { int right_0 = count ( s . begin ( ) , s . end ( ) , '0' ) ; int left_1 = 0 ; int n = s . size ( ) ; int res = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == '0' ) { right_0 -= 1 ; } else { left_1 += 1 ; } res = min ( res , right_0 + left_1 ) ; } return res ; } int main ( ) { string s = "001101" ; int count = minimumDeletions ( s ) ; cout << count ; return 0 ; }
Minimum substring flips required to convert a Binary String to another | C ++ program for the above approach ; Function to count the minimum number of reversals required to make the given binary strings s1 and s2 same ; Stores the minimum count of reversal of substrings required ; If the length of the strings are not the same then return - 1 ; Iterate over each character ; If s1 [ i ] is not equal to s2 [ i ] ; Iterate until s1 [ i ] != s2 [ i ] ; Increment answer by 1 ; Return the resultant count of reversal of substring required ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int canMakeSame ( string s1 , string s2 ) { int ans = 0 ; if ( s1 . size ( ) != s2 . size ( ) ) { return -1 ; } int N = s1 . length ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( s1 [ i ] != s2 [ i ] ) { while ( i < s1 . length ( ) && s1 [ i ] != s2 [ i ] ) { i ++ ; } ans ++ ; } } return ans ; } int main ( ) { string S1 = "100001" ; string S2 = "110111" ; cout << canMakeSame ( S1 , S2 ) ; return 0 ; }
Count intervals that intersects with a given meeting time | C ++ implementation of the above approach ; Function to convert a time in 24 hour format to an equivalent integer ; Removes " : " at 3 rd position ; Calculate hours ; Stores the time in 24 hours format ; If time is in " AM " ; If hh is equal to 12 ; If time is in " PM " ; If hh is equal to 12 ; Return time ; Function to count number of intervals in which p lies ; Stores the count ; Stores the integer value of 24 hours time format of P ; Traverse the array ; Stores the integer value of 24 hours time format of arr [ i ] [ 0 ] ; Stores the integer value of 24 hours time format of arr [ i ] [ 1 ] ; If M lies within the [ L , R ] ; Increment ans by 1 ; Return ans ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int convert ( string str ) { str . replace ( 2 , 1 , " " ) ; int h1 = ( int ) str [ 1 ] - '0' ; int h2 = ( int ) str [ 0 ] - '0' ; int hh = ( h2 * 10 + h1 % 10 ) ; int time = 0 ; if ( str [ 5 ] == ' A ' ) { if ( hh == 12 ) time += stoi ( str . substr ( 2 , 2 ) ) ; else { time += stoi ( str . substr ( 0 , 2 ) ) ; } } else { if ( hh == 12 ) { time += stoi ( str . substr ( 0 , 4 ) ) ; } else { time += stoi ( str . substr ( 0 , 4 ) ) ; time += 1200 ; } } return time ; } int countOverlap ( string arr [ ] [ 2 ] , int n , string p ) { int ans = 0 ; int M = convert ( p ) ; for ( int i = 0 ; i < n ; i ++ ) { int L = convert ( arr [ i ] [ 0 ] ) ; int R = convert ( arr [ i ] [ 1 ] ) ; if ( ( L <= M && M <= R ) || ( M >= R && M <= L ) ) ans ++ ; } return ans ; } int main ( ) { string arr [ ] [ 2 ] = { { "12:00 : AM " , "11:55 : PM " } , { "12:01 : AM " , "11:50 : AM " } , { "12:30 : AM " , "12:00 : PM " } , { "11:57 : AM " , "11:59 : PM " } } ; string P = "12:01 : PM " ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countOverlap ( arr , N , P ) << endl ; }
Count points which are revisited while following the path specified by a given string | C ++ program for the above approach ; Function to find the number of times already visited position is revisited after starting traversal from { X , Y } ; Stores the x and y temporarily ; Stores the number of times an already visited position is revisited ; Initialize hashset ; Insert the starting coordinates ; Traverse over the string ; Update the coordinates according to the current directions ; If the new { X , Y } has been visited before , then increment the count by 1 ; Otherwise ; Insert new { x , y } ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count ( string S , int X , int Y ) { int N = S . length ( ) ; int temp_x = 0 , temp_y = 0 ; int count = 0 ; set < pair < int , int > > s ; s . insert ( { X , Y } ) ; for ( int i = 0 ; i < N ; i ++ ) { temp_x = X ; temp_y = Y ; if ( S [ i ] == ' U ' ) { X ++ ; } else if ( S [ i ] == ' D ' ) { X -- ; } else if ( S [ i ] == ' R ' ) { Y ++ ; } else { Y -- ; } if ( s . find ( { temp_x + X , temp_y + Y } ) != s . end ( ) ) { count ++ ; } else { s . insert ( { temp_x + X , temp_y + Y } ) ; } } return count ; } int main ( ) { string S = " RDDUDL " ; int X = 0 , Y = 0 ; cout << count ( S , X , Y ) ; return 0 ; }
Sum of frequencies of characters of a string present in another string | C ++ program for the above approach ; Function to find sum of frequencies of characters of S1 present in S2 ; Insert all characters of string S1 in the set ; Traverse the string S2 ; Check if X is present in bset or not ; Increment count by 1 ; Finally , print the count ; Driver Code ; Given strings
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countTotalFrequencies ( string S1 , string S2 ) { set < char > bset ; for ( auto x : S1 ) bset . insert ( x ) ; int count = 0 ; for ( auto x : S2 ) { if ( bset . find ( x ) != bset . end ( ) ) count += 1 ; } cout << count << endl ; } int main ( ) { string S1 = " geEksFOR " ; string S2 = " GeEksforgeEKS " ; countTotalFrequencies ( S1 , S2 ) ; }
Check if characters of a string can be made non | C ++ program for the above approach ; Function to check if it 's possible to make the string s non decreasing ; Stores length of string ; Stores the last character that is not ' ? ' ; Traverse the string S ; If current character of the string is ' ? ' ; If s [ i ] is not ' ? ' and is less than C ; Otherwise ; Update C ; Return 1 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int nonDecreasing ( string s ) { int size = s . length ( ) ; char c = ' a ' ; for ( int i = 0 ; i < size ; i ++ ) { if ( s [ i ] == ' ? ' ) { continue ; } else if ( ( s [ i ] != ' ? ' ) && ( s [ i ] < c ) ) { return 0 ; } else { c = s [ i ] ; } } return 1 ; } int main ( ) { string S = " abb ? xy ? " ; if ( nonDecreasing ( S ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; }
Make a given Binary String non | C ++ program for the above approach ; Function to return the length of smallest subsequence required to be removed to make the given string non - decreasing ; Length of the string ; Count of zeros and ones ; Traverse the string ; Count minimum removals to obtain strings of the form "00000 . . . . " or "11111 . . . " ; Increment count ; Remove 1 s and remaining 0 s ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int min_length ( string str ) { int n = str . length ( ) ; int total_zeros = 0 ; int total_ones = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == '0' ) total_zeros ++ ; else total_ones ++ ; } int ans = min ( total_zeros , total_ones ) ; int cur_zeros = 0 , cur_ones = 0 ; for ( char x : str ) { if ( x == '0' ) cur_zeros ++ ; else cur_ones ++ ; ans = min ( ans , cur_ones + ( total_zeros - cur_zeros ) ) ; } cout << ans ; } int main ( ) { string str = "10011" ; min_length ( str ) ; return 0 ; }
Print all words occurring in a sentence exactly K times | CPP program for the above approach ; Function to print all the words occurring k times in a string ; Stores the words ; Traverse the list ; Check for count ; Print the word ; Remove from list ; Driver Code ; Given string ; Given value of K ; Function call to find all words occurring K times
#include <bits/stdc++.h> NEW_LINE using namespace std ; void kFreqWords ( string S , int K ) { string temp = " " ; vector < string > l ; for ( auto x : S ) { if ( x == ' ▁ ' ) { l . push_back ( temp ) ; temp = " " ; } else temp += x ; } for ( auto x : l ) { if ( count ( l . begin ( ) , l . end ( ) , x ) == K ) { cout << x << endl ; remove ( l . begin ( ) , l . end ( ) , x ) ; } } } int main ( ) { string S = " banana ▁ is ▁ in ▁ yellow ▁ and ▁ sun ▁ flower ▁ is ▁ also ▁ in ▁ yellow ▁ " ; int K = 2 ; kFreqWords ( S , K ) ; }
Check if substrings from three given strings can be concatenated to form a palindrome | C ++ program for the above approach ; Function to check if substrings from three given strings can be concatenated to form a palindrome ; Mask for S1 and S2 ; Set ( i - ' a ' ) th bit in maskA ; Set ( i - ' a ' ) th bit in maskC ; If the bitwise AND is > 0 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string make_palindrome ( string S1 , string S2 , string S3 ) { int maskA = 0 , maskC = 0 ; for ( char i : S1 ) maskA |= ( 1 << ( i - ' a ' ) ) ; for ( char i : S3 ) maskC |= ( 1 << ( i - ' a ' ) ) ; if ( ( maskA & maskC ) > 0 ) return " YES " ; return " NO " ; } int main ( ) { string S1 = " adcb " , S2 = " bcdb " , S3 = " abe " ; cout << make_palindrome ( S1 , S2 , S3 ) ; }
Length of longest prefix anagram which are common in given two strings | C ++ program for the above approach ; Function to check if two arrays are identical or not ; Iterate over the range [ 0 , SIZE ] ; If frequency any character is not same in both the strings ; Otherwise ; Function to find the maximum length of the required string ; Store the count of characters in string str1 ; Store the count of characters in string str2 ; Stores the maximum length ; Minimum length of str1 and str2 ; Increment the count of characters of str1 [ i ] in freq1 [ ] by one ; Increment the count of characters of str2 [ i ] in freq2 [ ] by one ; Checks if prefixes are anagram or not ; Finally print the ans ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define SIZE 26 NEW_LINE bool longHelper ( int freq1 [ ] , int freq2 [ ] ) { for ( int i = 0 ; i < SIZE ; ++ i ) { if ( freq1 [ i ] != freq2 [ i ] ) { return false ; } } return true ; } int longCommomPrefixAnagram ( string s1 , string s2 , int n1 , int n2 ) { int freq1 [ 26 ] = { 0 } ; int freq2 [ 26 ] = { 0 } ; int ans = 0 ; int mini_len = min ( n1 , n2 ) ; for ( int i = 0 ; i < mini_len ; ++ i ) { freq1 [ s1 [ i ] - ' a ' ] ++ ; freq2 [ s2 [ i ] - ' a ' ] ++ ; if ( longHelper ( freq1 , freq2 ) ) { ans = i + 1 ; } } cout << ans ; } int main ( ) { string str1 = " abaabcdezzwer " ; string str2 = " caaabbttyh " ; int N = str1 . length ( ) ; int M = str2 . length ( ) ; longCommomPrefixAnagram ( str1 , str2 , N , M ) ; return 0 ; }
Lexicographic rank of a Binary String | C ++ program for the above approach ; Function to find the rank of a string ; Store the length of the string ; Stores its equivalent decimal value ; Traverse the string ; Store the number of strings of length less than N occurring before the given string ; Store the decimal equivalent number of string bin ; Store the rank in answer ; Print the answer ; Driver program
#include <iostream> NEW_LINE using namespace std ; void findRank ( string s ) { int N = s . size ( ) ; string bin ; for ( int i = 0 ; i < N ; i ++ ) { if ( s [ i ] == '0' ) bin += "0" ; else bin += "1" ; } long long X = 1ll << N ; long long res = 0 , val = 1 ; for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( bin [ i ] == '1' ) res += ( val ) ; val *= 2ll ; } long long Y = res ; long ans = X + Y - 1 ; cout << ans ; } int main ( ) { string S = "001" ; findRank ( S ) ; return 0 ; }
Find the GCD of an array made up of numeric strings | CPP program for the above approach ; Recursive function to return gcd of A and B ; Base case ; Length of A is greater ; Calculate GCD ; Store the GCD of the length of the strings ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int GCD ( int lena , int lenb ) { if ( lena == 0 ) return lenb ; if ( lenb == 0 ) return lena ; if ( lena == lenb ) return lena ; if ( lena > lenb ) return GCD ( lena - lenb , lenb ) ; return GCD ( lena , lenb - lena ) ; } string StringGCD ( string a , string b ) { int gcd = GCD ( a . size ( ) , b . size ( ) ) ; if ( a . substr ( 0 , gcd ) == b . substr ( 0 , gcd ) ) { int x = ( ( int ) b . size ( ) / gcd ) ; int y = ( ( int ) a . size ( ) / gcd ) ; string r = " " , s = " " ; while ( x -- ) s += a ; while ( y -- ) r += b ; if ( s == r ) return a . substr ( 0 , gcd ) ; } return " - 1" ; } int main ( ) { string a = " geeksgeeks " ; string b = " geeks " ; cout << ( StringGCD ( a , b ) ) ; }
Calculate score of a string consisting of balanced parentheses | C ++ program to implement the above approach ; Function to calculate score of parentheses ; Stores index of character of string ; Stores total scores obtained from the string ; Iterate over characters of the string ; If s [ i ] is ' ( ' ; If top element of stack is ' ( ' ; Stores score of inner parentheses ; Calculate score of inner parentheses ; Update count ; Pop from stack ; Insert score of inner parentheses ; Update i ; Calculate score of the string ; Update ans ; Driver Code
#include <iostream> NEW_LINE #include <stack> NEW_LINE using namespace std ; long long scoreOfParentheses ( string S ) { stack < string > s ; int i = 0 ; long long ans = 0 ; while ( i < S . length ( ) ) { if ( S [ i ] == ' ( ' ) s . push ( " ( " ) ; else { if ( s . top ( ) == " ( " ) { s . pop ( ) ; s . push ( "1" ) ; } else { long long count = 0 ; while ( s . top ( ) != " ( " ) { count += stoi ( s . top ( ) ) ; s . pop ( ) ; } s . pop ( ) ; s . push ( to_string ( 2 * count ) ) ; } } i ++ ; } while ( ! s . empty ( ) ) { ans += stoi ( s . top ( ) ) ; s . pop ( ) ; } return ans ; } int main ( ) { string S1 = " ( ( ) ( ( ) ) ) " ; cout << scoreOfParentheses ( S1 ) << endl ; return 0 ; }
Minimize cost to rearrange substrings to convert a string to a Balanced Bracket Sequence | C ++ program for the above approach ; Function to count minimum number of operations to convert the string to a balanced bracket sequence ; Initialize the integer array ; Traverse the string ; Decrement a [ i ] ; Increment a [ i ] ; Update the sum as current value of arr [ i ] ; If answer exists ; Traverse from i ; Find all substrings with 0 sum ; Print the sum of sizes ; No answer exists ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countMinMoves ( string str ) { int n = str . size ( ) ; int a [ n ] = { 0 } ; int j , ans = 0 , i , sum = 0 ; for ( i = 0 ; i < n ; i ++ ) { if ( str [ i ] == ' ) ' ) { a [ i ] += sum - 1 ; } else { a [ i ] += sum + 1 ; } sum = a [ i ] ; } if ( sum == 0 ) { i = 1 ; while ( i < n ) { j = i - 1 ; while ( i < n && a [ i ] != 0 ) i ++ ; if ( i < n && a [ i - 1 ] < 0 ) { ans += i - j ; if ( j == 0 ) ans ++ ; } i ++ ; } cout << ans << endl ; } else cout << " - 1 STRNEWLINE " ; } int main ( ) { string str = " ) ( ( ) " ; countMinMoves ( str ) ; return 0 ; }
Check if a given string can be converted to a Balanced Bracket Sequence | C ++ program for the above approach ; Function to check if the string can be balanced by replacing the ' $ ' with opening or closing brackets ; If string can never be balanced ; Declare 2 stacks to check if all ) can be balanced with ( or $ and vice - versa ; Store the count the occurence of ( , ) and $ ; Traverse the string ; Increment closed bracket count by 1 ; If there are no opening bracket to match it then return false ; Otherwise , pop the character from the stack ; If current character is an opening bracket or $ , push it to the stack ; Increment symbol count by 1 ; Increment open bracket count by 1 ; Traverse the string from end and repeat the same process ; If there are no closing brackets to match it ; Otherwise , pop character from stack ; Store the extra ( or ) which are not balanced yet ; Check if $ is available to balance the extra brackets ; Count ramaining $ after balancing extra ( and ) ; Check if each pair of $ is convertable in ( ) ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool canBeBalanced ( string sequence ) { if ( sequence . size ( ) % 2 ) return false ; stack < char > stack_ , stack2_ ; int countOpen = 0 , countClosed = 0 ; int countSymbol = 0 ; for ( int i = 0 ; i < sequence . size ( ) ; i ++ ) { if ( sequence [ i ] == ' ) ' ) { countClosed ++ ; if ( stack_ . empty ( ) ) { return false ; } else { stack_ . pop ( ) ; } } else { if ( sequence [ i ] == ' $ ' ) { countSymbol ++ ; } else { countOpen ++ ; } stack_ . push ( sequence [ i ] ) ; } } for ( int i = sequence . size ( ) - 1 ; i >= 0 ; i -- ) { if ( sequence [ i ] == ' ( ' ) { if ( stack2_ . empty ( ) ) { return false ; } else { stack2_ . pop ( ) ; } } else { stack2_ . push ( sequence [ i ] ) ; } } int extra = abs ( countClosed - countOpen ) ; if ( countSymbol < extra ) { return false ; } else { countSymbol -= extra ; if ( countSymbol % 2 == 0 ) { return true ; } } return false ; } int main ( ) { string S = " ( ) ( $ " ; if ( canBeBalanced ( S ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; }
Queries to calculate difference between the frequencies of the most and least occurring characters in specified substring | C ++ program for the above approach ; Function to find difference between maximum and minimum frequency of a character in given range ; Stores length of string ; Stores count of queries ; Iterate over the characters of the string ; Stores l - value of a query ; Stores r - value of a query ; Store count of every character laying in range [ l , r ] ; Update frequency of current character ; Stores maximum frequency of characters in given range ; Stores minimum frequency of characters in given range ; Iterate over all possible characters of the given string ; Update mx ; If ( j + ' a ' ) is present ; difference between max and min ; Driver Code ; Given string ; Given queries ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxDiffFreq ( vector < pair < int , int > > queries , string S ) { int N = S . size ( ) ; int Q = queries . size ( ) ; for ( int i = 0 ; i < Q ; ++ i ) { int l = queries [ i ] . first - 1 ; int r = queries [ i ] . second - 1 ; int freq [ 26 ] = { 0 } ; for ( int j = l ; j <= r ; j ++ ) { freq [ S [ j ] - ' a ' ] ++ ; } int mx = 0 ; int mn = 99999999 ; for ( int j = 0 ; j < 26 ; j ++ ) { mx = max ( mx , freq [ j ] ) ; if ( freq [ j ] ) mn = min ( mn , freq [ j ] ) ; } cout << mx - mn << endl ; } } int main ( ) { string S = " abaabac " ; vector < pair < int , int > > queries { { 2 , 6 } , { 1 , 7 } } ; maxDiffFreq ( queries , S ) ; }
Count substrings consisting of equal number of a , b , c and d | C ++ program to implement the above approach ; Function to count the substring with equal number of a , b , c and d ; Stores relative frequency of the characters { ' a ' , ' b ' , ' c ' , ' d ' } ; Initially , frequencies of ' a ' , ' b ' , ' c ' and ' d ' are 0. ; Stores relative frequency of ' a ' ; Stores relative frequency of ' b ' ; Stores relative frequency of ' c ' ; Stores relative frequency of ' d ' ; Stores count of substring with equal number of ' a ' , ' b ' , ' c ' and ' d ' ; Iterate over the characters of the string ; If current character is ' a ' ; Update p ; Stores minimum of { p , q , r , s } ; Update p ; Update q ; Update r ; Update s ; If current character is b ; Update q ; Stores minimum of { p , q , r , s } ; Update p ; Update q ; Update r ; Update s ; Update r ; Stores minimum of { p , q , r , s } ; Update p ; Update q ; Update r ; Update s ; Update s ; Stores minimum of { p , q , r , s } ; Update p ; Update q ; Update r ; Update s ; Update relative frequency of { p , q , r , s } ; Traverse the map ; Stores count of relative frequency ; Update cntSub ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubstrings ( string str ) { map < pair < pair < int , int > , pair < int , int > > , int > mp ; mp [ { { 0 , 0 } , { 0 , 0 } } ] ++ ; int p = 0 ; int q = 0 ; int r = 0 ; int s = 0 ; int cntSub = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] == ' a ' ) { p ++ ; int Y = min ( min ( s , r ) , min ( p , q ) ) ; p -= Y ; q -= Y ; r -= Y ; s -= Y ; } else if ( str [ i ] == ' b ' ) { q ++ ; int Y = min ( min ( p , q ) , min ( r , s ) ) ; p -= Y ; q -= Y ; r -= Y ; s -= Y ; } else if ( str [ i ] == ' c ' ) { r ++ ; int Y = min ( min ( p , q ) , min ( r , s ) ) ; p -= Y ; q -= Y ; r -= Y ; s -= Y ; } else if ( str [ i ] == ' d ' ) { s ++ ; int Y = min ( min ( p , q ) , min ( r , s ) ) ; p -= Y ; q -= Y ; r -= Y ; s -= Y ; } mp [ { { p , q } , { r , s } } ] ++ ; } for ( auto & e : mp ) { int freq = e . second ; cntSub += ( freq ) * ( freq - 1 ) / 2 ; } return cntSub ; } int main ( ) { string str = " abcdefg " ; cout << countSubstrings ( str ) ; return 0 ; }
Spell Checker using Trie | C ++ program to implement the above approach ; Structure of a Trie node ; Store address of a character ; Check if the character is last character of a string or not ; Constructor function ; Function to insert a string into Trie ; Traverse the string , s ; Initialize a node ; Update temp ; Mark the last character of the string to true ; Function to print suggestions of the string ; If current character is the last character of a string ; Iterate over all possible characters of the string ; If current character present in the Trie ; Insert current character into Trie ; Function to check if the string is present in Trie or not ; Traverse the string ; If current character not present in the Trie ; Update root ; Driver Code ; Given array of strings ; Initialize a Trie ; Insert strings to trie
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct TrieNode { TrieNode * Trie [ 256 ] ; bool isEnd ; TrieNode ( ) { for ( int i = 0 ; i < 256 ; i ++ ) { Trie [ i ] = NULL ; } isEnd = false ; } } ; void InsertTrie ( TrieNode * root , string s ) { TrieNode * temp = root ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( temp -> Trie [ s [ i ] ] == NULL ) { temp -> Trie [ s [ i ] ] = new TrieNode ( ) ; } temp = temp -> Trie [ s [ i ] ] ; } temp -> isEnd = true ; } void printSuggestions ( TrieNode * root , string res ) { if ( root -> isEnd == true ) { cout << res << " ▁ " ; } for ( int i = 0 ; i < 256 ; i ++ ) { if ( root -> Trie [ i ] != NULL ) { res . push_back ( i ) ; printSuggestions ( root -> Trie [ i ] , res ) ; res . pop_back ( ) ; } } } bool checkPresent ( TrieNode * root , string key ) { for ( int i = 0 ; i < key . length ( ) ; i ++ ) { if ( root -> Trie [ key [ i ] ] == NULL ) { printSuggestions ( root , key . substr ( 0 , i ) ) ; return false ; } root = root -> Trie [ key [ i ] ] ; } if ( root -> isEnd == true ) { return true ; } printSuggestions ( root , key ) ; return false ; } int main ( ) { vector < string > str = { " gee " , " geeks " , " ape " , " apple " , " geeksforgeeks " } ; string key = " geek " ; TrieNode * root = new TrieNode ( ) ; for ( int i = 0 ; i < str . size ( ) ; i ++ ) { InsertTrie ( root , str [ i ] ) ; } if ( checkPresent ( root , key ) ) { cout << " YES " ; } return 0 ; }
Count strings from given array having all characters appearing in a given string | C ++ program to implement the above approach ; Function to count the number of strings from an array having all characters appearing in the string S ; Initialize a set to store all distinct characters of string S ; Traverse over string S ; Insert characters into the Set ; Stores the required count ; Traverse the array ; Traverse over string arr [ i ] ; Check if character in arr [ i ] [ j ] is present in the string S or not ; Increment the count if all the characters of arr [ i ] are present in the string S ; Finally , print the count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countStrings ( string S , vector < string > & list ) { unordered_set < char > valid ; for ( auto x : S ) { valid . insert ( x ) ; } int cnt = 0 ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { int j = 0 ; for ( j = 0 ; j < list [ i ] . size ( ) ; j ++ ) { if ( valid . count ( list [ i ] [ j ] ) ) continue ; else break ; } if ( j == list [ i ] . size ( ) ) cnt ++ ; } return cnt ; } int main ( ) { vector < string > arr = { " ab " , " aab " , " abaaaa " , " bbd " } ; string S = " ab " ; cout << countStrings ( S , arr ) << endl ; }
Minimize a string by removing all occurrences of another string | C ++ program for the above approach ; Function to find the minimum length to which string str can be reduced to by removing all occurrences of string K ; Initialize stack of characters ; Push character into the stack ; If stack size >= K . size ( ) ; Create empty string to store characters of stack ; Traverse the string K in reverse ; If any of the characters differ , it means that K is not present in the stack ; Push the elements back into the stack ; Store the string ; Remove top element ; Size of stack gives the minimized length of str ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minLength ( string str , int N , string K , int M ) { stack < char > stackOfChar ; for ( int i = 0 ; i < N ; i ++ ) { stackOfChar . push ( str [ i ] ) ; if ( stackOfChar . size ( ) >= M ) { string l = " " ; for ( int j = M - 1 ; j >= 0 ; j -- ) { if ( K [ j ] != stackOfChar . top ( ) ) { int f = 0 ; while ( f != l . size ( ) ) { stackOfChar . push ( l [ f ] ) ; f ++ ; } break ; } else { l = stackOfChar . top ( ) + l ; stackOfChar . pop ( ) ; } } } } return stackOfChar . size ( ) ; } int main ( ) { string S1 = " fffoxoxoxfxo " ; string S2 = " fox " ; int N = S1 . length ( ) ; int M = S2 . length ( ) ; cout << minLength ( S1 , N , S2 , M ) ; return 0 ; }
Largest palindrome not exceeding N which can be expressed as product of two 3 | C ++ program for the above approach ; Function to find the largest palindrome not exceeding N which can be expressed as the product of two 3 - digit numbers ; Stores all palindromes ; Stores the product ; Check if X is palindrome ; Check n is less than N ; If true , append it in the list ; Print the largest palindrome ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void palindrome_prod ( string N ) { vector < int > palindrome_list ; for ( int i = 101 ; i < 1000 ; i ++ ) { for ( int j = 121 ; j < 1000 ; j += ( i % 11 == 0 ) ? 1 : 11 ) { int n = i * j ; string x = to_string ( n ) ; string y = x ; reverse ( y . begin ( ) , y . end ( ) ) ; if ( x == y ) { if ( n < stoi ( N ) ) { palindrome_list . push_back ( i * j ) ; } } } } cout << ( * max_element ( palindrome_list . begin ( ) , palindrome_list . end ( ) ) ) ; } int main ( ) { string N = "101110" ; palindrome_prod ( N ) ; return 0 ; }
Check if given strings can be made same by swapping two characters of same or different strings | C ++ program to implement the above approach ; Function to check if all strings can be made equal by swapping any pair of characters from the same or different strings ; Stores length of string ; Store frequency of each distinct character of the strings ; Traverse the array ; Iterate over the characters ; Update frequency of arr [ i ] [ j ] ; Traverse the array cntFreq [ ] ; If cntFreq [ i ] is divisible by N or not ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isEqualStrings ( string arr [ ] , int N ) { int M = arr [ 0 ] . length ( ) ; int cntFreq [ 256 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { cntFreq [ arr [ i ] [ j ] - ' a ' ] ++ ; } } for ( int i = 0 ; i < 256 ; i ++ ) { if ( cntFreq [ i ] % N != 0 ) { return false ; } } return true ; } int main ( ) { string arr [ ] = { " aab " , " bbc " , " cca " } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( isEqualStrings ( arr , N ) ) { cout << " YES " ; } else { cout << " NO " ; } return 0 ; }
Minimize a binary string by repeatedly removing even length substrings of same characters | C ++ program for the above approach ; Recursive function to print stack elements from bottom to top without changing their order ; If stack is empty ; Pop top element of the stack ; Recursively call the function PrintStack ; Print the stack element from the bottom ; Push the same element onto the stack to preserve the order ; Function to minimize binary string by removing substrings consisting of same character ; Declare a stack of characters ; Push the first character of the string into the stack ; Traverse the string s ; If Stack is empty ; Push current character into the stack ; Check if the current character is same as the top of the stack ; If true , pop the top of the stack ; Otherwise , push the current element ; Print stack from bottom to top ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void PrintStack ( stack < char > s ) { if ( s . empty ( ) ) return ; char x = s . top ( ) ; s . pop ( ) ; PrintStack ( s ) ; cout << x ; s . push ( x ) ; } void minString ( string s ) { stack < char > Stack ; Stack . push ( s [ 0 ] ) ; for ( int i = 1 ; i < s . size ( ) ; i ++ ) { if ( Stack . empty ( ) ) { Stack . push ( s [ i ] ) ; } else { if ( Stack . top ( ) == s [ i ] ) { Stack . pop ( ) ; } else { Stack . push ( s [ i ] ) ; } } } PrintStack ( Stack ) ; } int main ( ) { string str = "101001" ; minString ( str ) ; return 0 ; }
Probability of collision between two trucks | C ++ program for the above approach ; Function to calculate total number of accidents ; String size ; Function to calculate count of all possible collision ; Stores the count of collisions ; Total number of truck in lane b ; Count total number of collisions while traversing the string a ; Function to calculate the probability of collisions ; Evaluate total outcome that is all the possible accident ; Evaluate favourable outcome i . e . , count of collision of trucks ; Print desired probability ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; double count_of_accident ( string a , string b ) { int n = a . size ( ) , m = b . size ( ) ; if ( n > m ) return ( m * ( m + 1 ) ) / 2 ; else return ( n * ( n + 1 ) ) / 2 + ( m - n ) * n ; } double count_of_collision ( string a , string b ) { int n = a . size ( ) , m = b . size ( ) ; int answer = 0 ; int count_of_truck_in_lane_b = 0 ; for ( int i = 0 ; i < m ; i ++ ) if ( b [ i ] == ' T ' ) count_of_truck_in_lane_b ++ ; for ( int i = 0 ; i < n && i < m ; i ++ ) { if ( a [ i ] == ' T ' ) answer += count_of_truck_in_lane_b ; if ( b [ i ] == ' T ' ) count_of_truck_in_lane_b -- ; } return answer ; } double findProbability ( string a , string b ) { double total_outcome = count_of_accident ( a , b ) ; double favourable_outcome = count_of_collision ( a , b ) ; cout << favourable_outcome / total_outcome ; } int main ( ) { string S = " TCCBCTTB " , T = " BTCCBBTT " ; findProbability ( S , T ) ; return 0 ; }
Count alphanumeric palindromes of length N | C ++ program for the above approach ; Function to calculate ( x ^ y ) mod p ; Initialize result ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now ; Return the final result ; Driver Code ; Given N ; Base Case ; Check whether n is even or odd ; Function Call ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int power ( int x , int y , int p ) { int res = 1 ; x = x % p ; if ( x == 0 ) return 0 ; while ( y > 0 ) { if ( ( y & 1 ) == 1 ) res = ( res * x ) % p ; y = y >> 1 ; x = ( x * x ) % p ; } return res ; } int main ( ) { int N = 3 ; int flag , k , m ; if ( ( N == 1 ) || ( N == 2 ) ) cout << 62 ; else m = 1000000000 + 7 ; if ( N % 2 == 0 ) { k = N / 2 ; flag = true ; } else { k = ( N - 1 ) / 2 ; flag = false ; } if ( flag != 0 ) { int a = power ( 62 , k , m ) ; cout << a ; } else { int a = power ( 62 , ( k + 1 ) , m ) ; cout << a ; } }
Length of the longest substring with every character appearing even number of times | C ++ program for the above approach ; Function to find length of the longest substring with each element occurring even number of times ; Initialize unordered_map ; Stores the length of the longest required substring ; Traverse the string ; Stores the value of the digit present at current index ; Bitwise XOR of the mask with 1 left - shifted by val ; Check if the value of mask is already present in ind or not ; Update the final answer ; Otherwise ; Return the answer ; Driver Code ; Given string ; Length of the given string ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int lenOfLongestReqSubstr ( string s , int N ) { unordered_map < int , int > ind ; int mask = 0 ; ind [ 0 ] = -1 ; int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int val = s [ i ] - '0' ; mask ^= ( 1 << val ) ; if ( ind . find ( mask ) != ind . end ( ) ) { ans = max ( ans , i - ind [ mask ] ) ; } else ind [ mask ] = i ; } return ans ; } int main ( ) { string s = "223015150" ; int N = s . length ( ) ; cout << lenOfLongestReqSubstr ( s , N ) ; return 0 ; }
Count distinct strings possible by replacing each character by its Morse code | C ++ program to implement the above approach ; Function to count unique array elements by replacing each character by its Morse code ; Stores Morse code of all lowercase characters ; Stores distinct elements of string by replacing each character by Morse code ; Stores length of arr [ ] array ; Traverse the array ; Stores the Morse code of arr [ i ] ; Stores length of current string ; Update temp ; Insert temp into st ; Return count of elements in the set ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int uniqueMorseRep ( vector < string > & arr ) { vector < string > morseCode = { " . - " , " - . . . " , " - . - . " , " - . . " , " . " , " . . - . " , " - - . " , " . . . . " , " . . " , " . - - - " , " - . - " , " . - . . " , " - - " , " - . " , " - - - " , " . - - . " , " - - . - " , " . - . " , " . . . " , " - " , " . . - " , " . . . - " , " . - - " , " - . . - " , " - . - - " , " - - . . " } ; set < string > st ; int N = arr . size ( ) ; for ( int i = 0 ; i < N ; i ++ ) { string temp = " " ; int M = arr [ i ] . length ( ) ; for ( int j = 0 ; j < M ; j ++ ) { temp += morseCode [ arr [ i ] [ j ] - ' a ' ] ; } st . insert ( temp ) ; } return st . size ( ) ; } int main ( ) { vector < string > arr = { " gig " , " zeg " , " gin " , " msn " } ; cout << uniqueMorseRep ( arr ) << endl ; }
Maximum repeating character for every index in given String | C ++ Program to implement the above approach ; Function to print the maximum repeating character at each index of the String ; Stores frequency of each distinct character ; Stores frequency of maximum repeating character ; Stores the character having maximum frequency ; Traverse the String ; Stores current character ; Update the frequency of str [ i ] ; If frequency of current character exceeds max ; Update max ; Update charMax ; Print the required output ; Driver Code ; Stores length of str
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findFreq ( string str , int N ) { int freq [ 256 ] ; memset ( freq , 0 , sizeof ( freq ) ) ; int max = 0 ; char charMax = '0' ; for ( int i = 0 ; i < N ; i ++ ) { char ch = str [ i ] ; freq [ ch ] ++ ; if ( freq [ ch ] >= max ) { max = freq [ ch ] ; charMax = ch ; } cout << charMax << " - > " << max << endl ; } } int main ( ) { string str = " abbc " ; int N = str . size ( ) ; findFreq ( str , N ) ; }
Minimize cost to convert given string to a palindrome | C ++ program for the above approach ; Function to find the minimum cost to convert the string into a palindrome ; Length of the string ; If iointer is in the second half ; Reverse the string ; Pointing to initial position ; Find the farthest index needed to change on left side ; Find the farthest index needed to change on right side ; Changing the variable to make string palindrome ; min distance to travel to make string palindrome ; Total cost ; Return the minimum cost ; Driver Code ; Given string S ; Given pointer P ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinCost ( string str , int pos ) { int n = str . length ( ) ; if ( pos >= n / 2 ) { reverse ( str . begin ( ) , str . end ( ) ) ; pos = n - pos - 1 ; } int left , right ; left = right = pos ; for ( int i = pos ; i >= 0 ; -- i ) { if ( str [ i ] != str [ n - i - 1 ] ) { left = i ; } } for ( int i = pos ; i < n / 2 ; ++ i ) { if ( str [ i ] != str [ n - i - 1 ] ) { right = i ; } } int ans = 0 ; for ( int i = left ; i <= right ; ++ i ) { if ( str [ i ] != str [ n - i - 1 ] ) ans += 1 ; } int dis = min ( ( 2 * ( pos - left ) + ( right - pos ) ) , ( 2 * ( right - pos ) + ( pos - left ) ) ) ; ans = ans + dis ; return ans ; } int main ( ) { string S = " bass " ; int P = 3 ; cout << findMinCost ( S , P ) ; return 0 ; }
Minimize replacements by previous or next alphabet required to make all characters of a string the same | C ++ program for the above approach ; Function to find the minimum count of operations to make all characters of the string same ; Set min to some large value ; Find minimum operations for each character ; Initialize cnt ; Add the value to cnt ; Update minValue ; Return minValue ; Driver Code ; Given string str ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minCost ( string s , int n ) { int minValue = 100000000 ; for ( int i = 0 ; i <= 25 ; i ++ ) { int cnt = 0 ; for ( int j = 0 ; j < n ; j ++ ) { cnt += min ( abs ( i - ( s [ j ] - ' a ' ) ) , 26 - abs ( i - ( s [ j ] - ' a ' ) ) ) ; } minValue = min ( minValue , cnt ) ; } return minValue ; } int main ( ) { string str = " geeksforgeeks " ; int N = str . length ( ) ; cout << minCost ( str , N ) ; return 0 ; }
Longest palindromic string possible by concatenating strings from a given array | C ++ program for the above approach ; Stores the distinct strings from the given array ; Insert the strings into set ; Stores the left and right substrings of the given string ; Stores the middle substring ; Traverse the array of strings ; Reverse the current string ; Checking if the string is itself a palindrome or not ; Check if the reverse of the string is present or not ; Append to the left substring ; Append to the right substring ; Erase both the strings from the set ; Print the left substring ; Print the middle substring ; Print the right substring ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void max_len ( string s [ ] , int N , int M ) { unordered_set < string > set_str ; for ( int i = 0 ; i < N ; i ++ ) { set_str . insert ( s [ i ] ) ; } vector < string > left_ans , right_ans ; string mid ; for ( int i = 0 ; i < N ; i ++ ) { string t = s [ i ] ; reverse ( t . begin ( ) , t . end ( ) ) ; if ( t == s [ i ] ) { mid = t ; } else if ( set_str . find ( t ) != set_str . end ( ) ) { left_ans . push_back ( s [ i ] ) ; right_ans . push_back ( t ) ; set_str . erase ( s [ i ] ) ; set_str . erase ( t ) ; } } for ( auto x : left_ans ) { cout << x ; } cout << mid ; reverse ( right_ans . begin ( ) , right_ans . end ( ) ) ; for ( auto x : right_ans ) { cout << x ; } } int main ( ) { int N = 4 , M = 3 ; string s [ ] = { " omg " , " bbb " , " ffd " , " gmo " } ; max_len ( s , N , M ) ; return 0 ; }
Minimize steps defined by a string required to reach the destination from a given source | C ++ program for the above approach ; Function to find the minimum length of string required to reach from source to destination ; Size of the string ; Stores the index of the four directions E , W , N , S ; If destination reached ; Iterate over the string ; Move east ; Change x1 according to direction E ; Move west ; Change x1 according to direction W ; Move north ; Change y1 according to direction N ; Move south ; Change y1 according to direction S ; Store the max of all positions ; Print the minimum length of string required ; Otherwise , it is impossible ; Driver Code ; Given string ; Given source and destination ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimum_length ( int x1 , int y1 , int x2 , int y2 , string str ) { int n = str . size ( ) ; int pos1 , pos2 , pos3 , pos4 ; pos1 = -1 ; pos2 = -1 ; pos3 = -1 ; pos4 = -1 ; if ( x1 == x2 && y1 == y2 ) { cout << 0 << endl ; } else { for ( int i = 0 ; i < n ; i ++ ) { if ( x2 > x1 ) { if ( str [ i ] == ' E ' ) { x1 = x1 + 1 ; if ( x1 == x2 ) { pos1 = i ; } } } if ( x2 < x1 ) { if ( str [ i ] == ' W ' ) { x1 = x1 - 1 ; if ( x1 == x2 ) { pos2 = i ; } } } if ( y2 > y1 ) { if ( str [ i ] == ' N ' ) { y1 = y1 + 1 ; if ( y1 == y2 ) { pos3 = i ; } } } if ( y2 < y1 ) { if ( str [ i ] == ' S ' ) { y1 = y1 - 1 ; if ( y1 == y2 ) { pos4 = i ; } } } } int z ; z = max ( max ( max ( pos1 , pos2 ) , pos3 ) , pos4 ) ; if ( x1 == x2 && y1 == y2 ) { cout << z + 1 << endl ; } else { cout << " - 1" << endl ; } } } int main ( ) { string str = " SESNW " ; int x1 = 0 , x2 = 1 , y1 = 0 , y2 = 1 ; minimum_length ( x1 , y1 , x2 , y2 , str ) ; return 0 ; }
Remove all duplicate adjacent characters from a string using Stack | C ++ program to implement the above approach ; Function to remove adjacent duplicate elements ; Store the string without duplicate elements ; Store the index of str ; Traverse the string str ; Checks if stack is empty or top of the stack is not equal to current character ; If top element of the stack is equal to the current character ; If stack is empty ; If stack is not Empty ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string ShortenString ( string str1 ) { stack < char > st ; int i = 0 ; while ( i < str1 . length ( ) ) { if ( st . empty ( ) || str1 [ i ] != st . top ( ) ) { st . push ( str1 [ i ] ) ; i ++ ; } else { st . pop ( ) ; i ++ ; } } if ( st . empty ( ) ) { return ( " Empty ▁ String " ) ; } else { string short_string = " " ; while ( ! st . empty ( ) ) { short_string = st . top ( ) + short_string ; st . pop ( ) ; } return ( short_string ) ; } } int main ( ) { string str1 = " azzxzy " ; cout << ShortenString ( str1 ) ; return 0 ; }
Count ways to place all the characters of two given strings alternately | C ++ Program to implement the above approach ; Function to get the factorial of N ; Function to get the total number of distinct ways ; Length of str1 ; Length of str2 ; If both strings have equal length ; If both strings do not have equal length ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int fact ( int n ) { int res = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { res = res * i ; } return res ; } int distinctWays ( string str1 , string str2 ) { int n = str1 . length ( ) ; int m = str2 . length ( ) ; if ( n == m ) { return 2 * fact ( n ) * fact ( m ) ; } return fact ( n ) * fact ( m ) ; } int main ( ) { string str1 = " aegh " ; string str2 = " rsw " ; cout << distinctWays ( str1 , str2 ) ; }
Smallest string without any multiplication sign that represents the product of two given numbers | C ++ program for the above approach ; Function to find the string which evaluates to the product of A and B ; Stores the result ; 2 ^ log <= B && 2 ^ ( log + 1 ) > B ; Update res to res += A X 2 ^ log ; Update res to res += A X 2 ^ 0 ; Find the remainder ; If remainder is not equal to 0 ; Return the resultant string ; Function to find the minimum length representation of A * B ; Find representation of form A << k1 + A << k2 + ... + A << kn ; Find representation of form B << k1 + B << k2 + ... + B << kn ; Compare the length of the representations ; Driver code ; Product A X B ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string len ( long A , long B ) { string res = " " ; long Log = 0 ; do { Log = ( long ) ( log ( B ) / log ( 2 ) ) ; if ( Log != 0 ) { res = res + to_string ( A ) + " < < " + to_string ( Log ) ; } else { res += A ; break ; } B = B - ( long ) pow ( 2 , Log ) ; if ( B != 0 ) { res += " + " ; } else break ; } while ( Log != 0 ) ; return res ; } void minimumString ( long A , long B ) { string res1 = len ( A , B ) ; string res2 = len ( B , A ) ; if ( res1 . length ( ) > res2 . length ( ) ) { cout << res2 << endl ; } else { cout << res1 << endl ; } } int main ( ) { long A = 6 ; long B = 10 ; minimumString ( A , B ) ; return 0 ; }
Count substrings of a given string whose anagram is a palindrome | C ++ program for the above approach ; Function to print count of substrings whose anagrams are palindromic ; Stores the answer ; Iterate over the string ; Set the current character ; Parity update ; Print the final count ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countSubstring ( string s ) { int res = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int x = 0 ; for ( int j = i ; j < s . length ( ) ; j ++ ) { int temp = 1 << s [ j ] - ' a ' ; x ^= temp ; if ( ( x & ( x - 1 ) ) == 0 ) res ++ ; } } cout << res ; } int main ( ) { string str = " aaa " ; countSubstring ( str ) ; return 0 ; }
Count substrings of a given string whose anagram is a palindrome | C ++ program for the above approach ; Function to get the count of substrings whose anagrams are palindromic ; Store the answer ; Map to store the freq of masks ; Set frequency for mask 00. . .00 to 1 ; Store mask in x from 0 to i ; Update answer ; Update frequency ; Print the answer ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countSubstring ( string s ) { int answer = 0 ; unordered_map < int , int > m ; m [ 0 ] = 1 ; int x = 0 ; for ( int j = 0 ; j < s . length ( ) ; j ++ ) { x ^= 1 << ( s [ j ] - ' a ' ) ; answer += m [ x ] ; for ( int i = 0 ; i < 26 ; ++ i ) { answer += m [ x ^ ( 1 << i ) ] ; } m [ x ] += 1 ; } cout << answer ; } int main ( ) { string str = " abab " ; countSubstring ( str ) ; return 0 ; }
Sum of an array of large numbers | C ++ program for the above approach ; Function to print the result of the summation of numbers having K - digit ; Reverse the array to obtain the result ; Print every digit of the answer ; Function to calculate the total sum ; Stores the array of large numbers in integer format ; Convert each element from character to integer ; Stores the carry ; Stores the result of summation ; Initialize the sum ; Calculate sum ; Update the sum by adding existing carry ; Store the number of digits ; Increase count of digits ; If the number exceeds 9 , Store the unit digit in carry ; Store the rest of the sum ; Append digit by digit into result array ; Append result until carry is 0 ; Print the result ; Driver Code ; Given N array of large numbers
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printResult ( vector < int > result ) { reverse ( result . begin ( ) , result . end ( ) ) ; int i = 0 ; while ( i < result . size ( ) ) { cout << result [ i ] ; i ++ ; } } void sumOfLargeNumbers ( string v [ ] , int k , int N ) { vector < vector < int > > x ( 1000 ) ; for ( int i = 0 ; i < k ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { x [ i ] . push_back ( v [ i ] [ j ] - '0' ) ; } } int carry = 0 ; vector < int > result ; for ( int i = N - 1 ; i >= 0 ; i -- ) { int sum = 0 ; for ( int j = 0 ; j < k ; j ++ ) sum += x [ j ] [ i ] ; sum += carry ; int temp = sum ; int count = 0 ; while ( temp > 9 ) { temp = temp % 10 ; count ++ ; } long long int l = pow ( 10 , count ) ; if ( l != 1 ) carry = ( double ) sum / l ; sum = sum % 10 ; result . push_back ( sum ) ; } while ( carry != 0 ) { int a = carry % 10 ; result . push_back ( a ) ; carry = carry / 10 ; } printResult ( result ) ; } int main ( ) { int K = 10 ; int N = 5 ; string arr [ ] = { "1111111111" , "1111111111" , "1111111111" , "1111111111" , "1111111111" } ; sumOfLargeNumbers ( arr , N , K ) ; return 0 ; }
Reverse words in a given string | Set 2 | C ++ Program to implement the above approach ; Function to reverse the words of a given string ; Stack to store each word of the string ; Store the whole string in string stream ; Push each word of the string into the stack ; Print the string in reverse order of the words ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printRev ( string str ) { stack < string > st ; stringstream ss ( str ) ; string temp ; while ( getline ( ss , temp , ' ▁ ' ) ) { st . push ( temp ) ; } while ( ! st . empty ( ) ) { cout << st . top ( ) << " ▁ " ; st . pop ( ) ; } } int main ( ) { string str ; str = " geeks ▁ quiz ▁ practice ▁ code " ; printRev ( str ) ; return 0 ; }
Count of substrings of a Binary string containing only 1 s | C ++ implementation to find count of substring containing only ones ; Function to find the total number of substring having only ones ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countOfSubstringWithOnlyOnes ( string s ) { int res = 0 , count = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { count = s [ i ] == '1' ? count + 1 : 0 ; res = ( res + count ) ; } return res ; } int main ( ) { string s = "0110111" ; cout << countOfSubstringWithOnlyOnes ( s ) << endl ; return 0 ; }
Count of Distinct strings possible by inserting K characters in the original string | C ++ program for the above approach ; Function to calculate and return x ^ n in log ( n ) time using Binary Exponentiation ; Function to calculate the factorial of a number ; Function to calculate combination ; nCi = ( n ! ) / ( ( n - i ) ! * i ! ) ; Using Euler 's theorem of Modular multiplicative inverse to find the inverse of a number. (1/a)%mod=a^(m?2)%mod ; Function to find the count of possible strings ; Number of ways to form all possible strings ; Number of ways to form strings that don 't contain the input string as a subsequence ; Checking for all prefix length from 0 to | S | - 1. ; to calculate nCi ; Select the remaining characters 25 ^ ( N - i ) ; Add the answer for this prefix length to the final answer ; Answer is the difference of allWays and noWays ; Print the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define int long long int NEW_LINE const int mod = 1e9 + 7 ; int binExp ( int base , int power ) { int x = 1 ; while ( power ) { if ( power % 2 == 1 ) x = ( ( x % mod ) * ( base % mod ) ) % mod ; base = ( ( base % mod ) * ( base % mod ) ) % mod ; power = power / 2 ; } return x ; } int fact ( int num ) { int result = 1 ; for ( int i = 1 ; i <= num ; ++ i ) { result = ( ( result % mod ) * ( i % mod ) ) % mod ; } return result ; } int calculate_nCi ( int N , int i ) { int nfact = fact ( N ) ; int ifact = fact ( i ) ; int dfact = fact ( N - i ) ; int inv_ifact = binExp ( ifact , mod - 2 ) ; int inv_dfact = binExp ( dfact , mod - 2 ) ; int denm = ( ( inv_ifact % mod ) * ( inv_dfact % mod ) ) % mod ; int answer = ( ( nfact % mod ) * ( denm % mod ) ) % mod ; return answer ; } void countSubstring ( int N , int s , int k ) { int allWays = binExp ( 26 , N ) ; int noWays = 0 ; for ( int i = 0 ; i < s ; ++ i ) { int nCi = calculate_nCi ( N , i ) ; int remaining = binExp ( 25 , N - i ) ; int multiply = ( ( nCi % mod ) * ( remaining % mod ) ) % mod ; noWays = ( ( noWays % mod ) + ( multiply % mod ) ) % mod ; } int answer = ( ( allWays % mod ) - ( noWays % mod ) ) % mod ; if ( answer < 0 ) answer += mod ; cout << answer ; } int32_t main ( ) { string str = " abc " ; int k = 2 ; int s = str . length ( ) ; int N = s + k ; countSubstring ( N , s , k ) ; }
Calculate Sum of ratio of special characters to length of substrings of the given string | C ++ Program to implement the above approach ; Stores frequency of special characters in the array ; Stores prefix sum ; Function to check whether a character is special or not ; If current character is special ; Otherwise ; Function to find sum of ratio of count of special characters and length of substrings ; Calculate the prefix sum of special nodes ; Generate prefix sum array ; Calculate ratio for substring ; Driver Code ;
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 1e5 + 5 ; vector < int > prefix ( N , 0 ) ; vector < int > sum ( N , 0 ) ; bool isSpecial ( char c , vector < char > & special ) { for ( auto & i : special ) if ( i == c ) return true ; return false ; } double countRatio ( string & s , vector < char > & special ) { int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { prefix [ i ] = int ( isSpecial ( s [ i ] , special ) ) ; if ( i > 0 ) prefix [ i ] += prefix [ i - 1 ] ; } for ( int i = 0 ; i < n ; i ++ ) { sum [ i ] = prefix [ i ] ; if ( i > 0 ) sum [ i ] += sum [ i - 1 ] ; } double ans = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { int count = sum [ n - 1 ] - ( i > 1 ? sum [ i - 2 ] : 0 ) ; count -= ( i < n ? sum [ n - i - 1 ] : 0 ) ; ans += double ( count ) / double ( i ) ; } return ans ; } int main ( ) { string s = " abcd " ; vector < char > special = { ' b ' , ' c ' } ; double ans = countRatio ( s , special ) ; cout << fixed << setprecision ( 6 ) << ans << endl ; return 0 ; }
Minimum replacements in a string to make adjacent characters unequal | C ++ program to find minimum replacements in a string to make adjacent characters unequal ; Function which counts the minimum number of required operations ; n stores the length of the string s ; ans will store the required ans ; i is the current index in the string ; Move j until characters s [ i ] & s [ j ] are equal or the end of the string is reached ; diff stores the length of the substring such that all the characters are equal in it ; We need atleast diff / 2 operations for this substring ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void count_minimum ( string s ) { int n = s . length ( ) ; int ans = 0 ; int i = 0 ; while ( i < n ) { int j = i ; while ( s [ j ] == s [ i ] && j < n ) { j ++ ; } int diff = j - i ; ans += diff / 2 ; i = j ; } cout << ans << endl ; } int main ( ) { string str = " caaab " ; count_minimum ( str ) ; return 0 ; }
Minimum cost to convert given string to consist of only vowels | C ++ program for the above approach ; Function to find the minimum cost ; Store vowels ; Loop for iteration of string ; Loop to calculate the cost ; Add minimum cost ; Driver Code ; Given String ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int min_cost ( string st ) { string vow = " aeiou " ; int cost = 0 ; for ( int i = 0 ; i < st . size ( ) ; i ++ ) { vector < int > costs ; for ( int j = 0 ; j < 5 ; j ++ ) costs . push_back ( abs ( st [ i ] - vow [ j ] ) ) ; cost += * min_element ( costs . begin ( ) , costs . end ( ) ) ; } return cost ; } int main ( ) { string str = " abcde " ; cout << ( min_cost ( str ) ) ; }
Check if a given string is Even | C ++ program to implement the above approach ; Function to check if the string str is palindromic or not ; Pointers to iterate the string from both ends ; If characters are found to be distinct ; Return true if the string is palindromic ; Function to generate string from characters at odd indices ; Function to generate string from characters at even indices ; Functions to checks if string is Even - Odd Palindrome or not ; Generate odd indexed string ; Generate even indexed string ; Check for Palindrome ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( string str ) { int l = 0 ; int h = str . size ( ) - 1 ; while ( h > l ) { if ( str [ l ++ ] != str [ h -- ] ) { return false ; } } return true ; } string makeOddString ( string str ) { string odd = " " ; for ( int i = 1 ; i < str . size ( ) ; i += 2 ) { odd += str [ i ] ; } return odd ; } string makeevenString ( string str ) { string even = " " ; for ( int i = 0 ; i < str . size ( ) ; i += 2 ) { even += str [ i ] ; } return even ; } void checkevenOddPalindrome ( string str ) { string odd = makeOddString ( str ) ; string even = makeevenString ( str ) ; if ( isPalindrome ( odd ) && isPalindrome ( even ) ) cout << " Yes " << endl ; else cout << " No " << endl ; } int main ( ) { string str = " abzzab " ; checkevenOddPalindrome ( str ) ; return 0 ; }
Check given string is oddly palindrome or not | C ++ program for the above approach ; Function to check if the string str is palindromic or not ; Iterate the string str from left and right pointers ; Keep comparing characters while they are same ; If they are not same then return false ; Return true if the string is palindromic ; Function to make string using odd indices of string str ; Functions checks if characters at odd index of the string forms palindrome or not ; Make odd indexed string ; Check for Palindrome ; Driver Code ; Given string ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( string str ) { int l = 0 ; int h = str . size ( ) - 1 ; while ( h > l ) { if ( str [ l ++ ] != str [ h -- ] ) { return false ; } } return true ; } string makeOddString ( string str ) { string odd = " " ; for ( int i = 1 ; i < str . size ( ) ; i += 2 ) { odd += str [ i ] ; } return odd ; } void checkOddlyPalindrome ( string str ) { string odd = makeOddString ( str ) ; if ( isPalindrome ( odd ) ) cout << " Yes " << endl ; else cout << " No " << endl ; } int main ( ) { string str = " ddwfefwde " ; checkOddlyPalindrome ( str ) ; return 0 ; }
Count of binary strings of given length consisting of at least one 1 | C ++ Program to implement the above approach ; Function to return the count of strings ; Calculate pow ( 2 , n ) ; Return pow ( 2 , n ) - 1 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long count_strings ( long n ) { int x = 1 ; for ( int i = 1 ; i < n ; i ++ ) { x = ( 1 << x ) ; } return x - 1 ; } int main ( ) { long n = 3 ; cout << count_strings ( n ) ; return 0 ; }
String formed with middle character of every right substring followed by left sequentially | C ++ implementation of the above approach ; Function to decrypt and print the new string ; If the whole string has been traversed ; To calculate middle index of the string ; Print the character at middle index ; Recursively call for right - substring ; Recursive call for left - substring ; Driver Code
#include <iostream> NEW_LINE using namespace std ; void decrypt ( string Str , int Start , int End ) { if ( Start > End ) { return ; } int mid = ( Start + End ) >> 1 ; cout << Str [ mid ] ; decrypt ( Str , mid + 1 , End ) ; decrypt ( Str , Start , mid - 1 ) ; } int main ( ) { int N = 4 ; string Str = " abcd " ; decrypt ( Str , 0 , N - 1 ) ; cout << " STRNEWLINE " ; N = 6 ; Str = " gyuitp " ; decrypt ( Str , 0 , N - 1 ) ; return 0 ; }
Check whether the binary equivalent of a number ends with given string or not | C ++ implementation of the above approach ; Function returns true if s1 is suffix of s2 ; Function to check if binary equivalent of a number ends in "111" or not ; To store the binary number ; Count used to store exponent value ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isSuffix ( string s1 , string s2 ) { int n1 = s1 . length ( ) ; int n2 = s2 . length ( ) ; if ( n1 > n2 ) return false ; for ( int i = 0 ; i < n1 ; i ++ ) if ( s1 [ n1 - i - 1 ] != s2 [ n2 - i - 1 ] ) return false ; return true ; } bool CheckBinaryEquivalent ( int N , string str ) { int B_Number = 0 ; int cnt = 0 ; while ( N != 0 ) { int rem = N % 2 ; int c = pow ( 10 , cnt ) ; B_Number += rem * c ; N /= 2 ; cnt ++ ; } string bin = to_string ( B_Number ) ; return isSuffix ( str , bin ) ; } int main ( ) { int N = 23 ; string str = "111" ; if ( CheckBinaryEquivalent ( N , str ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Count of substrings consisting only of vowels | C ++ program to Count all substrings in a string which contains only vowels ; Function to check if a character is vowel or not ; Function to check whether string contains only vowel ; Check if the character is not vowel then invalid ; Function to Count all substrings in a string which contains only vowels ; Generate all substring of s ; If temp contains only vowels ; Increment the count ; Driver Program
#include <iostream> NEW_LINE using namespace std ; bool isvowel ( char ch ) { return ( ch == ' a ' or ch == ' e ' or ch == ' i ' or ch == ' o ' or ch == ' u ' ) ; } bool isvalid ( string & s ) { int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! isvowel ( s [ i ] ) ) return false ; } return true ; } int CountTotal ( string & s ) { int ans = 0 ; int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { string temp = " " ; for ( int j = i ; j < n ; j ++ ) { temp += s [ j ] ; if ( isvalid ( temp ) ) ans += 1 ; } } return ans ; } int main ( ) { string s = " aeoibsddaaeiouudb " ; cout << ( CountTotal ( s ) ) << endl ; return 0 ; }
Longest substring of vowels with no two adjacent alphabets same | C ++ implementation of the above approach ; Function to check a character is vowel or not ; Function to check a substring is valid or not ; If size is 1 then check only first character ; If 0 'th character is not vowel then invalid ; If two adjacent characters are same or i 'th char is not vowel then invalid ; Function to find length of longest substring consisting only of vowels and no similar adjacent alphabets ; Stores max length of valid substring ; For current substring ; Check if substring is valid ; Size of substring is ( j - i + 1 ) ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isVowel ( char c ) { return ( c == ' a ' c == ' e ' c == ' i ' c == ' o ' c == ' u ' ) ; } bool isValid ( string & s ) { int n = s . size ( ) ; if ( n == 1 ) return ( isVowel ( s [ 0 ] ) ) ; if ( isVowel ( s [ 0 ] ) == false ) return false ; for ( int i = 1 ; i < n ; i ++ ) { if ( s [ i ] == s [ i - 1 ] || ! isVowel ( s [ i ] ) ) return false ; } return true ; } int findMaxLen ( string & s ) { int maxLen = 0 ; int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { string temp = " " ; for ( int j = i ; j < n ; j ++ ) { temp = temp + s [ j ] ; if ( isValid ( temp ) ) maxLen = max ( maxLen , ( j - i + 1 ) ) ; } } return maxLen ; } int main ( ) { string Str = " aeoibsddaeiouudb " ; cout << findMaxLen ( Str ) << endl ; return 0 ; }