feliciafay
feliciafay

Reputation: 43

Design a data structure with insertion, deletion, get random in O(1) time complexity,

It was a recent interview question. Please design a data structure with insertion, deletion, get random in o(1) time complexity, the data structure can be a basic data structures such as arrays, can be a modification of basic data structures, and can be a combination of basic data structures.

Upvotes: 3

Views: 1811

Answers (2)

Bernhard Barker
Bernhard Barker

Reputation: 55589

Combine an array with a hash-map of element to array index.

Insertion can be done by appending to the array and adding to the hash-map.

Deletion can be done by first looking up and removing the array index in the hash-map, then swapping the last element with that element in the array, updating the previously last element's index appropriately, and decreasing the array size by one (removing the last element).

Get random can be done by returning a random index from the array.

All operations take O(1).

Well, in reality, it's amortised (from resizing the array) expected (from expected hash collisions) O(1), but close enough.

Upvotes: 6

Callum
Callum

Reputation: 862

A radix tree would work. See http://en.wikipedia.org/wiki/Radix_tree. Insertion and deletion are O(k) where k is the maximum length of the keys. If all the keys are the same length (e.g., all pointers), then k is a constant so the running time is O(1).

In order to implement get random, maintain a record of the total number of leaves in each subtree (O(k)). The total number of leaves in tree is recorded at the root. To pick one at random, generate a random integer to represent the index of the element to pick. Recursively scan down the tree, always following the branch that contains the element you picked. You always know which branch to choose because you know how many leaves can be reached from each subtree. The height of the tree is no more than k, so this is O(k), or O(1) when k is constant.

Upvotes: 2

Related Questions