Arrays & Strings — Introduction
You build a big string by appending one character at a time in a loop —
s += c, a million times. It feels like a million cheap operations. It’s actually closer to a trillion. The same loop on a list is genuinely cheap. Same idea, wildly different cost — and the reason is the single most important property of strings.
Today’s two structures look almost identical — both are ordered sequences you index into — but one subtle difference (mutability) changes how you must use them.
Arrays
- An array is a contiguous block of memory holding a fixed number of elements of the same type.
- You access elements by index (position), starting at 0. Because the layout is contiguous, that access is
O(1)— the address is computed directly (you’ll see exactly how on the memory representation page).
Strings
- A string is a sequence of characters — letters, digits, symbols, spaces — used to represent text.
- In many languages (Python, Java, JavaScript, C#), strings are immutable: once created, they can’t be changed. Any operation that looks like it modifies a string actually builds a brand-new string.
Feel the immutability
Run this. The id() (object identity) changes after +=, proving the original string was never modified — a whole new object was made:
The practical rule: never build a large string with repeated += in a loop. Collect the pieces in a list and "".join(...) them at the end (Python), or use a StringBuilder/StringBuffer (Java) or std::string with += (C++ strings are mutable, so this is fine there). Same output, O(n) instead of O(n²).
Quick check
This is the foundation for everything in Day 2. Next, dig into arrays — start with declaration & initialization and memory representation — then the strings track, before the techniques that make these structures sing.