Quick Overview

This question evaluates a candidate's competency in data-structure design, randomized algorithms, and algorithmic complexity analysis within the Coding & Algorithms domain, with a focus on achieving expected O(1) operations for insert, remove, and uniform sampling.

Design O(1) random-sampling set

Company: xAI

Role: Machine Learning Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Technical Screen

Design a data structure that supports insert(x), remove(x), and get_random() that returns a uniformly random element among the present items, all in expected O( 1) time. Detail the algorithms and data structures you would use, how you handle deleting the last element and gaps, and how you would test the uniformity of get_random(). Discuss extensions such as supporting duplicates or thread-safety and the impact on complexity.

Quick Answer: This question evaluates a candidate's competency in data-structure design, randomized algorithms, and algorithmic complexity analysis within the Coding & Algorithms domain, with a focus on achieving expected O(1) operations for insert, remove, and uniform sampling.

Implement a simulation of a randomized set data structure with no duplicate values. It must support insert(x), remove(x), and get_random() in expected O(1) time. To make testing deterministic, each get_random operation is given an integer index r; your get_random should return the element currently stored at index r in the internal dense array. In a real randomized set, r would be chosen uniformly at random from 0 to current_size - 1, which makes every present item equally likely. You must maintain the dense array using the standard swap-with-last deletion strategy so removals do not leave gaps.

Constraints

  • 0 <= len(commands) == len(values) <= 200000
  • commands[i] is one of "insert", "remove", or "get_random"
  • -1000000000 <= values[i] <= 1000000000 for insert/remove operations
  • For every get_random operation, the set is non-empty and 0 <= values[i] < current set size
  • Duplicate values are not stored; inserting an existing value must not change the set

Examples

Input: (["insert", "insert", "get_random", "remove", "get_random", "insert", "remove"], [1, 2, 0, 1, 0, 2, 3])

Expected Output: [1, 1, 1, 1, 2, 0, 0]

Explanation: Insert 1 and 2. Random index 0 returns 1. Removing 1 swaps 2 into the only slot, so the next random index 0 returns 2. Inserting duplicate 2 fails, and removing absent 3 fails.

Input: ([], [])

Expected Output: []

Explanation: No operations produce no results.

Hints

  1. A dynamic array gives O(1) access by random index, but cannot remove arbitrary elements in O(1) unless you avoid preserving order.
  2. Keep a hash map from value to its index in the array. To remove a value, move the last array element into the removed value's slot, update that moved element's index, then pop the last position.

Loading coding console...