ποΈ Design Data Structures
One-line summary: Build custom data structures combining existing primitives (hash maps, heaps, linked lists) to meet specific time/space requirements.
Diagramβ
Conceptβ
Design problems ask you to implement a class with specific operations at defined complexities.
Key building blocks:
- Hash Map + Doubly Linked List β LRU Cache (O(1) get/put)
- Hash Map + Min/Max Heap β LFU Cache
- Two Stacks β Queue; Two Queues β Stack
- Trie + Hash Map β prefix-based lookups
- Hash Map + Array β O(1) insert/delete/getRandom
Common Patternsβ
LRU Cache Skeletonβ
class LRUCache {
constructor(capacity) {
this.cap = capacity;
this.map = new Map();
}
get(key) {
if (!this.map.has(key)) return -1;
const val = this.map.get(key);
this.map.delete(key);
this.map.set(key, val);
return val;
}
put(key, value) {
this.map.delete(key);
if (this.map.size === this.cap) this.map.delete(this.map.keys().next().value);
this.map.set(key, value);
}
}
O(1) Insert/Delete/GetRandomβ
class RandomizedSet {
constructor() {
this.map = new Map();
this.arr = [];
}
insert(val) {
if (this.map.has(val)) return false;
this.map.set(val, this.arr.length);
this.arr.push(val);
return true;
}
remove(val) {
if (!this.map.has(val)) return false;
const i = this.map.get(val),
last = this.arr[this.arr.length - 1];
this.arr[i] = last;
this.map.set(last, i);
this.arr.pop();
this.map.delete(val);
return true;
}
getRandom() {
return this.arr[Math.floor(Math.random() * this.arr.length)];
}
}
Pitfallsβ
- LRU with JS Map: insertion order is preserved β use
map.keys().next()to get LRU - Thread safety not relevant in JS (single-threaded), but clarify in interviews
- Always clarify expected time complexity before designing
Practice Problemsβ
Related Topicsβ
- Heap β LFU, median stream
- Linked List β LRU doubly linked list
- Hashing β O(1) lookups
β Back to Home Β· Β© sparshjaswal