Data Structure Design

Build a class whose every operation meets a required cost by combining a hash map, an array, a linked list, a stack or a sorted list, each covering what the others cannot do.

Overview

The method: one structure per weakness

A design problem gives you a list of operations and a target cost for each one. No single built-in structure meets all of them, so you combine two or three. The method is always the same: write down the operations, find the one that is hardest to make fast, pick the structure that makes it fast, then add a second structure to cover what the first one cannot do.

As a routine, it runs like this.

  • List every operation and its target cost.
  • Find the one that is hardest to make fast.
  • Pick the structure that makes it fast.
  • Check whether every cost is met. If not, add a helper structure that covers the gap, and check again.
  • Once every cost is met, write the update rule: every write touches every part, so every helper structure stays in step.

To pick parts quickly, you need to know what each building block is good at. Each one is fast at one or two things and slow at others, and knowing this list is most of the skill.

  • Hash map: lookup, insert and delete by key are O(1) on average. It is slow at anything about order, and at a random pick.
  • Array (dynamic): index, append and picking a random slot are O(1). Deleting from the middle is slow, O(n).
  • Doubly linked list: removing or moving a node you already hold is O(1). Finding a node by value is slow, O(n).
  • Stack: push, pop and top are O(1). It is slow at anything but the top.
  • Sorted array: search is O(log n). Inserting in the middle is slow, O(n).
  • Min or max heap: the smallest or largest item is O(1) to read, and push and pop are O(log n). It is slow to find or remove an arbitrary item.

Every combination below is two of these blocks glued together, plus a rule that keeps them consistent.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio