Strings
Strings
A string is a sequence of characters stored as a contiguous array of bytes. Understanding how strings are stored and copied is essential — hidden O(n) costs trip up even experienced engineers.
How are strings handled as a data structure?
A string is an immutable sequence of characters. Reading a character by index is O(1), but every "modification" creates a new string, so building a string with += in a loop can be O(n²). Collect pieces in an array and join them, or use template literals. Many string problems are solved with two pointers, hash maps of character counts, or sliding windows.
const s = "racecar";
s[0]; // "r"
const isPalindrome = (t) => t === [...t].reverse().join("");
const counts = {};
for (const ch of "banana") counts[ch] = (counts[ch] ?? 0) + 1; // { b:1, a:3, n:2 }
const parts = []; for (const w of ["a", "b"]) parts.push(w); parts.join("-");Memory layout
Strings are stored as indexed character arrays. Each character occupies 1–4 bytes depending on encoding. Most modern languages use UTF-8 or UTF-16, meaning a single "character" can be multiple bytes.
h
[0]e
[1]l
[2]l
[3]o
[4]