Stack and monotonic stack interview questions

10 coding interview questions on stacks and monotonic stacks, each with the correct answer and a full explanation.

Valid Parentheses (every bracket closes with the same type in the right order) for s = "(]" and s = "((". Which check is complete?
Show answer

Answer

Match each closer to the stack top and return True only if the stack is empty at the end
Both conditions matter: "(]" mismatches and "((" leaves items on the stack. Counting types accepts "([)]". Skipping the final empty check accepts "((". The mirror check rejects valid strings like "()()".

Source: LeetCode 20. Valid Parentheses

Min Stack (a stack that also returns its current minimum) with O(1) getMin. What do you store?
Show answer

Answer

Each entry as (value, min so far)
Storing the min so far with each entry restores the previous min on pop. A single global min is lost when that min is popped. A sorted list makes push O(n). A heap gives O(log n) push and cannot delete the popped value efficiently.

Source: LeetCode 155. Min Stack

Daily Temperatures (for each day, how many days until a warmer one), n up to 105. What does the monotonic stack hold and what is the time?
Show answer

Answer

Indices with decreasing temperatures, O(n)
Indices of days still waiting for a warmer day form a decreasing stack, and each is pushed and popped once. Values alone lose the distance, and there is no log factor. An increasing stack answers the previous smaller element, not the next warmer one. Scanning all later days is the brute force.

Source: LeetCode 739. Daily Temperatures

Evaluate Reverse Polish Notation ["4","13","5","/","+"] where division truncates toward zero. In Python, which division is right for negative operands?
Show answer

Answer

int(a / b)
int(a / b) truncates toward zero, matching the spec, for operands in the given range. a // b floors, so -7 // 2 is -4 instead of -3. round rounds to nearest. floor is the same as //. Also pop b before a.

Source: LeetCode 150. Evaluate Reverse Polish Notation

Queue using two stacks (in and out). When do you move items to out?
Show answer

Answer

Only when out is empty, then move all of in
Moving only when out is empty keeps FIFO order and makes each item move once, so operations are amortized O(1). Moving on every pop is O(n) per pop and breaks order if out is not empty. Moving on push reverses order each time. A size threshold mixes orders.

Source: LeetCode 232. Implement Queue using Stacks

Decode String such as "3[a2[c]]" to "accaccacc". Approach?
Show answer

Answer

Stack of (previous string, repeat count). On a digit build the number (it can be multiple digits). On [ push and reset. On ] pop and set cur = prev + count * cur. Pitfall: reading only one digit.

Source: LeetCode 394. Decode String

Largest Rectangle in Histogram (largest rectangle area under the bars) with a monotonic increasing stack of indices. When you pop index i at current index r, what is the width?
Show answer

Answer

r - stack[-1] - 1 after popping, or r if the stack is empty
Bar i extends from just after the new top to just before r. r - i misses the left extension. r - i + 1 includes r, which is shorter. i - stack[-1] measures only the left side.

Source: LeetCode 84. Largest Rectangle in Histogram

Largest Rectangle in Histogram (largest rectangle area under the bars) with a monotonic stack. Why append a 0 height at the end?
Show answer

Answer

It forces every remaining bar to be popped and measured
Bars still on the stack at the end are never measured without a final flush. Heights are non negative. You still need the empty stack case for width. The stack stays increasing.

Source: LeetCode 84. Largest Rectangle in Histogram

Next Greater Element II (next larger value for each element) on a circular array of n. How do you handle wraparound?
Show answer

Answer

Iterate i from 0 to 2n - 1 using i % n, pushing only in the first pass
A second pass resolves elements whose greater value is before them, and only n results are kept. Returning 2n answers is the wrong size. Two independent runs lose the pending stack. Sorting loses positions.

Source: LeetCode 503. Next Greater Element II

A monotonic stack loop has a while pop inside a for loop. Why is it O(n) and not O(n2)?
Show answer

Answer

Each index is pushed once and popped at most once
Total pops cannot exceed total pushes, so the while body runs at most n times overall. A single iteration can pop many. The stack can hold n items. Input need not be sorted.

Source: LeetCode 739. Daily Temperatures

These questions come from the Coding Interview Practice pack in Bertopia.

More coding topics

Practise these on your commute