String Problems
String Problems
Anagrams:
Anagrams are words or phrases formed by rearranging the letters of
another word or phrase.
Best Approach: Use a hash table (e.g., unordered_map in C++ or
defaultdict in Python) to store the frequency of characters in each
string. Compare the frequency of characters in both strings. If the
frequencies match for all characters, the strings are anagrams.
#include <iostream>
#include <unordered_map>
#include <string>
int main() {
std::string s1 = "listen";
std::string s2 = "silent";
if (areAnagrams(s1, s2)) {
std::cout << "Strings are anagrams\n";
} else {
std::cout << "Strings are not anagrams\n";
}
return 0;
}
Explanation:
1. The function areAnagrams takes two strings s1 and s2 as input and returns
true if they are anagrams, false otherwise.
2. First, it checks if the lengths of the strings are equal. If they are not, then the
strings cannot be anagrams, so it returns false.
3. Then, it creates an unordered_map freqMap to store the frequency of
characters in s1.
4. It iterates through each character in s1 and increments the frequency of that
character in freqMap.
5. Next, it iterates through each character in s2 and decrements the frequency of
that character in freqMap.
6. Finally, it checks if all frequencies in freqMap are zero. If any frequency is non-
zero, it means the frequencies of characters in s1 and s2 don't match, so it
returns false. Otherwise, it returns true.
In the main function, we test the areAnagrams function with two example strings
"listen" and "silent".
2. Substring Search:
Given a string and a pattern, find all occurrences of the pattern in the
string.
Best Approach: Use efficient string matching algorithms such as
Knuth-Morris-Pratt (KMP) algorithm, Boyer-Moore algorithm, or Rabin-
Karp algorithm. These algorithms can achieve linear or sublinear time
complexity for substring search.
#include <iostream>
#include <vector>
#include <string>
while (i < m) {
if (pattern[i] == pattern[len]) {
len++;
lps[i] = len;
i++;
} else {
if (len != 0) {
len = lps[len - 1];
} else {
lps[i] = 0;
i++;
}
}
}
return lps;
}
while (i < n) {
if (pattern[j] == text[i]) {
j++;
i++;
}
if (j == m) {
positions.push_back(i - j);
j = lps[j - 1];
} else if (i < n && pattern[j] != text[i]) {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
return positions;
}
int main() {
std::string text = "ABABDABACDABABCABAB";
std::string pattern = "ABABCABAB";
if (positions.empty()) {
std::cout << "Pattern not found in the text.\n";
} else {
std::cout << "Pattern found at positions:";
for (int pos : positions) {
std::cout << " " << pos;
}
std::cout << "\n";
}
return 0;
}
Explanation:
1. The function computeLPS computes the Longest Prefix Suffix (LPS) array for
the given pattern. This array stores the length of the longest proper prefix
which is also a suffix for each prefix of the pattern.
2. The function search uses the computed LPS array to perform substring search
in the text using the KMP algorithm.
3. In the main function, we test the search function with an example text and
pattern. The positions where the pattern is found in the text are printed.
This implementation of the KMP algorithm efficiently finds all occurrences of the
pattern in the given text.
#include <iostream>
#include <vector>
#include <string>
std::string longestCommonSubsequence(const std::string& str1, const std::string& str2) {
int m = str1.length();
int n = str2.length();
return lcs;
}
int main() {
std::string str1 = "AGGTAB";
std::string str2 = "GXTXAYB";
std::cout << "Longest Common Subsequence: " << lcs << std::endl;
return 0;
}
Explanation:
#include <iostream>
#include <string>
#include <vector>
return dp[m][n];
}
int main() {
std::string s = "adceb";
std::string p = "*a*b";
if (isMatch(s, p)) {
std::cout << "Pattern matches the string.\n";
} else {
std::cout << "Pattern does not match the string.\n";
}
return 0;
}
Explanation:
1. The function isMatch takes two strings s and p as input and returns true if the
pattern matches the string, otherwise returns false.
2. It initializes a 2D vector dp to store the matching status. dp[i][j] represents
whether the pattern p.substr(0, j) matches the string s.substr(0, i).
3. It sets dp[0][0] = true because an empty pattern matches an empty string.
4. It handles patterns starting with '*' by setting dp[0][j] = true for all j where
p[j - 1] == '*'.
5. It fills the dp table bottom-up using dynamic programming. If the characters
at indices i-1 and j-1 in s and p respectively are equal or if p[j-1] is a
wildcard character '?' (matching any single character), it updates dp[i][j]
based on dp[i-1][j-1]. If p[j-1] is a wildcard character '*' (matching any
sequence of characters), it updates dp[i][j] based on dp[i][j-1] or dp[i-
1][j].
6. Finally, it returns dp[m][n] where m and n are the lengths of the input strings
s and p respectively.
In the main function, we test the isMatch function with example strings "adceb" and
"*a*b", and print whether the pattern matches the string or not.
#include <iostream>
#include <string>
#include <vector>
int start = 0; // Start index of the longest palindromic substring found so far
int maxLen = 1; // Length of the longest palindromic substring found so far
int main() {
std::string s = "babad";
return 0;
}
Explanation:
#include <iostream>
#include <string>
std::string compressed;
int count = 1;
char prevChar = s[0];
int main() {
std::string s = "aabcccccaaa";
std::cout << "Original string: " << s << std::endl;
std::string compressed = compressString(s);
std::cout << "Compressed string: " << compressed << std::endl;
return 0;
}
Explanation:
7. Edit Distance:
1. Problem: Given two strings, find the minimum number of operations
(insertion, deletion, or substitution) required to convert one string into
another.
2. Approach: Use dynamic programming to calculate the edit distance
between the two strings.
3. Time Complexity: O(m * n), where m and n are the lengths of the two
input strings.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
return dp[m][n];
}
int main() {
std::string word1 = "horse";
std::string word2 = "ros";
std::cout << "Minimum edit distance: " << distance << std::endl;
return 0;
}
Explanation:
1. The function minDistance takes two strings word1 and word2 as input and
returns the minimum number of operations required to convert word1 into
word2.
2. It initializes a 2D vector dp to store the edit distance between substrings of
word1 and word2. dp[i][j] represents the edit distance between
word1.substr(0, i) and word2.substr(0, j).
3. It initializes the first row and column of the dp table with the indices as they
represent the cost of converting an empty string to a substring of the other
string.
4. It fills the dp table bottom-up using dynamic programming. If the characters
at indices i-1 and j-1 in word1 and word2 respectively are equal, no
operation is required (dp[i][j] = dp[i-1][j-1]). Otherwise, the edit
distance is calculated as 1 + the minimum of deletion, insertion, or
substitution operations.
5. Finally, it returns dp[m][n], where m and n are the lengths of word1 and word2
respectively.
6. In the main function, we test the minDistance function with example strings
"horse" and "ros", and print the result.
8. String Rotation:
Problem: Given two strings, check if one string is a rotation of the
other.
Approach: Concatenate one string with itself and check if the other
string is a substring of the concatenated string.
Time Complexity: O(n), where n is the length of the input string.
#include <iostream>
#include <string>
int main() {
std::string s1 = "waterbottle";
std::string s2 = "erbottlewat";
if (isRotation(s1, s2)) {
std::cout << "s2 is a rotation of s1." << std::endl;
} else {
std::cout << "s2 is not a rotation of s1." << std::endl;
}
return 0;
}
Explanation:
1. The function isRotation takes two strings s1 and s2 as input and returns
true if s2 is a rotation of s1, otherwise returns false.
2. It first checks if the lengths of s1 and s2 are equal. If they are not equal, it
immediately returns false because s2 cannot be a rotation of s1.
3. It concatenates s1 with itself to create a string concat that contains all
possible rotations of s1.
4. It checks if s2 is a substring of concat using the find function. If s2 is found
in concat, it returns true; otherwise, it returns false.
5. In the main function, we test the isRotation function with example strings
"waterbottle" and "erbottlewat", and print the result.
#include <iostream>
#include <string>
#include <unordered_set>
return maxLength;
}
int main() {
std::string s = "abcabcbb";
return 0;
}
Explanation:
#include <iostream>
#include <string>
#include <unordered_set>
#include <vector>
return dp[n];
}
int main() {
std::string s = "leetcode";
std::unordered_set<std::string> wordDict = {"leet", "code"};
if (wordBreak(s, wordDict)) {
std::cout << "String can be segmented into words from the dictionary." << std::endl;
} else {
std::cout << "String cannot be segmented into words from the dictionary." << std::endl;
}
return 0;
}
Explanation:
#include <iostream>
#include <string>
return count;
}
int main() {
std::string s = "abc";
std::cout << "Total number of palindromic substrings: " << countPalindromicSubstrings(s)
<< std::endl;
return 0;
}
Explanation:
#include <iostream>
#include <string>
#include <algorithm>
void reverseWords(std::string& s) {
int n = s.length();
int main() {
std::string s = "the sky is blue";
reverseWords(s);
std::cout << "Reversed string: " << s << std::endl;
return 0;
}
Explanation:
1. The function reverseWords takes a string s as input and reverses the order of
words in it.
2. It first reverses the entire string using the std::reverse function, which
reverses the elements in the range [first, last).
3. Then, it iterates through each character of the reversed string. When it
encounters a space character ' ', it means it has found the end of a word. At
this point, it reverses the characters in the range [start, end) (where start
is the start index of the current word and end is the index of the space
character) using the std::reverse function.
4. If the loop reaches the end of the string ( end == n - 1), it means the last
word in the string has been processed, so it reverses the characters in the
range [start, end + 1) to reverse the last word.
5. In the main function, we test the reverseWords function with an example
string "the sky is blue", and print the reversed string.