<AI/>
enru
All posts

Insert, delete, get random in O(1)

Design a data structure that inserts, removes and returns a random unique value in constant time by combining an array with a hash map.

Difficulty
Medium
Published
Topics
#hash table#data structures

Problem Description

Implement a data structure for storing numbers that supports the following methods:

  1. insert: adds a new element to the structure without creating duplicates.
  2. remove: removes the given element.
  3. getRandom: returns a random element among the previously added ones, each with equal probability.

Constraints

All methods must run in constant time: O(1).

Examples

Adding values to the structure.

typescript
const store = new Store()
 
store.insert(1)
store.insert(2)
store.insert(3)
store.insert(2)
 
// values: 1, 2, 3

Solution

The first idea is to use a data structure based on a hash table, since it naturally stores only unique values. Besides, insertion and removal in a hash table take constant time, which meets our requirements. However, getting a random value would require converting all values into an array and then picking a random index, which makes it linear because of the extra conversion.

On the other hand, we could store the data in an array. That makes getting a random value easy, but complicates adding and removing elements.

  • Adding a new element requires checking for duplicates, which also takes linear time.
  • Removing an element from the middle of the array requires shifting its whole tail one position to the left, which also takes linear time.

Fortunately, we can combine both approaches and get constant time for all operations.

We store the values in an array values. In addition, we keep a hash table indexesMap with the index of each element in the array. The key is the number, and the value is its index in the array.

Now let's define the logic of each method.

insert

When adding a new element, we first check whether it exists in the hash table. If it doesn't, we add it to the array first and then to the table. This prevents duplicates.

remove

When removing an element, we first check whether it's in the hash table. If it's not, we simply return.

We need to remove the element from the array, but that can only be done in constant time when removing the last element. Since we don't need to preserve insertion order, we get the element's index from the hash table and swap it with the last element. After the swap, we can remove the last element. We also need to remove the element from the table and update the index of the element we moved.

getRandom

To get a random element, we generate a random number from 0 to the index of the last element of the array. Then we just return the value at that index.

typescript
export class Store {
  private indexesMap: Map<number, number>;
  private values: number[];
 
  constructor() {
    this.indexesMap = new Map();
    this.values = [];
  }
 
  insert(value: number) {
    if (this.indexesMap.has(value)) {
      return;
    }
 
    this.values.push(value);
    this.indexesMap.set(value, this.values.length - 1);
  }
 
  remove(value: number) {
    const index = this.indexesMap.get(value);
    if (!index) {
      return;
    }
 
    const last = this.values.pop();
    if (!last) {
      return;
    }
 
    this.values[index] = last;
    this.indexesMap.set(last, index);
 
    this.indexesMap.delete(value);
  }
 
  getRandom(): number {
    return this.values[Math.floor(Math.random() * this.values.length)];
  }
 
  // Method for tests
  getValues(): number[] {
    return this.values;
  }
}

Complexity Analysis

Time Complexity

All methods are implemented to run in constant time O(1), as required.

Space Complexity

We store the data in an array plus a hash map duplicating it, so the total is O(2n). The overall space complexity is linear: O(n), since the factor of 2 can be dropped.

A Go hack

The solution above is universal and works in any language. However, some languages have quirks that can simplify the solution.

In particular, Go's hash maps don't guarantee the order of keys during iteration. Moreover, the iteration order is deliberately randomized. Reportedly, this is how the language authors discourage developers from relying on the order of keys in maps.

This means that in Go we can implement the required structure using only a map. Keep in mind, though, that Go's iteration order is random but not perfectly uniform, so this is more of a fun trick than a strict solution.

go
package unique_value_structure
 
type Store struct {
	values map[int]bool
}
 
func New() *Store {
	return &Store{
		values: make(map[int]bool),
	}
}
 
func (s *Store) Insert(value int) {
	s.values[value] = true
}
 
func (s *Store) Remove(value int) {
	delete(s.values, value)
}
 
func (s *Store) GetRandom() int {
	for val := range s.values {
		return val
	}
	return 0
}