Coding Interview Patterns Module 8
Stacks and monotonic stacks interview questions
Interview questions on stacks and monotonic stacks: short warm-ups, then what each harder question tests, the first step of a good answer and its follow-ups.
Warm-up questions
Short questions with short answers, each answered in full.
-
Fresher to mid
How do you recognise that a coding problem wants a stack?
-
Fresher to mid
In Java, should a stack be a java.util.Stack or an ArrayDeque, and does it matter which end you push to?
-
Fresher to mid
When is a counter enough to check brackets, and when do you need a stack?
-
Fresher to mid
What does a monotonic stack keep, and why are the values on it in order?
It keeps the positions whose answer is still open, in the order they arrived. In a next-greater scan, a position waits on the stack until a later value beats it. The values on the stack never rise from the bottom to the top, because a newer value larger than an older one would already have popped it. That order is what makes the method fast: a new value can only answer a run of the newest positions, at the top, so it pops them and stops at the first position it does not beat. Each position is pushed once and popped at most once, so a whole list costs O(n). Keep positions rather than values: the value is one lookup away, and the answer is often a distance.
From the lesson Next greater element with a monotonic stack
Questions with model answers
What each question tests, the first step of a good answer and the follow-ups to expect.
-
Fresher to mid
An editor lets people type, delete and paste anywhere in a document of up to 50 MB. Design undo and redo: what does each stack entry store, what happens to the redo stack after a new edit, and how do you keep the history's memory bounded?
- What it tests
- Inverse operations against snapshots, the redo rule after a new edit, grouping keystrokes, and bounding the history's memory with numbers.
- First step
- Compare what an entry could store before choosing. A snapshot of the whole document costs up to 50 MB per step, so 100 steps could need 5 GB. An inverse operation stores only a position and the characters inserted or removed, so it is as large as the edit itself. Choose operations, then list what each kind of edit needs to be reversed exactly.
- Follow-ups
-
- Typing a word should undo as one step, not one step per key. How?
- Only the last 1,000 steps may be kept. Which structure do you use, and what is dropped?
- A 20 MB paste is undone and then redone. What does each step cost?
- Why must a new edit after an undo clear the redo stack?
From the lesson Stack patterns: nesting and undo
Model answer, Pro. Model answers open with any pass; prices are in the notice on this page.Opening the model answers with your pass…
Model answers open with any MySmartCoPilot pass.
- Pro pass · 1 week₹79$2.99
- 30 days₹179$5.99
- 1 year₹1,699$45
One payment; a pass never renews. The price shown is the total you pay: no fees or charges are added at checkout.
Passes can’t be bought right now, so the model answers can’t be opened at the moment. If you have a pass, enter your licence key.
It also opens every other in-depth part in Learn and every Pro tool. Sales are final, except where the law gives you a right to withdraw, for example in the EU and the UK (refund policy).
In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 4 minutes
-
Mid to senior
Your path simplifier passes every test. A user reports that for a folder reached through a symbolic link, your answer for "../config" is not where the operating system goes. Explain why, say when simplifying the text is still the right choice, and what you would change.
- What it tests
- Lexical against physical resolution of "..", symbolic links, and the security cost of checking a path before it is resolved.
- First step
- Draw the link. Say /srv/app is a symbolic link to /data/releases/v7. As text, /srv/app/../config simplifies to /srv/config. The operating system follows the link first, so ".." from inside it is /data/releases, and the path means /data/releases/config. Simplifying the text treats ".." as "drop the last name", which is right only when that name is a real folder.
- Follow-ups
-
- Which of the two does a shell's cd do by default, and how do you ask for the other?
- How do you get the physical answer in Python, Java and C++?
- A file server simplifies a requested path and checks that it starts with /srv/files/. How can a symbolic link get past the check, and what is the fix?
From the lesson Stack patterns: nesting and undo
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 4 minutes
-
Mid to senior
A code editor must underline the first bracket that breaks a file of up to 20 MB, and update the underline within 16 ms of every keystroke. A full rescan is too slow. What do you store, and what does one edit cost?
- What it tests
- Incremental checking: what an edit cannot change, summaries of blocks that combine, and costing a rescan against a frame budget with numbers.
- First step
- Estimate the rescan first: 20 MB at a few hundred megabytes a second is 50 to 100 ms, several frames. Then notice that an edit at position p cannot change the stack before p, so the work should depend on the edit, not on the file.
- Follow-ups
-
- The file has only one kind of bracket. Can each edit cost O(log n)?
- Brackets inside strings and comments must be ignored.
- The user pastes 1 MB into the middle of the file.
From the lesson Bracket matching and minimum fixes
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 4 minutes
-
Mid to senior
A candidate counts the fewest insertions that balance a string of (), [] and {} with a stack: when a closer does not match the top, insert the top's closer. Give an input where this is wrong, a correct method, and its cost for a string of 500 characters.
- What it tests
- Breaking a greedy rule with a small input, the interval dynamic program for mixed brackets, and turning O(n³) into a time estimate.
- First step
- Try the smallest inputs on which the rule has to choose. For (]) it closes the ( early, and then both closers need partners: 3 insertions, while inserting one [ gives ([]). Then ask which choices a correct method must keep open for the first bracket of every piece of the string.
- Follow-ups
-
- Does the opposite rule, treating the closer as unmatched, fix it?
- Are the fewest insertions always equal to the fewest removals?
- The string grows to 100,000 characters. What can you still offer?
From the lesson Bracket matching and minimum fixes
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Fresher to mid
A spreadsheet formula uses only round brackets. Remove the fewest brackets so that it becomes valid, and return the result. Explain why no smaller fix exists, and how your answer changes when the formula has 10⁷ characters and memory is tight.
- What it tests
- Marking brackets without a partner, the lower bound behind the count, and a two-pass version that needs no stack of positions.
- First step
- Read from the left, counting open brackets: a ) that arrives with nothing open must go, and so must every ( still open at the end. Before coding, say why each of those removals is forced, using the balance of each prefix: openers minus closers so far.
- Follow-ups
-
- Several results are valid. Which one does your method return?
- Return every distinct valid result with the fewest removals.
- The formula can be read twice but never stored whole.
From the lesson Bracket matching and minimum fixes
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Fresher to mid
An interviewer points at the while loop inside your for loop and says your next-greater solution is O(n²). Show that it is O(n), and say which input makes the stack largest.
- What it tests
- Aggregate (amortised) analysis by counting pushes and pops, and the worst case of the stack's memory.
- First step
- Count stack operations over the whole run instead of loop iterations per step: ask how many times one index can go onto the stack and how many times it can come off, whatever the input. For the memory, look for an input in which no index is ever popped.
- Follow-ups
-
- Which input makes one while loop run the longest, and does that contradict the bound?
- Which input fills the stack, and how much memory is that at n = 10⁶?
- Does the bound survive the circular version?
From the lesson Next greater element with a monotonic stack
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 4 minutes
-
Mid to senior
A sensor sends one reading a minute for a year, and each reading's wait for a higher one must be reported as soon as it is known. How much memory can the waiting readings take, and how would you bound it?
- What it tests
- Using a monotonic stack online, the worst case of its memory in numbers, and bounding it with a horizon, merged equal readings or storage.
- First step
- A year of minutes is 525,600 readings. A reading leaves the stack only when a higher one arrives, so a stretch in which readings never rise keeps all of them. Size that worst case before designing: at 8 bytes an entry, a minute number and a value, it is about 4.2 MB, small for one sensor and large for a million.
- Follow-ups
-
- Only waits of at most 24 hours matter. What changes?
- Readings repeat for hours at a time. Can equal readings share one entry?
- The process restarts at midnight. What must it save to carry on?
From the lesson Next greater element with a monotonic stack
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 4 minutes
-
Fresher to mid
A Java min stack keeps a second ArrayDeque<Integer> of minimums. It passes every test with small numbers, but in production, with prices in the thousands, cheapest() sometimes returns a price that was undone. Find the likely bug, explain why the small tests miss it, and fix it.
- What it tests
- Java's boxing rules: == on two Integer objects compares references, the guaranteed cache of -128 to 127, and choosing tests that can fail.
- First step
- Look at every comparison between two values taken from the deques. peekLast() returns an Integer, so == between two of them asks whether they are the same object. Then ask which values Java promises to box into the same object every time.
- Follow-ups
-
- Why did every small test pass?
- Would int[] arrays avoid the bug, and what else would change?
- Do Python's is and JavaScript's === have the same trap?
From the lesson Stacks that know their minimum
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A min stack must hold up to 10⁸ 32-bit readings on a device with 1 GB of memory. Compare pairs, a second stack of minimums and the encoded single stack: what does each cost in the worst case, and which do you ship?
- What it tests
- Memory arithmetic with worst cases, how the order of the readings changes the second stack, the encoded trick's width, and how growable arrays allocate.
- First step
- Do the arithmetic before choosing: 10⁸ readings of 4 bytes are 400 MB on their own, and pairs double that to 800 MB. Then ask which order of readings makes the second stack as large as the first.
- Follow-ups
-
- The readings arrive in falling order. What happens to each design?
- Can a run of equal minimums be stored once?
- The readings can be negative. What does that change?
From the lesson Stacks that know their minimum
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 4 minutes
-
Mid to senior
Prices arrive one per second, and after each one a dashboard shows the lowest price of the last 600 seconds. Design it with O(1) amortised work per price, prove the bound, and say what the slowest single update costs.
- What it tests
- Building a queue with a minimum from two min stacks, amortised analysis by counting the work per price, and the cost of the worst single update.
- First step
- A window drops its oldest price, so it is a queue, not a stack. Build the queue from two stacks that each know their minimum, then count how many pushes and pops one price causes over its whole life.
- Follow-ups
-
- The window is still 600 seconds, but prices arrive at irregular times.
- A monotonic deque can also do it. Which would you pick, and why?
- The dashboard must never stall for more than 1 ms.
From the lesson Stacks that know their minimum
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 4 minutes
-
Mid to senior
When your histogram stack pops a bar, you compute its width from two indices. Which two, why is that the widest rectangle of the bar's height, and what changes when several bars share a height?
- What it tests
- The invariant of a stack of rising bars, the argument for each boundary, and what ties do to the maximum.
- First step
- Freeze the stack at the moment bar t is popped and write down what you know: which bar caused the pop, which bar now sits under t, and what the order of the stack says about the bars between them. Then argue the left side and the right side separately.
- Follow-ups
-
- Why may a popped bar get a rectangle that is too narrow, and does that change the answer?
- Write the same boundaries as two arrays. What do you gain and what does it cost?
- How would you also return the position of the best rectangle?
From the lesson Largest rectangle in a histogram
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 4 minutes
-
Fresher to mid
Your Java histogram solution passes every small test but returns too small an area on a hidden test whose bars are up to 10⁹ tall. What happened, and how do you find every other place where it can happen?
- What it tests
- Integer ranges, how Java evaluates a product of two ints, and checking every intermediate value against the limits.
- First step
- Bound the answer from the limits first: 100,000 bars of 10⁹ make areas up to 10¹⁴, while an int holds at most 2,147,483,647. Then find the first expression that can produce a value that large, and ask in which type Java computes it, not only where the result is stored.
- Follow-ups
-
- Why does the wrong answer come out positive instead of negative?
- How would you make Java fail loudly instead of wrapping?
- Which languages of a five-language solution need the same fix, and which do not?
From the lesson Largest rectangle in a histogram
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A land-use map has 2,000 × 2,000 cells, each open or built. Find the largest rectangle of open cells: give your plan, its time and memory, and how you would test it.
- What it tests
- Reducing a grid to one histogram per row, costing the plan with numbers, and testing it against a brute force.
- First step
- Fix the row on which the rectangle's bottom edge lies, and look up each column from that row: describe what the open cells above it form, and how that connects to a row of bars. Then cost one row's work and multiply by 2,000 rows.
- Follow-ups
-
- The map is too large for memory and arrives one row at a time. Does the method still work?
- Return the coordinates of the plot, not just its area.
- Plots must be squares. What changes?
From the lesson Largest rectangle in a histogram
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
Your sum of subarray minimums comes out too large whenever the input repeats values. Explain why, fix it, and prove that every subarray is now counted exactly once.
- What it tests
- Contribution counting with nearest smaller elements, a tie rule that counts each subarray once, and a proof that the count is unique.
- First step
- Try the smallest repeat, [1, 1]: its three subarrays have minimum 1 and should add 3, but the solution gives 4. Find which items count the subarray [1, 1], and look at where each item's two boundaries stop when they meet an equal value.
- Follow-ups
-
- Which subarrays does each item count after the fix, on [2, 2, 2]?
- Your one-pass version pops on >=. Which side is strict there?
- How do you test the tie rule without knowing the answer by hand?
From the lesson Contribution counting with monotonic stacks
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Fresher to mid
The sum of subarray minimums for 300,000 prices of up to 10⁹ must be returned modulo 10⁹ + 7. Where can a Java or JavaScript solution lose exactness, and how do you keep every step exact?
- What it tests
- Bounding intermediate values from the limits, the ranges of 64-bit integers and of exact JavaScript numbers, and where the reductions go.
- First step
- Bound every value from the limits before writing the arithmetic: a price is at most 10⁹, and one element can be the minimum of a great many subarrays. Find the input that makes a single element's share largest, and compare that share with 2⁶³ − 1 and with 2⁵³.
- Follow-ups
-
- Where exactly do you put the reductions, and why is that enough?
- Why does the JavaScript product print digits that look right?
- Could you avoid the modulus with a double or a 128-bit integer?
From the lesson Contribution counting with monotonic stacks
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
For an array of daily prices, return the sum over all subarrays of (maximum − minimum), modulo 10⁹ + 7. Give an O(n) method, the cost of the naive one at n = 10⁵, and how you handle the subtraction under the modulus.
- What it tests
- Splitting a sum over subarrays, counting maximums as well as minimums, and subtraction under a modulus.
- First step
- Cost the naive method first: the double loop visits n(n + 1)/2 subarrays, about 5 × 10⁹ at n = 10⁵. Then look for a way to write the sum of all the spreads as sums you already know how to count element by element.
- Follow-ups
-
- Which languages need care with the subtraction under the modulus, and why?
- How do ties work for maximums?
- Only subarrays of length at least 2 count. What changes?
From the lesson Contribution counting with monotonic stacks
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
Explain why deleting a digit that is larger than the digit after it never makes the result worse, and turn that into a proof that the stack method returns the smallest number.
- What it tests
- An exchange or window argument for a greedy rule, the role of the deletion budget, and what equal digits should do.
- First step
- Compare two candidates of the same length at their first difference: the leftmost digits decide. Then ask how far into the code the answer's first digit can lie when only k digits may be deleted, and which of those digits it must be.
- Follow-ups
-
- Should an equal digit pop the top?
- Does deleting digits one at a time, always the first digit larger than the next one, give the same answer?
- What is the cost of that one-at-a-time version?
From the lesson Greedy choices with a monotonic stack
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Fresher to mid
Your remove-k-digits solution passes the examples but fails hidden tests. List the edge cases you would test, the bug each one catches, and the smallest input for each.
- What it tests
- Designing edge cases from the exits of the code: deletions left over, leading zeros, an empty result, ties and the budget check.
- First step
- Walk through the code's exits instead of guessing inputs: list every way the loop can end and every form the result can take when it is returned, then give each one the smallest input that reaches it.
- Follow-ups
-
- How would you generate such cases automatically?
- Which edge case is the slowest, and how large should it be?
- The result may not start with 0. What changes?
From the lesson Greedy choices with a monotonic stack
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Senior to staff
A code of 10⁹ digits arrives as a stream, and exactly 10⁶ of its digits must be deleted to leave the smallest number, which you write out as you go. How much memory do you need, and when can a digit be written?
- What it tests
- Turning an offline greedy into a streaming one, when a stack entry becomes final under a budget, and memory bounds with numbers.
- First step
- Ask when a kept digit can still be popped: what must happen first to the digits above it, and what that costs from the budget. A digit that can no longer be popped is final and can be written. Then bound, in bytes, how many digits are not yet final when k = 10⁶.
- Follow-ups
-
- How do you handle leading zeros when digits are written before the end?
- What data structure lets you write from the bottom and pop from the top?
- The deletions left must also cover the end of the stream. How do you finish?
From the lesson Greedy choices with a monotonic stack
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
Explain why the robots left on your stack can never meet one another, and why settling each new robot moving left against the top of the stack gives the same survivors as the meetings in the order they really happen.
- What it tests
- Stating and keeping a stack invariant for a simulation, the order of meetings, and why independent meetings can be settled in any order.
- First step
- Describe the stack by directions alone: write down, from the bottom up, which ways its robots can be moving, and check that no pair in that pattern can close in. Then check that each kind of newcomer keeps the pattern, and in which order a robot moving left reaches the robots on its left.
- Follow-ups
-
- Two meetings happen at the same moment at different places. Does the order you settle them matter?
- How would you show that the stack and the brute force agree, without trusting the argument?
- Return, for every robot, which robot knocked it off.
From the lesson Stack simulations: collisions and spans
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Senior to staff
The robots now move at different speeds, and a robot that catches up with a slower one fights it. Which part of the stack solution breaks, what would you use instead, and what does it cost for 200,000 robots?
- What it tests
- Seeing when a nearest-first order no longer holds, choosing a simulation and its data structures for the new order, and updating only what a meeting changes.
- First step
- Find the assumption the stack used: with equal speeds, meetings involve neighbours and happen nearest first, in a known order. Then ask what decides which meeting comes next when speeds differ, and what you would need to find that meeting quickly, again and again.
- Follow-ups
-
- When two robots meet, which meeting times must you recompute?
- How do you skip meeting times that are out of date?
- Positions are integers and speeds small integers. How do you compare meeting times exactly?
From the lesson Stack simulations: collisions and spans
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A test harness logs the order in which values were pushed to a stack and the order they were popped. Checking a log by simulation works on your tests, but values can repeat. Is the simulation still right? If not, give the smallest failing log and a correct method.
- What it tests
- When a greedy simulation is exact, what repeated values change, and an exact method with its cost.
- First step
- Recall why the simulation is right for distinct values: what would happen to the next value to leave if it were not popped the moment it reaches the top? Then ask whether that argument still holds when another copy of the same value is on the stack or still to be pushed.
- Follow-ups
-
- Why is the simulation exact when every value is distinct?
- How large an input can your exact method handle?
- Can you speed it up when only a few values repeat?
From the lesson Stack simulations: collisions and spans
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
All Coding Interview Patterns interview questions · The Coding Interview Patterns track