PrepStack · Markdown HTML

Stack-based state simulation

Stack and monotone deque · HTML

Formal shape

Read tokens left to right. Each token triggers push, pop, reduce, or top-frame mutation; the stack is the minimal set of contexts from the processed prefix that can affect the future.

Recognition signals

False friends

SignalWhy it is different
First-in-first-out event handlingWhen the earliest arrival must be processed first, use a queue.
Delimiter validity onlyThe narrower balanced-delimiter-stack template is easier to prove.

Core invariant

After each input prefix, frames from bottom to top are exactly the unfinished contexts in opening order, and the top is the only context directly affected next.

State, transition, and processing order

ItemDefinition
StateToken cursor and a frame stack, with each frame storing only information needed to resume its parent context.
TransitionAn opening event pushes a frame, a closing event pops and reduces into its parent, and an ordinary token updates the top frame.
Frontier / orderA chain from oldest to newest unfinished context, exposing only the top to the next transition.

Python skeleton

def normalize_path(parts):
    stack = []
    for part in parts:
        if part in ('', '.'):
            continue
        if part == '..':
            if stack:
                stack.pop()
        else:
            stack.append(part)
    return '/' + '/'.join(stack)

Correctness sketch

  1. An ordinary segment appends the current deepest context while preserving order.
  2. A parent operation removes only the most recent effective segment, exactly matching LIFO semantics.
  3. Induction over all tokens leaves precisely the path segments that were never canceled.

Complexity

TimeSpaceParameters
O(n)O(d)n is token/input length and d maximum unfinished depth; output joining also costs output length.

Edge cases

Error patterns

PatternWhy it fails / fix
Oversized framesCopying the entire prefix into each frame can inflate O(n) work to O(n²).
Popping an empty stackDefine closing or undo behavior when no context exists.
Confusing child and parent stateSpecify frame fields and the reduction performed after pop.

Selection and exclusion rules

RelationTemplateBoundary

Original micro-example

PartDetail
ResultThe normalized path is /home/pics/2026.
SetupPath parts [home,docs,..,pics,.,2026].
TracePush home/docs, pop docs on .., ignore ., then push pics/2026.

Recall prompts

My notes