← All patterns
Strings
Character counting, palindromes, and parsing.
Reach for it when
- Palindromic substrings (expand around center)
- Character frequency comparisons
- Parse or build strings efficiently
Core idea
Strings are immutable in Python, so build results in a list and join once. For palindromes, expand around each of the 2n - 1 centers. For anagram-like questions, compare fixed-size frequency arrays of length 26.
Template · O(n²) for center expansion, O(n) for counting
def count_palindromes(s): count = 0 for center in range(2 * len(s) - 1): l, r = center // 2, (center + 1) // 2 while l >= 0 and r < len(s) and s[l] == s[r]: count += 1 l, r = l - 1, r + 1 return countint countPalindromes(const string& s) { int n = s.size(), count = 0; for (int center = 0; center < 2 * n - 1; center++) { int l = center / 2, r = (center + 1) / 2; while (l >= 0 && r < n && s[l] == s[r]) { count++; l--; r++; } } return count;}Common pitfalls
- Repeated string concatenation in a loop is O(n²)
- Forgetting even-length centers
Practice · 0 / 6 done
- Longest Common PrefixEasy
- Roman to IntegerEasy
- Invalid TransactionsMedium
- Largest NumberMedium
- Reverse Words in a StringMedium
- Search Suggestions SystemMedium