Custom Data Structures

Design a class whose every method meets a required time bound, by combining a hash map, a linked list, an array or a stack so that each covers what the others cannot.

Overview

What the problem asks

A design problem lists methods and a time bound for each: get and put in O(1), or push, pop, top and getMin in O(1). No single built-in structure meets every bound at once. The work is to pick two or three that together do, and to keep them in step on every call.

A small set of building blocks covers almost every requirement you will meet. Each one gives exactly one cheap operation.

  • Find by key in O(1): use a hash map, from key to node or index.
  • Remove a known node in O(1): use a doubly linked list, because the node knows its neighbors.
  • A random element in O(1): use an array, and index it by a random number.
  • Delete from an array in O(1): swap the element with the last one, then pop. Only the end of an array is cheap to remove.
  • The min or max so far in O(1): keep a second stack, or store the min with each entry. The history is a stack too.
  • The least or most frequent in O(1): keep buckets by frequency, linked in order. A count only moves by one, so a key only ever moves to a neighboring bucket.

The method is always the same: list the operations, map each to a building block above, and design the fields so every operation stays inside its bound. In five steps:

  • List the methods and their bounds.
  • Map each method to the primitive operation it needs.
  • Choose fields that cover every primitive. The fields are the union of those primitives.
  • Write each method, updating every field.
  • Check every bound and every edge case, and check that no method breaks another's bound.

The rest of this chapter runs that method on four classic problems, starting with the most common one.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio