Handbooks / Data Structures & Algorithms / Chapter 2
Arrays and Hashing
7 pages · ~5 min✓ Reviewed
Builds on Big-O and Recursion. Next up: String Algorithms.
Arrays and Strings: The Mental Model
1. Array Layout and Costs
- Array = contiguous memory
arr[i]is found at base address + i * size- Middle insert or delete shifts elements
| Operation | Cost | Why |
|---|---|---|
Access arr[i] | O(1) | base + i*size |
| Insert or delete at end | O(1) | nothing shifts |
| Insert or delete in middle | O(n) | elements shift |
| Search, unsorted | O(n) | scan every item |
| Search, sorted | O(log n) | binary search |
2. Dynamic Arrays
- List, ArrayList, vector grow capacity by a constant factor when full
- Vector often 2x, ArrayList 1.5x, CPython list ~1.125x
- One resize copies everything: O(n)
- Append is amortized O(1): resizes are rare