Skip to content
DSAPrep

    ↑↓ to move · Enter to open · Esc to close

    ← 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 count

    Common pitfalls

    • Repeated string concatenation in a loop is O(n²)
    • Forgetting even-length centers

    Practice · 0 / 6 done