Cost of Core Data Structure Ops and When Threads Hurt
Heaps, Sorting & SearchModel answerLast updated
Give worst-case Big-O for four common array, hash table and heap operations, then explain why adding threads does not always speed a program up, with concrete counterexamples.
This is a two-part conceptual question. Answer in prose, with a short justification for each item.
Part 1: Worst-case running time
For each operation below, give the worst-case Big-O in terms of the number of stored elements n, and explain in a sentence or two where the cost comes from.
- Deleting a given value from a sorted array (the array must stay contiguous and sorted afterward).
- Testing whether a given key is present in a hash table.
- Extracting (removing and returning) the smallest item of a binary min-heap.
- Reading the element at 0-based position
iof a sorted array.
Part 2: Threads and speed
Does running a program on several threads always make it faster than running it on one? Take a position, explain your reasoning, and give at least one concrete scenario in which the multithreaded version is slower.
A strong answer separates the best/average case from the worst case where relevant, names the dominant phase of each operation, and mentions caveats an interviewer might probe.
Hints
Hint 1
For the array deletion, split the work into two phases: finding the value and closing the gap. Which phase dominates in the worst case?
Hint 2
For the hash table, ask what happens when many keys land in the same bucket. Distinguish expected cost from guaranteed cost, and consider the effect of chaining versus open addressing.
Hint 3
For threads, list the overheads that parallelism introduces (creation, context switches, locks, cache-line sharing) and compare them to the useful work done per task. Also consider whether the work is I/O-bound or CPU-bound.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Worst-case complexity
The method is to break each operation into phases (locate, then modify) and report the dominant phase in the worst case. Stopping after the locate phase is the most common error.
1. Delete a value from a sorted array: O(n)
- Locate: binary search finds the value in O(log n).
- Modify: arrays are contiguous, so every element to the right of the deleted slot must shift one position left. Deleting the first element moves n − 1 items.
- Total: O(log n + n) = O(n).
- Common mistake: answering O(log n). Sortedness speeds up the search but does nothing for the shifting.
- Leaving a tombstone avoids the shift, but then indexing and length no longer behave like a plain array, so it is a different data structure.
2. Key lookup in a hash table: O(n) worst case, O(1) expected
- With a decent hash function and a bounded load factor, the expected cost is O(1).
- Worst case: all keys collide into one bucket, through a poor hash function or adversarial input.
- Chaining: a linear scan of a chain of length n.
- Open addressing: the probe sequence can visit O(n) slots.
- Caveats worth mentioning:
- Some implementations (for example Java 8+
HashMap) turn long chains into balanced trees, giving O(log n) worst case for comparable keys. - Hashing a key of length k costs O(k), so for strings the honest expected cost is O(k).
- Resizing affects inserts (amortized O(1)), not lookups.
- Randomized or keyed hash seeds defend against deliberately colliding inputs.
- Some implementations (for example Java 8+
3. Extract-min from a binary min-heap: O(log n)
- The minimum sits at the root, so reading it is O(1).
- Removal: move the last element to the root, shrink the heap, then sift down by repeatedly swapping with the smaller child.
- A binary heap is a complete tree of height ⌊log₂ n⌋, and each level costs O(1) comparisons, so the total is O(log n).
- Contrast with peek-min (O(1)) and building a heap from n items (O(n)).
4. Element at index i of a sorted array: O(1)
- Arrays support random access: the address is
base + i * element_size, one arithmetic step and one memory read. - Sortedness is irrelevant here. If the task is "i-th smallest", it is just
a[i]. For an unsorted array it would be expected O(n) with quickselect, and for a linked list O(i).
| Operation | Worst case | Dominant cost |
|---|---|---|
| Delete by value, sorted array | O(n) | shifting elements |
| Hash table lookup | O(n), expected O(1) | collisions |
| Heap extract-min | O(log n) | sift-down along tree height |
| Index i, sorted array | O(1) | direct addressing |
Part 2: Is multithreading always faster?
No. Threads help only when there is enough independent work to outweigh their overheads and there are hardware resources (cores, memory bandwidth) to run it in parallel.
Why it can be slower
- Creation and scheduling cost. Starting a thread costs tens of microseconds, and a context switch costs roughly 1-10 µs plus cold caches. For small tasks, overhead exceeds the useful work.
- Lock contention. If threads mostly compete for one mutex, execution is effectively serial plus handoff cost.
- Cache effects. Cache-line ping-pong and false sharing (independent variables on the same 64-byte line) force cores to invalidate each other's caches constantly.
- Oversubscription. More runnable threads than cores adds switching without adding compute.
- Shared bottlenecks. A loop that streams a huge array is limited by memory bandwidth; a few threads already saturate it.
- Amdahl's law. If a fraction s of the work is serial, speedup is capped at 1/s regardless of thread count.
- Runtime limits. In standard CPython, the GIL allows only one thread to run Python bytecode at a time, so CPU-bound threads do not run in parallel and add switching cost.
- Latency predictability. In latency-sensitive systems, jitter from scheduling and locks can matter more than throughput.
Concrete examples where threads lose
- Shared counter. Eight threads increment one mutex-protected counter 10 million times each. Every increment fights for the lock and bounces the cache line, so this is usually several times slower than one thread doing 80 million increments.
- False sharing. Threads write to adjacent slots of a
counts[thread_id]array. There is no logical sharing, yet performance can fall below the single-threaded version. Padding each slot to its own cache line fixes it. - Tiny workloads. Summing 1,000 numbers across 8 threads costs more in startup and join than in arithmetic.
- CPU-bound Python under the GIL. Splitting a pure-Python loop across four threads is typically no faster, and often slightly slower, than running it serially.
import threading
import time
def cpu_work(n):
total = 0
for i in range(n):
total += i * i
return total
def run_single(n, parts):
start = time.perf_counter()
for _ in range(parts):
cpu_work(n // parts)
return time.perf_counter() - start
def run_threaded(n, parts):
start = time.perf_counter()
ts = [threading.Thread(target=cpu_work, args=(n // parts,)) for _ in range(parts)]
for t in ts:
t.start()
for t in ts:
t.join()
return time.perf_counter() - start
if __name__ == "__main__":
N, PARTS = 20_000_000, 4
print("single :", round(run_single(N, PARTS), 2))
print("threaded:", round(run_threaded(N, PARTS), 2))
Using multiprocessing or a free-threaded Python build would be needed to get real CPU parallelism here.
When threads do help
- I/O-bound work (network, disk), where threads overlap waiting time.
- Large, embarrassingly parallel CPU work on several cores with little shared mutable state.
A common low-latency pattern is a single-threaded, core-pinned hot path that hands work to other threads through lock-free queues, avoiding locks and context switches where timing matters most.
Common mistakes
- Giving O(log n) for deleting from a sorted array.
- Stating O(1) for hash lookup without mentioning the worst case.
- Saying "more threads means faster" without considering overheads, serial fractions, or the runtime.
- Confusing I/O-bound and CPU-bound workloads.