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]
[5]

C-style: null terminator \0 marks end. Python/Java: length stored separately.

Complexity

Index access s[i]O(1)

Constant time

Concatenation s1 + s2 — copies both stringsO(n)

Linear time

Substring / sliceO(n)

Linear time

Search / indexOfO(n)

Linear time

Reverse in-place (two-pointer)O(n)

Linear time

Two-pointer reverse — animated

reverse('hello!')step 1/7

// Array state

h
L
e
[1]
l
[2]
l
[3]
o
[4]
!
R
→ Start: left=0, right=5

// Pseudocode

1function reverse(s):
2 left = 0, right = len(s) - 1
3 while left < right:
4 swap(s[left], s[right])
5 left++, right--
6 return s // O(n/2) = O(n)

Palindrome check — trace it

isPalindrome.pseudo
1
2
3
4
5
6
7
8
9

// Trace output

Click ▶ Run to trace execution

Substring / slice

substring(s, start, end)
1function substring(s, start, end):
2 result = []
3 for i from start to end - 1:
4 result.append(s[i])
5 return result.join('') // O(n) — copying chars
⚠️Concatenation in loops
In many languages, strings are immutable. s = s + char inside a loop creates a new string every iteration — O(n²) total. Use a builder/list and join once at the end.
🔍Unicode gotcha
Iterating by index gives bytes, not characters, in UTF-8 encoded strings. Emoji like 🔥 are 4 bytes. Always use language-level character iterators for multi-byte string processing.

🎯 Quick Check

You concatenate n strings of average length L in a loop using +. What is the total time complexity?

Strings: summary

Key points

  • Strings are immutable: s[0] = "x" does nothing.
  • Use [...str] or for…of to iterate by character, which handles emoji correctly.
  • Anagram checks: compare sorted characters, or compare character-count maps (O(n)).

Frequently asked questions

›How do I reverse a string in JavaScript?

[...str].reverse().join(""). The spread handles multi-byte characters like emoji better than split("").

›Is string concatenation O(n)?

Each concatenation copies, so repeated += in a loop can be O(n²) in the worst case. Engines optimise this well, but array.join is the safe pattern.