call(back)
Algorithms & Data StructuresmediumSign in to star problems

Set Without a Hash Function

Implement a set of integers from scratch. It stores distinct values and supports add(x) (returns whether x was inserted), remove(x) (returns whether x was present), contains(x) and size().

Do not use the language's built-in Set, Map or an object used as a dictionary, and do not hash. The backing storage is an array of a fixed length that you allocate yourself (new Array(capacity)); when the number of stored elements grows or shrinks enough, allocate an array of a different length and move the elements across.

s = new ArraySet()
s.add(3)       ->  true
s.add(3)       ->  false     // already present
s.contains(3)  ->  true
s.remove(7)    ->  false     // absent
s.remove(3)    ->  true
s.size()       ->  0

Explain your growth and shrink policy and the cost of each operation. Then be ready to discuss how hashing a value to an index would improve it, and what changes if several threads use the set at once.

Hints

Hint 1

Keep the live elements packed at the front of the array and track the count yourself. remove can swap the last element into the hole, so nothing shifts.

Hint 2

Grow by doubling when the array is full, and shrink when it is a quarter full rather than half: a gap between the two thresholds stops an add/remove pair at the boundary from reallocating every time.

Hint 3

Without hashing, contains is a linear scan, so add and remove are O(n) too. With a hash, the scan becomes a lookup in one bucket or a short probe sequence.

Topics

Asked at

Similar Problems6