Q&A-1Explain the contiguous-array cost model and how it changes a production decision.
Answer
The 90-second answer. An array is one contiguous allocation of equal-width slots. Element i sits at base + i × width, so indexing is one multiply-add and one load: O(1) regardless of n. Inserting or deleting at position i shifts every element after it, so those are O(n) in the number of elements moved. The production consequence is not the asymptotics, which everyone knows, but the layout: contiguous slots mean a scan touches every byte of every cache line it loads, and the hardware prefetcher runs ahead of it. That is why a flat array often beats a linked list or a hash map on a hot read path even when its big-O looks worse.
The mechanism, with numbers. On x86-64 a cache line is 64 bytes and a pointer is 8 bytes, so one line holds 8 pointers. Scanning a 1,000,000-element array of pointers touches 125,000 lines, and because the access is sequential the prefetcher hides most of the latency: the scan is bandwidth-bound, roughly 8 MB moved. A linked list of the same 1,000,000 elements touches one line per node, and those lines are scattered, so each hop is a dependent load that cannot be prefetched: on the order of 1,000,000 cache misses. At a typical ~80–100 ns DRAM latency against ~1 ns for L1, that is the difference between a few milliseconds and tens of milliseconds for the same logical traversal. (These are typical orders of magnitude, not a benchmark.)
Where it bites in production. The classic failure is a queue built on a Python list: q.pop(0) is O(n) because CPython memmoves the remaining pointers down. A 1,000,000-element list holds 8 MB of pointers; one front-pop moves ~8 MB, which at ~10 GB/s is ~0.8 ms. At 1,000 pops/s that is 0.8 core-seconds per second: a single core saturated by bookkeeping. Symptom: p99 latency climbs linearly with queue depth while p50 stays flat. Detection: a profiler (py-spy, perf) shows time in list_ass_slice/memmove rather than in your code, and allocation counters stay flat, which rules out GC. Fix: collections.deque, which is O(1) at both ends.
Same shape in Go: s = append(s[:i], s[i+1:]...) inside a loop is O(n²) and shows up as memmove in a CPU profile.
Choosing. Use an array when access is index-driven, iteration is the hot path, and mutation is at the end (append is amortised O(1) because CPython over-allocates). Reach for a deque for double-ended queues, a linked structure or an index-plus-free-list when you insert and delete in the middle and hold stable references, and a hash map when you need lookup by key rather than position. If a hot loop reads only one field of each record, split into parallel arrays (struct-of-arrays) so each cache line carries 8 useful values instead of 1.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.