2dbi
Home/Uber/Design a key-value store with O(1) get, put, delete, and getRandom
UUber·DSASDE-2

Design a key-value store with O(1) get, put, delete, and getRandom

This is a classic data-structure design problem requiring O(1) for get, put, delete, and uniform-random sampling simultaneously.

Core idea: pair a hash map with a dynamic array (vector).

  • The map stores key → index into the array.
  • The array stores (key, value) pairs.
  • getRandom: return array[rand() % size].
  • delete: swap the target element with the last element, update the swapped element's index in the map, then pop the last — this keeps the array contiguous without gaps.

All four operations reduce to O(1) hash-map and array ops.

Edge cases to cover: deleting the only element, deleting the last element (no swap needed), get on missing key, duplicate puts.

The C++ follow-up requires templating the class (template<typename K, typename V>) and handling hash support for generic K.

added yesterday
Leaderboard
Language
Account