4.1 Monotonic Stack
Demo · approach · কোড — আগে নিজে চেষ্টা, আটকালে খুলুন
Demo: Largest Rectangle in Histogram — LC 84 (Hard — Google High)
Statement (Demo): Given an integer array heights where heights[i] is the height of bar i (each bar has width 1), return the area of the largest rectangle in the histogram.
Example: heights=[2,1,5,6,2,3] → 10 | ⚡ n ≤ 10⁵, 0 ≤ heights[i] ≤ 10⁴
Approach: Keep indices on a stack with increasing heights. When a shorter bar arrives, pop — for the popped bar, the right boundary is the current index and the left boundary is the new stack top. Process a height-0 sentinel at the end to pop everything.
function largestRectangleArea(heights) {
const stack = []; // indices, heights increasing
let best = 0;
for (let i = 0; i <= heights.length; i++) {
const h = i === heights.length ? 0 : heights[i]; // sentinel at the end
while (stack.length && heights[stack[stack.length - 1]] >= h) {
const height = heights[stack.pop()];
const left = stack.length ? stack[stack.length - 1] + 1 : 0;
best = Math.max(best, height * (i - left));
}
stack.push(i);
}
return best;
}
Complexity: Time O(n) (each index pushed once, popped once), Space O(n)
নোট · ফাঁকা
প্রবলেম
- Daily Temperaturesplan · দিন ০১০🔥 Must-doLC 739(simplest form of the monotonic stack — do this first)
Statement: Given an integer array
temperatures, return for each day how many days until a warmer temperature, or0if none comes.
Example:[73,74,75,71,69,72,76,73]→[1,1,4,2,1,1,0,0]| ⚡n ≤ 10⁵,30 ≤ temp ≤ 100নোট · ফাঁকা
- Next Greater Element Iplan · দিন ০২৬LC 496
Statement: Given two distinct integer arrays
nums1andnums2(nums1is a subset ofnums2), for each element ofnums1return the first greater element to its right innums2, or-1.
Example:nums1=[4,1,2], nums2=[1,3,4,2]→[-1,3,-1]| ⚡n ≤ 1000নোট · ফাঁকা
- Next Greater Element IILC 503(circular → loop twice, index mod n)
Statement: Given a circular integer array
nums, return the next greater number for every element (the search wraps around to the start), or-1.
Example:[1,2,1]→[2,-1,2]| ⚡n ≤ 10⁴নোট · ফাঁকা
- Online Stock SpanLC 901
Statement: Design
StockSpannerwhosenext(price)returns today's span — how many consecutive days, ending today, had a price ≤ today's price.
Example:nextcalls[100,80,60,70,60,75,85]→[1,1,1,2,1,4,6]| ⚡ at most 10⁴ callsনোট · ফাঁকা