Pattern Studioalgorithmic thinking
All patterns

Simulation

Greedy Algorithms & Mathematical Optimization
Intermediate
Interactive

Execute movement commands while preserving position state.

Time
O(moves)
Space
O(grid) for visualization
ActiveComparingMatch / bestIn windowFrontierVisitedExcludedAnswer
No frames to display.

The idea

Simulation translates a problem statement directly into state updates. A grid walker applies one command at a time, validates the next position, and records the resulting path.

Analogy

This visualization makes the state transitions behind simulation explicit, one decision at a time.

When to reach for it

  • The problem exhibits this pattern's defining invariant.
  • A direct brute-force approach repeats work or explores unnecessary choices.
  • You need a standard interview-ready template.

Language-independent template

for move in moves:
    next = position + direction[move]
    if next is in bounds:
        position = next

Complexity — time O(moves), space O(grid) for visualization.

Common mistakes

  • Choosing the wrong state or invariant.
  • Updating state before preserving the value needed next.
  • Missing a boundary or base case.

Practice progression

Canonical interview problems, ordered from foundation to advanced application.

Easy

Determine whether a sequence of moves returns to the start.

Medium

Return matrix values in clockwise spiral order.

Hard

Clean every reachable cell using only move, turn, and clean operations.

Variations

Change the input to exercise another path.
Adapt the invariant to a related optimization or counting problem.