Pattern Reference
Simulation
"Implement the problem description faithfully. Text processing, game simulation, protocol implementation."
Loading...
Deep Dive Tutorial
Simulation problems are deceptively "easy" — the algorithm is just "do what the problem says." The real challenge is getting every edge case right: what happens at boundaries, when states change, when conditions overlap. The key: read the problem carefully, code the process step by step, and test edge cases methodically.
Common Simulation Patterns
| Pattern | Key Challenge | Example |
|---|---|---|
| Direction tracking | Rotation, turning at boundaries | Spiral matrix, robot moves |
| State machine | Valid state transitions | LRU, game states, parsers |
| Event simulation | Process events in order | Meeting rooms, task scheduler |
| String manipulation | Boundary conditions, indices | Reverse words, zigzag |
| Number manipulation | Overflow, digit extraction | Happy number, digit reversal |
| Grid simulation | Out-of-bounds, visited tracking | Game of Life, robot paths |
Worked Problems
gamepad-2
Simulation checklist:
1. Read the problem statement word by word — every sentence may be a constraint
2. Identify the state: what needs to be tracked at each step?
3. Code the transitions: what changes on each event/step?
4. Boundary conditions: what happens at edges, start, end?
5. Test with simple cases first, then edge cases
In-place update trick: When you need to update a grid "simultaneously," encode old/new states as different numbers. First pass: set encoded values. Second pass: decode. Avoids reading your own updates.
1. Read the problem statement word by word — every sentence may be a constraint
2. Identify the state: what needs to be tracked at each step?
3. Code the transitions: what changes on each event/step?
4. Boundary conditions: what happens at edges, start, end?
5. Test with simple cases first, then edge cases
In-place update trick: When you need to update a grid "simultaneously," encode old/new states as different numbers. First pass: set encoded values. Second pass: decode. Avoids reading your own updates.