Strings
How text is stored, why strings are often immutable, and the techniques behind every string problem.
A string is a sequence of characters. Under the hood it is almost always an array of code units (bytes or 16-bit chars) plus a length. Everything you know about arrays applies — O(1) indexing, O(n) search — with two twists: encoding and immutability.
Encoding: characters are numbers
Computers store numbers, so each character is mapped to a number (a code point) and then encoded into bytes. See Data Representation for the full story.
| Language | Internal representation | "héllo".length |
|---|---|---|
| Java | UTF-16 (compact Latin-1 when possible) | 5 |
| JavaScript | UTF-16 code units | 5 |
| Python 3 | Code points (flexible 1/2/4-byte storage) | 5 |
| Rust / Go | UTF-8 bytes | 6 bytes |
Immutability
In Java, Python, JavaScript, C# and Go, strings are immutable: every "modification" creates a new string. Benefits: safe to share between threads, safe as hash-map keys, hash code can be cached, and literals can be interned (deduplicated).
The cost: building a string with += in a loop copies the whole string every time — O(n²) total.
// ✗ O(n²): each += copies the entire string so far
String s = "";
for (int i = 0; i < n; i++) s += i;
// ✓ O(n): StringBuilder is a mutable, growable char array
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) sb.append(i);
String result = sb.toString();# ✗ O(n²) in general (CPython sometimes optimises in-place, don't rely on it)
s = ""
for i in range(n):
s += str(i)
# ✓ O(n): collect parts, join once
result = "".join(str(i) for i in range(n))// Modern engines use "ropes" so += is usually fine, but join is predictable
let s = "";
for (let i = 0; i < n; i++) s += i;
const parts: string[] = [];
for (let i = 0; i < n; i++) parts.push(String(i));
const result = parts.join("");Essential operations
| Operation | Typical cost | Notes |
|---|---|---|
s[i] / charAt(i) | O(1) | |
length | O(1) | Stored, not computed (except C's strlen: O(n)) |
Concatenate a + b | O(len a + len b) | New string |
| Substring / slice | O(k) | Copies k chars |
indexOf(pattern) | O(n·m) worst | Naive; KMP is O(n+m) |
Compare a.equals(b) | O(min length) | Use equals, never ==, in Java |
Core techniques
Frequency counting
Anagrams, permutations, "first unique character" — count characters in a fixed-size array (26 for lowercase letters) or a hash map.
boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
int[] count = new int[26];
for (int i = 0; i < s.length(); i++) {
count[s.charAt(i) - 'a']++;
count[t.charAt(i) - 'a']--;
}
for (int c : count) if (c != 0) return false;
return true;
}from collections import Counter
def is_anagram(s: str, t: str) -> bool:
return Counter(s) == Counter(t)function isAnagram(s: string, t: string): boolean {
if (s.length !== t.length) return false;
const count = new Array(26).fill(0);
for (let i = 0; i < s.length; i++) {
count[s.charCodeAt(i) - 97]++;
count[t.charCodeAt(i) - 97]--;
}
return count.every((c) => c === 0);
}Two pointers from both ends
Palindromes and reversals: compare s[l] with s[r], move inward.
boolean isPalindrome(String s) {
int l = 0, r = s.length() - 1;
while (l < r) {
while (l < r && !Character.isLetterOrDigit(s.charAt(l))) l++;
while (l < r && !Character.isLetterOrDigit(s.charAt(r))) r--;
if (Character.toLowerCase(s.charAt(l++)) != Character.toLowerCase(s.charAt(r--))) return false;
}
return true;
}def is_palindrome(s: str) -> bool:
l, r = 0, len(s) - 1
while l < r:
while l < r and not s[l].isalnum(): l += 1
while l < r and not s[r].isalnum(): r -= 1
if s[l].lower() != s[r].lower():
return False
l, r = l + 1, r - 1
return Truefunction isPalindrome(s: string): boolean {
const ok = (c: string) => /[a-z0-9]/i.test(c);
let l = 0, r = s.length - 1;
while (l < r) {
while (l < r && !ok(s[l])) l++;
while (l < r && !ok(s[r])) r--;
if (s[l].toLowerCase() !== s[r].toLowerCase()) return false;
l++; r--;
}
return true;
}Other go-to tools
- Sliding window for "longest/shortest substring with property X" → Sliding Window.
- Hashing / rolling hash for substring matching → Rabin–Karp.
- Tries for prefix queries over many words → Tries.
- DP for edit distance, LCS, palindromic subsequences → DP on sequences.
- A string is an array of encoded characters; know whether your language counts bytes, UTF-16 units or code points.
- Immutable strings are safe and hashable, but repeated
+=can be O(n²) — use a builder / join. - Most string problems reduce to counting, two pointers, sliding window, hashing, tries or DP.
QWhy are strings immutable in Java?easy
Security (a validated filename/URL can't change afterwards), thread safety without locks, a cacheable hashCode (great for HashMap keys), and the string pool: identical literals can share one object only if nobody can mutate it.
QWhat's the difference between == and equals() for Java strings?easy
== compares references (same object?), equals() compares contents. Two equal literals may be == because of interning, but strings built at runtime usually aren't. Always use equals.
QFind the first non-repeating character in a string.easy
Two passes: count frequencies (array of 26 or a map), then scan the string again and return the first char with count 1. O(n) time, O(1) space for a fixed alphabet.
QGroup a list of words into anagram groups.medium
Use a hash map whose key is a canonical form: the sorted word (O(k log k)) or a 26-length count tuple (O(k)). Append each word to its key's list. Total O(n·k).