Skip to contentKEEP THE CRAFTTHE SANCTUARY

Monotonic Stack

Keep unresolved indices in value order so the first strictly greater arrival resolves a suffix of them. Distances need original positions, equal values stay unresolved, and diagnostic stack snapshots have costs beyond the linear core.

1 practice exercise3 interview problems

Recognize it when For each value, the answer is the first qualifying neighbor later in scan order.

Checking your account…

Monotonic Stack Code Labs

Wait for a Neighbor That Can Resolve a Value

For next greater, an earlier value must wait until a strictly greater value appears. A plain nested scan repeatedly searches that future suffix. A monotonic stack keeps only unresolved indices: when a new value is greater than the top, it resolves that top and may resolve more pending values beneath it.

Derive the Actual Order from the Pop Condition

The trace Lab pops smaller values when a larger value arrives. What remains from bottom to top is therefore non-increasing, with equal values allowed. Indices themselves always increase. The function’s existing name does not define the comparison; read the actual pop rule and distinguish index order from value order.

Trace Monotonic Pops

Reference
def increasing_stack_trace(values):
    stack=[]
    trace=[]
    for index,value in enumerate(values):
        popped=[]
        while stack and values[stack[-1]] < value:
            popped.append(stack.pop())
        stack.append(index)
        trace.append([index,popped,stack.copy()])
    return trace
Practice

Implement increasing_stack_trace(values). Return [index, popped_indexes, stack_indexes] for each value while maintaining a non-increasing stack of values (indices increase; equal values stay unresolved).

Public tests

  • Pop resolved candidates

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Monotonic Pops

def increasing_stack_trace(values):
    stack=[]
    trace=[]
    for index,value in enumerate(values):
        popped=[]
        while stack and values[stack[-1]] < value:
            popped.append(stack.pop())
        stack.append(index)
        trace.append([index,popped,stack.copy()])
    return trace

Resolve Several Pending Indices with One Arrival

The existing trace on [5, 3, 3, 6] retains equal 3 values until the final strictly greater arrival. Snapshot entries show indices, not their values.

Step Executed statement State Why
Push 5 stack.append(index) stack=[0], values at stack=[5] There is no earlier pending value to resolve.
Push 3 stack.append(index) stack=[0,1], values at stack=[5,3] A smaller arrival cannot resolve 5.
Keep equal 3 stack.append(index) 3 < 3 is False; stack becomes [0,1,2] The contract needs a strictly greater value, so equality remains pending.
Resolve with 6 popped.append(stack.pop()) popped=[2,1,0], stack=[] 6 is the first strictly greater arrival for all three pending indices.
Snapshot new frontier stack.append(index); trace.append([index,popped,stack.copy()]) last entry=[3,[2,1,0],[3]] Index 3 now waits for a future greater value; copy preserves this moment.
Return return trace four decision snapshots The trace exposes pending-state changes without computing distances.
Print Output
print(increasing_stack_trace([5, 3, 3, 6])) [[0, [], [0]], [1, [], [0, 1]], [2, [], [0, 1, 2]], [3, [2, 1, 0], [3]]]

Turn Resolved Indices into Distances

The second Lab stores result[previous]=index-previous for each popped index. The current value is the first qualifying neighbor because an earlier qualifying arrival would already have removed that index. Equal values do not qualify under a strictly-greater contract. Indices remaining after the scan have no greater successor and keep the specified zero sentinel.

Find Next Greater Distances

Reference
def next_greater_distance(values):
    result=[0]*len(values)
    stack=[]
    for index,value in enumerate(values):
        while stack and values[stack[-1]] < value:
            previous=stack.pop()
            result[previous]=index-previous
        stack.append(index)
    return result
Practice

Implement next_greater_distance(values). Return distance to the next strictly greater value for each index, or 0.

Public tests

  • Resolve each index once

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Find Next Greater Distances

def next_greater_distance(values):
    result=[0]*len(values)
    stack=[]
    for index,value in enumerate(values):
        while stack and values[stack[-1]] < value:
            previous=stack.pop()
            result[previous]=index-previous
        stack.append(index)
    return result

Count Pushes, Pops and Copies Separately

The core is O(n): an index enters once and can leave once, even when one arrival causes many pops. The trace additionally copies the unresolved stack each iteration. Decreasing input keeps every index pending, so copied sizes grow from 1 to n and the trace takes O(n²) time/output. Do not use diagnostic allocation to describe the core distance Lab, or omit it when describing the trace.

Defend Nearest-Neighbor Order in an Interview

A heap retrieves by global priority and does not by itself prove which qualifying neighbor was first. A monotonic stack uses scan order and permanent resolution. Explain the direction of the inequality, what equals mean, why popped indices never return and how unresolved sentinels are assigned. Begin practice with a duplicate pair, then a value that pops several pending indices at once.

Template To Memorize

Learn this shape by heart; most problems in this family change only one or two lines of it.

Monotonic stack

Bigger arrives, smaller leaves: pop it and give it its answer.

For each item you need the next (or previous) item that is greater or smaller.

Trigger words

  • next greater
  • next smaller
  • previous smaller
  • days until warmer
  • largest rectangle
  • histogram
def next_greater(nums):
    answer = [-1] * len(nums)
    stack = []                       # indices still waiting for a greater value
    for i, num in enumerate(nums):
        while stack and nums[stack[-1]] < num:
            j = stack.pop()
            answer[j] = num          # num is the first greater value after j
        stack.append(i)
    return answer

Spot it when

  • 'Next greater element', 'days until a warmer temperature'.
  • Largest rectangle under bars.

Remember

  • Store indices, not values, so you can compute distances like i - j.
  • Every index is pushed and popped at most once: O(n).

How problems bend it

  • Days to wait: Set answer[j] = i - j instead of the value.
  • Next smaller: Flip the comparison to nums[stack[-1]] > num.
  • Previous smaller: Pop while the top is >= the current value; whatever is left on top is the answer for i, then push i.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Next-greater-distance core scanO(n)O(n)Every input index is pushed once and popped at most once; total while iterations are O(n).

Space

O(n) stack/result space; the diagnostic trace can retain O(n²) copied stack indices.

Assumptions

  • The diagnostic Lab copies its entire stack on each iteration. A decreasing input retains stacks of sizes 1 through n, yielding O(n²) time and trace space.
  • Python list append/pop at the end support stack use; copy() snapshots prevent aliasing but cost time proportional to the stack length.

Invariants Worth Saying Aloud

  1. Stack indices increase from bottom to top and their values are non-increasing; equal values are allowed.
  2. Every stacked index is unresolved, and the current strictly greater value is the first valid answer for each index it pops.

When To Use Or Avoid Monotonic Stack

Use It When

  • Find next strictly greater distances by retaining unresolved indices in a non-increasing value stack.
  • Adapt comparison and sentinel rules explicitly for next-smaller or span contracts.

Choose Another Tool When

  • Use a heap when global priority, rather than nearest scan-order qualification, decides the answer.
  • Do not copy this strict comparison into equal-or-greater queries without changing duplicate ownership.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Resolving equal values as strictly greater

On [3, 3], <= pops the first index even though the second value is not greater, assigning a false next-greater answer.

Prevent it: Use the comparison required by the exact strict or non-strict contract.

Avoid

while stack and values[stack[-1]] <= value:
    stack.pop()

Use instead

while stack and values[stack[-1]] < value:
    stack.pop()

Storing values when the result needs distance

A stored value 8 is not the earlier position 0; subtracting it from current index 2 yields a negative distance.

Prevent it: Store indices, retrieve their values for comparisons and subtract positions for distances.

Avoid

previous = stack.pop()
distance = index-previous

Use instead

previous = index_stack.pop()
distance = index-previous

Saving a live stack reference in the trace

Appending stack itself lets later pops and pushes change a supposedly earlier observation.

Prevent it: Use a shallow copy for index snapshots and include its O(stack length) cost in tracing bounds.

Avoid

trace.append(stack)
stack.pop()
stack.append(2)

Use instead

trace.append(stack.copy())
stack.pop()
stack.append(2)

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.