4.3 Design Problems (Custom Stack/Queue)
চিনবেন কীভাবে
"implement a stack/queue with X" — extra information (min/max) in O(1), or simulating one structure with another
Demo · approach · কোড — আগে নিজে চেষ্টা, আটকালে খুলুন
Demo: Min Stack — LC 155 (Medium — Amazon/Google High)
Statement (Demo): Design MinStack with push(val), pop(), top() and getMin(), all O(1). getMin() always returns the current minimum.
Example: push(-2), push(0), push(-3) → getMin()=-3, pop(), top()=0, getMin()=-2 | ⚡ at most 3×10⁴ calls
Approach: Store each element paired with "the minimum so far" — popping automatically restores the previous minimum.
class MinStack {
constructor() {
this.stack = [];
} // [value, minSoFar] pairs
push(val) {
const min = this.stack.length ? Math.min(val, this.getMin()) : val;
this.stack.push([val, min]);
}
pop() {
this.stack.pop();
}
top() {
return this.stack[this.stack.length - 1][0];
}
getMin() {
return this.stack[this.stack.length - 1][1];
}
}
Complexity: Every operation O(1), Space O(n)
Demo · Min Stackplan · দিন ০২৯LC 155
নোট · ফাঁকা
প্রবলেম
- Implement Queue using Stacksplan · দিন ০১০LC 232(two stacks: in + out, amortized O(1))
Statement: Implement a FIFO queue using two stacks, supporting
push(x),pop(),peek()andempty().
Example:push(1), push(2), peek()=1, pop()=1, empty()=false| ⚡ at most 100 calls,1 ≤ x ≤ 9নোট · ফাঁকা
আরও দেখুন
LRU/LFU Cache → see 10.3 (Design)