Arrays
Contiguous memory with O(1) access by index - the base most patterns build on.
- active this step
- result
- not reached yet
Start the writer at 0
Everything left of write will be the finished, non-zero part.
VARIABLES
- read
- -
- write
- 0
- nums
- [0, 1, 0, 3, 12]
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
An array stores elements side by side, so any index is read in constant time. Python lists are dynamic arrays that grow as you append.
Why it matters
Fast indexed access and cache-friendly scans make arrays the default container for sequences.
Think of it like this
A row of numbered lockers: you can open locker 42 directly, but adding one in the middle means shifting everyone after it.
Use it when
- You need fast access by position
- You scan the data in order once or a few times
- You can update values in place
Avoid it when
- Frequent inserts or deletes at the front or middle - each is O(n)
- Membership checks on large data - use a set or dict
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| Read or write nums[i] | O(1) | O(1) |
| Append to the end | O(1) amortized | O(1) |
| Insert or delete at the front | O(n) | O(1) |
Often confused with: linked lists - cheap inserts once you hold the node, but O(n) access by index.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- O(1) extra space usually means rewriting the array in place
- Values in the range 1..n hint that indices can double as markers
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Removing items from a list while looping over it - indices shift under you
- Calling insert(0, x) or pop(0) in a loop, turning O(n) into O(n²)
- Off-by-one errors such as range(len(nums) - 1)
Edge cases to test
- Empty array or a single element
- All zeros, or no zeros at all
- Negative numbers and duplicates
Knowledge check
Quick check to lock in the intuition.
What does nums.pop(0) cost on a Python list of n items?
Practice
Apply what you just watched on real interview problems.