text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Hexadecimal equivalents in Binary Valued Graph | C ++ implementation to find hexadecimal equivalents of all connected components ; Function to traverse the undirected graph using the Depth first traversal ; Marking the visited vertex as true ; Store the connected chain ; Recursive call to the DFS algorithm ; Function to create map between binary number and its equivalent hexadecimal ; Function to return hexadecimal equivalent of each connected component ; Length of string before ' . ' ; Add min 0 's in the beginning to make left substring length divisible by 4 ; If decimal point exists ; Length of string after ' . ' ; Add min 0 's in the end to make right substring length divisible by 4 ; Create map between binary and its equivalent hex code ; Extract from left , substring of size 4 and add its hex code ; If ' . ' is encountered add it to result ; Required hexadecimal number ; Function to find the hexadecimal equivalents of all connected components ; Initializing boolean array to mark visited vertices ; Following loop invokes DFS algorithm ; Variable to hold temporary length ; Container to store each chain ; DFS algorithm ; Variable to hold each chain size ; Container to store values of vertices of individual chains ; Storing the values of each chain ; Printing binary chain ; Converting the array with vertex values to a binary string using string stream ; Printing the hexadecimal values ; Driver Program ; Initializing graph in the form of adjacency list ; Defining the number of edges and vertices ; Assigning the values for each vertex of the undirected graph ; Constructing the undirected graph | #include <bits/stdc++.h> NEW_LINE using namespace std ; void depthFirst ( int v , vector < int > graph [ ] , vector < bool > & visited , vector < int > & storeChain ) { visited [ v ] = true ; storeChain . push_back ( v ) ; for ( auto i : graph [ v ] ) { if ( visited [ i ] == false ) { depthFirst ( i , graph , visited , storeChain ) ; } } } void createMap ( unordered_map < string , char > * um ) { ( * um ) [ "0000" ] = '0' ; ( * um ) [ "0001" ] = '1' ; ( * um ) [ "0010" ] = '2' ; ( * um ) [ "0011" ] = '3' ; ( * um ) [ "0100" ] = '4' ; ( * um ) [ "0101" ] = '5' ; ( * um ) [ "0110" ] = '6' ; ( * um ) [ "0111" ] = '7' ; ( * um ) [ "1000" ] = '8' ; ( * um ) [ "1001" ] = '9' ; ( * um ) [ "1010" ] = ' A ' ; ( * um ) [ "1011" ] = ' B ' ; ( * um ) [ "1100" ] = ' C ' ; ( * um ) [ "1101" ] = ' D ' ; ( * um ) [ "1110" ] = ' E ' ; ( * um ) [ "1111" ] = ' F ' ; } string hexaDecimal ( string bin ) { int l = bin . size ( ) ; int t = bin . find_first_of ( ' . ' ) ; int len_left = t != -1 ? t : l ; for ( int i = 1 ; i <= ( 4 - len_left % 4 ) % 4 ; i ++ ) bin = '0' + bin ; if ( t != -1 ) { int len_right = l - len_left - 1 ; for ( int i = 1 ; i <= ( 4 - len_right % 4 ) % 4 ; i ++ ) bin = bin + '0' ; } unordered_map < string , char > bin_hex_map ; createMap ( & bin_hex_map ) ; int i = 0 ; string hex = " " ; while ( 1 ) { hex += bin_hex_map [ bin . substr ( i , 4 ) ] ; i += 4 ; if ( i == bin . size ( ) ) break ; if ( bin . at ( i ) == ' . ' ) { hex += ' . ' ; i ++ ; } } return hex ; } void hexValue ( vector < int > graph [ ] , int vertices , vector < int > values ) { vector < bool > visited ( 10001 , false ) ; for ( int i = 1 ; i <= vertices ; i ++ ) { if ( visited [ i ] == false ) { int sizeChain ; vector < int > storeChain ; depthFirst ( i , graph , visited , storeChain ) ; sizeChain = storeChain . size ( ) ; int chainValues [ sizeChain + 1 ] ; for ( int i = 0 ; i < sizeChain ; i ++ ) { int temp = values [ storeChain [ i ] - 1 ] ; chainValues [ i ] = temp ; } cout << " Chain β = β " ; for ( int i = 0 ; i < sizeChain ; i ++ ) { cout << chainValues [ i ] << " β " ; } cout << " TABSYMBOL " ; stringstream ss ; ss << chainValues [ 0 ] ; string s = ss . str ( ) ; for ( int i = 1 ; i < sizeChain ; i ++ ) { stringstream ss1 ; ss1 << chainValues [ i ] ; string s1 = ss1 . str ( ) ; s . append ( s1 ) ; } cout << " Hexadecimal β " << " equivalent β = β " ; cout << hexaDecimal ( s ) << endl ; } } } int main ( ) { vector < int > graph [ 1001 ] ; int E , V ; E = 4 ; V = 7 ; vector < int > values ; values . push_back ( 0 ) ; values . push_back ( 1 ) ; values . push_back ( 1 ) ; values . push_back ( 1 ) ; values . push_back ( 0 ) ; values . push_back ( 1 ) ; values . push_back ( 1 ) ; graph [ 1 ] . push_back ( 2 ) ; graph [ 2 ] . push_back ( 1 ) ; graph [ 3 ] . push_back ( 4 ) ; graph [ 4 ] . push_back ( 3 ) ; graph [ 4 ] . push_back ( 5 ) ; graph [ 5 ] . push_back ( 4 ) ; graph [ 6 ] . push_back ( 5 ) ; graph [ 5 ] . push_back ( 6 ) ; graph [ 6 ] . push_back ( 7 ) ; graph [ 7 ] . push_back ( 6 ) ; hexValue ( graph , V , values ) ; return 0 ; } |
Check if the number is balanced | C ++ program to check if a number is Balanced or not ; Function to check whether N is Balanced Number or not ; Calculating the Leftsum and rightSum simultaneously ; Typecasting each character to integer and adding the digit to respective sums ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void BalancedNumber ( string s ) { int Leftsum = 0 ; int Rightsum = 0 ; for ( int i = 0 ; i < s . size ( ) / 2 ; i ++ ) { Leftsum += int ( s [ i ] - '0' ) ; Rightsum += int ( s [ s . size ( ) - 1 - i ] - '0' ) ; } if ( Leftsum == Rightsum ) cout << " Balanced " << endl ; else cout << " Not β Balanced " << endl ; } int main ( ) { string s = "12321" ; BalancedNumber ( s ) ; return 0 ; } |
Count of N size strings consisting of at least one vowel and one consonant | C ++ program to count all possible strings of length N consisting of atleast one vowel and one consonant ; Function to return base ^ exponent ; Function to count all possible strings ; All possible strings of length N ; vowels only ; consonants only ; Return the final result ; Driver Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; const unsigned long long mod = 1e9 + 7 ; unsigned long long expo ( unsigned long long base , unsigned long long exponent ) { unsigned long long ans = 1 ; while ( exponent != 0 ) { if ( ( exponent & 1 ) == 1 ) { ans = ans * base ; ans = ans % mod ; } base = base * base ; base %= mod ; exponent >>= 1 ; } return ans % mod ; } unsigned long long findCount ( unsigned long long N ) { unsigned long long ans = ( expo ( 26 , N ) - expo ( 5 , N ) - expo ( 21 , N ) ) % mod ; ans += mod ; ans %= mod ; return ans ; } int main ( ) { unsigned long long N = 3 ; cout << findCount ( N ) ; return 0 ; } |
Sum of decomposition values of all suffixes of an Array | C ++ implementation to find the sum of Decomposition values of all suffixes of an array ; Function to find the decomposition values of the array ; Stack ; Variable to maintain min value in stack ; Loop to iterate over the array ; Condition to check if the stack is empty ; Condition to check if the top of the stack is greater than the current element ; Loop to pop the element out ; the size of the stack is the max no of subarrays for suffix till index i from the right ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define int long long int NEW_LINE int decompose ( vector < int > S ) { stack < int > s ; int N = S . size ( ) ; int ans = 0 ; int nix = INT_MAX ; for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( s . empty ( ) ) { s . push ( S [ i ] ) ; nix = S [ i ] ; } else { if ( S [ i ] < s . top ( ) ) { s . push ( S [ i ] ) ; nix = min ( nix , S [ i ] ) ; } else { int val = S [ i ] ; while ( ! s . empty ( ) && val >= s . top ( ) ) { s . pop ( ) ; } nix = min ( nix , S [ i ] ) ; s . push ( nix ) ; } } ans += s . size ( ) ; } return ans ; } signed main ( ) { vector < int > S = { 9 , 6 , 9 , 35 } ; cout << decompose ( S ) << endl ; return 0 ; } |
Maximum number of set bits count in a K | C ++ program to find the maximum set bits in a substring of size K ; Function that find Maximum number of set bit appears in a substring of size K . ; Traverse string 1 to k ; Increment count if character is set bit ; Traverse string k + 1 to length of string ; Remove the contribution of the ( i - k ) th character which is no longer in the window ; Add the contribution of the current character ; Update maxCount at for each window of size k ; Return maxCount ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSetBitCount ( string s , int k ) { int maxCount = 0 , n = s . length ( ) ; int count = 0 ; for ( int i = 0 ; i < k ; i ++ ) { if ( s [ i ] == '1' ) count ++ ; } maxCount = count ; for ( int i = k ; i < n ; i ++ ) { if ( s [ i - k ] == '1' ) count -- ; if ( s [ i ] == '1' ) count ++ ; maxCount = max ( maxCount , count ) ; } return maxCount ; } int main ( ) { string s = "100111010" ; int k = 3 ; cout << ( maxSetBitCount ( s , k ) ) ; return 0 ; } |
Minimum characters to be deleted from the beginning of two strings to make them equal | C ++ Program to count minimum number of characters to be deleted from the beginning of the two strings to make the strings equal ; Function that finds minimum character required to be deleted ; Iterate in the strings ; Check if the characters are not equal ; Return the result ; Driver Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minDel ( string s1 , string s2 ) { int i = s1 . length ( ) ; int j = s2 . length ( ) ; while ( i > 0 && j > 0 ) { if ( s1 [ i - 1 ] != s2 [ j - 1 ] ) { break ; } i -- ; j -- ; } return i + j ; } int main ( ) { string s1 = " geeksforgeeks " , s2 = " peeks " ; cout << minDel ( s1 , s2 ) << endl ; } |
Minimum characters to be deleted from the end to make given two strings equal | C ++ Program to count minimum number of characters to be deleted to make the strings equal ; Function that finds minimum character required to be deleted ; Iterate in the strings ; Check if the characters are not equal ; Return the result ; Driver Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minDel ( string s1 , string s2 ) { int i = 0 ; while ( i < min ( s1 . length ( ) , s2 . length ( ) ) ) { if ( s1 [ i ] != s2 [ i ] ) { break ; } i ++ ; } int ans = ( s1 . length ( ) - i ) + ( s2 . length ( ) - i ) ; return ans ; } int main ( ) { string s1 = " geeks " , s2 = " geeksfor " ; cout << minDel ( s1 , s2 ) << endl ; } |
Count of triplets from the given string with non | C ++ Program to count of triplets from the given string with non - equidistant characters ; Function to count valid triplets ; Store frequencies of a , b and c ; If the current letter is ' a ' ; If the current letter is ' b ' ; If the current letter is ' c ' ; Calculate total no of triplets ; Subtract invalid triplets ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void CountValidTriplet ( string s , int n ) { int count_a = 0 , count_b = 0 , count_c = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ' a ' ) count_a ++ ; if ( s [ i ] == ' b ' ) count_b ++ ; if ( s [ i ] == ' c ' ) count_c ++ ; } int Total_triplet = count_a * count_b * count_c ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( ( 2 * j - i ) < n && s [ j ] != s [ i ] && s [ j * 2 - i ] != s [ j ] && s [ 2 * j - i ] != s [ i ] ) Total_triplet -- ; } } cout << Total_triplet ; } int main ( ) { string s = " abcbcabc " ; int n = s . length ( ) ; CountValidTriplet ( s , n ) ; return 0 ; } |
Check if given Parentheses expression is balanced or not | C ++ program for the above approach . ; Function to check if parentheses are balanced ; Initialising Variables ; Traversing the Expression ; It is a closing parenthesis ; This means there are more Closing parenthesis than opening ones ; If count is not zero , It means there are more opening parenthesis ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isBalanced ( string exp ) { bool flag = true ; int count = 0 ; for ( int i = 0 ; i < exp . length ( ) ; i ++ ) { if ( exp [ i ] == ' ( ' ) { count ++ ; } else { count -- ; } if ( count < 0 ) { flag = false ; break ; } } if ( count != 0 ) { flag = false ; } return flag ; } int main ( ) { string exp1 = " ( ( ( ) ) ) ( ) ( ) " ; if ( isBalanced ( exp1 ) ) cout << " Balanced β STRNEWLINE " ; else cout << " Not β Balanced β STRNEWLINE " ; string exp2 = " ( ) ) ( ( ( ) ) " ; if ( isBalanced ( exp2 ) ) cout << " Balanced β STRNEWLINE " ; else cout << " Not β Balanced β STRNEWLINE " ; return 0 ; } |
Longest Palindromic Subsequence of two distinct characters | C ++ implementation to find Longest Palindromic Subsequence consisting of two distinct characters only ; Function that prints the length of maximum required subsequence ; Calculate length of string ; Store number of occurrences of each character and position of each chatacter in string ; Iterate all characters ; Calculate number of occurences of the current character ; Iterate half of the number of positions of current character ; Determine maximum length of a character between l and r position ; Compute the maximum from all ; Printing maximum length ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void longestPalindrome ( string s ) { int n = s . length ( ) ; vector < vector < int > > pref ( 26 , vector < int > ( n , 0 ) ) ; vector < vector < int > > pos ( 26 ) ; pref [ s [ 0 ] - ' a ' ] [ 0 ] ++ ; pos [ s [ 0 ] - ' a ' ] . push_back ( 0 ) ; for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 0 ; j < 26 ; j ++ ) pref [ j ] [ i ] += pref [ j ] [ i - 1 ] ; int index = s [ i ] - ' a ' ; pref [ index ] [ i ] ++ ; pos [ index ] . push_back ( i ) ; } int ans = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) { int size = pos [ i ] . size ( ) ; ans = max ( ans , size ) ; for ( int j = 0 ; j < size / 2 ; j ++ ) { int l = pos [ i ] [ j ] ; int r = pos [ i ] [ size - j - 1 ] - 1 ; for ( int k = 0 ; k < 26 ; k ++ ) { int sum = pref [ k ] [ r ] - pref [ k ] [ l ] ; ans = max ( ans , 2 * ( j + 1 ) + sum ) ; } } } cout << ans << " STRNEWLINE " ; } int main ( ) { string S = " bbccdcbb " ; longestPalindrome ( S ) ; return 0 ; } |
Check if a given string can be formed using characters of adjacent cells of a Matrix | C ++ Program to check if a given word can be formed from the adjacent characters in a matrix of characters ; Function to check if the word exists ; If index exceeds board range ; If the current cell does not contain the required character ; If the cell contains the required character and is the last character of the word required to be matched ; Return true as word is found ; Mark cell visited ; Check Adjacent cells for the next character ; Restore cell value ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkWord ( vector < vector < char > > & board , string & word , int index , int row , int col ) { if ( row < 0 || col < 0 || row >= board . size ( ) || col >= board [ 0 ] . size ( ) ) return false ; if ( board [ row ] [ col ] != word [ index ] ) return false ; else if ( index == word . size ( ) - 1 ) return true ; char temp = board [ row ] [ col ] ; board [ row ] [ col ] = ' * ' ; if ( checkWord ( board , word , index + 1 , row + 1 , col ) || checkWord ( board , word , index + 1 , row - 1 , col ) || checkWord ( board , word , index + 1 , row , col + 1 ) || checkWord ( board , word , index + 1 , row , col - 1 ) ) { board [ row ] [ col ] = temp ; return true ; } board [ row ] [ col ] = temp ; return false ; } int main ( ) { vector < vector < char > > board = { { ' A ' , ' B ' , ' C ' , ' E ' } , { ' S ' , ' F ' , ' C ' , ' S ' } , { ' A ' , ' D ' , ' E ' , ' E ' } } ; string word = " CFDASABCESEE " ; for ( int i = 0 ; i < board . size ( ) ; i ++ ) { for ( int j = 0 ; j < board [ 0 ] . size ( ) ; j ++ ) { if ( board [ i ] [ j ] == word [ 0 ] && checkWord ( board , word , 0 , i , j ) ) { cout << " True " << ' ' ; return 0 ; } } } cout << " False " << ' ' ; return 0 ; } |
Split the number N by maximizing the count of subparts divisible by K | C ++ program to split the number N by maximizing the count of subparts divisible by K ; Function to count the subparts ; Total subStr till now ; If it can be divided , then this substring is one of the possible answer ; Convert string to long long and check if its divisible with X ; Consider there is no vertical cut between this index and the next one , hence take total carrying total substr a . ; If there is vertical cut between this index and next one , then we start again with subStr as " " and add b for the count of subStr upto now ; Return max of both the cases ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int count ( string N , int X , string subStr , int index , int n ) { if ( index == n ) return 0 ; string a = subStr + N [ index ] ; int b = 0 ; if ( stoll ( a ) % X == 0 ) b = 1 ; int m1 = count ( N , X , a , index + 1 , n ) ; int m2 = b + count ( N , X , " " , index + 1 , n ) ; return max ( m1 , m2 ) ; } int main ( ) { string N = "00001242" ; int K = 3 ; int l = N . length ( ) ; cout << count ( N , K , " " , 0 , l ) << endl ; return 0 ; } |
Check if a number ends with another number or not | C ++ program for the above approach ; Function to check if B is a suffix of A or not ; Convert numbers into strings ; Find the lengths of strings s1 and s2 ; Base Case ; Traverse the strings s1 & s2 ; If at any index characters are unequals then return false ; Return true ; Driver Code ; Given numbers ; Function Call ; If B is a suffix of A , then print " Yes " | #include " bits / stdc + + . h " NEW_LINE using namespace std ; bool checkSuffix ( int A , int B ) { string s1 = to_string ( A ) ; string s2 = to_string ( B ) ; int n1 = s1 . length ( ) ; int n2 = s2 . length ( ) ; if ( n1 < n2 ) { return false ; } for ( int i = 0 ; i < n2 ; i ++ ) { if ( s1 [ n1 - i - 1 ] != s2 [ n2 - i - 1 ] ) { return false ; } } return true ; } int main ( ) { int A = 12345 , B = 45 ; bool result = checkSuffix ( A , B ) ; if ( result ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; } |
Check if a number ends with another number or not | C ++ program for the above approach ; Function to check if B is a suffix of A or not ; Convert numbers into strings ; Check if s2 is a suffix of s1 or not using ends_with ( ) function ; If result is true , print " Yes " ; Driver Code ; Given numbers ; Function Call | #include <bits/stdc++.h> NEW_LINE #include <boost/algorithm/string.hpp> NEW_LINE using namespace std ; void checkSuffix ( int A , int B ) { string s1 = to_string ( A ) ; string s2 = to_string ( B ) ; bool result ; result = boost :: algorithm :: ends_with ( s1 , s2 ) ; if ( result ) { cout << " Yes " ; } else { cout << " No " ; } } int main ( ) { int A = 12345 , B = 45 ; checkSuffix ( A , B ) ; return 0 ; } |
Octal equivalents of connected components in Binary valued graph | C ++ implementation to find octal equivalents of all connected components ; Function to traverse the undirected graph using the Depth first traversal ; Marking the visited vertex as true ; Store the connected chain ; Recursive call to the DFS algorithm ; Function to create map between binary number and its equivalent octal value ; Function to return octal equivalent of each connected component ; length of string before ' . ' ; add min 0 's in the beginning to make left substring length divisible by 3 ; if decimal point exists ; length of string after ' . ' ; add min 0 's in the end to make right substring length divisible by 3 ; create map between binary and its equivalent octal code ; one by one extract from left , substring of size 3 and add its octal code ; if ' . ' is encountered add it to result ; required octal number ; Function to find the octal equivalents of all connected components ; Initializing boolean array to mark visited vertices ; Following loop invokes DFS algorithm ; Variable to hold temporary length ; Container to store each chain ; DFS algorithm ; Variable to hold each chain size ; Container to store values of vertices of individual chains ; Storing the values of each chain ; Printing binary chain ; Converting the array with vertex values to a binary string using string stream ; Printing the octal values ; Driver code to test above function ; Initializing graph in the form of adjacency list ; Defining the number of edges and vertices ; Assigning the values for each vertex of the undirected graph ; Constructing the undirected graph | #include <bits/stdc++.h> NEW_LINE using namespace std ; void depthFirst ( int v , vector < int > graph [ ] , vector < bool > & visited , vector < int > & storeChain ) { visited [ v ] = true ; storeChain . push_back ( v ) ; for ( auto i : graph [ v ] ) { if ( visited [ i ] == false ) { depthFirst ( i , graph , visited , storeChain ) ; } } } void createMap ( unordered_map < string , char > * um ) { ( * um ) [ "000" ] = '0' ; ( * um ) [ "001" ] = '1' ; ( * um ) [ "010" ] = '2' ; ( * um ) [ "011" ] = '3' ; ( * um ) [ "100" ] = '4' ; ( * um ) [ "101" ] = '5' ; ( * um ) [ "110" ] = '6' ; ( * um ) [ "111" ] = '7' ; } string Octal ( string bin ) { int l = bin . size ( ) ; int t = bin . find_first_of ( ' . ' ) ; int len_left = t != -1 ? t : l ; for ( int i = 1 ; i <= ( 3 - len_left % 3 ) % 3 ; i ++ ) bin = '0' + bin ; if ( t != -1 ) { int len_right = l - len_left - 1 ; for ( int i = 1 ; i <= ( 3 - len_right % 3 ) % 3 ; i ++ ) bin = bin + '0' ; } unordered_map < string , char > bin_oct_map ; createMap ( & bin_oct_map ) ; int i = 0 ; string octal = " " ; while ( 1 ) { octal += bin_oct_map [ bin . substr ( i , 3 ) ] ; i += 3 ; if ( i == bin . size ( ) ) break ; if ( bin . at ( i ) == ' . ' ) { octal += ' . ' ; i ++ ; } } return octal ; } void octalValue ( vector < int > graph [ ] , int vertices , vector < int > values ) { vector < bool > visited ( 1001 , false ) ; for ( int i = 1 ; i <= vertices ; i ++ ) { if ( visited [ i ] == false ) { int sizeChain ; vector < int > storeChain ; depthFirst ( i , graph , visited , storeChain ) ; sizeChain = storeChain . size ( ) ; int chainValues [ sizeChain + 1 ] ; for ( int i = 0 ; i < sizeChain ; i ++ ) { int temp = values [ storeChain [ i ] - 1 ] ; chainValues [ i ] = temp ; } cout << " Chain β = β " ; for ( int i = 0 ; i < sizeChain ; i ++ ) { cout << chainValues [ i ] << " β " ; } cout << " TABSYMBOL " ; stringstream ss ; ss << chainValues [ 0 ] ; string s = ss . str ( ) ; for ( int i = 1 ; i < sizeChain ; i ++ ) { stringstream ss1 ; ss1 << chainValues [ i ] ; string s1 = ss1 . str ( ) ; s . append ( s1 ) ; } cout << " Octal β equivalent β = β " ; cout << Octal ( s ) << endl ; } } } int main ( ) { vector < int > graph [ 1001 ] ; int E , V ; E = 4 ; V = 7 ; vector < int > values ; values . push_back ( 0 ) ; values . push_back ( 1 ) ; values . push_back ( 0 ) ; values . push_back ( 0 ) ; values . push_back ( 0 ) ; values . push_back ( 1 ) ; values . push_back ( 1 ) ; graph [ 1 ] . push_back ( 2 ) ; graph [ 2 ] . push_back ( 1 ) ; graph [ 3 ] . push_back ( 4 ) ; graph [ 4 ] . push_back ( 3 ) ; graph [ 4 ] . push_back ( 5 ) ; graph [ 5 ] . push_back ( 4 ) ; graph [ 6 ] . push_back ( 7 ) ; graph [ 7 ] . push_back ( 6 ) ; octalValue ( graph , V , values ) ; return 0 ; } |
Binary string with given frequencies of sums of consecutive pairs of characters | C ++ program to generate a binary string with given frequencies of sums of consecutive pair of characters ; A Function that generates and returns the binary string ; P : Frequency of consecutive characters with sum 0 Q : Frequency of consecutive characters with sum 1 R : Frequency of consecutive characters with sum 2 ; If no consecutive character adds up to 1 ; Not possible if both P and Q are non - zero ; If P is not equal to 0 ; Append 0 P + 1 times ; Append 1 R + 1 times ; Append "01" to satisfy Q ; Append "0" P times ; Append "1" R times ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string build_binary_str ( int p , int q , int r ) { string ans = " " ; if ( q == 0 ) { if ( p != 0 && r != 0 ) { return " - 1" ; } else { if ( p ) { ans = string ( p + 1 , '0' ) ; } else { ans = string ( r + 1 , '1' ) ; } } } else { for ( int i = 1 ; i <= q + 1 ; i ++ ) { if ( i % 2 == 0 ) { ans += '0' ; } else { ans += '1' ; } } ans . insert ( 1 , string ( p , '0' ) ) ; ans . insert ( 0 , string ( r , '1' ) ) ; } return ans ; } int main ( ) { int p = 1 , q = 2 , r = 2 ; cout << build_binary_str ( p , q , r ) ; return 0 ; } |
Check if there exists a permutation of given string which doesn 't contain any monotonous substring | C ++ implementation such that there are no monotonous string in given string ; Function to check a string doesn 't contains a monotonous substring ; Loop to iterate over the string and check that it doesn 't contains the monotonous substring ; Function to check that there exist a arrangement of string such that it doesn 't contains monotonous substring ; Loop to group the characters of the string into two buckets ; Sorting the two buckets ; Condition to check if the concatenation point doesn 't contains the monotonous string ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( string s ) { bool ok = true ; for ( int i = 0 ; i + 1 < s . size ( ) ; ++ i ) ok &= ( abs ( s [ i ] - s [ i + 1 ] ) != 1 ) ; return ok ; } string monotonousString ( string s ) { string odd = " " , even = " " ; for ( int i = 0 ; i < s . size ( ) ; ++ i ) { if ( s [ i ] % 2 == 0 ) odd += s [ i ] ; else even += s [ i ] ; } sort ( odd . begin ( ) , odd . end ( ) ) ; sort ( even . begin ( ) , even . end ( ) ) ; if ( check ( odd + even ) ) return " Yes " ; else if ( check ( even + odd ) ) return " Yes " ; return " No " ; } int main ( ) { string str = " abcd " ; string ans ; ans = monotonousString ( str ) ; cout << ans << endl ; return 0 ; } |
Length of the smallest substring which contains all vowels | C ++ Program to find the length of the smallest substring of which contains all vowels ; Function to return the index for respective vowels to increase their count ; Returns - 1 for consonants ; Function to find the minimum length ; Store the starting index of the current substring ; Store the frequencies of vowels ; If the current character is a vowel ; Increase its count ; Move start as much right as possible ; Condition for valid substring ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int get_index ( char ch ) { if ( ch == ' a ' ) return 0 ; else if ( ch == ' e ' ) return 1 ; else if ( ch == ' i ' ) return 2 ; else if ( ch == ' o ' ) return 3 ; else if ( ch == ' u ' ) return 4 ; else return -1 ; } int findMinLength ( string s ) { int n = s . size ( ) ; int ans = n + 1 ; int start = 0 ; int count [ 5 ] = { 0 } ; for ( int x = 0 ; x < n ; x ++ ) { int idx = get_index ( s [ x ] ) ; if ( idx != -1 ) { count [ idx ] ++ ; } int idx_start = get_index ( s [ start ] ) ; while ( idx_start == -1 count [ idx_start ] > 1 ) { if ( idx_start != -1 ) { count [ idx_start ] -- ; } start ++ ; if ( start < n ) idx_start = get_index ( s [ start ] ) ; } if ( count [ 0 ] > 0 && count [ 1 ] > 0 && count [ 2 ] > 0 && count [ 3 ] > 0 && count [ 4 ] > 0 ) { ans = min ( ans , x - start + 1 ) ; } } if ( ans == n + 1 ) return -1 ; return ans ; } int main ( ) { string s = " aaeebbeaccaaoiuooooooooiuu " ; cout << findMinLength ( s ) ; return 0 ; } |
Number of strings which starts and ends with same character after rotations | C ++ program for the above approach ; Function to find the count of string with equal end after rotations ; To store the final count ; Traverse the string ; If current character is same as the previous character then increment the count ; Return the final count ; Driver Code ; Given string ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countStrings ( string s ) { int cnt = 0 ; for ( int i = 1 ; s [ i ] ; i ++ ) { if ( s [ i ] == s [ i + 1 ] ) { cnt ++ ; } } return cnt ; } int main ( ) { string str ( " aacbb " ) ; cout << countStrings ( str ) ; return 0 ; } |
Check if frequency of each character is equal to its position in English Alphabet | C ++ program for the above approach ; Initialise frequency array ; Traverse the string ; Update the frequency ; Check for valid string ; If frequency is non - zero ; If freq is not equals to ( i + 1 ) , then return false ; Return true ; ; Driver Code ; Given string str | #include " bits / stdc + + . h " NEW_LINE using namespace std ; bool checkValidString ( string str ) { int freq [ 26 ] = { 0 } ; for ( int i = 0 ; str [ i ] ; i ++ ) { freq [ str [ i ] - ' a ' ] ++ ; } for ( int i = 0 ; i < 26 ; i ++ ) { if ( freq [ i ] != 0 ) { if ( freq [ i ] != i + 1 ) { return false ; } } } return true ; } int main ( ) { string str = " abbcccdddd " ; if ( checkValidString ( str ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Print all the non | C ++ program to print all the non - repeating words from the two given sentences ; Function to print all the non - repeating words from the two given sentences ; Concatenate the two strings into one ; Iterating over the whole concatenated string ; Searching for the word in A . If while searching , we reach the end of the string , then the word is not present in the string ; Initialise word for the next iteration ; Driver code | #include <bits/stdc++.h> NEW_LINE #include <string.h> NEW_LINE using namespace std ; void removeRepeating ( string s1 , string s2 ) { string s3 = s1 + " β " + s2 + " β " ; string words = " " ; int i = 0 ; for ( auto x : s3 ) { if ( x == ' β ' ) { if ( s1 . find ( words ) == string :: npos || s2 . find ( words ) == string :: npos ) cout << words ; words = " " ; } else { words = words + x ; } } } int main ( ) { string s1 = " I β have β go β a β pen " ; string s2 = " I β want β to β go β park " ; removeRepeating ( s1 , s2 ) ; return 0 ; } |
Convert the number from International system to Indian system | C ++ program to convert the number from International system to Indian system ; Function to convert a number represented in International numeric system to Indian numeric system . ; Find the length of the input string ; Removing all the separators ( , ) from the input string ; Reverse the input string ; Declaring the output string ; Process the input string ; Add a separator ( , ) after the third number ; Then add a separator ( , ) after every second number ; Reverse the output string ; Return the output string back to the main function ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string convert ( string input ) { int len = input . length ( ) ; for ( int i = 0 ; i < len ; ) { if ( input [ i ] == ' , β ' ) { input . erase ( input . begin ( ) + i ) ; len -- ; i -- ; } else if ( input [ i ] == ' β ' ) { input . erase ( input . begin ( ) + i ) ; len -- ; i -- ; } else { i ++ ; } } reverse ( input . begin ( ) , input . end ( ) ) ; string output ; for ( int i = 0 ; i < len ; i ++ ) { if ( i == 2 ) { output += input [ i ] ; output += " , β " ; } else if ( i > 2 && i % 2 == 0 && i + 1 < len ) { output += input [ i ] ; output += " , β " ; } else { output += input [ i ] ; } } reverse ( output . begin ( ) , output . end ( ) ) ; return output ; } int main ( ) { string input1 = "123 , β 456 , β 789" ; string input2 = "90 , β 050 , β 000 , β 000" ; cout << convert ( input1 ) << endl ; cout << convert ( input2 ) ; } |
Construct the Cypher string based on the given conditions | C ++ program for the above approach ; Function to check whether a number is prime or not ; Function to check if a prime number can be expressed as sum of two Prime Numbers ; If the N && ( N - 2 ) is Prime ; Function to check semiPrime ; Loop from 2 to sqrt ( num ) ; Increment the count of prime numbers ; If num is greater than 1 , then add 1 to it ; Return '1' if count is 2 else return '0' ; Function to make the Cypher string ; Resultant string ; Make string for the number N ; Check for semiPrime ; Traverse to make Cypher string ; If index is odd add the current character ; Else current character is changed ; Check for sum of two primes ; Traverse to make Cypher string ; If index is odd then current character is changed ; Else add the current character ; If the resultant string is " " then print - 1 ; Else print the resultant string ; Driver Code ; Given Number ; Function Call | #include " bits / stdc + + . h " NEW_LINE using namespace std ; bool isPrime ( int n ) { if ( n <= 1 ) return false ; for ( int i = 2 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) return false ; } return true ; } bool isPossibleSum ( int N ) { if ( isPrime ( N ) && isPrime ( N - 2 ) ) { return true ; } else { return false ; } } bool checkSemiprime ( int num ) { int cnt = 0 ; for ( int i = 2 ; cnt < 2 && i * i <= num ; ++ i ) { while ( num % i == 0 ) { num /= i , ++ cnt ; } } if ( num > 1 ) { ++ cnt ; } return cnt == 2 ; } void makeCypherString ( int N ) { string semiPrime = " " ; string sumOfPrime = " " ; string str = to_string ( N ) ; if ( checkSemiprime ( N ) ) { for ( int i = 0 ; str [ i ] ; i ++ ) { if ( i & 1 ) { semiPrime += str [ i ] ; } else { semiPrime += char ( str [ i ] - '0' + 65 ) ; } } } if ( isPossibleSum ( N ) ) { for ( int i = 0 ; str [ i ] ; i ++ ) { if ( i & 1 ) { sumOfPrime += char ( str [ i ] - '0' + 65 ) ; } else { sumOfPrime += str [ i ] ; } } } if ( semiPrime + sumOfPrime == " " ) { cout << " - 1" ; } else { cout << semiPrime + sumOfPrime ; } } int main ( ) { int N = 1011243 ; makeCypherString ( N ) ; return 0 ; } |
Maximum splits in binary string such that each substring is divisible by given odd number | C ++ Program to split a given binary string into maximum possible segments divisible by given odd number K ; Function to calculate maximum splits possible ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void max_segments ( string str , int K ) { int n = str . length ( ) ; int s = 0 , sum = 0 , count = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { int a = str [ i ] - '0' ; sum += a * pow ( 2 , s ) ; s ++ ; if ( sum != 0 && sum % K == 0 ) { count ++ ; sum = 0 ; s = 0 ; } } if ( sum != 0 ) cout << " - 1" << endl ; else cout << count << endl ; } int main ( ) { string str = "10111001" ; int K = 5 ; max_segments ( str , K ) ; return 0 ; } |
Make the string lexicographically smallest and non palindromic by replacing exactly one character | C ++ program to make the string lexicographically smallest non palindromic string by replacing exactly one character ; Function to find the required string ; length of the string ; Iterate till half of the string ; replacing a non ' a ' char with ' a ' ; Check if there is no ' a ' in string we replace last char of string by ' b ' ; If the input is a single character ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string findStr ( string S ) { int n = S . size ( ) ; for ( int i = 0 ; i < n / 2 ; ++ i ) { if ( S [ i ] != ' a ' ) { S [ i ] = ' a ' ; return S ; } } S [ n - 1 ] = ' b ' ; return n < 2 ? " β - 1 β " : S ; } int main ( ) { string str = " a " ; cout << findStr ( str ) << endl ; string str1 = " abccba " ; cout << findStr ( str1 ) << endl ; return 0 ; } |
Find the k | C ++ program find the Kth string in lexicographical order consisting of N - 2 xs and 2 ys ; Function to find the Kth string in lexicographical order which consists of N - 2 xs and 2 ys ; Iterate for all possible positions of Left most Y ; If i is the left most position of Y ; Put Y in their positions ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void kth_string ( int n , int k ) { for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( k <= ( n - i - 1 ) ) { for ( int j = 0 ; j < n ; j ++ ) { if ( j == i or j == n - k ) cout << ' Y ' ; else cout << ' X ' ; } break ; } k -= ( n - i - 1 ) ; } } int main ( ) { int n = 5 , k = 7 ; kth_string ( n , k ) ; return 0 ; } |
Transform string str1 into str2 by taking characters from string str3 | C ++ program of the above approach ; Function to check whether str1 can be transformed to str2 ; To store the frequency of characters of string str3 ; Declare two pointers & flag ; Traverse both the string and check whether it can be transformed ; If both pointers point to same characters increment them ; If the letters don 't match check if we can find it in string C ; If the letter is available in string str3 , decrement it 's frequency & increment the ptr2 ; If letter isn 't present in str3[] set the flag to false and break ; If the flag is true and both pointers points to their end of respective strings then it is possible to transformed str1 into str2 , otherwise not . ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void convertString ( string str1 , string str2 , string str3 ) { map < char , int > freq ; for ( int i = 0 ; str3 [ i ] ; i ++ ) { freq [ str3 [ i ] ] ++ ; } int ptr1 = 0 ; int ptr2 = 0 ; bool flag = true ; while ( ptr1 < str1 . length ( ) && ptr2 < str2 . length ( ) ) { if ( str1 [ ptr1 ] == str2 [ ptr2 ] ) { ptr1 ++ ; ptr2 ++ ; } else { if ( freq [ str3 [ ptr2 ] ] > 0 ) { freq [ str3 [ ptr2 ] ] -- ; ptr2 ++ ; } else { flag = false ; break ; } } } if ( flag && ptr1 == str1 . length ( ) && ptr2 == str2 . length ( ) ) { cout << " YES " << endl ; } else { cout << " NO " << endl ; } } int main ( ) { string str1 = " abyzfe " ; string str2 = " abcdeyzf " ; string str3 = " popode " ; convertString ( str1 , str2 , str3 ) ; return 0 ; } |
Decrypt the String according to given algorithm | C ++ implementation of the approach ; Function that returns ( num % 26 ) ; Initialize result ; One by one process all digits of ' num ' ; Function to return the decrypted string ; To store the final decrypted answer ; One by one check for each character if it is a numeric character ; Modulo the number found in the string by 26 ; Driver code ; Print the decrypted string | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MOD = 26 ; int modulo_by_26 ( string num ) { int res = 0 ; for ( int i = 0 ; i < num . length ( ) ; i ++ ) res = ( res * 10 + ( int ) num [ i ] - '0' ) % MOD ; return res ; } string decrypt_message ( string s ) { string decrypted_str = " " ; string num_found_so_far = " " ; for ( int i = 0 ; i < s . length ( ) ; ++ i ) { if ( s [ i ] >= '0' && s [ i ] <= '9' ) { num_found_so_far += s [ i ] ; } else if ( num_found_so_far . length ( ) > 0 ) { decrypted_str += ' a ' + modulo_by_26 ( num_found_so_far ) ; num_found_so_far = " " ; } } if ( num_found_so_far . length ( ) > 0 ) { decrypted_str += ' a ' + modulo_by_26 ( num_found_so_far ) ; } return decrypted_str ; } int main ( ) { string s = "32ytAAcV4ui30hf10hj18" ; cout << decrypt_message ( s ) ; return 0 ; } |
Maximum number of overlapping string | C ++ implementation to find the maximum number of occurrence of the overlapping count ; Function to find the maximum overlapping strings ; Get the current character ; Condition to check if the current character is the first character of the string T then increment the overlapping count ; Condition to check previous character is also occurred ; Update count of previous and current character ; Condition to check the current character is the last character of the string T ; Condition to check the every subsequence is a valid string T ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxOverlap ( string S , string T ) { string str = T ; int count [ T . length ( ) ] = { 0 } ; int overlap = 0 ; int max_overlap = 0 ; for ( int i = 0 ; i <= S . length ( ) ; i ++ ) { int index = str . find ( S [ i ] ) ; if ( index == 0 ) { overlap ++ ; if ( overlap >= 2 ) max_overlap = max ( overlap , max_overlap ) ; count [ index ] ++ ; } else { if ( count [ index - 1 ] <= 0 ) return -1 ; count [ index ] ++ ; count [ index - 1 ] -- ; } if ( index == 4 ) overlap -- ; } if ( overlap == 0 ) return max_overlap ; else return -1 ; } int main ( ) { string S = " chcirphirp " ; string T = " chirp " ; cout << maxOverlap ( S , T ) ; return 0 ; } |
Minimum number of operations required to make two strings equal | C ++ implementation to find the minimum number of operations to make two strings equal ; Function to find out parent of an alphabet ; Function to merge two different alphabets ; Merge a and b using rank compression ; Function to find the minimum number of operations required ; Initializing parent to i and rank ( size ) to 1 ; We will store our answerin this vector ; Traversing strings ; If they have different parents ; Find their respective parents and merge them ; Store this in our Answer vector ; Number of operations ; Driver Code ; Two strings S1 and S2 ; Function Call | #include <bits/stdc++.h> NEW_LINE #define MAX 500001 NEW_LINE using namespace std ; int parent [ MAX ] ; int Rank [ MAX ] ; int find ( int x ) { return parent [ x ] = parent [ x ] == x ? x : find ( parent [ x ] ) ; } void merge ( int r1 , int r2 ) { if ( r1 != r2 ) { if ( Rank [ r1 ] > Rank [ r2 ] ) { parent [ r2 ] = r1 ; Rank [ r1 ] += Rank [ r2 ] ; } else { parent [ r1 ] = r2 ; Rank [ r2 ] += Rank [ r1 ] ; } } } void minimumOperations ( string s1 , string s2 ) { for ( int i = 1 ; i <= 26 ; i ++ ) { parent [ i ] = i ; Rank [ i ] = 1 ; } vector < pair < char , char > > ans ; for ( int i = 0 ; i < s1 . length ( ) ; i ++ ) { if ( s1 [ i ] != s2 [ i ] ) { if ( find ( s1 [ i ] - 96 ) != find ( s2 [ i ] - 96 ) ) { int x = find ( s1 [ i ] - 96 ) ; int y = find ( s2 [ i ] - 96 ) ; merge ( x , y ) ; ans . push_back ( { s1 [ i ] , s2 [ i ] } ) ; } } } cout << ans . size ( ) << endl ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) cout << ans [ i ] . first << " - > " << ans [ i ] . second << endl ; } int main ( ) { string s1 , s2 ; s1 = " abb " ; s2 = " dad " ; minimumOperations ( s1 , s2 ) ; return 0 ; } |
Find the N | C ++ program to find the N - th lexicographic permutation of string using Factroid method ; Function to calculate nth permutation of string ; Creating an empty stack ; Subtracting 1 from N because the permutations start from 0 in factroid method ; Loop to generate the factroid of the sequence ; Loop to generate nth permutation ; Remove 1 - element in each cycle ; Final answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void string_permutation ( long long int n , string str ) { stack < int > s ; string result ; n = n - 1 ; for ( int i = 1 ; i < str . size ( ) + 1 ; i ++ ) { s . push ( n % i ) ; n = n / i ; } for ( int i = 0 ; i < str . size ( ) ; i ++ ) { int a = s . top ( ) ; result += str [ a ] ; int j ; for ( j = a ; j < str . length ( ) ; j ++ ) str [ j ] = str [ j + 1 ] ; str [ j + 1 ] = ' \0' ; s . pop ( ) ; } cout << result << endl ; } int main ( ) { string str = " abcde " ; long long int n = 11 ; string_permutation ( n , str ) ; return 0 ; } |
Defanged Version of Internet Protocol Address | C ++ implementation to find the defanged version of the IP address ; Function to generate a defanged version of IP address . ; Loop to iterate over the characters of the string ; Driven Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string GeberateDefangIP ( string str ) { string defangIP = " " ; for ( char c : str ) ( c == ' . ' ) ? defangIP += " [ . ] " : defangIP += c ; return defangIP ; } int main ( ) { string str = "255.100.50.0" ; cout << GeberateDefangIP ( str ) ; return 0 ; } |
Longest palindromic string formed by concatenation of prefix and suffix of a string | C ++ implementation of the above approach ; Function used to calculate the longest prefix which is also a suffix ; Traverse the string ; Update the lps size ; Returns size of lps ; Function to calculate the length of longest palindromic substring which is either a suffix or prefix ; Append a character to separate the string and reverse of the string ; Reverse the string ; Append the reversed string ; Function to find the Longest palindromic string formed from concatenation of prefix and suffix of a given string ; Calculating the length for which prefix is reverse of suffix ; Append prefix to the answer ; Store the remaining string ; If the remaining string is not empty that means that there can be a palindrome substring which can be added between the suffix & prefix ; Calculate the length of longest prefix palindromic substring ; Reverse the given string to find the longest palindromic suffix ; Calculate the length of longest prefix palindromic substring ; If the prefix palindrome is greater than the suffix palindrome ; Append the prefix to the answer ; If the suffix palindrome is greater than the prefix palindrome ; Append the suffix to the answer ; Finally append the suffix to the answer ; Return the answer string ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int kmp ( string s ) { vector < int > lps ( s . size ( ) , 0 ) ; for ( int i = 1 ; i < s . size ( ) ; i ++ ) { int previous_index = lps [ i - 1 ] ; while ( previous_index > 0 && s [ i ] != s [ previous_index ] ) { previous_index = lps [ previous_index - 1 ] ; } lps [ i ] = previous_index + ( s [ i ] == s [ previous_index ] ? 1 : 0 ) ; } return lps [ lps . size ( ) - 1 ] ; } int remainingStringLongestPallindrome ( string s ) { string t = s + " ? " ; reverse ( s . begin ( ) , s . end ( ) ) ; t += s ; return kmp ( t ) ; } string longestPrefixSuffixPallindrome ( string s ) { int length = 0 ; int n = s . size ( ) ; for ( int i = 0 , j = n - 1 ; i < j ; i ++ , j -- ) { if ( s [ i ] != s [ j ] ) { break ; } length ++ ; } string ans = s . substr ( 0 , length ) ; string remaining = s . substr ( length , ( n - ( 2 * length ) ) ) ; if ( remaining . size ( ) ) { int longest_prefix = remainingStringLongestPallindrome ( remaining ) ; reverse ( remaining . begin ( ) , remaining . end ( ) ) ; int longest_suffix = remainingStringLongestPallindrome ( remaining ) ; if ( longest_prefix > longest_suffix ) { reverse ( remaining . begin ( ) , remaining . end ( ) ) ; ans += remaining . substr ( 0 , longest_prefix ) ; } else { ans += remaining . substr ( 0 , longest_suffix ) ; } } ans += s . substr ( n - length , length ) ; return ans ; } int main ( ) { string str = " rombobinnimor " ; cout << longestPrefixSuffixPallindrome ( str ) << endl ; } |
Generate a string with maximum possible alphabets with odd frequencies | C ++ program to generate a string of length n with maximum possible alphabets with each of them occuring odd number of times . ; Function to generate a string of length n with maximum possible alphabets each occuring odd number of times . ; If n is odd ; Add all characters from b - y ; Append a to fill the remaining length ; If n is even ; Add all characters from b - z ; Append a to fill the remaining length ; Driven code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string generateTheString ( int n ) { string ans = " " ; if ( n % 2 ) { for ( int i = 0 ; i < min ( n , 24 ) ; i ++ ) { ans += ( char ) ( ' b ' + i ) ; } if ( n > 24 ) { for ( int i = 0 ; i < ( n - 24 ) ; i ++ ) ans += ' a ' ; } } else { for ( int i = 0 ; i < min ( n , 25 ) ; i ++ ) { ans += ( char ) ( ' b ' + i ) ; } if ( n > 25 ) { for ( int i = 0 ; i < ( n - 25 ) ; i ++ ) ans += ' a ' ; } } return ans ; } int main ( ) { int n = 34 ; cout << generateTheString ( n ) ; return 0 ; } |
Move all occurrence of letter ' x ' from the string s to the end using Recursion | C ++ implementation to Move all occurrence of letter x from the string s to the end using Recursion ; Function to move all ' x ' in the end ; Store current character ; Check if current character is not ' x ' ; recursive function call ; Check if current character is ' x ' ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void moveAtEnd ( string s , int i , int l ) { if ( i >= l ) return ; char curr = s [ i ] ; if ( curr != ' x ' ) cout << curr ; moveAtEnd ( s , i + 1 , l ) ; if ( curr == ' x ' ) cout << curr ; return ; } int main ( ) { string s = " geekxsforgexxeksxx " ; int l = s . length ( ) ; moveAtEnd ( s , 0 , l ) ; return 0 ; } |
Construct a string of length L such that each substring of length X has exactly Y distinct letters | C ++ implementation to construct a string of length L such that each substring of length X has exactly Y distinct letters . ; Initialize p equal to the ASCII value of a ; Iterate till the length of the string ; Driver code | #include <iostream> NEW_LINE using namespace std ; void String ( int l , int x , int y ) { int p = 97 ; for ( int j = 0 ; j < l ; j ++ ) { char ans = ( char ) ( p + ( j % y ) ) ; cout << ans ; } } int main ( ) { int l = 6 ; int x = 5 ; int y = 3 ; String ( l , x , y ) ; return 0 ; } |
Find the final co | C ++ implementation of the above approach ; Function to print the final position of the point after traversing through the given directions ; Traversing through the given directions ; If its north or south the point will move left or right ; If its west or east the point will move upwards or downwards ; Returning the final position ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void finalCoordinates ( int SX , int SY , string D ) { for ( int i = 0 ; i < D . length ( ) ; i ++ ) { if ( D [ i ] == ' N ' ) SY += 1 ; else if ( D [ i ] == ' S ' ) SY -= 1 ; else if ( D [ i ] == ' E ' ) SX += 1 ; else SX -= 1 ; } string ans = ' ( ' + to_string ( SX ) + ' , ' + to_string ( SY ) + ' ) ' ; cout << ans << endl ; } int main ( ) { int SX = 2 , SY = 2 ; string D = " NSSE " ; finalCoordinates ( SX , SY , D ) ; } |
Frequency of smallest character in first sentence less than that of second sentence | C ++ program for the above approach ; Function to count the frequency of minimum character ; Sort the string s ; Return the count with smallest character ; Function to count number of frequency of smallest character of string arr1 [ ] is less than the string in arr2 [ ] ; To store the frequency of smallest character in each string of arr2 ; Traverse the arr2 [ ] ; Count the frequency of smallest character in string s ; Append the frequency to freq [ ] ; Sort the frequency array ; Traverse the array arr1 [ ] ; Count the frequency of smallest character in string s ; find the element greater than f ; Find the count such that arr1 [ i ] < arr2 [ j ] ; Print the count ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countMinFreq ( string s ) { sort ( s . begin ( ) , s . end ( ) ) ; return count ( s . begin ( ) , s . end ( ) , s [ 0 ] ) ; } void countLessThan ( vector < string > & arr1 , vector < string > & arr2 ) { vector < int > freq ; for ( string s : arr2 ) { int f = countMinFreq ( s ) ; freq . push_back ( f ) ; } sort ( freq . begin ( ) , freq . end ( ) ) ; for ( string s : arr1 ) { int f = countMinFreq ( s ) ; auto it = upper_bound ( freq . begin ( ) , freq . end ( ) , f ) ; int cnt = freq . size ( ) - ( it - freq . begin ( ) ) ; cout << cnt << ' β ' ; } } int main ( ) { vector < string > arr1 , arr2 ; arr1 = { " yyy " , " zz " } ; arr2 = { " x " , " xx " , " xxx " , " xxxx " } ; countLessThan ( arr1 , arr2 ) ; return 0 ; } |
Lexicographically all Shortest Palindromic Substrings from a given string | C ++ program to find Lexicographically all Shortest Palindromic Substrings from a given string ; Function to find all lexicographically shortest palindromic substring ; Array to keep track of alphabetic characters ; Iterate to print all lexicographically shortest substring ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void shortestPalindrome ( string s ) { int abcd [ 26 ] = { 0 } ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) abcd [ s [ i ] - 97 ] = 1 ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( abcd [ i ] == 1 ) cout << char ( i + 97 ) << " β " ; } } int main ( ) { string s = " geeksforgeeks " ; shortestPalindrome ( s ) ; return 0 ; } |
Remove duplicates from string keeping the order according to last occurrences | C ++ program to remove duplicate character from character array and print in sorted order ; Used as index in the modified string ; Traverse through all characters ; Check if str [ i ] is present before it ; If not present , then add it to result . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string removeDuplicates ( string str ) { int n = str . length ( ) ; string res = " " ; for ( int i = 0 ; i < n ; i ++ ) { int j ; for ( j = i + 1 ; j < n ; j ++ ) if ( str [ i ] == str [ j ] ) break ; if ( j == n ) res = res + str [ i ] ; } return res ; } int main ( ) { string str = " geeksforgeeks " ; cout << removeDuplicates ( str ) ; return 0 ; } |
Remove duplicates from string keeping the order according to last occurrences | C ++ program to remove duplicate character from character array and print in sorted order ; Used as index in the modified string ; Create an empty hash table ; Traverse through all characters from right to left ; If current character is not in ; Reverse the result string ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string removeDuplicates ( string str ) { int n = str . length ( ) ; unordered_set < char > s ; string res = " " ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( s . find ( str [ i ] ) == s . end ( ) ) { res = res + str [ i ] ; s . insert ( str [ i ] ) ; } } reverse ( res . begin ( ) , res . end ( ) ) ; return res ; } int main ( ) { string str = " geeksforgeeks " ; cout << removeDuplicates ( str ) ; return 0 ; } |
Count of numbers in a range that does not contain the digit M and which is divisible by M . | C ++ implementation to illustrate the program ; Function to count all the numbers which does not contain the digit ' M ' and is divisible by M ; Storing all the distinct digits of a number ; Checking if the two conditions are satisfied or not ; Driver code ; Lower Range ; Upper Range ; The digit | #include <bits/stdc++.h> NEW_LINE using namespace std ; void contain ( int L , int U , int M ) { int count = 0 ; for ( int j = L ; j < U ; j ++ ) { set < string > num ; string str = to_string ( j ) ; num . insert ( str ) ; if ( j % M == 0 and num . find ( to_string ( M ) ) == num . end ( ) ) { count += 1 ; } } cout << count - 2 ; } int main ( ) { int L = 106 ; int U = 200 ; int M = 7 ; contain ( L , U , M ) ; } |
Longest string which is prefix string of at least two strings | C ++ program to find longest string which is prefix string of at least two strings ; Function to find Max length of the prefix ; Base case ; Iterating over all the alphabets ; Checking if char exists in current string or not ; If atleast 2 string have that character ; Recursive call to i + 1 ; Driver code ; Initialising strings ; push strings into vectors . | #include <bits/stdc++.h> NEW_LINE using namespace std ; int max1 = 0 ; int MaxLength ( vector < string > v , int i , int m ) { if ( i >= m ) { return m - 1 ; } for ( int k = 0 ; k < 26 ; k ++ ) { char c = ' a ' + k ; vector < string > v1 ; for ( int j = 0 ; j < v . size ( ) ; j ++ ) { if ( v [ j ] [ i ] == c ) { v1 . push_back ( v [ j ] ) ; } } if ( v1 . size ( ) >= 2 ) { max1 = max ( max1 , MaxLength ( v1 , i + 1 , m ) ) ; } else { max1 = max ( max1 , i - 1 ) ; } } return max1 ; } int main ( ) { string s1 , s2 , s3 , s4 , s5 ; s1 = " abcde " ; s2 = " abcsd " ; s3 = " bcsdf " ; s4 = " abcda " ; s5 = " abced " ; vector < string > v ; v . push_back ( s1 ) ; v . push_back ( s2 ) ; v . push_back ( s3 ) ; v . push_back ( s4 ) ; v . push_back ( s5 ) ; int m = v [ 0 ] . size ( ) ; cout << MaxLength ( v , 0 , m ) + 1 << endl ; return 0 ; } |
Periodic Binary String With Minimum Period and a Given Binary String as Subsequence . | C ++ implementation to find the periodic string with minimum period ; Function to find the periodic string with minimum period ; Print the string S if it consists of similar elements ; Find the required periodic string with period 2 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findPeriodicString ( string S ) { int l = 2 * S . length ( ) ; int count = 0 ; for ( int i = 0 ; i < S . length ( ) ; i ++ ) { if ( S [ i ] == '1' ) count ++ ; } if ( count == S . length ( ) count == 0 ) cout << S << " STRNEWLINE " ; else { char arr [ l ] ; for ( int i = 0 ; i < l ; i += 2 ) { arr [ i ] = '1' ; arr [ i + 1 ] = '0' ; } for ( int i = 0 ; i < l ; i ++ ) cout << arr [ i ] ; cout << " STRNEWLINE " ; } } int main ( ) { string S = "1111001" ; findPeriodicString ( S ) ; return 0 ; } |
Print Strings In Reverse Dictionary Order Using Trie | C ++ program to print array of string in reverse dictionary order using trie ; Trie node ; endOfWord is true if the node represents end of a word ; Function will return the new node initialized NULL ; Initialize null to the all child ; Function will insert the string in a trie recursively ; Create a new node ; Recursive call for insertion of string ; Make the endOfWord true which represents the end of string ; Function call to insert a string ; Function call with necessary arguments ; Function to check whether the node is leaf or not ; Function to display the content of trie ; If node is leaf node , it indicates end of string , so a null character is added and string is displayed ; Assign a null character in temporary string ; check if NON NULL child is found add parent key to str and call the display function recursively for child node ; Function call for displaying content ; Driver code ; After inserting strings , trie will look like root / \ a t | | n h | \ | s y e | | \ w i r | | | e r e | r | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define CHILDREN 26 NEW_LINE #define MAX 100 NEW_LINE struct trie { trie * child [ CHILDREN ] ; bool endOfWord ; } ; trie * createNode ( ) { trie * temp = new trie ( ) ; temp -> endOfWord = false ; for ( int i = 0 ; i < CHILDREN ; i ++ ) { temp -> child [ i ] = NULL ; } return temp ; } void insertRecursively ( trie * itr , string str , int i ) { if ( i < str . length ( ) ) { int index = str [ i ] - ' a ' ; if ( itr -> child [ index ] == NULL ) { itr -> child [ index ] = createNode ( ) ; } insertRecursively ( itr -> child [ index ] , str , i + 1 ) ; } else { itr -> endOfWord = true ; } } void insert ( trie * itr , string str ) { insertRecursively ( itr , str , 0 ) ; } bool isLeafNode ( trie * root ) { return root -> endOfWord != false ; } void displayContent ( trie * root , char str [ ] , int level ) { if ( isLeafNode ( root ) ) { str [ level ] = ' \0' ; cout << str << endl ; } for ( int i = CHILDREN - 1 ; i >= 0 ; i -- ) { if ( root -> child [ i ] ) { str [ level ] = i + ' a ' ; displayContent ( root -> child [ i ] , str , level + 1 ) ; } } } void display ( trie * itr ) { int level = 0 ; char str [ MAX ] ; displayContent ( itr , str , level ) ; } int main ( ) { trie * root = createNode ( ) ; insert ( root , " their " ) ; insert ( root , " there " ) ; insert ( root , " answer " ) ; insert ( root , " any " ) ; display ( root ) ; return 0 ; } |
Check if two strings after processing backspace character are equal or not | C ++ implementation to Check if two strings after processing backspace character are equal or not ; function to compare the two strings ; the index of character in string which would be removed when backspace is encountered ; checks if a backspace is encountered or not . In case the first character is # , no change in string takes place ; the character after the # is added after the character at position rem_ind1 ; checks if a backspace is encountered or not ; check if the value of rem_ind1 and rem_ind2 is same , if not then it means they have different length ; check if resultant strings are empty ; check if each character in the resultant string is same ; Driver code ; initialise two strings | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool compare ( string s , string t ) { int ps , pt , i ; ps = -1 ; for ( i = 0 ; i < s . size ( ) ; i ++ ) { if ( s [ i ] == ' # ' && ps != -1 ) ps -= 1 ; else if ( s [ i ] != ' # ' ) { s = s [ i ] ; ps += 1 ; } } pt = -1 ; for ( i = 0 ; i < t . size ( ) ; i ++ ) { if ( t [ i ] == ' # ' && pt != -1 ) pt -= 1 ; else if ( t [ i ] != ' # ' ) { t [ pt + 1 ] = t [ i ] ; pt += 1 ; } } if ( pt != ps ) return false ; else if ( ps == -1 && pt == -1 ) return true ; else { for ( i = 0 ; i <= pt ; i ++ ) { if ( s [ i ] != t [ i ] ) return false ; } return true ; } } int main ( ) { string s = " geee # e # ks " ; string t = " gee # # eeks " ; if ( compare ( s , t ) ) cout << " True " ; else cout << " False " ; } |
Queries to find total number of duplicate character in range L to R in the string S | CPP implementation to Find the total number of duplicate character in a range L to R for Q number of queries in a string S ; Vector of vector to store position of all characters as they appear in string ; Function to store position of each character ; Inserting position of each character as they appear ; Function to calculate duplicate characters for Q queries ; Variable to count duplicates ; Iterate over all 26 characters ; Finding the first element which is less than or equal to L ; Check if first pointer exists and is less than R ; Incrementing first pointer to check if the next duplicate element exists ; Check if the next element exists and is less than R ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < vector < int > > v ( 26 ) ; void calculate ( string s ) { for ( int i = 0 ; i < s . size ( ) ; i ++ ) { v [ s [ i ] - ' a ' ] . push_back ( i ) ; } } void query ( int L , int R ) { int duplicates = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) { auto first = lower_bound ( v [ i ] . begin ( ) , v [ i ] . end ( ) , L - 1 ) ; if ( first != v [ i ] . end ( ) && * first < R ) { first ++ ; if ( first != v [ i ] . end ( ) && * first < R ) duplicates ++ ; } } cout << duplicates << endl ; } int main ( ) { string s = " geeksforgeeks " ; int Q = 2 ; int l1 = 1 , r1 = 5 ; int l2 = 4 , r2 = 8 ; calculate ( s ) ; query ( l1 , r1 ) ; query ( l2 , r2 ) ; return 0 ; } |
Count the minimum number of groups formed in a string | C ++ implementation to Count the minimum number of groups formed in a string by replacing consecutive characters with same single character ; Function to count the minimum number of groups formed in the given string s ; Initializing count as one since the string is not NULL ; Comparing adjacent characters ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void group_formed ( string S ) { int count = 1 ; for ( int i = 0 ; i < S . size ( ) - 1 ; i ++ ) { if ( S [ i ] != S [ i + 1 ] ) count += 1 ; } cout << ( count ) ; } int main ( ) { string S = " TTWWW " ; group_formed ( S ) ; } |
Find the Substring with maximum product | C ++ program to find the maximum product substring ; Function to return the value of a character ; Function to find the maximum product substring ; To store substrings ; Check if current product is maximum possible or not ; If product is 0 ; Return the substring with maximum product ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int value ( char x ) { return ( int ) ( x - ' a ' ) ; } string maximumProduct ( string str , int n ) { string answer = " " , curr = " " ; long long maxProduct = 0 , product = 1 ; for ( int i = 0 ; i < n ; i ++ ) { product *= 1LL * value ( str [ i ] ) ; curr += str [ i ] ; if ( product >= maxProduct ) { maxProduct = product ; answer = curr ; } if ( product == 0 ) { product = 1 ; curr = " " ; } } return answer ; } int main ( ) { string str = " sdtfakdhdahdzz " ; int n = str . size ( ) ; cout << maximumProduct ( str , n ) << endl ; return 0 ; } |
Sum of minimum and the maximum difference between two given Strings | C ++ program to find the sum of the minimum and the maximum difference between two given strings ; Function to find the sum of the minimum and the maximum difference between two given strings ; Variables to store the minimum difference and the maximum difference ; Iterate through the length of the string as both the given strings are of the same length ; For the maximum difference , we can replace " + " in both the strings with different char ; For the minimum difference , we can replace " + " in both the strings with the same char ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( string a , string b ) { int l = a . length ( ) ; int min = 0 , max = 0 ; for ( int i = 0 ; i < l ; i ++ ) { if ( a [ i ] == ' + ' b [ i ] == ' + ' a [ i ] != b [ i ] ) max ++ ; if ( a [ i ] != ' + ' && b [ i ] != ' + ' && a [ i ] != b [ i ] ) min ++ ; } cout << min + max << endl ; } int main ( ) { string s1 = " a + c " , s2 = " + + b " ; solve ( s1 , s2 ) ; return 0 ; } |
Minimum letters to be removed to make all occurrences of a given letter continuous | C ++ implementation of the above approach ; Function to find the minimum number of deletions required to make the occurrences of the given character K continuous ; Find the first occurrence of the given letter ; Iterate from the first occurrence till the end of the sequence ; Find the index from where the occurrence of the character is not continuous ; Update the answer with the number of elements between non - consecutive occurrences of the given letter ; Update the count for all letters which are not equal to the given letter ; Return the count ; Driver code ; Calling the function ; Calling the function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int noOfDeletions ( string str , char k ) { int ans = 0 , cnt = 0 , pos = 0 ; while ( pos < str . length ( ) && str [ pos ] != k ) { pos ++ ; } int i = pos ; while ( i < str . length ( ) ) { while ( i < str . length ( ) && str [ i ] == k ) { i = i + 1 ; } ans = ans + cnt ; cnt = 0 ; while ( i < str . length ( ) && str [ i ] != k ) { i = i + 1 ; cnt = cnt + 1 ; } } return ans ; } int main ( ) { string str1 = " ababababa " ; char k1 = ' a ' ; cout << noOfDeletions ( str1 , k1 ) << endl ; string str2 = " kprkkoinkopt " ; char k2 = ' k ' ; cout << noOfDeletions ( str2 , k2 ) << endl ; } |
Check whether an array of strings can correspond to a particular number X | C ++ implementation to check whether array of strings can correspond to a number X ; Function to find the maximum base possible for the number N ; Function to find the decimal equivalent of the number ; Condition to check if the number is convertible to another base ; Function to check that the array can correspond to a number X ; counter to count the numbers those are convertible to X ; Loop to iterate over the array ; Convert the current string to every base for checking whether it will correspond to X from any base ; Condition to check if every number of the array can be converted to X ; Driver Code ; The set of strings in base from [ 2 , 36 ] | #include <bits/stdc++.h> NEW_LINE using namespace std ; int val ( char c ) { if ( c >= '0' && c <= '9' ) return ( int ) c - '0' ; else return ( int ) c - ' A ' + 10 ; } int toDeci ( string str , int base ) { int len = str . size ( ) ; int power = 1 ; int num = 0 ; int i ; for ( i = len - 1 ; i >= 0 ; i -- ) { if ( val ( str [ i ] ) >= base ) { return -1 ; } num += val ( str [ i ] ) * power ; power = power * base ; } return num ; } void checkCorrespond ( vector < string > str , int x ) { int counter = 0 ; int n = str . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 2 ; j <= 36 ; j ++ ) { if ( toDeci ( str [ i ] , j ) == x ) { counter ++ ; break ; } } } if ( counter == n ) cout << " YES " << " STRNEWLINE " ; else cout << " NO " << " STRNEWLINE " ; } int main ( ) { int x = 16 ; vector < string > str = { "10000" , "20" , "16" } ; checkCorrespond ( str , x ) ; return 0 ; } |
Count of same length Strings that exists lexicographically in between two given Strings | C ++ program to find the count of same length Strings that exists lexicographically in between two given Strings ; Function to find the count of strings less than given string lexicographically ; Find length of string s ; Looping over the string characters and finding strings less than that character ; Function to find the count of same length Strings that exists lexicographically in between two given Strings ; Count string less than S1 ; Count string less than S2 ; Total strings between S1 and S2 would be difference between the counts - 1 ; If S1 is lexicographically greater than S2 then return 0 , otherwise return the value of totalString ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int LexicoLesserStrings ( string s ) { int count = 0 ; int len ; len = s . size ( ) ; for ( int i = 0 ; i < len ; i ++ ) { count += ( s [ i ] - ' a ' ) * pow ( 26 , len - i - 1 ) ; } return count ; } int countString ( string S1 , string S2 ) { int countS1 , countS2 , totalString ; countS1 = LexicoLesserStrings ( S1 ) ; countS2 = LexicoLesserStrings ( S2 ) ; totalString = countS2 - countS1 - 1 ; return ( totalString < 0 ? 0 : totalString ) ; } int main ( ) { string S1 , S2 ; S1 = " cda " ; S2 = " cef " ; cout << countString ( S1 , S2 ) ; return 0 ; } |
Longest Subsequence of a String containing only vowels | C ++ program to find the longest subsequence containing only vowels ; Function to check whether a character is vowel or not ; Returns true if x is vowel ; Function to find the longest subsequence which contain all vowels ; Length of the string ; Iterating through the string ; Checking if the character is a vowel or not ; If it is a vowel , then add it to the final string ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isVowel ( char x ) { x = tolower ( x ) ; return ( x == ' a ' x == ' e ' x == ' i ' x == ' o ' x == ' u ' ) ; } string longestVowelSubsequence ( string str ) { string answer = " " ; int n = str . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( isVowel ( str [ i ] ) ) { answer += str [ i ] ; } } return answer ; } int main ( ) { string str = " geeksforgeeks " ; cout << longestVowelSubsequence ( str ) << endl ; return 0 ; } |
Maximum repeated frequency of characters in a given string | C ++ implementation to find the maximum repeated frequency of characters in the given string ; Function to find the maximum repeated frequency of the characters in the given string ; Hash - Array to store the frequency of characters ; Loop to find the frequency of the characters ; Hash map to store the occurrence of frequencies of characters ; Loop to find the maximum Repeated frequency from hash - map ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findMaxFrequency ( string s ) { int arr [ 26 ] = { 0 } ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) arr [ s [ i ] - ' a ' ] ++ ; unordered_map < int , int > hash ; for ( int i = 0 ; i < 26 ; i ++ ) if ( arr [ i ] != 0 ) hash [ arr [ i ] ] ++ ; int max_count = 0 , res = -1 ; for ( auto i : hash ) { if ( max_count < i . second ) { res = i . first ; max_count = i . second ; } } cout << " Frequency β " << res << " β is β repeated β " << max_count << " β times " ; } int main ( ) { string s = " geeksgeeks " ; findMaxFrequency ( s ) ; return 0 ; } |
Generate string with Hamming Distance as half of the hamming distance between strings A and B | C ++ implementation of the above approach ; Function to find the required string ; Find the hamming distance between A and B ; If distance is odd , then resultant string is not possible ; Make the resultant string ; To store the final string ; Pick k characters from each string ; Pick K characters from string B ; Pick K characters from string A ; Append the res characters from string to the resultant string ; Print the resultant string ; Driver 's Code ; Function to find the resultant string | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findString ( string A , string B ) { int dist = 0 ; for ( int i = 0 ; A [ i ] ; i ++ ) { if ( A [ i ] != B [ i ] ) { dist ++ ; } } if ( dist & 1 ) { cout << " Not β Possible " << endl ; } else { string res = " " ; int K = dist / 2 ; for ( int i = 0 ; A [ i ] ; i ++ ) { if ( A [ i ] != B [ i ] && K > 0 ) { res . push_back ( B [ i ] ) ; K -- ; } else if ( A [ i ] != B [ i ] ) { res . push_back ( A [ i ] ) ; } else { res . push_back ( A [ i ] ) ; } } cout << res << endl ; } } int main ( ) { string A = "1001010" ; string B = "0101010" ; findString ( A , B ) ; return 0 ; } |
Longest suffix such that occurrence of each character is less than N after deleting atmost K characters | C ++ implementation to find longest suffix of the string such that occurrence of each character is less than K ; Function to find the maximum length suffix in the string ; Length of the string ; Map to store the number of occurrence of character ; Loop to iterate string from the last character ; Condition to check if the occurrence of each character is less than given number ; Condition when character cannot be deleted ; Longest suffix ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void maximumSuffix ( string s , int n , int k ) { int i = s . length ( ) - 1 ; int arr [ 26 ] = { 0 } ; string suffix = " " ; while ( i > -1 ) { int index = s [ i ] - ' a ' ; if ( arr [ index ] < n ) { arr [ index ] ++ ; suffix += s [ i ] ; i -- ; continue ; } if ( k == 0 ) break ; k -- ; i -- ; } reverse ( suffix . begin ( ) , suffix . end ( ) ) ; cout << suffix ; } int main ( ) { string str = " iahagafedcba " ; int n = 1 , k = 2 ; maximumSuffix ( str , n , k ) ; return 0 ; } |
XOR of two Binary Strings | C ++ Implementation to find the XOR of the two Binary Strings ; Function to find the XOR of the two Binary Strings ; Loop to iterate over the Binary Strings ; If the Character matches ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string xoring ( string a , string b , int n ) { string ans = " " ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == b [ i ] ) ans += "0" ; else ans += "1" ; } return ans ; } int main ( ) { string a = "1010" ; string b = "1101" ; int n = a . length ( ) ; string c = xoring ( a , b , n ) ; cout << c << endl ; } |
Find Kth largest string from the permutations of the string with two characters | C ++ implementation of above approach ; Function to print the kth largest string ; loop to iterate through series ; total takes the position of second y ; i takes the position of first y ; calculating first y position ; calculating second y position from first y ; print all x before first y ; print first y ; print all x between first y and second y ; print second y ; print x which occur after second y ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void kthString ( int n , int k ) { int total = 0 ; int i = 1 ; while ( total < k ) { total = total + n - i ; i ++ ; } int first_y_position = i - 1 ; int second_y_position = k - ( total - n + first_y_position ) ; for ( int j = 1 ; j < first_y_position ; j ++ ) cout << " x " ; cout << " y " ; int j = first_y_position + 1 ; while ( second_y_position > 1 ) { cout << " x " ; second_y_position -- ; j ++ ; } cout << " y " ; while ( j < n ) { cout << " x " ; j ++ ; } } int main ( ) { int n = 5 ; int k = 7 ; kthString ( n , k ) ; return 0 ; } |
Largest and Smallest N | C ++ program to find the largest and smallest N - digit numbers in Octal Number System ; Function to return the largest N - digit number in Octal Number System ; Append '7' N times ; Function to return the smallest N - digit number in Octal Number System ; Append '0' ( N - 1 ) times to 1 ; Function to print the largest and smallest N - digit Octal number ; Driver code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; string findLargest ( int N ) { string largest = string ( N , '7' ) ; return largest ; } string findSmallest ( int N ) { string smallest = "1" + string ( ( N - 1 ) , '0' ) ; return smallest ; } void printLargestSmallest ( int N ) { cout << " Largest : β " << findLargest ( N ) << endl ; cout << " Smallest : β " << findSmallest ( N ) << endl ; } int main ( ) { int N = 4 ; printLargestSmallest ( N ) ; return 0 ; } |
Count of substrings whose Decimal equivalent is greater than or equal to K | C ++ implementation to count the substrings whose decimal equivalent is greater than or equal to K ; Function to count number of substring whose decimal equivalent is greater than or equal to K ; Left pointer of the substring ; Right pointer of the substring ; Loop to maintain the last occurrence of the 1 in the string ; Variable to count the substring ; Loop to maintain the every possible end index of the substring ; Loop to find the substring whose decimal equivalent is greater than or equal to K ; Condition to check no of bits is out of bound ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned long long countSubstr ( string & s , int k ) { int n = s . length ( ) ; int l = n - 1 ; int r = n - 1 ; int arr [ n ] ; int last_indexof1 = -1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == '1' ) { arr [ i ] = i ; last_indexof1 = i ; } else { arr [ i ] = last_indexof1 ; } } unsigned long long no_of_substr = 0 ; for ( r = n - 1 ; r >= 0 ; r -- ) { l = r ; while ( l >= 0 && ( r - l + 1 ) <= 64 && stoull ( s . substr ( l , r - l + 1 ) , 0 , 2 ) < k ) { l -- ; } if ( r - l + 1 <= 64 ) no_of_substr += l + 1 ; else { no_of_substr += arr [ l + 1 ] + 1 ; } } return no_of_substr ; } int main ( ) { string s = "11100" ; unsigned long long int k = 3 ; cout << countSubstr ( s , k ) ; } |
Perfect Cube String | C ++ program to find if string is a perfect cube or not . ; Finding ASCII values of each character and finding its sum ; Find the cube root of sum ; Check if sum is a perfect cube ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPerfectCubeString ( string str ) { int sum = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) sum += ( int ) str [ i ] ; long double cr = round ( cbrt ( sum ) ) ; return ( cr * cr * cr == sum ) ; } int main ( ) { string str = " ll " ; if ( isPerfectCubeString ( str ) ) cout << " Yes " ; else cout << " No " ; } |
Program to find the XOR of ASCII values of characters in a string | C ++ program to find XOR of ASCII value of characters in string ; Function to find the XOR of ASCII value of characters in string ; store value of first character ; Traverse string to find the XOR ; Return the XOR ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int XorAscii ( string str , int len ) { int ans = int ( str [ 0 ] ) ; for ( int i = 1 ; i < len ; i ++ ) { ans = ( ans ^ ( int ( str [ i ] ) ) ) ; } return ans ; } int main ( ) { string str = " geeksforgeeks " ; int len = str . length ( ) ; cout << XorAscii ( str , len ) << endl ; str = " GfG " ; len = str . length ( ) ; cout << XorAscii ( str , len ) ; return 0 ; } |
CamelCase Pattern Matching | C ++ to find CamelCase Pattern matching ; Function that prints the camel case pattern matching ; Map to store the hashing of each words with every uppercase letter found ; Traverse the words array that contains all the string ; Initialise str as empty ; length of string words [ i ] ; For every uppercase letter found map that uppercase to original words ; Traverse the map for pattern matching ; If pattern matches then print the corresponding mapped words ; If word not found print " No β match β found " ; Driver 's Code ; Pattern to be found ; Function call to find the words that match to the given pattern | #include " bits / stdc + + . h " NEW_LINE using namespace std ; void CamelCase ( vector < string > & words , string pattern ) { map < string , vector < string > > map ; for ( int i = 0 ; i < words . size ( ) ; i ++ ) { string str = " " ; int l = words [ i ] . length ( ) ; for ( int j = 0 ; j < l ; j ++ ) { if ( words [ i ] [ j ] >= ' A ' && words [ i ] [ j ] <= ' Z ' ) { str += words [ i ] [ j ] ; map [ str ] . push_back ( words [ i ] ) ; } } } bool wordFound = false ; for ( auto & it : map ) { if ( it . first == pattern ) { wordFound = true ; for ( auto & itt : it . second ) { cout << itt << endl ; } } } if ( ! wordFound ) { cout << " No β match β found " ; } } int main ( ) { vector < string > words = { " Hi " , " Hello " , " HelloWorld " , " HiTech " , " HiGeek " , " HiTechWorld " , " HiTechCity " , " HiTechLab " } ; string pattern = " HT " ; CamelCase ( words , pattern ) ; return 0 ; } |
Encryption and Decryption of String according to given technique | C ++ implementation for Custom Encryption and Decryption of String ; Function to encrypt the string ; Matrix to generate the Encrypted String ; Fill the matrix row - wise ; Loop to generate encrypted string ; Function to decrypt the string ; Matrix to generate the Encrypted String ; Fill the matrix column - wise ; Loop to generate decrypted string ; Driver Code ; Encryption of String ; Decryption of String | #include <bits/stdc++.h> NEW_LINE using namespace std ; string encryption ( string s ) { int l = s . length ( ) ; int b = ceil ( sqrt ( l ) ) ; int a = floor ( sqrt ( l ) ) ; string encrypted ; if ( b * a < l ) { if ( min ( b , a ) == b ) { b = b + 1 ; } else { a = a + 1 ; } } char arr [ a ] [ b ] ; memset ( arr , ' β ' , sizeof ( arr ) ) ; int k = 0 ; for ( int j = 0 ; j < a ; j ++ ) { for ( int i = 0 ; i < b ; i ++ ) { if ( k < l ) { arr [ j ] [ i ] = s [ k ] ; } k ++ ; } } for ( int j = 0 ; j < b ; j ++ ) { for ( int i = 0 ; i < a ; i ++ ) { encrypted = encrypted + arr [ i ] [ j ] ; } } return encrypted ; } string decryption ( string s ) { int l = s . length ( ) ; int b = ceil ( sqrt ( l ) ) ; int a = floor ( sqrt ( l ) ) ; string decrypted ; char arr [ a ] [ b ] ; memset ( arr , ' β ' , sizeof ( arr ) ) ; int k = 0 ; for ( int j = 0 ; j < b ; j ++ ) { for ( int i = 0 ; i < a ; i ++ ) { if ( k < l ) { arr [ j ] [ i ] = s [ k ] ; } k ++ ; } } for ( int j = 0 ; j < a ; j ++ ) { for ( int i = 0 ; i < b ; i ++ ) { decrypted = decrypted + arr [ i ] [ j ] ; } } return decrypted ; } int main ( ) { string s = " Geeks β For β Geeks " ; string encrypted ; string decrypted ; encrypted = encryption ( s ) ; cout << encrypted << endl ; decrypted = decryption ( encrypted ) ; cout << decrypted ; return 0 ; } |
Program to accept String starting with Capital letter | C ++ program to accept String starting with Capital letter ; Function to check if first character is Capital ; Function to check ; Driver function | #include <iostream> NEW_LINE using namespace std ; int checkIfStartsWithCapital ( string str ) { if ( str [ 0 ] >= ' A ' && str [ 0 ] <= ' Z ' ) return 1 ; else return 0 ; } void check ( string str ) { if ( checkIfStartsWithCapital ( str ) ) cout << " Accepted STRNEWLINE " ; else cout << " Not β Accepted STRNEWLINE " ; } int main ( ) { string str = " GeeksforGeeks " ; check ( str ) ; str = " geeksforgeeks " ; check ( str ) ; return 0 ; } |
Program to accept a Strings which contains all the Vowels | C ++ implementation to check that a string contains all vowels ; Function to to check that a string contains all vowels ; Hash Array of size 5 such that the index 0 , 1 , 2 , 3 and 4 represent the vowels a , e , i , o and u ; Loop the string to mark the vowels which are present ; Loop to check if there is any vowel which is not present in the string ; Function to to check that a string contains all vowels ; Driver Code | #include <iostream> NEW_LINE using namespace std ; int checkIfAllVowels ( string str ) { int hash [ 5 ] = { 0 } ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] == ' A ' str [ i ] == ' a ' ) hash [ 0 ] = 1 ; else if ( str [ i ] == ' E ' str [ i ] == ' e ' ) hash [ 1 ] = 1 ; else if ( str [ i ] == ' I ' str [ i ] == ' i ' ) hash [ 2 ] = 1 ; else if ( str [ i ] == ' O ' str [ i ] == ' o ' ) hash [ 3 ] = 1 ; else if ( str [ i ] == ' U ' str [ i ] == ' u ' ) hash [ 4 ] = 1 ; } for ( int i = 0 ; i < 5 ; i ++ ) { if ( hash [ i ] == 0 ) { return 1 ; } } return 0 ; } int checkIfAllVowelsArePresent ( string str ) { if ( checkIfAllVowels ( str ) ) cout << " Not β Accepted STRNEWLINE " ; else cout << " Accepted STRNEWLINE " ; } int main ( ) { string str = " aeioubc " ; checkIfAllVowelsArePresent ( str ) ; return 0 ; } |
Smallest odd number with even sum of digits from the given number N | C ++ program to find the smallest odd number with even sum of digits from the given number N ; Function to find the smallest odd number whose sum of digits is even from the given string ; Converting the given string to a list of digits ; An empty array to store the digits ; For loop to iterate through each digit ; If the given digit is odd then the digit is appended to the array b ; Sorting the list of digits ; If the size of the list is greater than 1 then a 2 digit smallest odd number is returned Since the sum of two odd digits is always even ; Else , - 1 is returned ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int smallest ( string s ) { vector < int > a ( s . length ( ) ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) a [ i ] = s [ i ] - '0' ; vector < int > b ; for ( int i = 0 ; i < a . size ( ) ; i ++ ) { if ( ( a [ i ] ) % 2 != 0 ) b . push_back ( a [ i ] ) ; } sort ( b . begin ( ) , b . end ( ) ) ; if ( b . size ( ) > 1 ) return ( b [ 0 ] ) * 10 + ( b [ 1 ] ) ; return -1 ; } int main ( ) { cout << ( smallest ( "15470" ) ) ; } |
Number formed by deleting digits such that sum of the digits becomes even and the number odd | C ++ implementation to convert a number into odd number such that digit - sum is odd ; Function to convert a number into odd number such that digit - sum is odd ; Loop to find any first two odd number such that their sum is even and number is odd ; Print the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void converthenumber ( int n ) { string s = to_string ( n ) ; string res ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s [ i ] == '1' s [ i ] == '3' s [ i ] == '5' s [ i ] == '7' s [ i ] == '9' ) res += s [ i ] ; if ( res . size ( ) == 2 ) break ; } if ( res . size ( ) == 2 ) cout << res << endl ; else cout << " - 1" << endl ; } int main ( ) { int n = 18720 ; converthenumber ( n ) ; return 0 ; } |
Longest palindromic String formed using concatenation of given strings in any order | C ++ implementation to find the longest palindromic String formed using concatenation of given strings in any order ; Function to find the longest palindromic from given array of strings ; Loop to find the pair of strings which are reverse of each other ; Loop to find if any palindromic string is still left in the array ; Update the answer with all strings of pair1 ; Update the answer with palindromic string s1 ; Update the answer with all strings of pair2 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void longestPalindrome ( string a [ ] , int n ) { string pair1 [ n ] ; string pair2 [ n ] ; int r = 0 ; for ( int i = 0 ; i < n ; i ++ ) { string s = a [ i ] ; reverse ( s . begin ( ) , s . end ( ) ) ; for ( int j = i + 1 ; j < n ; j ++ ) { if ( a [ i ] != " " && a [ j ] != " " ) { if ( s == a [ j ] ) { pair1 [ r ] = a [ i ] ; pair2 [ r ++ ] = a [ j ] ; a [ i ] = " " ; a [ j ] = " " ; break ; } } } } string s1 = " " ; for ( int i = 0 ; i < n ; i ++ ) { string s = a [ i ] ; reverse ( a [ i ] . begin ( ) , a [ i ] . end ( ) ) ; if ( a [ i ] != " " ) { if ( a [ i ] == s ) { s1 = a [ i ] ; break ; } } } string ans = " " ; for ( int i = 0 ; i < r ; i ++ ) { ans = ans + pair1 [ i ] ; } if ( s1 != " " ) { ans = ans + s1 ; } for ( int j = r - 1 ; j >= 0 ; j -- ) { ans = ans + pair2 [ j ] ; } cout << ans << endl ; } int main ( ) { string a1 [ 2 ] = { " aba " , " aba " } ; int n1 = sizeof ( a1 ) / sizeof ( a1 [ 0 ] ) ; longestPalindrome ( a1 , n1 ) ; string a2 [ 5 ] = { " abc " , " dba " , " kop " , " abd " , " cba " } ; int n2 = sizeof ( a2 ) / sizeof ( a2 [ 0 ] ) ; longestPalindrome ( a2 , n2 ) ; } |
Program to print the given digit in words | C ++ implementation of the above approach ; Function to return the word of the corresponding digit ; Switch block to check for each digit c ; For digit 0 ; For digit 1 ; For digit 2 ; For digit 3 ; For digit 4 ; For digit 5 ; For digit 6 ; For digit 7 ; For digit 8 ; For digit 9 ; Function to iterate through every digit in the given number ; Finding each digit of the number ; Print the digit in words ; Driver code | #include " bits / stdc + + . h " NEW_LINE using namespace std ; void printValue ( char digit ) { switch ( digit ) { case '0' : cout << " Zero β " ; break ; case '1' : cout << " One β " ; break ; case '2' : cout << " Two β " ; break ; case '3' : cout << " Three β " ; break ; case '4' : cout << " Four β " ; break ; case '5' : cout << " Five β " ; break ; case '6' : cout << " Six β " ; break ; case '7' : cout << " Seven β " ; break ; case '8' : cout << " Eight β " ; break ; case '9' : cout << " Nine β " ; break ; } } void printWord ( string N ) { int i , length = N . length ( ) ; for ( i = 0 ; i < length ; i ++ ) { printValue ( N [ i ] ) ; } } int main ( ) { string N = "123" ; printWord ( N ) ; return 0 ; } |
Sum of all LCP of maximum length by selecting any two Strings at a time | C ++ program to find Sum of all LCP of maximum length by selecting any two Strings at a time ; Using map to store the pointers of children nodes for dynamic implementation , for making the program space efiicient ; Counts the number of times the node is visited while making the trie ; Initially visited value for all nodes is zero ; Head node of the trie is initialize as ' \0' , after this all strings add ; Function to insert the strings in the trie ; Inserting character - by - character ; If the node of ch is not present in map make a new node and add in map ; Recursive function to calculate the answer argument is passed by reference ; To store changed visited values from children of this node i . e . number of nodes visited by its children ; Updating the visited variable , telling number of nodes that have already been visited by its children ; If node -> visited > 1 , means more than one string has prefix up till this node common in them ; Number of string pair with current node common in them ; Updating visited variable of current node ; Returning the total number of nodes already visited that needs to be updated to previous node ; Function to run the dfs function for the first time and give the answer variable ; Stores the final answer as sum of all depths ; Driver Function | #include <bits/stdc++.h> NEW_LINE using namespace std ; class TrieNode { public : char val ; map < char , TrieNode * > children ; int visited ; TrieNode ( char x ) { val = x ; visited = 0 ; } } ; class Trie { public : TrieNode * head ; Trie ( ) { head = new TrieNode ( ' \0' ) ; } void addWord ( string s ) { TrieNode * temp = head ; const unsigned int n = s . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { char ch = s [ i ] ; if ( ! temp -> children [ ch ] ) { temp -> children [ ch ] = new TrieNode ( ch ) ; } temp = temp -> children [ ch ] ; temp -> visited ++ ; } } int dfs ( TrieNode * node , int & ans , int depth ) { int vis = 0 ; for ( auto child : node -> children ) { vis += dfs ( child . second , ans , depth + 1 ) ; } node -> visited -= vis ; int string_pair = 0 ; if ( node -> visited > 1 ) { string_pair = ( node -> visited / 2 ) ; ans += ( depth * string_pair ) ; node -> visited -= ( 2 * string_pair ) ; } return ( 2 * string_pair + vis ) ; } int dfshelper ( ) { int ans = 0 ; dfs ( head , ans , 0 ) ; return ans ; } } ; int main ( ) { Trie T ; string str [ ] = { " babab " , " ababb " , " abbab " , " aaaaa " , " babaa " , " babbb " } ; int n = 6 ; for ( int i = 0 ; i < n ; i ++ ) { T . addWord ( str [ i ] ) ; } int ans = T . dfshelper ( ) ; cout << ans << endl ; return 0 ; } |
Print all possible combinations of words from Dictionary using Trie | C ++ implementation of the approach ; Trie node ; isEndOfWord is true if node represents the end of the word ; Returns new trie node ; If not present , inserts key into trie If the key is prefix of trie node , marks the node as leaf node ; Mark node as leaf ; Returns true if the key is present in the trie ; Result stores the current prefix with spaces between words ; Process all prefixes one by one ; Extract substring from 0 to i in prefix ; If trie conatins this prefix then check for the remaining string . Otherwise ignore this prefix ; If no more elements are there then print ; Add this element to the previous prefix ; If ( result == word ) then return If you don 't want to print last word ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int ALPHABET_SIZE = 26 ; struct TrieNode { struct TrieNode * children [ ALPHABET_SIZE ] ; bool isEndOfWord ; } ; struct TrieNode * getNode ( void ) { struct TrieNode * pNode = new TrieNode ; pNode -> isEndOfWord = false ; for ( int i = 0 ; i < ALPHABET_SIZE ; i ++ ) pNode -> children [ i ] = NULL ; return pNode ; } void insert ( struct TrieNode * root , string key ) { struct TrieNode * pCrawl = root ; for ( int i = 0 ; i < key . length ( ) ; i ++ ) { int index = key [ i ] - ' a ' ; if ( ! pCrawl -> children [ index ] ) pCrawl -> children [ index ] = getNode ( ) ; pCrawl = pCrawl -> children [ index ] ; } pCrawl -> isEndOfWord = true ; } bool search ( struct TrieNode * root , string key ) { struct TrieNode * pCrawl = root ; for ( int i = 0 ; i < key . length ( ) ; i ++ ) { int index = key [ i ] - ' a ' ; if ( ! pCrawl -> children [ index ] ) return false ; pCrawl = pCrawl -> children [ index ] ; } return ( pCrawl != NULL && pCrawl -> isEndOfWord ) ; } void wordBreakAll ( TrieNode * root , string word , int n , string result ) { for ( int i = 1 ; i <= n ; i ++ ) { string prefix = word . substr ( 0 , i ) ; if ( search ( root , prefix ) ) { if ( i == n ) { result += prefix ; cout << " TABSYMBOL " << result << endl ; return ; } wordBreakAll ( root , word . substr ( i , n - i ) , n - i , result + prefix + " β " ) ; } } } int main ( ) { struct TrieNode * root = getNode ( ) ; string dictionary [ ] = { " sam " , " sung " , " samsung " } ; int n = sizeof ( dictionary ) / sizeof ( string ) ; for ( int i = 0 ; i < n ; i ++ ) { insert ( root , dictionary [ i ] ) ; } for ( int i = 0 ; i < n ; i ++ ) { cout << dictionary [ i ] << " : β STRNEWLINE " ; wordBreakAll ( root , dictionary [ i ] , dictionary [ i ] . length ( ) , " " ) ; } return 0 ; } |
Jaro and Jaro | C ++ implementation of above approach ; Function to calculate the Jaro Similarity of two strings ; If the strings are equal ; Length of two strings ; Maximum distance upto which matching is allowed ; Count of matches ; Hash for matches ; Traverse through the first string ; Check if there is any matches ; If there is a match ; If there is no match ; Number of transpositions ; Count number of occurrences where two characters match but there is a third matched character in between the indices ; Find the next matched character in second string ; Return the Jaro Similarity ; Driver code ; Print jaro Similarity of two strings | #include <bits/stdc++.h> NEW_LINE using namespace std ; double jaro_distance ( string s1 , string s2 ) { if ( s1 == s2 ) return 1.0 ; int len1 = s1 . length ( ) , len2 = s2 . length ( ) ; int max_dist = floor ( max ( len1 , len2 ) / 2 ) - 1 ; int match = 0 ; int hash_s1 [ s1 . length ( ) ] = { 0 } , hash_s2 [ s2 . length ( ) ] = { 0 } ; for ( int i = 0 ; i < len1 ; i ++ ) { for ( int j = max ( 0 , i - max_dist ) ; j < min ( len2 , i + max_dist + 1 ) ; j ++ ) if ( s1 [ i ] == s2 [ j ] && hash_s2 [ j ] == 0 ) { hash_s1 [ i ] = 1 ; hash_s2 [ j ] = 1 ; match ++ ; break ; } } if ( match == 0 ) return 0.0 ; double t = 0 ; int point = 0 ; for ( int i = 0 ; i < len1 ; i ++ ) if ( hash_s1 [ i ] ) { while ( hash_s2 [ point ] == 0 ) point ++ ; if ( s1 [ i ] != s2 [ point ++ ] ) t ++ ; } t /= 2 ; return ( ( ( double ) match ) / ( ( double ) len1 ) + ( ( double ) match ) / ( ( double ) len2 ) + ( ( double ) match - t ) / ( ( double ) match ) ) / 3.0 ; } int main ( ) { string s1 = " CRATE " , s2 = " TRACE " ; cout << jaro_distance ( s1 , s2 ) << endl ; return 0 ; } |
Print characters and their frequencies in order of occurrence using Binary Tree | C ++ implementation of the above approach ; Node in the tree where data holds the character of the string and cnt holds the frequency ; Function to add a new node to the Binary Tree ; Create a new node and populate its data part , set cnt as 1 and left and right children as NULL ; Function to add a node to the Binary Tree in level order ; Use the queue data structure for level order insertion and push the root of tree to Queue ; If the character to be inserted is present , update the cnt ; If the left child is empty add a new node as the left child ; If the character is present as a left child , update the cnt and exit the loop ; Add the left child to the queue for further processing ; If the right child is empty , add a new node to the right ; If the character is present as a right child , update the cnt and exit the loop ; Add the right child to the queue for further processing ; Function to print the level order traversal of the Binary Tree ; Add the root to the queue ; If the cnt of the character is more then one , display cnt ; If the cnt of character is one , display character only ; Add the left child to the queue for further processing ; Add the right child to the queue for further processing ; Driver code ; Add individual characters to the string one by one in level order ; Print the level order of the constructed binary tree | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { char data ; int cnt ; node * left , * right ; } ; node * add ( char data ) { node * newnode = new node ; newnode -> data = data ; newnode -> cnt = 1 ; newnode -> left = newnode -> right = NULL ; return newnode ; } node * addinlvlorder ( node * root , char data ) { if ( root == NULL ) { return add ( data ) ; } queue < node * > Q ; Q . push ( root ) ; while ( ! Q . empty ( ) ) { node * temp = Q . front ( ) ; Q . pop ( ) ; if ( temp -> data == data ) { temp -> cnt ++ ; break ; } if ( temp -> left == NULL ) { temp -> left = add ( data ) ; break ; } else { if ( temp -> left -> data == data ) { temp -> left -> cnt ++ ; break ; } Q . push ( temp -> left ) ; } if ( temp -> right == NULL ) { temp -> right = add ( data ) ; break ; } else { if ( temp -> right -> data == data ) { temp -> right -> cnt ++ ; break ; } Q . push ( temp -> right ) ; } } return root ; } void printlvlorder ( node * root ) { queue < node * > Q ; Q . push ( root ) ; while ( ! Q . empty ( ) ) { node * temp = Q . front ( ) ; if ( temp -> cnt > 1 ) { cout << temp -> data << temp -> cnt ; } else { cout << temp -> data ; } Q . pop ( ) ; if ( temp -> left != NULL ) { Q . push ( temp -> left ) ; } if ( temp -> right != NULL ) { Q . push ( temp -> right ) ; } } } int main ( ) { string s = " geeksforgeeks " ; node * root = NULL ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { root = addinlvlorder ( root , s [ i ] ) ; } printlvlorder ( root ) ; return 0 ; } |
Find the resultant String after replacing X with Y and removing Z | C ++ program to find the resultant String after replacing X with Y and removing Z ; Function to replace and remove ; Two pointer start and end points to beginning and end position in the string ; If start is having Z find X pos in end and replace Z with another character ; Find location for having different character instead of Z ; If found swap character at start and end ; Else increment start Also checkin for X at start position ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void replaceRemove ( string & s , char X , char Y , char Z ) { int start = 0 , end = s . size ( ) - 1 ; while ( start <= end ) { if ( s [ start ] == Z ) { while ( end >= 0 && s [ end ] == Z ) { end -- ; } if ( end > start ) { swap ( s [ start ] , s [ end ] ) ; if ( s [ start ] == X ) s [ start ] = Y ; start ++ ; } } else { if ( s [ start ] == X ) s [ start ] = Y ; start ++ ; } } while ( s . size ( ) > 0 && s [ s . size ( ) - 1 ] == Z ) { s . pop_back ( ) ; } } int main ( ) { string str = " batman " ; char X = ' a ' , Y = ' d ' , Z = ' b ' ; replaceRemove ( str , X , Y , Z ) ; if ( str . size ( ) == 0 ) { cout << -1 ; } else { cout << str ; } return 0 ; } |
Check if all bits can be made same by flipping two consecutive bits | C ++ program for the above approach ; Function to check if Binary string can be made equal ; Counting occurence of zero and one in binary string ; From above observation ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string canMake ( string & s ) { int o = 0 , z = 0 ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { if ( s [ i ] - '0' == 1 ) o ++ ; else z ++ ; } if ( o % 2 == 1 && z % 2 == 1 ) return " NO " ; else return " YES " ; } int main ( ) { string s = "01011" ; cout << canMake ( s ) << ' ' ; return 0 ; } |
Count of non | C ++ implementation of the above approach ; Function to find the count of the number of strings ; Loop to iterate over the frequency of character of string ; reduce the frequency of current element ; recursive call ; freq [ i ] ++ ; backtrack ; Function to count the number of non - empty sequences ; store the frequency of each character ; Maintain the frequency ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void countNumberOfStringsUtil ( vector < int > & freq , int & count ) { for ( int i = 0 ; i < 26 ; i ++ ) { if ( freq [ i ] > 0 ) { freq [ i ] -- ; count ++ ; countNumberOfStringsUtil ( freq , count ) ; } } } int countNumberOfStrings ( string s ) { vector < int > freq ( 26 , 0 ) ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { freq [ s [ i ] - ' A ' ] ++ ; } int count = 0 ; countNumberOfStringsUtil ( freq , count ) ; return count ; } int main ( ) { string s = " AAABBC " ; cout << countNumberOfStrings ( s ) ; return 0 ; } |
Minimum swaps required to make a binary string divisible by 2 ^ k | C ++ implementation of the approach ; Function to return the minimum swaps required ; To store the final answer ; To store the count of one and zero ; Loop from end of the string ; If s [ i ] = 1 ; If s [ i ] = 0 ; If c_zero = k ; If the result can 't be achieved ; Return the final answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinSwaps ( string s , int k ) { int ans = 0 ; int c_one = 0 , c_zero = 0 ; for ( int i = s . size ( ) - 1 ; i >= 0 ; i -- ) { if ( s [ i ] == '1' ) c_one ++ ; if ( s [ i ] == '0' ) c_zero ++ , ans += c_one ; if ( c_zero == k ) break ; } if ( c_zero < k ) return -1 ; return ans ; } int main ( ) { string s = "100111" ; int k = 2 ; cout << findMinSwaps ( s , k ) ; return 0 ; } |
Remove vowels from a string stored in a Binary Tree | C ++ program for the above approach ; Structure Representing the Node in the Binary tree ; Function to perform a level order insertion of a new Node in the Binary tree ; If the root is empty , make it point to the new Node ; In case there are elements in the Binary tree , perform a level order traversal using a Queue ; If the left child does not exist , insert the new Node as the left child ; In case the right child does not exist , insert the new Node as the right child ; Function to print the level order traversal of the Binary tree ; Function to check if the character is a vowel or not . ; Function to remove the vowels in the new Binary tree ; Declaring the root of the new tree ; If the given character is not a vowel , add it to the new Binary tree ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { char data ; Node * left , * right ; Node ( char _val ) { data = _val ; left = right = NULL ; } } ; Node * addinBT ( Node * root , char data ) { if ( root == NULL ) { root = new Node ( data ) ; } else { queue < Node * > Q ; Q . push ( root ) ; while ( ! Q . empty ( ) ) { Node * temp = Q . front ( ) ; Q . pop ( ) ; if ( temp -> left == NULL ) { temp -> left = new Node ( data ) ; break ; } else Q . push ( temp -> left ) ; if ( temp -> right == NULL ) { temp -> right = new Node ( data ) ; break ; } else Q . push ( temp -> right ) ; } } return root ; } void print ( Node * root ) { queue < Node * > Q ; Q . push ( root ) ; while ( Q . size ( ) ) { Node * temp = Q . front ( ) ; Q . pop ( ) ; cout << temp -> data ; if ( temp -> left ) Q . push ( temp -> left ) ; if ( temp -> right ) Q . push ( temp -> right ) ; } } bool checkvowel ( char ch ) { ch = tolower ( ch ) ; if ( ch == ' a ' ch == ' e ' ch == ' i ' ch == ' o ' ch == ' u ' ) { return true ; } else { return false ; } } Node * removevowels ( Node * root ) { queue < Node * > Q ; Q . push ( root ) ; Node * root1 = NULL ; while ( ! Q . empty ( ) ) { Node * temp = Q . front ( ) ; Q . pop ( ) ; if ( ! checkvowel ( temp -> data ) ) { root1 = addinBT ( root1 , temp -> data ) ; } if ( temp -> left ) { Q . push ( temp -> left ) ; } if ( temp -> right ) { Q . push ( temp -> right ) ; } } return root1 ; } int main ( ) { string s = " geeks " ; Node * root = NULL ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { root = addinBT ( root , s [ i ] ) ; } root = removevowels ( root ) ; print ( root ) ; return 0 ; } |
Number of sub | C ++ implementation of the approach ; Function to return the count of the required substrings ; To store the final answer ; Loop to find the answer ; Condition to update the answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubStr ( string str , int len ) { int ans = 0 ; for ( int i = 0 ; i < len ; i ++ ) { if ( str [ i ] == '0' ) ans += ( i + 1 ) ; } return ans ; } int main ( ) { string str = "10010" ; int len = str . length ( ) ; cout << countSubStr ( str , len ) ; return 0 ; } |
Smallest non | C ++ implementation of the approach ; Function to return the length of the smallest substring divisible by 2 ^ k ; To store the final answer ; Left pointer ; Right pointer ; Count of the number of zeros and ones in the current substring ; Loop for two pointers ; Condition satisfied ; Updated the answer ; Update the pointer and count ; Update the pointer and count ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findLength ( string s , int k ) { int ans = INT_MAX ; int l = 0 ; int r = 0 ; int cnt_zero = 0 , cnt_one = 0 ; while ( l < s . size ( ) and r <= s . size ( ) ) { if ( cnt_zero >= k and cnt_one >= 1 ) { ans = min ( ans , r - l ) ; l ++ ; if ( s [ l - 1 ] == '0' ) cnt_zero -- ; else cnt_one -- ; } else { if ( r == s . size ( ) ) break ; if ( s [ r ] == '0' ) cnt_zero ++ ; else cnt_one ++ ; r ++ ; } } if ( ans == INT_MAX ) return -1 ; return ans ; } int main ( ) { string s = "100" ; int k = 2 ; cout << findLength ( s , k ) ; return 0 ; } |
Largest sub | C ++ implementation of the approach ; Function to return the largest substring divisible by 2 ; While the last character of the string is '1' , pop it ; If the original string had no '0' ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string largestSubStr ( string s ) { while ( s . size ( ) and s [ s . size ( ) - 1 ] == '1' ) s . pop_back ( ) ; if ( s . size ( ) == 0 ) return " - 1" ; else return s ; } int main ( ) { string s = "11001" ; cout << largestSubStr ( s ) ; return 0 ; } |
Find whether X exists in Y after jumbling X | C ++ implementation of the approach ; Function that returns true if both the arrays have equal values ; Test the equality ; Function that returns true if any permutation of X exists as a substring in Y ; Base case ; To store cumulative frequency ; Finding the frequency of characters in X ; Finding the frequency of characters in Y upto the length of X ; Equality check ; Two pointer approach to generate the entire cumulative frequency ; Remove the first character of the previous window ; Add the last character of the current window ; Equality check ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 26 ; bool areEqual ( int * a , int * b ) { for ( int i = 0 ; i < MAX ; i ++ ) if ( a [ i ] != b [ i ] ) return false ; return true ; } bool xExistsInY ( string x , string y ) { if ( x . size ( ) > y . size ( ) ) return false ; int cnt_x [ MAX ] = { 0 } ; int cnt [ MAX ] = { 0 } ; for ( int i = 0 ; i < x . size ( ) ; i ++ ) cnt_x [ x [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < x . size ( ) ; i ++ ) cnt [ y [ i ] - ' a ' ] ++ ; if ( areEqual ( cnt_x , cnt ) ) return true ; for ( int i = 1 ; i < y . size ( ) - x . size ( ) + 1 ; i ++ ) { cnt [ y [ i - 1 ] - ' a ' ] -- ; cnt [ y [ i + x . size ( ) - 1 ] - ' a ' ] ++ ; if ( areEqual ( cnt , cnt_x ) ) return true ; } return false ; } int main ( ) { string x = " skege " ; string y = " geeksforgeeks " ; if ( xExistsInY ( x , y ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Reverse substrings between each pair of parenthesis | C ++ implementation of the approach ; Function to return the modified string ; Push the index of the current opening bracket ; Reverse the substring starting after the last encountered opening bracket till the current character ; To store the modified string ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string reverseParentheses ( string str , int len ) { stack < int > st ; for ( int i = 0 ; i < len ; i ++ ) { if ( str [ i ] == ' ( ' ) { st . push ( i ) ; } else if ( str [ i ] == ' ) ' ) { reverse ( str . begin ( ) + st . top ( ) + 1 , str . begin ( ) + i ) ; st . pop ( ) ; } } string res = " " ; for ( int i = 0 ; i < len ; i ++ ) { if ( str [ i ] != ' ) ' && str [ i ] != ' ( ' ) res += ( str [ i ] ) ; } return res ; } int main ( ) { string str = " ( skeeg ( for ) skeeg ) " ; int len = str . length ( ) ; cout << reverseParentheses ( str , len ) ; return 0 ; } |
Count of times second string can be formed from the characters of first string | C ++ implementation of the approach ; Function to update the freq [ ] array to store the frequencies of all the characters of str ; Update the frequency of the characters ; Function to return the maximum count of times patt can be formed using the characters of str ; To store the frequencies of all the characters of str ; To store the frequencies of all the characters of patt ; To store the result ; For every character ; If the current character doesn 't appear in patt ; Update the result ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 26 ; void updateFreq ( string str , int freq [ ] ) { int len = str . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { freq [ str [ i ] - ' a ' ] ++ ; } } int maxCount ( string str , string patt ) { int strFreq [ MAX ] = { 0 } ; updateFreq ( str , strFreq ) ; int pattFreq [ MAX ] = { 0 } ; updateFreq ( patt , pattFreq ) ; int ans = INT_MAX ; for ( int i = 0 ; i < MAX ; i ++ ) { if ( pattFreq [ i ] == 0 ) continue ; ans = min ( ans , strFreq [ i ] / pattFreq [ i ] ) ; } return ans ; } int main ( ) { string str = " geeksforgeeks " ; string patt = " geeks " ; cout << maxCount ( str , patt ) ; return 0 ; } |
Reduce the number to minimum multiple of 4 after removing the digits | C ++ implementation of the approach ; Function to return the minimum number that can be formed after removing the digits which is a multiple of 4 ; For every digit of the number ; Check if the current digit is divisible by 4 ; If any subsequence of two digits is divisible by 4 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int TEN = 10 ; int minNum ( string str , int len ) { int res = INT_MAX ; for ( int i = 0 ; i < len ; i ++ ) { if ( str [ i ] == '4' str [ i ] == '8' ) { res = min ( res , str [ i ] - '0' ) ; } } for ( int i = 0 ; i < len - 1 ; i ++ ) { for ( int j = i + 1 ; j < len ; j ++ ) { int num = ( str [ i ] - '0' ) * TEN + ( str [ j ] - '0' ) ; if ( num % 4 == 0 ) { res = min ( res , num ) ; } } } return ( ( res == INT_MAX ) ? -1 : res ) ; } int main ( ) { string str = "17" ; int len = str . length ( ) ; cout << minNum ( str , len ) ; return 0 ; } |
Check if two strings can be made equal by swapping one character among each other | C ++ implementation of the approach ; Function that returns true if the string can be made equal after one swap ; A and B are new a and b after we omit the same elements ; Take only the characters which are different in both the strings for every pair of indices ; If the current characters differ ; The strings were already equal ; If the lengths of the strings are two ; If swapping these characters can make the strings equal ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool canBeEqual ( string a , string b , int n ) { vector < char > A , B ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] != b [ i ] ) { A . push_back ( a [ i ] ) ; B . push_back ( b [ i ] ) ; } } if ( A . size ( ) == B . size ( ) and B . size ( ) == 0 ) return true ; if ( A . size ( ) == B . size ( ) and B . size ( ) == 2 ) { if ( A [ 0 ] == A [ 1 ] and B [ 0 ] == B [ 1 ] ) return true ; } return false ; } int main ( ) { string A = " SEEKSFORGEEKS " ; string B = " GEEKSFORGEEKG " ; if ( canBeEqual ( A , B , A . size ( ) ) ) printf ( " Yes " ) ; else printf ( " No " ) ; } |
Find the Mid | C ++ program to find the Mid - Alphabet for each index of the given Pair of Strings ; Function to find the mid alphabets ; For every character pair ; Get the average of the characters ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findMidAlphabet ( string s1 , string s2 , int n ) { for ( int i = 0 ; i < n ; i ++ ) { int mid = ( s1 [ i ] + s2 [ i ] ) / 2 ; cout << ( char ) mid ; } } int main ( ) { string s1 = " akzbqzgw " ; string s2 = " efhctcsz " ; int n = s1 . length ( ) ; findMidAlphabet ( s1 , s2 , n ) ; return 0 ; } |
Queries to find the count of vowels in the substrings of the given string | C ++ implementation of the approach ; Function that returns true if ch is a vowel ; pre [ i ] will store the count of vowels in the substring str [ 0. . . i ] ; Fill the pre [ ] array ; If current character is a vowel ; If its a consonant ; For every query ; Find the count of vowels for the current query ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 2 NEW_LINE bool isVowel ( char ch ) { return ( ch == ' a ' ch == ' e ' ch == ' i ' ch == ' o ' ch == ' u ' ) ; } void performQueries ( string str , int len , int queries [ ] [ N ] , int q ) { int pre [ len ] ; if ( isVowel ( str [ 0 ] ) ) pre [ 0 ] = 1 ; else pre [ 0 ] = 0 ; for ( int i = 1 ; i < len ; i ++ ) { if ( isVowel ( str [ i ] ) ) pre [ i ] = 1 + pre [ i - 1 ] ; else pre [ i ] = pre [ i - 1 ] ; } for ( int i = 0 ; i < q ; i ++ ) { if ( queries [ i ] [ 0 ] == 0 ) { cout << pre [ queries [ i ] [ 1 ] ] << " STRNEWLINE " ; } else { cout << ( pre [ queries [ i ] [ 1 ] ] - pre [ queries [ i ] [ 0 ] - 1 ] ) << " STRNEWLINE " ; } } } int main ( ) { string str = " geeksforgeeks " ; int len = str . length ( ) ; int queries [ ] [ N ] = { { 1 , 3 } , { 2 , 4 } , { 1 , 9 } } ; int q = ( sizeof ( queries ) / sizeof ( queries [ 0 ] ) ) ; performQueries ( str , len , queries , q ) ; return 0 ; } |
Check whether the given decoded string is divisible by 6 | C ++ implementation of the approach ; Function to return the sum of the digits of n ; Function that return true if the decoded string is divisible by 6 ; To store the sum of the digits ; For each character , get the sum of the digits ; If the sum of digits is not divisible by 3 ; Get the last digit of the number formed ; If the last digit is not divisible by 2 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sumDigits ( int n ) { int sum = 0 ; while ( n > 0 ) { int digit = n % 10 ; sum += digit ; n /= 10 ; } return sum ; } bool isDivBySix ( string str , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += ( int ) ( str [ i ] - ' a ' + 1 ) ; } if ( sum % 3 != 0 ) return false ; int lastDigit = ( ( int ) ( str [ n - 1 ] - ' a ' + 1 ) ) % 10 ; if ( lastDigit % 2 != 0 ) return false ; return true ; } int main ( ) { string str = " ab " ; int n = str . length ( ) ; if ( isDivBySix ( str , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Check the divisibility of Hexadecimal numbers | C ++ implementation of the approach ; Function that returns true if s is divisible by m ; Map to map characters to real values ; To store the remainder at any stage ; Find the remainder ; Check the value of remainder ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const string CHARS = "0123456789ABCDEF " ; const int DIGITS = 16 ; bool isDivisible ( string s , int m ) { unordered_map < char , int > mp ; for ( int i = 0 ; i < DIGITS ; i ++ ) { mp [ CHARS [ i ] ] = i ; } int r = 0 ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { r = ( r * 16 + mp [ s [ i ] ] ) % m ; } if ( ! r ) return true ; return false ; } int main ( ) { string s = "10" ; int m = 3 ; if ( isDivisible ( s , m ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Maximum number of splits of a binary number | C ++ implementation of the approach ; Function to return the required count ; If the splitting is not possible ; To store the final ans ; Counting the number of zeros ; Return the final answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int cntSplits ( string s ) { if ( s [ s . size ( ) - 1 ] == '1' ) return -1 ; int ans = 0 ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) ans += ( s [ i ] == '0' ) ; return ans ; } int main ( ) { string s = "10010" ; cout << cntSplits ( s ) ; return 0 ; } |
Modify the string such that every character gets replaced with the next character in the keyboard | C ++ implementation of the approach ; Function to return the modified string ; Map to store the next character on the keyboard for every possible lowercase character ; Update the string ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const string CHARS = " qwertyuiopasdfghjklzxcvbnm " ; const int MAX = 26 ; string getString ( string str , int n ) { unordered_map < char , char > uMap ; for ( int i = 0 ; i < MAX ; i ++ ) { uMap [ CHARS [ i ] ] = CHARS [ ( i + 1 ) % MAX ] ; } for ( int i = 0 ; i < n ; i ++ ) { str [ i ] = uMap [ str [ i ] ] ; } return str ; } int main ( ) { string str = " geeks " ; int n = str . length ( ) ; cout << getString ( str , n ) ; return 0 ; } |
Queries to find the count of characters preceding the given location | C ++ implementation of the approach ; returns character at index pos - 1 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Count ( string s , int pos ) { int c = s [ pos - 1 ] ; int counter = 0 ; for ( int i = 0 ; i < pos - 1 ; i ++ ) { if ( s [ i ] == c ) counter = counter + 1 ; } return counter ; } int main ( ) { string s = " abacsddaa " ; int pos ; int n = s . length ( ) ; int query [ ] = { 9 , 3 , 2 } ; int Q = sizeof ( query ) / sizeof ( query [ 0 ] ) ; for ( int i = 0 ; i < Q ; i ++ ) { pos = query [ i ] ; cout << Count ( s , pos ) << endl ; } return 0 ; } |
Queries to find the count of characters preceding the given location | C ++ implementation of the approach ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void Count ( vector < int > temp ) { int query [ ] = { 9 , 3 , 2 } ; int Q = sizeof ( query ) / sizeof ( query [ 0 ] ) ; for ( int i = 0 ; i < Q ; i ++ ) { int pos = query [ i ] ; cout << ( temp [ pos - 1 ] ) << endl ; } } vector < int > processing ( string s , int len ) { vector < int > temp ( len ) ; map < char , int > d ; for ( int i = 0 ; i < len ; i ++ ) { if ( d . find ( s [ i ] ) == d . end ( ) ) { d [ s [ i ] ] = i ; } else { temp [ i ] = temp [ d [ s [ i ] ] ] + 1 ; d [ s [ i ] ] = i ; } } return temp ; } int main ( ) { string s = " abacsddaa " ; int n = s . length ( ) ; vector < int > temp = processing ( s , n ) ; Count ( temp ) ; } |
Count of matchsticks required to represent the given number | C ++ implementation of the approach ; stick [ i ] stores the count of sticks required to represent the digit i ; Function to return the count of matchsticks required to represent the given number ; For every digit of the given number ; Add the count of sticks required to represent the current digit ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int sticks [ ] = { 6 , 2 , 5 , 5 , 4 , 5 , 6 , 3 , 7 , 6 } ; int countSticks ( string str , int n ) { int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { cnt += ( sticks [ str [ i ] - '0' ] ) ; } return cnt ; } int main ( ) { string str = "56" ; int n = str . length ( ) ; cout << countSticks ( str , n ) ; return 0 ; } |
Print characters in decreasing order of frequency | C ++ implementation of the approach ; Function to print the characters of the given string in decreasing order of their frequencies ; To store the ; Map 's size ; While there are elements in the map ; Finding the maximum value from the map ; Print the character alongwith its frequency ; Delete the maximum value ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printChar ( string str , int len ) { unordered_map < char , int > occ ; for ( int i = 0 ; i < len ; i ++ ) occ [ str [ i ] ] ++ ; int size = occ . size ( ) ; unordered_map < char , int > :: iterator it ; while ( size -- ) { unsigned currentMax = 0 ; char arg_max ; for ( it = occ . begin ( ) ; it != occ . end ( ) ; ++ it ) { if ( it -> second > currentMax || ( it -> second == currentMax && it -> first > arg_max ) ) { arg_max = it -> first ; currentMax = it -> second ; } } cout << arg_max << " β - β " << currentMax << endl ; occ . erase ( arg_max ) ; } } int main ( ) { string str = " geeksforgeeks " ; int len = str . length ( ) ; printChar ( str , len ) ; return 0 ; } |
Modulo of a large Binary String | C ++ implementation of the approach ; Function to return the value of ( str % k ) ; pwrTwo [ i ] will store ( ( 2 ^ i ) % k ) ; To store the result ; If current bit is 1 ; Add the current power of 2 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getMod ( string str , int n , int k ) { int pwrTwo [ n ] ; pwrTwo [ 0 ] = 1 % k ; for ( int i = 1 ; i < n ; i ++ ) { pwrTwo [ i ] = pwrTwo [ i - 1 ] * ( 2 % k ) ; pwrTwo [ i ] %= k ; } int res = 0 ; int i = 0 , j = n - 1 ; while ( i < n ) { if ( str [ j ] == '1' ) { res += ( pwrTwo [ i ] ) ; res %= k ; } i ++ ; j -- ; } return res ; } int main ( ) { string str = "1101" ; int n = str . length ( ) ; int k = 45 ; cout << getMod ( str , n , k ) << endl ; } |
Count number of binary strings such that there is no substring of length greater than or equal to 3 with all 1 's | C ++ implementation of the approach ; Function to return the count of all possible valid strings ; Fill 0 's in the dp array ; Base cases ; dp [ i ] [ j ] = number of possible strings such that '1' just appeared consecutively j times upto the ith index ; Taking previously calculated value ; Taking all possible cases that can appear at the Nth position ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const long MOD = 1000000007 ; long countStrings ( long N ) { long dp [ N + 1 ] [ 3 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ 1 ] [ 0 ] = 1 ; dp [ 1 ] [ 1 ] = 1 ; dp [ 1 ] [ 2 ] = 0 ; for ( int i = 2 ; i <= N ; i ++ ) { dp [ i ] [ 0 ] = ( dp [ i - 1 ] [ 0 ] + dp [ i - 1 ] [ 1 ] + dp [ i - 1 ] [ 2 ] ) % MOD ; dp [ i ] [ 1 ] = dp [ i - 1 ] [ 0 ] % MOD ; dp [ i ] [ 2 ] = dp [ i - 1 ] [ 1 ] % MOD ; } long ans = ( dp [ N ] [ 0 ] + dp [ N ] [ 1 ] + dp [ N ] [ 2 ] ) % MOD ; return ans ; } int main ( ) { long N = 3 ; cout << countStrings ( N ) ; return 0 ; } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.