Medium

2 min readOct 17, 2018

--

Problem

Design a data structure that supports all following operations in average O(1) time.

  1. insert(val): Inserts an item val to the set if not already present.
  2. remove(val): Removes an item val from the set if present.
  3. getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.

Example:

// Init an empty set.
RandomizedSet randomSet = new RandomizedSet();
// Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomSet.insert(1);
// Returns false as 2 does not exist in the set.
randomSet.remove(2);
// Inserts 2 to the set, returns true. Set now contains [1,2].
randomSet.insert(2);
// getRandom should return either 1 or 2 randomly.
randomSet.getRandom();
// Removes 1 from the set, returns true. Set now contains [2].
randomSet.remove(1);
// 2 was already in the set, so return false.
randomSet.insert(2);
// Since 2 is the only number in the set, getRandom always return 2.
randomSet.getRandom();

Solution

Actually it’s impossible to do insertion and deletion both in O(1) time. However, in this data structure, it only needs to support one more getRandom operation, which means the order or insert and delete is not important. Therefore we have a bypass strategy to make it happen.

Use a list to store all insert val and use a hash map to store indices of all val. While doing insert, do ordinary insertion to the list and save its corresponding index into hash map. It takes O(1) time obviously.

Once there is a deletion operation coming, we put the last element of the list to the index of the val which is going to be removed, update the index of original last element and erase the last one in list. By doing so, deletion can also be done in constant time.

Complexity

As problem describes, it takes O(1) time averagely. And it needs O(n) extra space for hash map and list, where n is the most element may be inserted.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Len Chen
Len Chen

No responses yet

Write a response