MCPcopy Create free account
hub / github.com/neetcode-gh/leetcode / fillStack

Function fillStack

javascript/0084-largest-rectangle-in-histogram.js:111–134  ·  view source on GitHub ↗
(heights, stack = [], maxArea = 0)

Source from the content-addressed store, hash-verified

109};
110
111const fillStack = (heights, stack = [], maxArea = 0) => {
112 for (let index = 0; index < heights.length; index++) {
113 /* Time O(N + N) */
114 let start = index;
115
116 const isCurrHeightLess = ([prevIndex, prevHeight], currHeight) =>
117 currHeight < prevHeight;
118 const canShrink = () =>
119 isCurrHeightLess(stack[stack.length - 1], heights[index]);
120 while (stack.length && canShrink()) {
121 /* Time O(N + N) */
122 const [_index, _height] = stack.pop();
123 const width = index - _index;
124 const area = _height * width;
125
126 maxArea = Math.max(maxArea, area);
127 start = _index;
128 }
129
130 stack.push([start, heights[index]]); /* Space O(N) */
131 }
132
133 return { stack, maxArea };
134};
135
136const getMaxArea = (heights, stack, maxArea) => {
137 for (const [index, height] of stack) {

Callers 1

largestRectangleAreaFunction · 0.85

Calls 3

canShrinkFunction · 0.70
popMethod · 0.45
pushMethod · 0.45

Tested by

no test coverage detected