Simulation
Tactic
Simulation executes the rules of a process directly while keeping state explicit. The tactic is to model exactly what changes after each event or step.
The invariant is faithful state. At the top of each loop, the variables represent the real process after all previous events have been applied.
Good simulation code names the state and transitions clearly. If many branches appear, convert them into small helper functions or a table of directions, operations, or cases.
Value
The value is correctness under detailed rules. Some problems have no hidden trick. They need careful state updates, boundary checks, and termination conditions.
Direct complexity example
- Brute force: Recompute the whole world after every event: or worse for
tevents and state sizen. - With this tactic: Maintain only the changing state and update it per event: often or depending on the needed data structure.
- Space: Space is the explicit state representation, often for counters or for boards, stacks, maps, or queues.
Challenges this solves
- spiral matrix
- asteroid collision
- string multiplication
- plus one
- LRU operations
- game-like rule execution
When to use it
Use this tactic when these conditions are true:
- the prompt gives concrete rules to execute
- edge cases are about state transitions
- the output is the final state after operations
- no stronger invariant simplifies the process
When not to use it
Reach for a different tactic when these warning signs appear:
- the state space repeats and needs cycle detection
- the rules can be summarized by math or greedy logic
- recomputing after each event is too slow and needs a data structure
- the problem asks for an optimum rather than rule execution
Terminology clues
These prompt words often point toward this concept:
- simulate
- process
- operations
- after each
- state
- rules
- collision
- move
Problems that use it
- 2. Add Two Numbers
- 7. Reverse Integer
- 43. Multiply Strings
- 48. Rotate Image
- 54. Spiral Matrix
- 66. Plus One
- 71. Simplify Path
- 73. Set Matrix Zeroes
- 150. Evaluate Reverse Polish Notation
- 155. Min Stack
- 224. Basic Calculator
- 271. Encode and Decode Strings
- 355. Design Twitter
- 735. Asteroid Collision
- 1046. Last Stone Weight
- 1047. Remove All Adjacent Duplicates In String