Arrays vs Hash Maps: Trade-offs for Sparse Active-Record Stores
Data Structure DesignModel answerLast updated
Compare arrays and hash maps across time complexity, memory, and cache behavior, then choose the right structure for a sparse integer-keyed active set.
Background
You are designing a core data store for a real-time order-tracking system. At any moment the system maintains metadata for a subset of orders drawn from a large integer ID space. You must choose the right underlying data structure before writing a single line of business logic, because that choice affects latency, memory footprint, and correctness under load.
Your Task
Answer the four questions below. Support every claim with concrete reasoning; numbers and examples are expected.
1. Time Complexity
Build a comparison table for search, insert, and delete across:
- an unsorted dynamic array
- a sorted array
- a hash map (average case and worst case)
Call out two subtleties that matter in production: when is the hash map worst case actually reachable, and what does "amortized O(1)" hide?
2. Memory Overhead
A hash map consistently uses more memory per element than a plain array. Explain the three structural reasons for this, and give rough byte counts to make the gap concrete.
3. Ordering and Data Locality
Describe what happens at the CPU cache level when you iterate sequentially through an array versus a hash map. How does memory layout influence which structure wins in a latency-sensitive loop, even when big-O complexity is identical?
4. Design Decision
Your system tracks orders whose IDs are unique integers drawn from the range 0 to 1,000,000. At any given moment exactly 1,000 of those IDs are active. Each active order carries a small metadata record.
- Evaluate a direct-address array sized to the full ID range.
- Evaluate a hash map keyed by order ID.
- Describe a hybrid approach that gives O(1) lookup and cache-friendly iteration over only the live records. Implement it in Python.
Constraints and Expected Output
- Inputs: a stream of
(order_id: int, price: float)pairs; IDs may appear multiple times (update semantics) or be cancelled (delete). - Outputs: fast point lookup by ID, fast full iteration over active orders only.
- Assume IDs could later grow beyond 32 bits; your design should remain valid.
- For the Python implementation: include
upsert(order_id, price),get(order_id) -> Optional[float],remove(order_id) -> bool, and__iter__.
Hints
Hint 1
For the complexity table, think carefully about what triggers a hash map's O(n) worst case and whether a good hash function alone is sufficient protection.
Hint 2
Memory overhead in a hash map comes from three independent sources: what is stored per entry, the mandatory fraction of empty slots, and any per-node allocation cost depending on the collision strategy.
Hint 3
The hybrid structure keeps two things in sync: a dense packed array for fast iteration, and a mapping from ID to position in that array for fast lookup. Think about what swap-remove does to that mapping when you delete.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Core Intuition
An array maps a position to a value. Elements are contiguous in memory, so index access is a single pointer offset and iteration is maximally cache-friendly.
A hash map maps an arbitrary key to a value by hashing the key to a slot. This generalises lookup to non-integer or sparse keys at the cost of hashing work, collision handling, extra memory, and scattered memory access.
The central question when choosing between them: is your key already a small, dense integer?
- Yes: the index is effectively the hash. Use an array.
- No: a hash map earns its overhead.
1. Time Complexity
| Operation | Unsorted array | Sorted array | Hash map (avg) | Hash map (worst) |
|---|---|---|---|---|
| Access by index | O(1) | O(1) | n/a | n/a |
| Search by key | O(n) | O(log n) | O(1) | O(n) |
| Insert at end | O(1) amortized | O(n) (shift) | O(1) amortized | O(n) |
| Delete | O(n) shift, or O(1) swap-remove | O(n) | O(1) | O(n) |
Two production-critical subtleties:
Worst case is reachable. A poor hash function, or an adversary who knows the function, can route many keys to the same bucket. Every operation then degrades to a linear scan. Python mitigates this for strings with hash randomisation (PYTHONHASHSEED), but integer hashes in CPython are the identity function, which can create clustering with structured input.
"Amortized O(1)" conceals latency spikes. Both a growing array and a rehashing dict periodically copy all their data. In a latency-sensitive context a single resize event can pause the process by several milliseconds. The fix is to pre-size both structures at startup with an explicit capacity argument.
2. Memory Overhead
A hash map costs more per element for three independent reasons:
-
More data per entry. An array stores only the value; the index is implicit. A hash map must store the key, the value, and usually the cached hash. CPython's dict stores all three, bringing baseline cost per entry to roughly 24 bytes plus index-table overhead.
-
Mandatory empty slots (load factor). Open-addressing tables deliberately keep a fraction of slots empty to limit probe-sequence length. CPython resizes at roughly 2/3 full; many C++ implementations use 0.5–0.875. That means 15–50% of allocated memory holds nothing.
-
Per-node allocation cost. Chained implementations (
std::unordered_map, JavaHashMap) allocate a heap node per entry. Each node carries anextpointer and allocator metadata, adding 16–32 bytes beyond the key-value pair itself.
Concrete comparison in CPython for 1,000 entries:
listof 1,000 object references: ~8 KBdictof 1,000int → intpairs: ~36 KBarray('d')of 1,000 doubles (typed): exactly 8 KB payload
3. Ordering and Data Locality
Array iteration walks memory sequentially. A 64-byte cache line holds eight 64-bit values, so you incur one cache miss per eight elements. The hardware prefetcher recognises the stride and speculatively loads the next line before you need it. The loop is also amenable to SIMD vectorisation.
Hash map iteration visits slots in hash order, which is pseudo-random by design:
- Chained maps require pointer-chasing per entry. A dependent load from cold DRAM costs roughly 100 ns versus ~1 ns from L1 cache, and the prefetcher cannot predict it.
- Open-addressing maps (including CPython's) are better because probes are adjacent in memory, but iteration still visits empty slots and the value objects themselves remain scattered on the heap.
Practical consequence: a tight loop over a 1,000-element packed array that fits in L2 cache can comfortably beat an O(1) hash lookup that misses the cache on every call. Big-O analysis assumes uniform operation cost; cache misses break that assumption.
4. Design Decision: IDs 0–1,000,000, 1,000 Active
Option A — Direct-address array (full range). 1M slots at, say, 32 bytes each consumes 32 MB to store 32 KB of live data. Lookups are O(1) with no hashing, but the 1,000 live records are spread across 32 MB, guaranteeing cache and TLB misses on every access. Iterating active records requires scanning all 1M slots.
Option B — Hash map keyed by order ID. Memory scales with active count: tens of KB, fitting comfortably in L2. Lookup, insert, and delete are O(1) average. It also remains correct if IDs later become sparse 64-bit values.
Option C — Sparse-set hybrid (recommended). Combine the benefits of both:
- Keep active records in a dense packed array — contiguous, fast to iterate, fits in cache.
- Maintain a separate
order_id → slot_indexmapping (a dict, or a bounded int array if the ID space stays 32-bit) for O(1) point lookup. - Use swap-remove on deletion: overwrite the removed slot with the last element and update its slot mapping. Keeps the dense array packed without shifting.
This gives deterministic O(1) lookup, O(1) insert, O(1) delete, and cache-friendly iteration over exactly the live records. The only constraint is that iteration order is not stable (swap-remove reshuffles elements), which is acceptable here.
from typing import Dict, Iterator, List, Optional, Tuple
class ActiveOrderStore:
"""
Sparse-set hybrid: O(1) add/get/remove, cache-friendly iteration.
Iteration order is not guaranteed stable across removals.
"""
def __init__(self) -> None:
self._ids: List[int] = [] # dense parallel arrays
self._prices: List[float] = []
self._slot: Dict[int, int] = {} # order_id -> index in dense arrays
def upsert(self, order_id: int, price: float) -> None:
"""Insert new order or update price of existing one."""
slot = self._slot.get(order_id)
if slot is not None:
self._prices[slot] = price
return
self._slot[order_id] = len(self._ids)
self._ids.append(order_id)
self._prices.append(price)
def get(self, order_id: int) -> Optional[float]:
"""Return price for an active order, or None if not present."""
slot = self._slot.get(order_id)
return None if slot is None else self._prices[slot]
def remove(self, order_id: int) -> bool:
"""Remove an order. Returns False if the ID was not active."""
slot = self._slot.pop(order_id, None)
if slot is None:
return False
last = len(self._ids) - 1
if slot != last:
# Swap the last element into the vacated slot.
moved_id = self._ids[last]
self._ids[slot] = moved_id
self._prices[slot] = self._prices[last]
self._slot[moved_id] = slot # update moved element's slot pointer
self._ids.pop()
self._prices.pop()
return True
def __len__(self) -> int:
return len(self._ids)
def __iter__(self) -> Iterator[Tuple[int, float]]:
"""Iterate over (order_id, price) pairs for all active orders."""
return zip(self._ids, self._prices)
Complexity summary: upsert O(1) amortized, get O(1), remove O(1). Iteration O(k) where k is the number of active orders, with no wasted slots visited.
Common Mistakes to Avoid
- Forgetting to update
_slotfor the moved element after swap-remove. This is the most frequent bug in sparse-set implementations; the mapping becomes stale and future lookups or removes silently operate on the wrong slot. - Using swap-remove when iteration order must be stable. It reorders the dense array. If ordered iteration is required, use a tombstone or a shift-delete instead, accepting O(n) delete cost.
- Not pre-sizing the dict. Python does not expose a constructor argument for initial capacity, but inserting a large batch via
dict.updatefrom a pre-built mapping avoids incremental rehashing. - Assuming integer hashing is collision-resistant. CPython hashes small integers to themselves. Structured or adversarial IDs can cause clustering; a multiplicative mix step eliminates it.