DSA · Beginner · Pattern 3 of 11
Strings
13 problems.
Your progress0%
- 1st Visit
- 0/13
- 2nd Visit
- 0/13
- Revise
- 0/13
About this pattern
String problems are array problems over characters, with a few recurring tools: frequency tables of size 26 or 256, comparing characters from both ends, building output in an appendable buffer rather than by repeated concatenation, and splitting on delimiters.
Signals include anagrams, palindromes, character-by-character transformations, prefixes shared by several words, and checks such as whether one string can be obtained from another by deleting characters. Most tasks run in O(n) time over the string length. In C++, remember that s + t copies both strings, so prefer push_back or += inside loops, and that std::string comparison is lexicographic.
// Frequency table for lowercase letters.
array<int, 26> freq{};
for (char c : s) freq[c - 'a']++;
// Is t a subsequence of s? Advance through t only on a match.
bool isSubsequence(const string& t, const string& s) {
size_t j = 0;
for (char c : s)
if (j < t.size() && c == t[j]) ++j;
return j == t.size();
}