Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 15 min · revision 1

Building Strings Without Quadratic Traps

Build run-length encoding in O(n) with list accumulation and str.join, detect anagrams and first unique characters with Counter, and avoid quadratic concatenation and repeated-scan traps.

Contentsand lesson path

What you will learn

  • Build and compare strings efficiently, using join instead of repeated concatenation and character counts instead of repeated scans.

Prerequisites: Complexity Analysis

01. The problem

Because Python str objects are immutable, you cannot overwrite characters in place the way In-Place Moves: Reverse, Rotate, Partition, Cyclic Sort rewrites a list. Every operation that produces a modified string allocates a brand-new str object in memory. That immutability creates two classic O(n^2) performance traps in text-processing functions: growing a result string with out += chunk inside a loop, and calling s.count(ch) or s.index(ch) inside a loop over every character.

In this worked example we implement two clean O(n) string solutions under a linear-time constraint—run-length encoding (rle_encode) and frequency-based checks (are_anagrams and first_unique_index)—and trace why each avoids quadratic work while handling empty strings and ties safely.

02. Step 1: run-length encoding with a list builder and join

Suppose we compress adjacent repeated characters ("aaabbcdddd" -> "a3b2c1d4") under a linear-time constraint. If you kept an output string out = "" and ran out += f"{run_char}{run_len}" at every run boundary, each concatenation allocates a new string copying all earlier characters—giving 1 + 2 + ... + n = O(n^2) worst-case time across n distinct single-character runs. Trace just four 10-character chunks joined one by one: the first copy writes 10 characters, the second copies 20, the third 30, and the fourth 40 (100 copies for 40 characters of output), and across 1,000 chunks that quadratic sum balloons to roughly 5,000,000 character copies.

Why not track runs by mutating a list of characters first? Because each run outputs a multi-character token such as "a12", we collect string tokens in a list[str] (parts). Appending to parts is O(1) amortised, and "".join(parts) runs in two clean steps inside CPython: it sums all token lengths once, allocates one final string buffer, and copies each character exactly once (O(n) total). Notice also the opening guard if not text: return "": because run_char = text[0] reads index 0 directly, omitting that empty-string guard would raise IndexError on "", whereas single-character input "a" skips the text[1:] loop and still flushes "a1" cleanly at the end.

Note one subtle CPython simplification before dismissing +=: CPython contains a reference-counting optimisation that can sometimes resize a string in place when no other variable references it. However, the Python language specification does not guarantee that optimisation, it fails as soon as another reference exists (such as keeping the previous version for logging or running on PyPy), and Python official docs explicitly mark repeated string concatenation as quadratic. Using list[str] + "".join(parts) is always O(n) and idiomatic.

Python · O(n) RLE builder and Counter-based character scans
from collections import Counter


def rle_encode(text: str) -> str:
    """Run-length encode adjacent identical characters in O(n)."""
    if not text:
        return ""
    parts: list[str] = []
    run_char = text[0]
    run_len = 1
    for ch in text[1:]:
        if ch == run_char:
            run_len += 1
        else:
            parts.append(f"{run_char}{run_len}")
            run_char = ch
            run_len = 1
    parts.append(f"{run_char}{run_len}")
    return "".join(parts)


def are_anagrams(s: str, t: str) -> bool:
    return len(s) == len(t) and Counter(s) == Counter(t)


def first_unique_index(s: str) -> int:
    counts = Counter(s)
    for i, ch in enumerate(s):
        if counts[ch] == 1:
            return i
    return -1


print("rle_encode:", rle_encode("aaabbcdddd"), repr(rle_encode("")))
print("anagrams:", are_anagrams("listen", "silent"), are_anagrams("abbc", "abcc"))
print("first_unique_index:", first_unique_index("swiss"), first_unique_index("otto"))
Expected output
rle_encode: a3b2c1d4 ''
anagrams: True False
first_unique_index: 1 -1

03. Step 2: character frequency tables instead of repeated scans

Look at are_anagrams and first_unique_index. Why not write all(s.count(ch) == t.count(ch) for ch in s)? Because every call to s.count(ch) scans the entire string s from start to finish (O(n)), so running it inside a loop over n characters takes O(n^2) time—and returning early on the first mismatch does not help inputs that are anagrams. Building collections.Counter(s) scans s once in O(n) time and stores every character frequency in a dict-backed table, so looking up counts[ch] later takes O(1) expected time. Checking len(s) == len(t) first also short-circuits unequal lengths in O(1) without hashing a single character.

Notice that Counter(s) == Counter(t) handles arbitrary Unicode characters ("café", emojis, punctuation) just as cleanly as lowercase English letters, because Python str indexing (s[i]) and iteration (for ch in s) operate on Unicode code points rather than raw UTF-8 bytes. (Remember that s[i] is O(1) in Python 3 because CPython stores each string internally using a fixed 1-, 2-, or 4-byte character width determined by its widest character.)

Why does first_unique_index scan s a second time instead of looping over counts.items()? Scanning enumerate(s) returns the original string index i directly, and its order comes from the string itself rather than from the map's iteration order, so the function states its intent without depending on how the counting table stores keys. What if s and t only contain lowercase ASCII 'a'..'z'? You could use a fixed 26-element list[int] (counts[ord(ch) - ord('a')]), trading Counter generality for lower per-key overhead while keeping O(n) time and O(1) auxiliary space.

When not to use RLE or Counter: run-length encoding expands inputs with few repeats ("abcd" becomes "a1b1c1d1", doubling length from 4 to 8). Each run costs one character plus its count, so with counts below 10 the output shrinks only when runs average more than two characters; count the runs before choosing RLE. This simple format also cannot decode strings that already contain digits ("a12" is ambiguous unless counts are delimited or escaped). Likewise, if you only check whether two strings are identical in exact order, s == t is already a single linear comparison—building two Counter dicts would waste memory and miss order mismatches.

04. Check your understanding

Practice check · 2 questions

Linear string building and frequency tables

Spot hidden quadratic scans and frequency bugs.

Q1. A log line is `"abcd" * 1000`: 4,000 characters in which no two neighbours are equal. What does `len(rle_encode(line))` return?
Q2. In `rle_encode`, look at the line `for ch in text[1:]:`. Does slicing `text[1:]` once before the loop ruin the `O(n)` time complexity?
Practice only: not graded, not saved, not evidence.

05. Apply it

Extend rle_encode to pass the skill practice requirements: handle empty strings "", single characters "x", and verify that replacing text[1:] with an index loop range(1, len(text)) saves one O(n) copy. Then write rle_decode(encoded: str) -> str for multi-digit counts (such as "a12b3") using a list[str] builder and "".join(), and test round-tripping letters-only strings with Hypothesis.

Next, apply index discipline to 2D grids in Lab: Grid Walks and Matrix Rotation.

06. Review prompt

Without looking back:

  1. Why is "".join(parts) guaranteed O(n) while s += part in a loop is unsafe to rely on?
  2. Why do set(s) == set(t) and sum(map(ord, s)) == sum(map(ord, t)) both fail as anagram tests?
  3. How do you find the first non-repeating character of a string in O(n) time?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check