মূল কনটেন্টে যান
🌍
গ্লোবাল DSA
প্যাটার্নটপিক 10 · Greedy, Trie & Design

10.3 Design (Cache & Data Structure Composition)

চিনবেন কীভাবে
"design/implement X with O(1) operations" — the answer is a combination of structures: HashMap + doubly linked list, map + heap, and so on
Demo · approach · কোড — আগে নিজে চেষ্টা, আটকালে খুলুন

Demo: LRU CacheLC 146 (Medium — Amazon/Meta/Google High)

Statement (Demo): Design a Least Recently Used cache with get(key) and put(key, value), both O(1). When capacity is exceeded, evict the least recently used key. Example: capacity=2: put(1,1), put(2,2), get(1)1, put(3,3) (evicts key 2) | ⚡ at most 2×10⁵ calls

Approach: Conceptually a HashMap + doubly linked list — O(1) lookup plus O(1) reordering. In JS, Map remembers insertion order, so one structure does both: on get, delete and re-set to move the key to the "recent" end; past capacity, delete the first key. (Be ready to explain the DLL version in the interview.)

class LRUCache {
  constructor(capacity) {
    this.capacity = capacity;
    this.map = new Map(); // insertion order = recency
  }
  get(key) {
    if (!this.map.has(key)) return -1;
    const val = this.map.get(key);
    this.map.delete(key);
    this.map.set(key, val); // mark as most recent
    return val;
  }
  put(key, value) {
    if (this.map.has(key)) this.map.delete(key);
    this.map.set(key, value);
    if (this.map.size > this.capacity)
      this.map.delete(this.map.keys().next().value); // evict least recent
  }
}

Complexity: get/put O(1)

নোট · ফাঁকা

প্রবলেম

  • (Hard — Amazon/Meta/Uber High; map of frequency → recency-ordered bucket, plus a minFreq pointer)

    Statement: Design a Least Frequently Used cache with O(1) get and put. On a frequency tie, evict the least recently used key.
    Example: capacity=2: put(1,1), put(2,2), get(1) (key 1 now has frequency 2), put(3,3) (evicts key 2, the lower frequency) | ⚡ at most 2×10⁵ calls

    নোট · ফাঁকা
  • Text Justificationplan · দিন ১১৭🔥 Must-doLC 68
    (Hard — Apple High; not an algorithm but careful simulation — a mine of edge cases)

    Statement: Given words and maxWidth, format the text so each line has exactly maxWidth characters and is fully justified; the last line is left-justified.
    Example: words=["This","is","an","example","of","text","justification."], maxWidth=16["This is an","example of text","justification. "] | ⚡ words.length ≤ 300

    নোট · ফাঁকা
আরও দেখুন
Min Stack, Queue using Stacks → 4.3; Serialize/Deserialize Binary Tree → 5.1; Median from Data Stream → 6.3; Task Scheduler → 6.4