C++ String
Competitive Problems
Programming Reference
8 classic string problems — each with explanation, example, complete C++ code, and a breakdown of which
container stores the answer and how to access it.
# Problem Container Used
01 Consecutive Repeating Characters vector>
02 Count Distinct Consecutive Pairs (length 2) set
03 Palindrome Check bool
04 Anagram Check bool + int[26]
05 Validating Excel Cell Reference bool
06 Validating an IP Address (IPv4) vector + bool
07 Isomorphic Strings Check unordered_map
08 Longest Window with No Repeating Characters unordered_map + int
Consecutive Repeating Characters
01 Find all characters that repeat consecutively in a string
Explanation
• Scan the string and compare each character with the next one.
• When s[i] == s[i+1], the character is repeating consecutively.
• Collect the character and its position into a result vector.
Example
Input: "aabbcddde" → Repeating: a(0), b(2), d(6), d(7)
C++ Code
#include
using namespace std;
int main() {
string s;
cin >> s;
// Store: pair — character and its index
vector> result;
for (int i = 0; i + 1 < (int)[Link](); i++)
if (s[i] == s[i+1])
result.push_back({s[i], i});
// Access: result[i].first = character
// result[i].second = index
for (auto& p : result)
cout << [Link] << " at index " << [Link] << "\n";
C++ String Problems — Competitive Programming Reference Page 1
}
Container & Access
Type: vector>
Stored in: result
result[i].first → the repeating character
result[i].second → its starting index
[Link]() → total count of repeating pairs
Count Distinct Consecutive Pairs (length 2)
02 Count unique 2-character substrings formed by adjacent characters
Explanation
• Extract every substring of length 2 using [Link](i, 2).
• Insert each into a set — sets automatically discard duplicates.
• The size of the set is the count of distinct consecutive pairs.
Example
Input: "abacab" → Pairs: ab, ba, ac, ca, ab → Distinct: {ab, ba, ac, ca} → Count: 4
C++ Code
#include
using namespace std;
int main() {
string s;
cin >> s;
// Store: set — only keeps unique pairs
set distinct;
for (int i = 0; i + 1 < (int)[Link](); i++)
[Link]([Link](i, 2));
// Access: iterate the set directly
cout << "Count: " << [Link]() << "\n";
for (const string& pair : distinct)
cout << pair << "\n";
}
Container & Access
Type: set
Stored in: distinct
[Link]() → count of distinct pairs
[Link]("ab") → 1 if "ab" exists, else 0
for (auto& p : distinct) → iterate all unique pairs
C++ String Problems — Competitive Programming Reference Page 2
Palindrome Check
03 Check if a string reads the same forwards and backwards
Explanation
• Use two pointers: left starting at 0, right at [Link]()-1.
• Move both inward — if any s[left] != s[right], it is NOT a palindrome.
• If all characters matched, it IS a palindrome. Result is a single bool.
Example
Input: "racecar" → true Input: "hello" → false
C++ Code
#include
using namespace std;
int main() {
string s;
cin >> s;
// Store: bool — single true/false answer
bool isPalin = true;
int l = 0, r = (int)[Link]() - 1;
while (l < r) {
if (s[l] != s[r]) { isPalin = false; break; }
l++; r--;
}
// Access: read isPalin directly
cout << (isPalin ? "Palindrome" : "Not Palindrome") << "\n";
}
Container & Access
Type: bool
Stored in: isPalin
isPalin → true if palindrome, false otherwise
if (isPalin) → use directly in conditions
Anagram Check
04 Check if two strings are anagrams (same characters, any order)
Explanation
• Two strings are anagrams if they have the same character frequency.
• Use a frequency array of size 26: increment for s1, decrement for s2.
• If all 26 entries are 0 at the end, the strings are anagrams.
Example
Input: "listen" "silent" → true Input: "hello" "world" → false
C++ String Problems — Competitive Programming Reference Page 3
C++ Code
#include
using namespace std;
int main() {
string a, b;
cin >> a >> b;
// Store: int[26] frequency array + bool result
int freq[26] = {};
bool isAnagram = ([Link]() == [Link]());
if (isAnagram) {
for (char c : a) freq[c - 'a']++;
for (char c : b) freq[c - 'a']--;
for (int x : freq)
if (x != 0) { isAnagram = false; break; }
}
// Access: read isAnagram directly
// freq[i] shows char balance (0 = matched)
cout << (isAnagram ? "Anagram" : "Not Anagram") << "\n";
}
Container & Access
Type: bool + int[26]
Stored in: isAnagram / freq
isAnagram → true if anagram, false otherwise
freq[c - 'a'] → frequency balance for character c
freq[0] → balance for 'a', freq[25] for 'z'
Validating Excel Cell Reference
05 Check if a string is a valid Excel cell like A1, BC234, XFD1048576
Explanation
• An Excel cell has 1-3 uppercase letters (column) followed by 1-7 digits (row).
• Column range: A to XFD (1 to 16384). Row range: 1 to 1048576.
• Split letters and digits, validate ranges, store result as bool.
Example
Input: "A1" → valid "XFD1048576" → valid "ZZZ99" → invalid
C++ Code
#include
using namespace std;
int colNum(const string& col) {
int num = 0;
for (char c : col) num = num * 26 + (c - 'A' + 1);
return num;
}
C++ String Problems — Competitive Programming Reference Page 4
int main() {
string s;
cin >> s;
// Store: bool — valid or not
bool valid = false;
int i = 0, n = [Link]();
string col = "", row = "";
while (i < n && isupper(s[i])) col += s[i++];
while (i < n && isdigit(s[i])) row += s[i++];
if (![Link]() && ![Link]() && i == n
&& [Link]() <= 3 && [Link]() <= 7
&& colNum(col) >= 1 && colNum(col) <= 16384
&& stoi(row) >= 1 && stoi(row) <= 1048576)
valid = true;
// Access: read valid directly
cout << (valid ? "Valid cell" : "Invalid cell") << "\n";
}
Container & Access
Type: bool
Stored in: valid
valid → true if valid Excel cell reference
col → the column letters part (string)
row → the row digits part (string)
Validating an IP Address (IPv4)
06 Check if a string is a valid IPv4 address like [Link]
Explanation
• A valid IPv4 has exactly 4 parts separated by dots.
• Each part must be a number from 0 to 255 with no leading zeros.
• Split by '.', validate each part, store overall result as bool.
Example
Input: "[Link]" → valid "[Link]" → invalid "[Link]" → invalid
C++ Code
#include
using namespace std;
int main() {
string s;
cin >> s;
// Store: vector for parts, bool for result
vector parts;
stringstream ss(s);
string token;
while (getline(ss, token, '.'))
C++ String Problems — Competitive Programming Reference Page 5
parts.push_back(token);
bool valid = ([Link]() == 4);
if (valid) {
for (const string& p : parts) {
if ([Link]() || [Link]() > 3) { valid=false; break; }
for (char c : p) if (!isdigit(c)) { valid=false; break; }
if (!valid) break;
// No leading zeros (except "0" itself)
if ([Link]() > 1 && p[0] == '0') { valid=false; break; }
if (stoi(p) > 255) { valid = false; break; }
}
}
// Access: parts[0..3] for each octet, valid for result
cout << (valid ? "Valid IP" : "Invalid IP") << "\n";
}
Container & Access
Type: vector + bool
Stored in: parts / valid
parts[0] → first octet (e.g. "192")
parts[1] → second octet (e.g. "168")
parts[2] → third octet (e.g. "1")
parts[3] → fourth octet (e.g. "1")
valid → true if all 4 octets are in range 0-255
Isomorphic Strings Check
07 Check if characters of s can be mapped one-to-one to characters of t
Explanation
• Two strings are isomorphic if every character in s maps to exactly one char in t,
• and no two characters in s map to the same character in t.
• Use two maps: s->t and t->s. Check consistency at each position.
Example
Input: "egg" "add" → true (e->a, g->d) Input: "foo" "bar" → false (o would map to both a and r)
C++ Code
#include
using namespace std;
int main() {
string s, t;
cin >> s >> t;
// Store: two unordered_maps for bidirectional mapping
unordered_map s2t, t2s;
bool isIso = ([Link]() == [Link]());
for (int i = 0; i < (int)[Link]() && isIso; i++) {
C++ String Problems — Competitive Programming Reference Page 6
char cs = s[i], ct = t[i];
if ([Link](cs) && s2t[cs] != ct) isIso = false;
if ([Link](ct) && t2s[ct] != cs) isIso = false;
s2t[cs] = ct;
t2s[ct] = cs;
}
// Access: s2t[c] gives what c maps to in t
// t2s[c] gives what c maps to in s
cout << (isIso ? "Isomorphic" : "Not Isomorphic") << "\n";
for (auto& [k,v] : s2t)
cout << k << " -> " << v << "\n";
}
Container & Access
Type: unordered_map
Stored in: s2t / t2s
s2t[c] → what character c in s maps to in t
t2s[c] → what character c in t maps back to in s
isIso → true if isomorphic, false otherwise
[Link]() → number of unique character mappings
Longest Window with No Repeating Characters
08 Find the longest contiguous substring where all characters are unique
Explanation
• Use sliding window with two pointers l (left) and r (right).
• Expand r and add s[r] to an unordered_map tracking frequency.
• If s[r] frequency exceeds 1, shrink from l until it is 1 again.
• Track the maximum window length and its start position.
Example
Input: "abcabcbb" → length 3, window "abc" Input: "pwwkew" → length 3, window "wke"
C++ Code
#include
using namespace std;
int main() {
string s;
cin >> s;
// Store: unordered_map for frequency
// int for max length, int for start index
unordered_map freq;
int l = 0, maxLen = 0, start = 0;
for (int r = 0; r < (int)[Link](); r++) {
freq[s[r]]++;
while (freq[s[r]] > 1) { // duplicate found
freq[s[l]]--;
C++ String Problems — Competitive Programming Reference Page 7
l++;
}
if (r - l + 1 > maxLen) {
maxLen = r - l + 1;
start = l; // save where window begins
}
}
// Access: [Link](start, maxLen) gives the actual window
cout << "Length: " << maxLen << "\n";
cout << "Window: " << [Link](start, maxLen) << "\n";
}
Container & Access
Type: unordered_map + int
Stored in: freq / maxLen / start
maxLen → length of the longest window
start → starting index of that window
[Link](start, maxLen) → the actual window string
freq[c] → current frequency of char c in window
C++ String Problems — Competitive Programming Reference Page 8