KatInterview

Cost of Core Data Structure Ops and When Threads Hurt

Heaps, Sorting & SearchModel answer
MediumModel answerHeaps, Sorting & Searchbig-ohash-tableheap

Last 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.

  1. Deleting a given value from a sorted array (the array must stay contiguous and sorted afterward).
  2. Testing whether a given key is present in a hash table.
  3. Extracting (removing and returning) the smallest item of a binary min-heap.
  4. Reading the element at 0-based position i of 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.