Skip to content
Visual explainer 3h 30m to learn 5 steps

Strings, immutability & character counting

Manipulate strings efficiently and solve anagram, palindrome and parsing problems.

By Invicly Tech, , in Data Structures & Algorithms. About 9 minutes to read.

Topic 8 of 54

In short

Strings are sequences of characters, and in Python they are immutable, so every modification builds a new string. Many string problems reduce to counting characters, comparing two ends, or scanning once while tracking state. Knowing these patterns solves most palindrome, anagram and parsing questions.

Explained simply

A string is a sequence of characters, like letters on a necklace. You can read any bead by its position, ask how many beads there are, and slice off a section. In Python, strings cannot be changed once made. They are immutable.

Immutable means every "change" builds a brand-new string. s = s + "x" does not add to s; it makes a new string and copies all of s into it. Do that in a loop thousands of times and you copy the same letters over and over.

The fix is simple: collect pieces in a list and join them once at the end. A list can grow cheaply, and join copies each character exactly one time.

Most string puzzles use the same few moves. Count how often each letter appears. Compare characters from both ends. Or walk through once, keeping track of where you are. Once you see these moves, anagram, palindrome and parsing problems stop being scary.

Press Play on a diagram to walk through it one step at a time.

CompareBuilding a string of n pieces
s += piece in a loop
  • May copy the whole string each time
  • O(n^2) characters copied worst case
  • Fine for a few pieces
''.join(pieces)
  • Computes final length once
  • O(total length)
  • Idiomatic and fast
FlowTwo-pointer palindrome check on "racecar"
  1. 1
    i=0, j=6

    r == r, move in

  2. 2
    i=1, j=5

    a == a, move in

  3. 3
    i=2, j=4

    c == c, move in

  4. 4
    i=3, j=3

    Pointers meet, stop

  5. 5
    Result

    Palindrome, 3 comparisons, O(1) space

CompareAnagram check: three ways
Sort both
  • sorted(a) == sorted(b)
  • O(n log n) time
  • O(n) space
  • Shortest code
Counter
  • Counter(a) == Counter(b)
  • O(n) time
  • Works for any characters
  • Clear and safe
26-count array
  • counts[ord(c) - 97]
  • O(n) time
  • O(1) space
  • Lowercase a-z only

In depth

Characters are numbers underneath

Every character has a code point, a number from the Unicode table. ord("a") is 97 and chr(97) is "a". Lowercase letters are consecutive, so ord(ch) - ord("a") maps "a" to 0 and "z" to 25.

That turns letter counting into array indexing: a list of 26 zeros works like a tiny hash map with no hashing. It is fast and its size never grows, which is why many solutions call it O(1) space. When the input may contain any Unicode text, use a dict or Counter instead.

  • ord("A") = 65, ord("a") = 97, ord("0") = 48
  • ch.isalnum(), ch.isdigit(), ch.lower() help with cleanup
  • 26 counts = constant space

Hidden costs of string operations

len(s) and s[i] are O(1). But many friendly-looking operations copy or scan. s[i:j] creates a new string of length j - i. s.replace, s.split, s.lower and s.strip scan the whole string. sub in s searches, which can cost up to O(n x m) in theory, though CPython is fast in practice.

The worst habit is slicing inside a loop: for i in range(n): check(s[i:]) quietly copies about n^2 / 2 characters. Pass indexes instead of slices.

Two pointers for palindromes

A palindrome reads the same both ways, like "level". Put one pointer at the start and one at the end. If the characters match, move both inward. If they differ, it is not a palindrome. Stop when the pointers meet.

This uses O(1) extra space, while s == s[::-1] builds a reversed copy, O(n) space. For "A man, a plan, a canal: Panama", skip characters that are not letters or digits and compare in lowercase.

Parsing: scan once and keep state

Parsing means turning raw text into pieces, like numbers and words. Instead of many split calls, walk the string one character at a time and keep a little state: the number you are building, or whether you are inside a word.

To read "12+345", keep num = 0. For each digit, do num = num x 10 + digit. When you hit a non-digit, the number is finished. This single pass is O(n) and handles multi-digit numbers naturally, which is the core of every calculator and tokenizer.

  • Build numbers with num = num * 10 + int(ch)
  • Flush the last token after the loop ends
  • Use str.isdigit() to classify characters
FlowScanning "12+345" once
  1. 1
    Read 1

    num = 0 x 10 + 1 = 1

  2. 2
    Read 2

    num = 1 x 10 + 2 = 12

  3. 3
    Read +

    Flush 12, record +, reset num

  4. 4
    Read 3, 4, 5

    num = 3, then 34, then 345

  5. 5
    End of string

    Flush the last token: 345

Learn it in 5 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Explain string immutability and its costs~40m
  2. 2
    Build strings with join, not +=~40m
  3. 3
    Count characters with arrays or Counter~40m
  4. 4
    Solve palindrome and anagram problems~40m
  5. 5
    Parse tokens from a string~40m

Key points

  • Indexing and len are O(1); slicing s[i:j] copies and is O(j - i).
  • Anagram check: compare Counters or sorted strings, O(n) or O(n log n).
  • Palindrome check with two pointers is O(n) time and O(1) space.
  • A fixed 26-slot count array is faster than a dict for lowercase letters.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
def is_anagram(a, b):          # O(n) time, O(1) space
    if len(a) != len(b):
        return False
    counts = [0] * 26
    for x, y in zip(a, b):
        counts[ord(x) - ord('a')] += 1
        counts[ord(y) - ord('a')] -= 1
    return all(c == 0 for c in counts)

print(is_anagram('listen', 'silent'))  # True

Grouping anagrams with a signature

Given ["eat", "tea", "tan", "ate", "nat", "bat"], group words that are anagrams. Give each word a signature: its letters sorted. "eat", "tea" and "ate" all become "aet". "tan" and "nat" become "ant". "bat" becomes "abt". Use the signature as a dict key and append the word. Each word costs O(k log k) for its length k.

python
from collections import defaultdict

def group_anagrams(words):
    groups = defaultdict(list)
    for w in words:
        groups["".join(sorted(w))].append(w)
    return list(groups.values())

print(group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))
# [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]

Compressing a string, the join way

Turn "aaabccdddd" into "a3b1c2d4". Walk the string and count runs of the same character. When the character changes, push the letter and its count into a list. Trace: a run of 3 a's, then 1 b, 2 c's, 4 d's. Joining once at the end keeps the whole thing O(n).

python
def compress(s):
    parts, i = [], 0
    while i < len(s):
        j = i
        while j < len(s) and s[j] == s[i]:
            j += 1
        parts.append(s[i] + str(j - i))
        i = j
    return "".join(parts)

print(compress("aaabccdddd"))  # a3b1c2d4

Quick reference

  • Strings are immutable: every change makes a new string
  • Build with a list and "".join(parts), not s += piece in a loop
  • ord(ch) - ord("a") maps a..z to 0..25
  • s[i:j] copies j - i characters; pass indexes instead
  • Palindrome: two pointers from both ends, O(1) space
  • Anagram: Counter(a) == Counter(b), O(n)
  • Parse numbers with num = num * 10 + int(ch)

Common mistakes

  • Slicing inside a loop, which hides an extra O(n) per iteration.
  • Assuming only ASCII input when the problem allows Unicode.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Why is s += c inside a loop of n steps potentially O(n^2)?

Question 2

2What is the extra space of a two-pointer palindrome check?

Question 3

3What does ord("d") - ord("a") return?

Question 4

4Checking anagrams by sorting both strings of length n costs:

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write is_clean_palindrome(s) that ignores case and any character that is not a letter or digit. Example: "A man, a plan, a canal: Panama" returns True, "race a car" returns False.

  2. Exercise 2medium

    Write reverse_words(s) that reverses the order of words, removing extra spaces. Example: " the sky is blue " returns "blue is sky the".

  3. Exercise 3hard

    Write evaluate(s) for a string with non-negative integers, +, - and spaces (no brackets). Example: "12 + 30 - 5" returns 37 and "100-1-1" returns 98. Do it in one pass without eval.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is s += "x" in a loop always slow in Python?
CPython sometimes optimises it in place when nothing else references the string, so it can look fast. That trick is not guaranteed, so join is the safe habit.
How do I change one character in a Python string?
You cannot change it in place. Build a new one, like s[:i] + "x" + s[i+1:], or convert to a list, edit it, and join it back when doing many edits.
Should I use a 26-length array or a Counter for letter counts?
Use the array when the input is guaranteed lowercase a-z and speed matters. Use Counter when characters can be anything; it is clearer and still O(n).

Go deeper

ShareXLinkedInWhatsApp