Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Implement a set that supports insert, delete and getRandom (uniformly random element) all in average O(1). Which combination works?

  1. A. A hash set alone
  2. B. A balanced BST with random descent
  3. C. A dynamic array of elements + a hash map from element to its index; delete swaps the element with the last one and pops
  4. D. A linked list with a hash map

Correct answer: C. A dynamic array of elements + a hash map from element to its index; delete swaps the element with the last one and pops

The array gives O(1) random access for getRandom; the map finds the index for O(1) delete by swap-with-last. A hash set cannot pick a uniform random element in O(1); a random BST descent is not uniform and costs O(log n); a linked list needs O(n) to reach a random position.

More Coding Interview Problems questions

Exams that ask this topic