LeetCode Collections: Interview Problems from Naive to Optimal / Module 04

Module 4: Stacks and Monotonic Stacks

Work five stack problems as spoken interviews, from brackets and calculators to a monotonic stack that finds the largest rectangle in one pass.

Here is a first answer to 84. Largest Rectangle in Histogram: try every pair of bars as the two ends of a rectangle, and keep the largest area.

// Try every pair of bars (left, right); the rectangle's height is the lowest bar between them.
// Time O(n^2): n(n+1)/2 pairs, and the lowest bar is kept up to date as right moves, O(1) per pair. Memory O(1).
export function largestRectangleAreaPairs(heights: number[]): number {
  let best = 0;
  for (let left = 0; left < heights.length; left++) {
    let lowest = heights[left];
    for (let right = left; right < heights.length; right++) {
      lowest = Math.min(lowest, heights[right]);
      best = Math.max(best, lowest * (right - left + 1));
    }
  }
  return best;
}

LeetCode allows up to 10⁵ bars, which makes about 5 × 10⁹ pairs, 50 times the budget from Module 1. In one call on 10⁵ random bars (atlimit.ts in the module folder), these loops took 6,120.7 ms. A monotonic stack took 2.8 ms on the same bars.

This module works five problems where a stack holds the items that are still waiting. They are brackets not yet closed, numbers not yet used, groups not yet finished, and bars whose rectangle can’t be measured yet. Each one follows the nine steps from Module 1, from the naive solution to the optimal one.

After this module, you can:

  • spot a stack problem: the most recent unfinished item is always the next one to finish
  • store extra facts with each stack entry (the minimum so far, the total before a group) so every operation stays O(1)
  • replace recursion with an explicit stack when the nesting can be as deep as the input, and say why Node.js needs it
  • find the nearest lower bar on each side of every bar in one pass with a monotonic stack

The code for this module is in module-04/ of the course repository, and node --test "module-04/**/*.test.ts" from its root runs every test. Every number on this page comes from Node.js 24.22.1 on an Apple M2 laptop with macOS.

The pattern: a stack holds what is still open

A stack is a sequence where you add and remove items at the same end, so the last item in is the first one out. That end is the top. In JavaScript an array is a stack as it is: push adds to the top, and pop removes from it. DSA Module 5 teaches it.

A stack fits when items arrive in order, but each one can only finish after every item that came after it. An open bracket waits until every bracket opened after it is closed. So the item on top is always the next one to finish, and a stack hands it over in O(1).

A monotonic stack is a stack whose values only rise (or only fall) from bottom to top. Before you push a new item, you pop every item that would break the order, and the new item is the answer each popped item was waiting for. Module 2 named it in a stretch answer, and DSA Module 5 builds it.

Signs that point to this pattern:

  • brackets, tags or groups that must close in the reverse order they opened
  • an operator that works on the most recent values
  • nesting that a recursive function could also handle
  • the nearest larger or smaller item to the left or right of every position

The cost is memory: O(n) in the worst case, when nothing finishes until the end. And a stack only shows its top. If a problem needs the minimum, or the oldest item, each entry needs extra facts, or the problem needs a different structure.

Rule: When the most recent unfinished item is always the next one to finish, keep the unfinished items on a stack.

20. Valid Parentheses

20. Valid Parentheses is rated Easy. You get a string made only of round, square and curly brackets. It’s valid when each closing bracket matches the most recent bracket that is still open, of the same kind, and nothing is left open at the end.

  • 1 ≤ n ≤ 10^4 (n = s.length)
  • s holds only the six characters ()[]{}

The signature is function isValid(s: string): boolean. Try it on LeetCode first.

Hint

When a closing bracket arrives, which open bracket must it match?

Interviewer: Tell me whether this string of brackets is balanced.

Candidate: Each closing bracket must match the most recent open one of the same kind, and nothing stays open. Can the string be empty?

Interviewer: No, it has at least one character.

Candidate: Then a single character is always invalid. Can the string hold anything else, like letters or spaces?

Interviewer: Only the six brackets.

Candidate: Is "([)]" valid? Each kind is balanced on its own.

Interviewer: No. Brackets must close in the right order.

The interviewer and the candidate are invented. The problems, limits and timings are real.

Candidate: Here’s my example, and three edge cases.

s            expected
"{[()]}()"   true     pairs close in the reverse order they opened
"("          false    still open at the end
"]"          false    a closer with nothing open
"))(("       false    the counts match, the order doesn't

Candidate: The naive solution uses one fact. A valid string always has an adjacent pair like (), because the innermost pair has nothing between its brackets. So I remove adjacent pairs until none are left, and check that nothing remains.

// Remove adjacent pairs until none are left.
// Time O(n^2): up to n/2 passes (deep nesting removes one pair per pass), each O(n). Memory O(n): a new string per pass.
export function isValidByRemoving(s: string): boolean {
  let previous = "";
  let current = s;
  while (current !== previous) {
    previous = current;
    current = current.replaceAll("()", "").replaceAll("[]", "").replaceAll("{}", "");
  }
  return current.length === 0;
}

Candidate: Deep nesting removes only one pair per pass, so there can be n/2 passes of O(n) each. That’s O(n²) time and O(n) memory for each new string. At 10⁴ characters it’s about 5 × 10⁷ steps, under the budget, so it fits.

atlimit.ts in the module folder times one call of each solution at LeetCode’s limit. One call is a rough number, and yours will differ. On 5,000 nested pairs, the deepest that 10⁴ characters can nest, isValidByRemoving took 112.7 ms.

Interviewer: It fits. What does it repeat?

Candidate: Each pass rescans the whole string to find the next innermost pair. But when I read left to right, the innermost open bracket is always the last one I opened and haven’t closed.

Candidate: So I keep the open brackets on a stack. For an opener, I push the closer it needs. For a closer, I pop, and the popped closer must be the same character.

// A stack of the closers we still expect.
// Time O(n): each character is pushed or popped once. Memory O(n): the stack holds up to n openers.
function isValid(s: string): boolean {
  const closerFor: Record<string, string> = { "(": ")", "[": "]", "{": "}" };
  const expected: string[] = [];
  for (const ch of s) {
    if (ch in closerFor) {
      expected.push(closerFor[ch]);
    } else if (expected.pop() !== ch) {
      return false;
    }
  }
  return expected.length === 0;
}

export { isValid };

Candidate: pop() on an empty array returns undefined, so a closer with nothing open fails the comparison. At the end the stack must be empty, or something never closed.

Interviewer: Walk me through your example.

Figure 1 traces "{[()]}()". The last column shows the expected closers after each step, with the top on the right.

s  [{] [[] [(] [)] []] [}] [(] [)]
    0   1   2   3   4   5   6   7

i  char  action              expected (top on the right)
0  {     push }              }
1  [     push ]              } ]
2  (     push )              } ] )
3  )     pop ), it matches   } ]
4  ]     pop ], it matches   }
5  }     pop }, it matches   (empty)
6  (     push )              )
7  )     pop ), it matches   (empty)
         the stack is empty: return true

Figure 1: the top of the stack is always the closer that the most recent open bracket needs, so each closer checks one item.

Pause and predict. For "))((", at which index does isValid return, and what does it return?

Candidate: At index 0. The first ) pops an empty stack and gets undefined, which isn’t ), so it returns false.

Candidate: For "(", the loop pushes ) and ends. The stack isn’t empty, so that’s false too.

Interviewer: Final cost?

Candidate: O(n) time: one push or one pop per character. O(n) memory: if every character is an opener, they all wait on the stack.

On the same 5,000 nested pairs, isValid took 0.5 ms, against 112.7 ms for removing pairs.

Interviewer: What if there’s only one kind of bracket?

The Candidate’s answer

Candidate: Then a counter replaces the stack. I add 1 for ( and subtract 1 for ), fail if it goes below 0, and check that it ends at 0. That’s O(n) time and O(1) memory.

Candidate: With three kinds, three counters aren’t enough, because they lose the order.

Interviewer: What if the string is source code, with other characters between the brackets?

The Candidate’s answer

Candidate: I skip every character that isn’t a bracket. The cost stays O(n) time and O(n) memory.

Interviewer: What if I want to know where it breaks?

The Candidate’s answer

Candidate: I push indexes instead of closers, and read the bracket at each index to know which closer it needs. Then I return the index of the first closer that doesn’t match.

Candidate: If the loop ends with indexes on the stack, I return the first one still there, the oldest bracket that never closed.

This version isn’t in the lab.

Two mistakes are common here. mistakes.ts in the module folder prints the wrong output of every mistake in this module.

  • No check at the end. Returning true after the loop accepts brackets that never close. "((" returns true instead of false. Return expected.length === 0.
  • One counter per kind. Counters check how many brackets of each kind close, not the order. "([)]" returns true instead of false. Use a stack.

Lab folder: module-04/0020-valid-parentheses/ in the course repository.

155. Min Stack

155. Min Stack is rated Medium. You build a stack class with push, pop and top, plus getMin, which returns the smallest value on the stack right now. Every method must run in O(1) time.

  • every value is a signed 32-bit integer: -2^31 ≤ value ≤ 2^31 - 1
  • pop, top and getMin are only called when the stack isn’t empty
  • at most 3 × 10^4 calls in total
  • every method must run in O(1) time

LeetCode’s TypeScript template is a class MinStack with push(value: number): void, pop(): void, top(): number and getMin(): number. Try it on LeetCode first.

Hint

The values below an entry can’t change while that entry is on the stack. What else stays true until it’s popped?

Interviewer: Build a stack that can also return its minimum.

Candidate: So push, pop, top and getMin, all in O(1). Can pop, top or getMin be called on an empty stack?

Interviewer: No, the tests never do that.

Candidate: Can the same value be pushed twice?

Interviewer: Yes.

Candidate: Then popping one copy of the minimum mustn’t lose the other copy. How large are the values?

Interviewer: Signed 32-bit integers.

Candidate: JavaScript numbers hold those exactly, so plain numbers are fine.

Candidate: Here’s my example, as a list of calls, and two edge cases. The first three rows are one run on one stack; the last two each start with an empty stack.

calls                          returns
push 5, push 3, push 7, getMin 3
push 3, pop, getMin            3        one 3 is still on the stack
pop, pop, getMin, top          5, 5
push 2, push 2, pop, getMin    2        a repeated minimum
push 9, top, getMin            9, 9     one value

Candidate: The naive solution is a plain stack whose getMin reads every value.

// A plain stack; getMin scans every value.
// Time: push, pop, top O(1); getMin O(n), it reads the whole stack. Memory O(n).
export class MinStackScan {
  private values: number[] = [];

  push(value: number): void {
    this.values.push(value);
  }

  pop(): void {
    this.values.pop();
  }

  top(): number {
    return this.values[this.values.length - 1];
  }

  getMin(): number {
    let min = this.values[0];
    for (const value of this.values) if (value < min) min = value;
    return min;
  }
}

Candidate: push, pop and top are O(1), and getMin is O(n). The worst case is 15,000 pushes and then 15,000 calls to getMin, about 2 × 10⁸ steps. The clock might allow it, but the page asks for O(1), so this breaks the rule.

With 15,000 pushes of random 32-bit values followed by 15,000 calls to getMin, MinStackScan took 359.5 ms.

Interviewer: Where’s the repeated work?

Candidate: Every getMin rescans values whose minimum I already knew when I pushed them. The values below an entry can’t change while it’s on the stack. So the minimum up to that entry stays true until the entry is popped.

Candidate: So each entry stores its value and the minimum of the stack up to and including it. I keep them in two arrays of the same length.

// Each entry stores its value and the minimum of the stack up to and including it.
// Time O(1) for every method: the minimum below never changes while the entry is on the stack. Memory O(n): two numbers per entry.
class MinStack {
  private values: number[] = [];
  private minimums: number[] = [];

  push(value: number): void {
    const min = this.minimums.length === 0 ? value : Math.min(value, this.getMin());
    this.values.push(value);
    this.minimums.push(min);
  }

  pop(): void {
    this.values.pop();
    this.minimums.pop();
  }

  top(): number {
    return this.values[this.values.length - 1];
  }

  getMin(): number {
    return this.minimums[this.minimums.length - 1];
  }
}

export { MinStack };

Pause and predict. After push 5, push 3, push 7, push 3, what does minimums hold? And after one pop?

Interviewer: Trace your example.

Figure 2 shows both arrays after each call of the first run, with the bottom of the stack on the left.

call      values      minimums    returns
push 5    5           5
push 3    5 3         5 3
push 7    5 3 7       5 3 3
getMin    5 3 7       5 3 3       3
push 3    5 3 7 3     5 3 3 3
pop       5 3 7       5 3 3
getMin    5 3 7       5 3 3       3
pop       5 3         5 3
pop       5           5
getMin    5           5           5
top       5           5           5

Figure 2: each entry carries the minimum up to it, so a pop brings back the minimum the stack had before that push.

Candidate: The 7 stores 3, because the 3 below it is still the minimum. When the second 3 is popped, the first 3’s entry still says 3. For push 2, push 2, pop, the remaining 2 has its own entry, so getMin returns 2.

Interviewer: Final cost?

Candidate: O(1) time for every method: each one reads or writes the end of two arrays. O(n) memory: two numbers per entry.

With the same 3 × 10⁴ calls, MinStack took 1.3 ms, against 359.5 ms for the scan.

Interviewer: Most entries repeat the same minimum. Can you store less?

The Candidate’s answer

Candidate: I keep a second stack that holds only minimums. I push to it when the new value is less than or equal to the current minimum, and pop from it when the popped value equals the minimum.

// A second stack that only takes a value when it is a new minimum or equal to it.
// Time O(1) for every method. Memory O(n) in the worst case (falling input), often less.
export class MinStackOfMinimums {
  private values: number[] = [];
  private minimums: number[] = [];

  push(value: number): void {
    this.values.push(value);
    // <= keeps duplicates of the minimum, so popping one copy leaves the other
    if (this.minimums.length === 0 || value <= this.getMin()) this.minimums.push(value);
  }

  pop(): void {
    const value = this.values.pop();
    if (value === this.getMin()) this.minimums.pop();
  }

  top(): number {
    return this.values[this.values.length - 1];
  }

  getMin(): number {
    return this.minimums[this.minimums.length - 1];
  }
}

Candidate: It’s still O(1) per method. Memory is O(n) when the values only fall, and often much less. The <= matters: each copy of the minimum needs its own entry.

Interviewer: Can you do it with O(1) extra memory?

The Candidate’s answer (stretch)

Candidate: Yes, by encoding the old minimum in the stored value. I keep only min. When a new minimum v arrives, I store 2v - min instead of v, which is below v.

Candidate: On pop, a stored value below min means the minimum changed at that entry. Then 2 * min - stored gives back the old minimum.

For 32-bit values, 2v - min can need 33 bits. That’s safe in JavaScript, because a number holds every integer exactly up to Number.MAX_SAFE_INTEGER, 2⁵³ − 1. In a language with 32-bit integers, it can overflow. The lab tests this version, MinStackEncoded, at both 32-bit limits.

Interviewer: What about a stack that returns its maximum?

The Candidate’s answer

Candidate: The same idea with Math.max: each entry stores the maximum up to it.

Two mistakes are common here:

  • One min field with no history. The field can’t go back when the minimum is popped. After push 3, push 1, pop, getMin returns 1 instead of 3. Store the minimum with each entry.
  • < instead of <= in the stack of minimums. A repeated minimum gets one entry for two copies. After push 2, push 2, pop, getMin returns undefined instead of 2. Push when the value is less than or equal to the minimum.

Lab folder: module-04/0155-min-stack/ in the course repository.

150. Evaluate Reverse Polish Notation

150. Evaluate Reverse Polish Notation is rated Medium. You get an arithmetic expression as a list of tokens in postfix notation: each operator comes after the two values it works on, its operands, so no parentheses are needed. You return the expression’s integer value, with division rounded toward zero.

Postfix is also called reverse Polish notation, after the Polish notation that Jan Łukasiewicz invented in 1924, which puts the operator first (Stanford Encyclopedia of Philosophy).

  • 1 ≤ n ≤ 10^4 (n = tokens.length)
  • each token is +, -, *, / or an integer from -200 to 200
  • the expression is valid and never divides by zero
  • every value along the way fits in a signed 32-bit integer

The signature is function evalRPN(tokens: string[]): number. Try it on LeetCode first.

Hint

When you meet an operator, where are its two operands?

Interviewer: Evaluate this postfix expression.

Candidate: Each operator applies to the two values before it, and its result becomes a value for a later operator. Is the input always valid?

Interviewer: Yes, and it never divides by zero.

Candidate: How does division round?

Interviewer: Toward zero.

Candidate: So -7 / 2 is -3, not -4. That’s Math.trunc, not Math.floor. Can the numbers be negative?

Interviewer: Yes, from -200 to 200.

Candidate: Then "-4" is a number and "-" is an operator. I’ll compare whole tokens, not the first character.

Candidate: Here’s my example and three edge cases.

tokens                           expected
["7","3","-","8","3","/","*"]    8        (7 - 3) * (8 / 3) = 4 * 2
["42"]                           42       one number
["-7","2","/"]                   -3       rounds toward zero
["3","-4","-"]                   7        "-4" is a number

Candidate: The naive solution finds the first operator. Its operands are the two tokens right before it, so I replace those three tokens with the result, and repeat until one value is left.

function isOperator(token: string): boolean {
  return token === "+" || token === "-" || token === "*" || token === "/";
}

function apply(operator: string, left: number, right: number): number {
  if (operator === "+") return left + right;
  if (operator === "-") return left - right;
  if (operator === "*") return left * right;
  return Math.trunc(left / right); // division rounds toward zero
}

// Find the first operator, replace it and its two operands with the result, repeat.
// Time O(n^2): up to n/2 operators, and each search and splice is O(n). Memory O(n): a copy of the tokens.
export function evalRPNBySplicing(tokens: string[]): number {
  const items: (string | number)[] = [...tokens];
  while (items.length > 1) {
    let i = 0;
    while (!(typeof items[i] === "string" && isOperator(items[i] as string))) i++;
    const result = apply(items[i] as string, Number(items[i - 2]), Number(items[i - 1]));
    items.splice(i - 2, 3, result);
  }
  return Number(items[0]);
}

Candidate: There are up to n/2 operators, and each search and splice is O(n), so it’s O(n²) time and O(n) memory for the copy. At 10⁴ tokens that’s at most about 5 × 10⁷ steps, so it fits.

With 9,999 tokens and every operator at the end, so each search walks past thousands of numbers, evalRPNBySplicing took 20.7 ms.

Interviewer: It fits. What does it repeat?

Candidate: Every search starts again at index 0 and walks past numbers it has already seen. Those numbers are waiting for an operator, and the next operator always takes the two most recent ones.

Candidate: So I keep the waiting numbers on a stack. A number is pushed. An operator pops two, applies itself, and pushes the result.

// A stack of operands: an operator pops the two most recent and pushes the result.
// Time O(n): one push or one pop-pop-push per token. Memory O(n): the stack holds up to (n + 1) / 2 numbers.
function evalRPN(tokens: string[]): number {
  const operands: number[] = [];
  for (const token of tokens) {
    if (isOperator(token)) {
      const right = operands.pop()!;
      const left = operands.pop()!;
      operands.push(apply(token, left, right));
    } else {
      operands.push(Number(token));
    }
  }
  return operands[0];
}

export { evalRPN };

Candidate: The first pop is the right operand, because it was pushed last. For 7 3 - that’s 3, so the result is 7 – 3. To paste this into LeetCode, paste isOperator and apply with it.

Pause and predict. In the Candidate’s example, what’s on the stack right before the *?

Interviewer: Trace it.

Figure 3 traces ["7","3","-","8","3","/","*"], with the top of the stack on the right.

token  action          operands (top on the right)
7      push            7
3      push            7 3
-      7 - 3 = 4       4
8      push            4 8
3      push            4 8 3
/      8 / 3 = 2       4 2
*      4 * 2 = 8       8
       return 8

Figure 3: an operator takes the two most recent values that no operator has used yet, and those are the top two of the stack.

Candidate: Before the *, the stack holds 4 and 2. For ["-7","2","/"], Math.trunc(-3.5) is -3. For ["42"], the loop pushes 42 and returns it.

Interviewer: Final cost?

Candidate: O(n) time: one push, or two pops and a push, per token. O(n) memory: up to (n + 1) / 2 numbers wait on the stack.

On the same 9,999 tokens, evalRPN took 0.8 ms, against 20.7 ms for splicing.

One more edge case matters when you write your own tests. ["0","-3","/"] returns -0, JavaScript’s negative zero, because Math.trunc keeps the sign of 0 / -3. JSON.stringify(-0) writes 0, but assert.strictEqual compares with Object.is, so assert.strictEqual(-0, 0) fails. That’s why the lab’s tests compare x + 0.

Interviewer: How would you check that a token list is a valid expression?

The Candidate’s answer

Candidate: I count instead of computing. A number adds one waiting value, and an operator needs two and leaves one.

Candidate: The list is valid if every operator finds at least two, and exactly one value is left at the end. That’s O(n) time and O(1) memory.

This version isn’t in the lab.

Interviewer: What if each operator comes before its operands, as in Polish notation?

The Candidate’s answer

Candidate: I read the tokens from right to left with the same stack. Then the first pop is the left operand, not the right one.

Interviewer: Can you turn an ordinary expression, like (7 - 3) * (8 / 3), into this form?

The Candidate’s answer (stretch)

Candidate: Yes, with a second stack that holds operators until their operands are written out. That’s Edsger Dijkstra’s shunting-yard algorithm (Dijkstra, 1961), which this course doesn’t cover.

Three mistakes are common here:

  • Math.floor instead of Math.trunc. Floor rounds down, not toward zero. ["-7","2","/"] returns -4 instead of -3.
  • Popping the operands in the wrong order. The first pop is the right operand. With the two swapped, ["7","3","-"] returns -4 instead of 4.
  • Finding operators by their first character. A test like token[0] === "-" takes "-4" for an operator. ["3","-4","-"] returns NaN instead of 7. Compare the whole token.

Lab folder: module-04/0150-evaluate-reverse-polish-notation/ in the course repository.

224. Basic Calculator

224. Basic Calculator is rated Hard. You get a valid expression with non-negative integers, +, -, parentheses and spaces, and you return its value. A minus may also stand in front of a single number or group with nothing on its left, as in -(2 + 3); that’s a unary minus.

You may not use a built-in function that evaluates strings, such as eval.

  • 1 ≤ n ≤ 3 × 10^5 (n = s.length)
  • s holds digits, +, -, (, ) and spaces, and is a valid expression
  • + is never unary, - can be, and two operators never follow each other
  • every number and every running value fits in a signed 32-bit integer

The signature is function calculate(s: string): number. Try it on LeetCode first.

Hint

With only + and -, a group’s value enters the outer sum once, with the sign in front of the group. What do you need to remember when a group opens?

Interviewer: Evaluate this expression, without eval.

Candidate: Only plus, minus and parentheses? No * or /?

Interviewer: Only plus and minus.

Candidate: Then there’s no precedence to handle, only groups. Can a minus be unary?

Interviewer: Yes, at the start or right after (. A plus never is, and two operators never follow each other.

Candidate: So I never see 1 - -2. Can numbers have several digits, and can spaces be anywhere?

Interviewer: Yes to both.

Candidate: And every value fits in 32 bits, so plain numbers are exact. Here are my cases.

s                       expected
"10 - (4 - (3 + 2))"    11       10 - (4 - 5) = 10 - (-1)
"7"                     7        one number
"-(2 + 3)"              -5       a unary minus before a group
"1-(-(-(5)))"           -4       unary minus inside nested groups

Candidate: The naive solution evaluates the innermost group first. I find the first ) and the ( right before it. The text between them has no parentheses, so I add it up, write its value in place of the group, and repeat.

function isDigit(ch: string): boolean {
  return ch >= "0" && ch <= "9";
}

// Adds up a string of numbers, '+', '-' and spaces, with no parentheses.
// A '-' flips the sign of the next number, so "--5" is 5 (the innermost-first solution makes such strings).
// Time O(length). Memory O(1).
function evaluateFlat(s: string): number {
  let total = 0;
  let sign = 1;
  let i = 0;
  while (i < s.length) {
    const ch = s[i];
    if (isDigit(ch)) {
      let number = 0;
      while (i < s.length && isDigit(s[i])) number = number * 10 + Number(s[i++]);
      total += sign * number;
      sign = 1;
      continue;
    }
    if (ch === "-") sign = -sign;
    i++;
  }
  return total;
}

// Evaluate the innermost pair of parentheses, write its value in its place, repeat.
// Time O(n^2): up to n/2 pairs, and each search and rebuild of the string is O(n). Memory O(n): a new string per pair.
export function calculateInnermostFirst(s: string): number {
  let expression = s;
  let close = expression.indexOf(")");
  while (close !== -1) {
    const open = expression.lastIndexOf("(", close);
    const value = evaluateFlat(expression.slice(open + 1, close));
    expression = expression.slice(0, open) + value + expression.slice(close + 1);
    close = expression.indexOf(")");
  }
  return evaluateFlat(expression);
}

Candidate: Writing a negative value can leave --5 in the string. evaluateFlat flips the sign once for each -, so that reads as 5.

Candidate: Each group costs a search and a rebuild of the string, O(n), and there can be n/2 groups. That’s O(n²) time and O(n) memory. At 3 × 10⁵ characters it’s about (1.5 × 10⁵)², over 10¹⁰ steps, so it’s too slow.

At the deepest nesting the limits allow, 149,999 pairs of parentheses around one digit, calculateInnermostFirst took 2,903.1 ms. The string search runs in native code, which keeps each step cheap, but the work still grows with the square of the depth.

Interviewer: What does it repeat?

Candidate: Every group rescans the string from the start to find the next ), and rebuilds the whole string to write one value. But reading left to right, when I meet (, the group’s value is everything up to its matching ).

Candidate: So I read the string once. On (, I call a function that evaluates the group and returns at its ). The caller adds the result with the sign in front of the group.

// Recursion: a '(' evaluates the group inside it with a recursive call.
// Time O(n): each character is read once. Memory O(depth) call frames; deep nesting overflows the call stack.
export function calculateRecursive(s: string): number {
  let i = 0;
  function group(): number {
    let total = 0;
    let sign = 1;
    while (i < s.length) {
      const ch = s[i];
      if (isDigit(ch)) {
        let number = 0;
        while (i < s.length && isDigit(s[i])) number = number * 10 + Number(s[i++]);
        total += sign * number;
        continue;
      }
      i++;
      if (ch === "+") sign = 1;
      else if (ch === "-") sign = -1;
      else if (ch === "(") total += sign * group();
      else if (ch === ")") return total;
    }
    return total;
  }
  return group();
}

Candidate: All the calls share one index, i, so each character is read once, by one call of group. That’s O(n) time. Each open group keeps one call waiting, so memory is O(depth).

The lab names it calculateRecursive, so it can sit next to the other versions. To paste it into LeetCode, rename it calculate and paste isDigit with it.

Interviewer: Trace your example.

Figure 4 shows each call of group on "10 - (4 - (3 + 2))", with spaces skipped. Depth 1 is the first call, and each ( starts a call one level deeper.

depth  reads  total  sign  what happens
1      10     10     1
1      -      10     -1
1      (      10     -1    call group() at depth 2
2      4      4      1
2      -      4      -1
2      (      4      -1    call group() at depth 3
3      3      3      1
3      +      3      1
3      2      5      1
3      )      5            return 5
2             -1           back at depth 2: 4 + (-1)(5) = -1
2      )      -1           return -1
1             11           back at depth 1: 10 + (-1)(-1) = 11
                           return 11

Figure 4: each ( starts a call with its own total and sign, and each ) returns the group’s total to the call that waits for it.

Candidate: For "-(2 + 3)", the minus sets sign to -1, the group returns 5, and the total is -5. For "1-(-(-(5)))", the innermost group returns 5, the next one -5, the next 5, and the outer sum is 1 – 5 = -4.

Interviewer: Final cost?

Candidate: O(n) time: each character is read once. O(depth) memory, one waiting call per open group, and the depth can reach about n/2.

Interviewer: The limits allow 3 × 10⁵ characters. What if they’re 149,999 opening parentheses, one digit, and 149,999 closing ones?

The Candidate’s answer

Candidate: Then group calls itself 149,999 levels deep, and Node.js runs out of call stack. The call stack is where the engine keeps one frame for each function call that hasn’t returned: its local variables and where to return. V8 caps the call stack’s size, so deep recursion throws.

In atlimit.ts, calculateRecursive threw RangeError: Maximum call stack size exceeded at that depth. A binary search on the depth found 7,030 levels as the deepest it handled in that run.

V8’s JIT compiler turns functions that run often into machine code while the program runs. The number changes with the size of each frame, and with how far the JIT compiler has optimized the function. DSA Module 6 measures both effects.

Candidate: The fix keeps the same idea, but saves what each call held in my own stack, an array in heap memory. A waiting call holds its total so far and the sign in front of the group. So on ( I push those two numbers and start a fresh total, and on ) I pop them and add the group to the outer total.

// One pass with an explicit stack: a '(' saves the total so far and the sign in front of the group.
// Time O(n): each character is read once and each '(' is pushed and popped once. Memory O(depth), at most O(n), on the heap.
function calculate(s: string): number {
  const saved: number[] = []; // pairs: total before the group, then the sign in front of it
  let total = 0;
  let sign = 1;
  let i = 0;
  while (i < s.length) {
    const ch = s[i];
    if (isDigit(ch)) {
      let number = 0;
      while (i < s.length && isDigit(s[i])) number = number * 10 + Number(s[i++]);
      total += sign * number;
      continue;
    }
    if (ch === "+") {
      sign = 1;
    } else if (ch === "-") {
      sign = -1;
    } else if (ch === "(") {
      saved.push(total, sign);
      total = 0;
      sign = 1;
    } else if (ch === ")") {
      const signBefore = saved.pop()!;
      const totalBefore = saved.pop()!;
      total = totalBefore + signBefore * total;
    }
    i++;
  }
  return total;
}

export { calculate };

Candidate: Each ( is pushed once and popped once, so it’s still O(n) time and O(depth) memory. But the memory is an array, which can grow as far as the heap allows.

Figure 5 traces the same example. saved holds pairs: the total before a group, and the sign in front of it.

reads  total  sign  saved (pairs)         what happens
10     10     1
-      10     -1
(      0      1     (10, -1)              save, start the group
4      4      1     (10, -1)
-      4      -1    (10, -1)
(      0      1     (10, -1) (4, -1)      save, start the group
3      3      1     (10, -1) (4, -1)
+      3      1     (10, -1) (4, -1)
2      5      1     (10, -1) (4, -1)
)      -1     1     (10, -1)              4 + (-1)(5) = -1
)      11     1                           10 + (-1)(-1) = 11
                                          return 11

Figure 5: the pairs in saved are the totals and signs that the waiting calls held in Figure 4, so an array replaces the call stack.

At a depth of 149,999, calculate returned 1 in 4.4 ms. The lab test checks both results at that depth: calculate returns 1, and calculateRecursive throws a RangeError. LeetCode doesn’t publish its test cases, so we don’t know whether they nest this deep, but the limits allow it.

Interviewer: What if the expression can also have * and /?

The Candidate’s answer (stretch)

Candidate: That’s LeetCode’s 227. Basic Calculator II, which this course doesn’t cover. I’d keep the last term apart, apply * and / to it as they come, and add it to the total when a + or - arrives.

Candidate: With parentheses as well, I’d use the shunting-yard algorithm from the last follow-up of Evaluate Reverse Polish Notation.

Neither version is in the lab.

Interviewer: What if the input might not be valid?

The Candidate’s answer

Candidate: The page promises a valid expression. In real code I’d check what Valid Parentheses checks: never pop an empty stack, and end with an empty one.

Three mistakes are common here:

  • Ignoring the sign in front of a group. A version whose ) adds the group as if a plus stood in front of it gets every negated group wrong. "10 - (4 - (3 + 2))" returns 19 instead of 11. Multiply the group by the saved sign.
  • One digit at a time. "12 + 3" returns 6 instead of 15. Read every digit of a number before you add it.
  • Recursion on input that can nest deep. At 149,999 levels, calculateRecursive throws RangeError: Maximum call stack size exceeded. Use an explicit stack when the depth can grow with the input.

Lab folder: module-04/0224-basic-calculator/ in the course repository.

84. Largest Rectangle in Histogram

84. Largest Rectangle in Histogram is rated Hard. Bars of width 1 stand side by side, with the given heights. You return the largest area of a rectangle that fits inside the bars: it covers a run of neighboring bars and is as tall as the lowest of them.

  • 1 ≤ n ≤ 10^5 (n = heights.length)
  • 0 ≤ heights[i] ≤ 10^4

The signature is function largestRectangleArea(heights: number[]): number. Try it on LeetCode first.

Hint

The best rectangle is as tall as its lowest bar. For one bar, how far can a rectangle of that height reach on each side?

Interviewer: Find the largest rectangle in this histogram.

Candidate: Each bar is 1 wide, and a rectangle covers neighboring bars, as tall as the lowest of them. Can a height be 0?

Interviewer: Yes.

Candidate: Then a zero bar splits the histogram: no rectangle with an area above 0 crosses it. Can the list be empty?

Interviewer: No, there’s at least one bar.

Candidate: The largest area is 10⁵ × 10⁴ = 10⁹, under 2³¹ – 1, so there’s no overflow. And with 10⁵ bars, n² is far over the budget, so I need O(n log n) or better.

Candidate: Here’s my example and four edge cases.

heights            expected
[1, 3, 4, 5, 1]    9        bars 3, 4, 5: height 3, width 3
[7]                7        one bar
[3, 3, 3, 3]       12       equal bars share one rectangle
[1, 2, 3, 4, 5]    9        rising: bars 3, 4, 5 again
[2, 0, 2]          2        a zero splits the bars

Figure 6 draws the Candidate’s example, with the best rectangle marked *.

  5               #
  4           #   #
  3       *   *   *
  2       *   *   *
  1   #   *   *   *   #
     [1] [3] [4] [5] [1]
      0   1   2   3   4

Figure 6: the best rectangle is as tall as its lowest bar, 3, and reaches as far as the bars stay at least that tall, from index 1 to 3.

Candidate: The naive solution tries every pair of bars as the two ends, and keeps the lowest bar between them up to date as the right end moves.

The Candidate writes largestRectangleAreaPairs, the function at the top of this page.

Candidate: That’s n(n + 1)/2 pairs at O(1) each, so O(n²) time and O(1) memory. At 10⁵ bars it’s 5 × 10⁹ steps, so it’s too slow. Searching for the lowest bar again for each pair would even be O(n³).

At 10⁵ random bars, largestRectangleAreaPairs took 6,120.7 ms.

Interviewer: What does it repeat?

Candidate: Most pairs can’t be the answer. The best rectangle is as tall as one of its bars, the lowest one. So for each bar, I use its height and widen the rectangle while the neighbors are at least as tall.

// For each bar, use its height and widen the rectangle while the neighbours are at least as tall.
// Time O(n^2) in the worst case (equal or rising bars: a bar walks past every bar at least as tall). Memory O(1).
export function largestRectangleAreaExpand(heights: number[]): number {
  let best = 0;
  for (let i = 0; i < heights.length; i++) {
    let left = i;
    while (left > 0 && heights[left - 1] >= heights[i]) left--;
    let right = i;
    while (right < heights.length - 1 && heights[right + 1] >= heights[i]) right++;
    best = Math.max(best, heights[i] * (right - left + 1));
  }
  return best;
}

Candidate: On random heights most walks stop soon, because a lower neighbor comes quickly. But with equal bars, or rising ones, a bar walks past every bar at least as tall, so the worst case is still O(n²). Memory is O(1).

At 10⁵ random bars, largestRectangleAreaExpand took 4.3 ms. At 10⁵ equal bars, it took 6,201.3 ms.

Interviewer: So what’s still repeated?

Candidate: Each bar only needs two facts: the nearest lower bar on its left, and the nearest lower bar on its right. The walks find them by stepping over taller bars, and the next bar steps over the same ones again.

Candidate: So I keep a stack of bar indexes with rising heights. When bar i is no taller than the bar on top, the top bar has found its right edge, i.

Candidate: Its left edge is the bar below it on the stack, because every bar between them is at least as tall and was already popped. So I pop the top and measure its rectangle.

Candidate: At the end I add a bar of height 0, so every bar still on the stack gets measured.

// A stack of bar indexes with rising heights. When a lower bar arrives, every taller bar on the stack
// has found its right edge (the new bar) and its left edge (the bar below it on the stack), so we pop it and measure.
// Time O(n): each index is pushed once and popped once. Memory O(n): the stack holds up to n indexes.
function largestRectangleArea(heights: number[]): number {
  const rising: number[] = [];
  let best = 0;
  for (let i = 0; i <= heights.length; i++) {
    const height = i === heights.length ? 0 : heights[i]; // a bar of height 0 after the end empties the stack
    while (rising.length > 0 && heights[rising[rising.length - 1]] >= height) {
      const top = rising.pop()!;
      const leftEdge = rising.length === 0 ? -1 : rising[rising.length - 1];
      best = Math.max(best, heights[top] * (i - leftEdge - 1));
    }
    rising.push(i);
  }
  return best;
}

export { largestRectangleArea };

Pause and predict. In the Candidate’s example, the stack holds indexes 0 to 3 when the last bar, of height 1, arrives at index 4. Which bars does it pop, and which pop finds the answer, 9?

Interviewer: Trace your example.

Figure 7 traces [1, 3, 4, 5, 1]. Index 5 is the bar of height 0 after the end. The stack column shows indexes after the step.

i  h  action                                     stack (indexes)   best
0  1  push                                       [0]               0
1  3  push                                       [0,1]             0
2  4  push                                       [0,1,2]           0
3  5  push                                       [0,1,2,3]         0
4  1  pop 3: 5 × (4-2-1) = 5                     [0,1,2]           5
      pop 2: 4 × (4-1-1) = 8                     [0,1]             8
      pop 1: 3 × (4-0-1) = 9                     [0]               9
      pop 0: 1 × (4-(-1)-1) = 4 (equal, short)   []                9
      push                                       [4]               9
5  0  pop 4: 1 × (5-(-1)-1) = 5, push            [5]               9

Figure 7: a bar is measured when a lower or equal bar arrives, and its left edge is the bar below it, so each index is pushed and popped once.

Candidate: The bar at index 4 pops all four bars. Bar 1, of height 3, gives 9: its left edge is bar 0 and its right edge is bar 4.

Candidate: Bar 0 is popped by a bar of equal height and measured short, 4 instead of 5. But the equal bar at index 4 is measured with the full width at the end, 5.

Candidate: So with >=, the last of several equal bars gets the right width. For [3, 3, 3, 3], the last 3 is popped by the height-0 bar with a width of 4, which gives 12.

Interviewer: Final cost?

Candidate: O(n) time. There’s a loop inside a loop, but each index is pushed once and popped at most once, so the inner while runs at most n times in total. O(n) memory: with rising heights, every index waits on the stack until the end.

At 10⁵ random bars, largestRectangleArea took 2.8 ms, and 0.6 ms at 10⁵ equal bars, against 6,120.7 ms for every pair.

Interviewer: What if the input is a grid of 0s and 1s, and I want the largest rectangle of 1s?

The Candidate’s answer

Candidate: That’s LeetCode’s 85. Maximal Rectangle, which this course doesn’t cover. For each row, I build a histogram: in each column, how many 1s stand one above the other, ending at this row.

Candidate: Then I run this function on each row’s histogram. That’s O(rows × cols) time.

This version isn’t in the lab.

Interviewer: Can you explain it with two simpler passes?

The Candidate’s answer

Candidate: One monotonic-stack pass from the left finds each bar’s nearest lower bar on the left. A second pass from the right finds the one on the right.

Candidate: Then each bar’s area is its height times right - left - 1. It’s the same O(n) time with two more arrays, but each pass is easier to explain.

This version isn’t in the lab.

Two mistakes are common here:

  • No bar of height 0 after the end. Bars still on the stack are never measured. [1, 2, 3, 4, 5] returns 0 instead of 9. Run the loop to heights.length, with height 0 there.
  • Width from the popped bar. i - top forgets that the rectangle also reaches left, over the taller bars popped earlier. [1, 4, 3] returns 4 instead of 6. Measure from the bar below it on the stack: i - leftEdge - 1.

Lab folder: module-04/0084-largest-rectangle-in-histogram/ in the course repository.

Measured: Largest Rectangle, every pair against the monotonic stack

Largest Rectangle in Histogram is the problem this module measures, with bench.ts from DSA Module 1. Every pair runs at 10,000, 20,000 and 40,000 bars, because it takes about a second at 40,000. The stack runs at the same sizes, and again at 100,000 to 800,000 bars, where its times are large enough to read. Each height is drawn at random from 0 to 10⁴, as the page allows.

// measure.ts: Module 4's measurement. 84. Largest Rectangle in Histogram, every pair against the monotonic stack.
// Run from the repository root: node module-04/measure.ts
import { bench } from "../shared/bench.ts";
import { largestRectangleAreaPairs, largestRectangleArea } from "./0084-largest-rectangle-in-histogram/solution.ts";

let sink = 0;

// Heights 0..10^4 at random, as the page allows.
const randomHeights = (n: number) => Array.from({ length: n }, () => Math.floor(Math.random() * 10_001));

bench("every pair, random heights", [10_000, 20_000, 40_000], randomHeights, (h) => (sink += largestRectangleAreaPairs(h)));
bench("monotonic stack, random heights", [10_000, 20_000, 40_000], randomHeights, (h) => (sink += largestRectangleArea(h)));
// The same stack at sizes large enough to read its growth, up to 8x the page's limit.
bench("monotonic stack, random heights, larger n", [100_000, 200_000, 400_000, 800_000], randomHeights, (h) => (sink += largestRectangleArea(h)));

console.log(`\nsink ${sink}`);

bench runs each size once to warm up, then five times on fresh inputs, and prints the median and how many times slower each size is than the one before.

Pause and predict. Every pair is O(n²) and the stack is O(n). When n doubles, how many times longer should each one take?

Here is what node module-04/measure.ts printed:


every pair, random heights
             n   median ms   x prev
        10,000       58.22         
        20,000      235.03      4.0
        40,000      980.12      4.2

monotonic stack, random heights
             n   median ms   x prev
        10,000        0.18         
        20,000        0.24      1.3
        40,000        0.45      1.9

monotonic stack, random heights, larger n
             n   median ms   x prev
       100,000        1.13         
       200,000        2.27      2.0
       400,000        4.53      2.0
       800,000        9.11      2.0

sink 7056857

These numbers come from one run on an Apple M2 laptop with macOS and Node.js 24.22.1. Your numbers will differ, but the ratios should look alike.

Every pair grew 4.0 and 4.2 times per doubling, which is O(n²). The stack’s first ratios, 1.3 and 1.9, come from times under half a millisecond, too small to read.

At the larger sizes the stack grew 2.0 times per doubling, which is O(n). At 40,000 bars the stack was about 2,200 times faster (0.45 against 980.12 ms). sink is the total of every area returned, so V8 can’t skip the calls.

Underneath: the array stack and the call stack

Every stack in this module is a plain array. push writes into spare room at the end of the array’s storage. When the room runs out, V8 allocates a larger store, about 1.5 times the old one plus 16 slots, and copies the elements. So push is amortized O(1): a copy happens now and then, but averaged over many pushes each one costs O(1).

pop lowers the length, and V8 shrinks the store only when the length falls well below its capacity. DSA Module 5 reads these rules in the source of V8 14.6, and found the pop rules unchanged since V8 12.4. Node.js 24.22.1 ships V8 13.6, between the two, and we didn’t reread its source.

pop on an empty array returns undefined and changes nothing (ECMAScript, Array.prototype.pop). isValid relies on that: a closer with nothing open compares itself with undefined and fails, with no extra check.

Recursion uses a different stack, the call stack, and V8 caps its size in bytes. On Node.js 24.22.1 on this arm64 Mac, node --v8-options lists --stack-size with a default of 984 KB. The array in calculate lives on the heap instead, which is why it handled 149,999 levels while calculateRecursive stopped at about 7,000. DSA Module 6 measures how many frames fit, and why raising --stack-size is not a safe fix.

Cheat sheet

Figure 8 maps each problem in this module to the sign that pointed to its solution.

sign in the problem                 problem  the stack keeps         cost
brackets close in reverse order     20       closers still needed    O(n)
O(1) minimum with push and pop      155      value and min so far    O(1) each
operator after its two operands     150      operands not yet used   O(n)
nested groups, depth up to n        224      total and sign before   O(n)
                                             each open group
largest rectangle under bars        84       indexes of rising       O(n)
                                             heights

Figure 8: when the most recent unfinished item is the next to finish, a stack replaces the rescan, and an array stack replaces deep recursion.

  • Pattern: push what’s still open; pop when the item that closes it arrives. Store extra facts per entry (a minimum, a total and a sign) to keep every step O(1).
  • Monotonic stack: pop every item the new one beats; each popped item has found its nearest lower (or higher) neighbor. Each index is pushed and popped once: O(n).
  • Deep nesting: recursion stops at a few thousand levels in Node.js; an array on the heap does not.
  • Final costs: 20, 150, 224 and 84 in O(n) time and O(n) memory; 155 in O(1) per method and O(n) memory.
  • Next: Module 5 halves a sorted range at each step, so a search among 10⁵ values takes about 17 comparisons.

Sources