Data Structures & AlgorithmsHardAmazon · Microsoft OA
Design a set supporting insert, delete and getRandom (uniform) all in O(1) average time. Which design works?
- A. An array plus a value → index map; delete by swapping in the last element and popping
- B. A hash set alone; getRandom picks a random bucket
- C. A balanced BST; getRandom walks a random path
- D. A linked list plus a hash map value → node
Correct answer: A. An array plus a value → index map; delete by swapping in the last element and popping
The array allows a uniform random index in O(1), and swapping with the last element keeps it dense so deletion is O(1). Random buckets are not uniform (buckets differ in size or are empty), a BST walk is O(log n) and biased, and a list cannot index randomly.
More Coding Interview Problems questions
- Problem: Rotate a linked list to the right by k places. python class N: def init(s, v, nx=None): s.v, s.nx = v, nx def rotate(h, k): n, t…
- Problem: Partition a linked list so that all nodes with values < x come before nodes ≥ x, preserving relative order within each part…
- List A has a nodes before it joins a shared tail of c nodes; list B has b nodes before the same tail, with a ≠ b. Pointer p walks A and…
- Problem: Move the coins of a binary tree so every node has exactly one coin; a move passes one coin along one edge. Count the minimum…
- Problem: Find the maximum |a − b| where a is an ancestor of b in a binary tree. python class T: def init(s, v): s.v, s.l, s.r = v, None…
- Problem: Return the (1-based) level of a binary tree with the largest sum of values (smallest level on ties). python class T: def init(s…