Builds onHash map lookupLinked list basics
01The idea
Design problems ask you to build a class with a few methods, such as put, get and remove. Each method has a speed target, such as O(1) or O(log n).
No single built-in structure meets every target, so you combine two or three. The work is in three steps:
- List every method and its target time.
- For each method, find which structure can do it in that time. A hash map finds a key in O(1). A linked list moves or removes a node in O(1) once you hold the node. A heap gives the smallest item in O(log n). An array gives any index in O(1).
- Decide how the structures stay in step. Every method that changes one structure must update the others in the same call.
Two moves come up again and again. The first is precomputing. Keep a running total, a count or a maximum up to date as data changes, so a later query is one lookup. The second is pointing into another structure. A hash map whose values are nodes in a linked list, or indices into an array, lets you go straight to an item and change it.
02How to spot it
You are in a design problem when:
- the problem says "implement", "design" or gives a class with named methods
- it lists methods that will be called many times in any order
- it gives a time target per method, such as "each call in O(1) on average"
Well-known examples include a cache that removes the least recently used item and a stack that also returns its minimum. Others are a set with random access and a store that answers queries about timestamps.
Before you code, write one line per method that says what it does to each structure. If a method needs a scan of all items, look for a structure or a running value that removes the scan.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue