Arrays and strings
The array is the most fundamental data structure: items stored side by side in memory, each reachable by its index. Python's list is a dynamic array, and strings are arrays of characters. Most interview problems start here.
How arrays work
An array is one contiguous block of memory. To find item i, the computer calculates start + i × item_size, so reading any index is O(1), however long the array is.
| Operation | Python | Cost |
|---|---|---|
| Read or write by index | a[i], a[i] = x |
O(1) |
| Append at the end | a.append(x) |
O(1) amortised |
| Remove from the end | a.pop() |
O(1) |
| Insert or remove at the front or middle | a.insert(0, x), a.pop(0) |
O(n): everything after it shifts |
| Search for a value | x in a, a.index(x) |
O(n) |
| Slice | a[i:j] |
O(j − i): it copies |
When you need fast operations at both ends, use collections.deque (next lessons).
Dynamic arrays grow by doubling
A list reserves extra room. When it fills up, it allocates a bigger block (about 1.125–2× larger) and copies everything over. Copies are rare, so appends are amortised O(1):
Classic array techniques
Prefix sums: range sums in O(1)
Precompute running totals once (O(n)), then any range sum is a subtraction:
In-place reversal and rotation
Kadane's algorithm: maximum subarray
Find the contiguous run with the largest sum, in one pass. At each position, either extend the current run or start fresh:
O(n) instead of the O(n²) of checking every subarray.
Strings
Python strings are immutable: every "change" makes a new string. Building a long string with += in a loop can cost O(n²) in total; collect pieces in a list and "".join() them once:
Counting characters
Many string problems are really counting problems:
Palindromes
2D arrays (matrices)
Grids appear everywhere: images, game boards, maps. Rotate a square matrix 90° clockwise by transposing and then reversing each row:
Watch out for a classic Python trap: [[0] * 3] * 3 creates three references to the same row. Use [[0] * 3 for _ in range(3)].
Practice
- Write
move_zeros(nums)that moves all zeros to the end in place, keeping the order of the other numbers (O(n), O(1) space). - Return the product of all elements except
nums[i]for eachi, without using division (hint: prefix and suffix products). - Write
compress("aaabccdddd")→"a3b1c2d4".
1.Why is reading a[500000] from a Python list O(1)?
2.What does inserting at the front of a list cost?
3.What does Kadane's algorithm find?