Home/Data structures & algorithms/Stacks and nested operations

Stacks and nested operations

Validate last-in-first-out order with a stack

A trace records resources loaded inside nested scopes and unloaded as those scopes exit. Counts alone can look correct even when the nesting is wrong: LOAD:a, LOAD:b, UNLOAD:a, UNLOAD:b loads and unloads both labels, but closes the outer resource while the inner one is still active.

A stack keeps exactly the information the trace needs: which unfinished operation must close next. Sorting the tokens or counting each label would discard that order.

Checking the order of nested resources

A stack records the unresolved nested operations. The most recent load must be the first unloaded, so only the top element can match. A count map would lose this ordering information.

Closing the most recent load

Push a, then b. The only valid next unload is b, leaving a on top. An unload on an empty stack is invalid, and leftover labels at the end mean scopes never closed. Parsing also follows the trace: once an ordering violation decides the result, a later malformed token must not replace that result with a different error.

go
stack := []string{"outer", "inner"}
top := stack[len(stack)-1]
stack = stack[:len(stack)-1]
fmt.Println(top)

Stopping at the first invalid operation

Validate a token when processing reaches it. Prevalidating the entire stream changes behavior when an earlier ordering failure should stop evaluation. This resembles parsers and nested resource scopes: syntax and semantic evaluation order can both be contractual. Linear processing uses O(depth) stack space.

Each token causes at most one push or pop, but parsing also costs time proportional to the token text inspected. Auxiliary storage follows the deepest open nesting and its labels. Repeated adjacent-pair reductions can rescan the sequence quadratically; they must still preserve the left-to-right error contract.

Balanced load/unload totals are only part of the trace contract; the resource lifetimes must also nest correctly.

Practice Stacks and nested operations

Implement the exercise in a full-screen workspace, then run its tests.

Open practice
Next lessonMonotonic deques