DSA · Pro · Pattern 8 of 9
Design Data Structures
10 problems.
Your progress0%
- 1st Visit
- 0/10
- 2nd Visit
- 0/10
- Revise
- 0/10
About this pattern
Design problems ask you to implement a class whose operations must each meet a time bound, typically O(1) or O(log n). The work lies in choosing and combining structures so that every operation is cheap: a hash map for direct lookup, a doubly linked list for ordered removal, an array for uniform random access, heaps or ordered sets for extremes, and lazy deletion when removing from a heap directly would be expensive. Read the required operations first, list what each one must find quickly, and make sure all structures stay consistent after every update. The same skill appears in contest problems that simulate a process driven by a stream of queries.
// Max-heap with lazy deletion: erase is O(log n), dead items are skipped later
struct LazyHeap {
priority_queue<int> live, dead;
void push(int x) { live.push(x); }
void erase(int x) { dead.push(x); } // x must currently be present
void clean() {
while (!dead.empty() && live.top() == dead.top()) {
live.pop();
dead.pop();
}
}
int top() { clean(); return live.top(); }
void pop() { clean(); live.pop(); }
bool empty() { clean(); return live.empty(); }
};