Skip to main content

πŸ—οΈ 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​

Design Patterns Overview Design Patterns GIF

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​

ProblemDifficultySolution
LC 146 β€” LRU CacheMedium
LC 460 β€” LFU CacheHard
LC 380 β€” Insert Delete GetRandom O(1)Medium
LC 705 β€” Design HashSetEasy
LC 706 β€” Design HashMapEasy
LC 641 β€” Design Circular DequeMedium
LC 208 β€” Implement TrieMedium
LC 355 β€” Design TwitterMedium
LC 1206 β€” Design SkiplistHard
CC β€” Cache Hits (CACHEHIT)Easy
LC 1146 β€” Snapshot ArrayMedium
LC 155 β€” Min StackMedium
LC 232 β€” Implement Queue using StacksEasy
LC 295 β€” Find Median from Data StreamHard
LC 346 β€” Moving Average from Data StreamEasy
LC 348 β€” Design Tic-Tac-ToeMedium
LC 362 β€” Design Hit CounterMedium
LC 381 β€” Insert Delete GetRandom O(1) - DuplicatesHard
LC 432 β€” All O`one Data StructureHard
LC 588 β€” Design In-Memory File SystemHard
LC 622 β€” Design Circular QueueMedium
LC 631 β€” Design Excel Sum FormulaHard
LC 716 β€” Max StackHard
LC 895 β€” Maximum Frequency StackHard
LC 1244 β€” Design A LeaderboardMedium
LC 1352 β€” Product of the Last K NumbersMedium
LC 1472 β€” Design Browser HistoryMedium
CC β€” Data Structure Design (DSDESIGN)Medium
CC β€” Custom Stack (CUSTSTACK)Easy

← Back to Home Β· Β© sparshjaswal