A string is a sequence of characters, stored as an array of code units under some encoding such as UTF-8 or UTF-16. Strings look simple, but encodings, immutability and hidden copying make them a common source of bugs and accidental O(n²) code. This lesson covers how strings are stored, what each operation really costs, and the handful of patterns (two pointers, frequency counts, reversal, substring search) behind most string problems.
Think of it like
A printed page and a typesetter's tray
An immutable string is a printed page: to fix one letter you reprint the whole page. Fine once, but painful if you reprint after every single letter you add. A string builder is the typesetter's tray, where letters are arranged freely and the page is printed once at the end. Knowing which one you are holding is the difference between O(n) and O(n²).
Characters and encodings
Unicode assigns every character a number called a code point, written like U+0041 for A. An encoding decides how code points become bytes. The encoding determines how much memory a string takes and, crucially, what "length" and "index" mean.
| Encoding | Unit size | Bytes per code point | Used by |
|---|---|---|---|
| ASCII | 7 bits | 1 (only 128 characters) | Protocols, legacy systems; a subset of UTF-8 |
| UTF-8 | 8 bits | 1 to 4 | The web, files, Linux, Go, Rust, Python I/O |
| UTF-16 | 16 bits | 2 or 4 (surrogate pairs) | Java and JavaScript strings, C#, Windows APIs |
| UTF-32 | 32 bits | Always 4 | Fixed width; rare for storage, used internally in some tools |
| Character | Code point | UTF-8 bytes | UTF-16 units |
|---|---|---|---|
| A | U+0041 | 1 (41) | 1 |
| é | U+00E9 | 2 (C3 A9) | 1 |
| € | U+20AC | 3 (E2 82 AC) | 1 |
| 𝄞 (G clef) | U+1D11E | 4 (F0 9D 84 9E) | 2 (surrogate pair) |
Immutability and string builders
In Java, Python, JavaScript, C# and Go, strings are immutable: every "modification" creates a new string. Immutability makes strings safe to share between threads, usable as hash map keys, cacheable (Java caches a string's hash code) and internable. C++ std::string is the notable exception: it is a mutable dynamic array of bytes.
# Slow: each += may copy the whole string built so far
s = ""
for word in words:
s += word + " "
# Fast: collect parts, copy once at the end
s = " ".join(words)| Language | String type | Efficient building |
|---|---|---|
| Python | str (immutable) | Append to a list, then "".join(parts); or io.StringIO |
| Java | String (immutable) | StringBuilder (amortized O(1) append) |
| JavaScript / TS | string (immutable) | Push to an array and join; engines often optimize +=, but do not rely on it |
| C++ | std::string (mutable) | += / push_back is amortized O(1); reserve when the size is known |
| C# | string (immutable) | StringBuilder |
Operation costs
| Operation | Time | Notes |
|---|---|---|
Index s[i] | O(1) | For fixed-width units. Indexing UTF-8 by code point is O(n), which is why Rust forbids s[i]. |
| Length | O(1) | Stored with the string (C's strlen is O(n): it scans for the terminating zero byte) |
Concatenate s + t | O(n + m) | Allocates and copies both |
| Substring or slice of length k | O(k) | Java, Python and JS copy; Go and Rust slices share memory in O(1) |
| Equality / comparison | O(min(n, m)) | Stops at the first difference; equal strings must be scanned fully |
| Hash | O(n) | Java caches it after the first call |
| Find a substring (naive) | O(n · m) | Linear-time algorithms in String Matching (KMP, Rabin-Karp, Z) |
| Split, join, replace, reverse | O(n) | Each creates new strings |
| Sort characters | O(n log n) | O(n + k) with counting sort over an alphabet of size k |
Pattern: palindromes
A palindrome reads the same forwards and backwards. The check is a textbook use of Two Pointers: compare the outermost characters and move both pointers inward. Real problems add twists, such as ignoring case and punctuation ("A man, a plan, a canal: Panama") or allowing one deletion.
To find the longest palindromic substring, flip the idea around: every palindrome has a center. A string of length n has 2n − 1 centers (each character, and each gap between neighbors for even lengths). Expanding outward from each center while the ends match finds every palindrome in O(n²) time and O(1) space.
- 1
Pick a center
Center
cfrom 0 to 2n − 2:lo = c // 2,hi = lo + c % 2. Odd c gives an even-length center between two characters. - 2
Expand
While
s[lo] == s[hi], moveloleft andhiright. - 3
Measure
The palindrome is
s[lo + 1 .. hi − 1], of lengthhi − lo − 1, because the loop overshot by one on each side. - 4
Keep the best
Track the longest one seen. Manacher's algorithm improves this to O(n), but expand-around-center is what interviews expect.
Pattern: anagrams via frequency counts
Two strings are anagrams when they contain the same characters with the same counts (listen and silent). Counting is the key idea, and it generalizes to permutations, "can you build X from Y" problems and sliding-window searches.
Sort both strings
- Anagrams sort to the same string
- O(n log n) time
- Works for any alphabet
- The sorted string is a handy group key
Count characters
- Increment for s, decrement for t, expect all zeros
- O(n) time
- O(1) space for a fixed alphabet (26 counters)
- Use a hash map for arbitrary Unicode
Grouping anagrams uses a canonical key per word: either the sorted word or its tuple of 26 counts. Words with the same key land in the same Hash Tables bucket. To find every anagram of p inside a longer text, slide a window of length |p| and update counts in O(1) per step (Sliding Window).
Pattern: reversing words
Turn " the sky is blue " into "blue is sky the". With extra space, split on whitespace, reverse the list and join: O(n). With a mutable buffer and O(1) extra space, use the same double-reversal trick as array rotation.
- 1
Reverse everything
"the sky is blue"becomes"eulb si yks eht". Words are now in the right order but spelled backwards. - 2
Reverse each word
"blue is sky the". - 3
Compact spaces
Use a write pointer to drop leading, trailing and repeated spaces while copying.
Pattern: substring search
The naive search tries every starting position and compares up to m characters, O(n · m) in the worst case (searching aaaab in aaaa…a). Linear-time algorithms avoid re-reading characters: KMP uses a failure function, Rabin-Karp compares rolling hashes, and the Z-algorithm precomputes match lengths. All three are covered in String Matching (KMP, Rabin-Karp, Z).
Other recurring patterns
- Frequency arrays and maps for counting, first unique character, and "ransom note" problems.
- Sliding window for the longest substring with at most k distinct characters or without repeats.
- Stacks for balanced brackets, decoding
3[ab]and removing adjacent duplicates (Stacks). - Tries for prefix queries and autocomplete (Tries (Prefix Trees)).
- Dynamic programming for edit distance and longest common subsequence (LCS & Edit Distance).
- Hashing for fast substring comparisons and duplicate detection.
Complexity
| Operation | Time | Space | Notes |
|---|---|---|---|
| Access character by index | O(1) | O(1) | Fixed-width encodings |
| Concatenate two strings | O(n + m) | O(n + m) | New string |
Build with repeated += (immutable) | O(n²) | O(n) | Use a builder or join |
| Build with a builder | O(n) | O(n) | Amortized O(1) appends |
| Palindrome check | O(n) | O(1) | Two pointers |
| Longest palindromic substring | O(n²) | O(1) | Expand around 2n − 1 centers |
| Anagram check (fixed alphabet) | O(n) | O(1) | 26 counters |
| Naive substring search | O(n · m) | O(1) | KMP or Z: O(n + m) |
Implementation
A case-insensitive palindrome check that skips non-alphanumeric characters, and the O(n²) longest palindromic substring.
def is_palindrome(s: str) -> bool:
"""Ignore case and non-alphanumeric characters."""
lo, hi = 0, len(s) - 1
while lo < hi:
if not s[lo].isalnum():
lo += 1
elif not s[hi].isalnum():
hi -= 1
elif s[lo].lower() != s[hi].lower():
return False
else:
lo += 1
hi -= 1
return True
def longest_palindrome(s: str) -> str:
"""Expand around each of the 2n - 1 centers: O(n^2) time, O(1) space."""
best_lo, best_len = 0, 0
for center in range(2 * len(s) - 1):
lo = center // 2
hi = lo + center % 2 # odd center index -> even-length palindrome
while lo >= 0 and hi < len(s) and s[lo] == s[hi]:
lo -= 1
hi += 1
length = hi - lo - 1 # the loop overshot by one on each side
if length > best_len:
best_lo, best_len = lo + 1, length
return s[best_lo:best_lo + best_len]
print(is_palindrome("A man, a plan, a canal: Panama")) # True
print(longest_palindrome("babad")) # babKey takeaways
- Strings are arrays of code units; the encoding (UTF-8, UTF-16) decides what length and indexing mean.
- Strings are immutable in Java, Python, JavaScript, C# and Go; build them with a builder or join, never with
+=in a loop. - Substrings, concatenation, hashing and comparison all cost time proportional to length.
- Two pointers solve palindrome checks; expand-around-center finds the longest palindrome in O(n²) with O(1) space.
- Frequency counts (26-slot arrays or hash maps) solve anagram, permutation and grouping problems in linear time.
- Double reversal reverses word order in place; linear-time substring search lives in KMP, Rabin-Karp and Z.
Common pitfalls
- Building strings with
+=inside a loop, which can be O(n²). - Assuming
lengthcounts visible characters; emoji, accents and surrogate pairs break that assumption. - Slicing inside a loop (
s[i:],substring) and forgetting each slice copies O(k) characters. - Comparing strings with
==in Java, which compares references; useequals. - Hard-coding a 26-letter array when the input may contain uppercase letters, digits or Unicode.
Interview tips
- Ask about the alphabet, case sensitivity and whitespace before choosing between an array of counts and a hash map.
- Mention string immutability and use a builder unprompted; interviewers notice accidental O(n²) concatenation.
- For palindrome problems, say "two pointers" or "expand around center" and state the 2n − 1 centers.
Real-world applications
- Text processing, search engines, log parsing and tokenizers.
- Spell checkers and autocomplete (tries, edit distance).
- DNA sequence analysis, which is string matching over a four-letter alphabet.
- Protocols and file formats, where encoding mistakes become security bugs.
Practice problems
Test yourself
In Java, what is the time complexity of building an n-character string with s += c inside a loop?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.