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?
- A. A hash set alone
- B. A balanced BST with random descent
- C. A dynamic array of elements + a hash map from element to its index; delete swaps the element with the last one and pops
- 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
- Problem: Support 'add number' and 'find a pair summing to t' where adds are 10⁵ and finds are rare, versus the opposite workload. Which…
- Problem: Map each word of a 10⁶-word document to its frequency, then print words in alphabetical order. Which choice gives O(n log n) with…
- Problem: Count the number of distinct islands by shape in a grid (shapes match only by translation). python def distinct(g): R, C =…
- Problem: Count subarrays with at most k distinct values, then use it to count subarrays with exactly k distinct values. python from…
- Problem: Find the number of 'nice' subarrays containing exactly k odd numbers using prefix counts. python def nice(a, k): cnt = {0: 1}…
- Problem: Return the shortest subarray with sum at least k when values can be negative (monotonic deque over prefix sums). python from…