Strings
Counting, comparing and building text without hidden copies.
- visited / done
- active this step
- ruled out
- result
Compare lengths
Both strings have 7 characters, so they might be anagrams.
VARIABLES
- len(s)
- 7
- len(t)
- 7
- counts
- {}
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
A Python string is an immutable sequence of characters. Most string problems reduce to counting characters, comparing positions, or scanning with pointers or a window.
Why it matters
Parsing input, matching patterns and validating formats all come down to string handling.
Think of it like this
A printed sentence: you can read any letter, but changing one means reprinting the whole line.
Use it when
- Counting or comparing characters
- Palindromes, anagrams and prefixes
- Building output piece by piece with a list and join
Avoid it when
- Building a long result with += in a loop - each step can copy the whole string
- Sorting just to compare anagrams when a count table is O(n)
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| Index s[i] | O(1) | O(1) |
| Slice s[a:b] | O(b − a) | O(b − a) |
| Join k pieces | O(total length) | O(total length) |
Often confused with: substring vs subsequence - a substring is contiguous; a subsequence can skip characters.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- “Only lowercase letters” means a 26-slot count array works
- Strings of length 10⁵ rule out generating every substring
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Using s += ch in a loop on large inputs
- Forgetting case and non-letters when the prompt says to ignore them
- Assuming one byte per character for Unicode input
Edge cases to test
- Empty strings
- Different lengths
- Repeated characters like "aaab"
Knowledge check
Quick check to lock in the intuition.
What is the fastest way to check whether two strings of length n are anagrams?
Practice
Apply what you just watched on real interview problems.